file_system.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "mime/multipart"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/gorilla/websocket"
  22. uuid "github.com/satori/go.uuid"
  23. fs "imuslab.com/arozos/mod/filesystem"
  24. fsp "imuslab.com/arozos/mod/filesystem/fspermission"
  25. hidden "imuslab.com/arozos/mod/filesystem/hidden"
  26. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  27. usage "imuslab.com/arozos/mod/info/usageinfo"
  28. module "imuslab.com/arozos/mod/modules"
  29. prout "imuslab.com/arozos/mod/prouter"
  30. "imuslab.com/arozos/mod/share"
  31. storage "imuslab.com/arozos/mod/storage"
  32. user "imuslab.com/arozos/mod/user"
  33. )
  34. var (
  35. thumbRenderHandler *metadata.RenderHandler
  36. shareManager *share.Manager
  37. systemReservedUploadMem int64 = 0
  38. )
  39. type trashedFile struct {
  40. Filename string
  41. Filepath string
  42. FileExt string
  43. IsDir bool
  44. Filesize int64
  45. RemoveTimestamp int64
  46. RemoveDate string
  47. OriginalPath string
  48. OriginalFilename string
  49. }
  50. func FileSystemInit() {
  51. router := prout.NewModuleRouter(prout.RouterOption{
  52. ModuleName: "File Manager",
  53. AdminOnly: false,
  54. UserHandler: userHandler,
  55. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  56. sendErrorResponse(w, "Permission Denied")
  57. },
  58. })
  59. //Upload related functions
  60. router.HandleFunc("/system/file_system/upload", system_fs_handleUpload)
  61. router.HandleFunc("/system/file_system/lowmemUpload", system_fs_handleLowMemoryUpload)
  62. //Other file operations
  63. router.HandleFunc("/system/file_system/validateFileOpr", system_fs_validateFileOpr)
  64. router.HandleFunc("/system/file_system/fileOpr", system_fs_handleOpr)
  65. router.HandleFunc("/system/file_system/ws/fileOpr", system_fs_handleWebSocketOpr)
  66. router.HandleFunc("/system/file_system/listDir", system_fs_handleList)
  67. router.HandleFunc("/system/file_system/listDirHash", system_fs_handleDirHash)
  68. router.HandleFunc("/system/file_system/listRoots", system_fs_listRoot)
  69. router.HandleFunc("/system/file_system/listDrives", system_fs_listDrives)
  70. router.HandleFunc("/system/file_system/newItem", system_fs_handleNewObjects)
  71. router.HandleFunc("/system/file_system/preference", system_fs_handleUserPreference)
  72. router.HandleFunc("/system/file_system/listTrash", system_fs_scanTrashBin)
  73. router.HandleFunc("/system/file_system/ws/listTrash", system_fs_WebSocketScanTrashBin)
  74. router.HandleFunc("/system/file_system/clearTrash", system_fs_clearTrashBin)
  75. router.HandleFunc("/system/file_system/restoreTrash", system_fs_restoreFile)
  76. router.HandleFunc("/system/file_system/zipHandler", system_fs_zipHandler)
  77. router.HandleFunc("/system/file_system/getProperties", system_fs_getFileProperties)
  78. router.HandleFunc("/system/file_system/pathTranslate", system_fs_handlePathTranslate)
  79. router.HandleFunc("/system/file_system/handleFilePermission", system_fs_handleFilePermission)
  80. router.HandleFunc("/system/file_system/search", system_fs_handleFileSearch)
  81. //Thumbnail caching functions
  82. router.HandleFunc("/system/file_system/handleFolderCache", system_fs_handleFolderCache)
  83. router.HandleFunc("/system/file_system/handleCacheRender", system_fs_handleCacheRender)
  84. //Register the module
  85. moduleHandler.RegisterModule(module.ModuleInfo{
  86. Name: "File Manager",
  87. Group: "System Tools",
  88. IconPath: "SystemAO/file_system/img/small_icon.png",
  89. Version: "1.0",
  90. StartDir: "SystemAO/file_system/file_explorer.html",
  91. SupportFW: true,
  92. InitFWSize: []int{1080, 580},
  93. LaunchFWDir: "SystemAO/file_system/file_explorer.html",
  94. SupportEmb: false,
  95. })
  96. //Register the Trashbin module
  97. moduleHandler.RegisterModule(module.ModuleInfo{
  98. Name: "Trash Bin",
  99. Group: "System Tools",
  100. IconPath: "SystemAO/file_system/trashbin_img/small_icon.png",
  101. Version: "1.0",
  102. StartDir: "SystemAO/file_system/trashbin.html",
  103. SupportFW: true,
  104. InitFWSize: []int{1080, 580},
  105. LaunchFWDir: "SystemAO/file_system/trashbin.html",
  106. SupportEmb: false,
  107. SupportedExt: []string{"*"},
  108. })
  109. //Register the Zip Extractor module
  110. moduleHandler.RegisterModule(module.ModuleInfo{
  111. Name: "Zip Extractor",
  112. Group: "System Tools",
  113. IconPath: "SystemAO/file_system/img/zip_extractor.png",
  114. Version: "1.0",
  115. SupportFW: false,
  116. LaunchEmb: "SystemAO/file_system/zip_extractor.html",
  117. SupportEmb: true,
  118. InitEmbSize: []int{260, 120},
  119. SupportedExt: []string{".zip"},
  120. })
  121. //Create user root if not exists
  122. err := os.MkdirAll(*root_directory+"users/", 0755)
  123. if err != nil {
  124. log.Println("Failed to create system storage root.")
  125. panic(err)
  126. }
  127. //Create database table if not exists
  128. err = sysdb.NewTable("fs")
  129. if err != nil {
  130. log.Println("Failed to create table for file system")
  131. panic(err)
  132. }
  133. //Create a RenderHandler for caching thumbnails
  134. thumbRenderHandler = metadata.NewRenderHandler()
  135. /*
  136. Share Related Registering
  137. This section of functions create and register the file share service
  138. for the arozos
  139. */
  140. //Create a share manager to handle user file sharae
  141. shareManager = share.NewShareManager(share.Options{
  142. AuthAgent: authAgent,
  143. Database: sysdb,
  144. UserHandler: userHandler,
  145. HostName: *host_name,
  146. TmpFolder: *tmp_directory,
  147. })
  148. //Share related functions
  149. router.HandleFunc("/system/file_system/share/new", shareManager.HandleCreateNewShare)
  150. router.HandleFunc("/system/file_system/share/delete", shareManager.HandleDeleteShare)
  151. router.HandleFunc("/system/file_system/share/edit", shareManager.HandleEditShare)
  152. router.HandleFunc("/system/file_system/share/checkShared", shareManager.HandleShareCheck)
  153. //Handle the main share function
  154. http.HandleFunc("/share", shareManager.HandleShareAccess)
  155. /*
  156. Nighly Tasks
  157. These functions allow file system to clear and maintain
  158. the arozos file system when no one is using the system
  159. */
  160. //Clear tmp folder if files is placed here too long
  161. RegisterNightlyTask(system_fs_clearOldTmpFiles)
  162. //Clear shares that its parent file no longer exists in the system
  163. shareManager.ValidateAndClearShares()
  164. RegisterNightlyTask(shareManager.ValidateAndClearShares)
  165. }
  166. /*
  167. File Search
  168. Handle file search in wildcard and recursive search
  169. */
  170. func system_fs_handleFileSearch(w http.ResponseWriter, r *http.Request) {
  171. //Get the user information
  172. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  173. if err != nil {
  174. sendErrorResponse(w, "User not logged in")
  175. return
  176. }
  177. //Get the search target root path
  178. vpath, err := mv(r, "path", true)
  179. if err != nil {
  180. sendErrorResponse(w, "Invalid vpath given")
  181. return
  182. }
  183. keyword, err := mv(r, "keyword", true)
  184. if err != nil {
  185. sendErrorResponse(w, "Invalid keyword given")
  186. return
  187. }
  188. //Check if case sensitive is enabled
  189. casesensitve, _ := mv(r, "casesensitive", true)
  190. //Translate the vpath to realpath
  191. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  192. if err != nil {
  193. sendErrorResponse(w, "Invalid path given")
  194. return
  195. }
  196. //Check if the search mode is recursive keyword or wildcard
  197. if len(keyword) > 1 && keyword[:1] == "/" {
  198. //Wildcard
  199. wildcard := keyword[1:]
  200. matchingFiles, err := filepath.Glob(filepath.Join(rpath, wildcard))
  201. if err != nil {
  202. sendErrorResponse(w, err.Error())
  203. return
  204. }
  205. //Prepare result struct
  206. results := []fs.FileData{}
  207. //Process the matching files. Do not allow directory escape
  208. srcAbs, _ := filepath.Abs(rpath)
  209. srcAbs = filepath.ToSlash(srcAbs)
  210. escaped := false
  211. for _, matchedFile := range matchingFiles {
  212. absMatch, _ := filepath.Abs(matchedFile)
  213. absMatch = filepath.ToSlash(absMatch)
  214. if !strings.Contains(absMatch, srcAbs) {
  215. escaped = true
  216. }
  217. thisVpath, _ := userinfo.RealPathToVirtualPath(matchedFile)
  218. results = append(results, fs.GetFileDataFromPath(thisVpath, matchedFile, 2))
  219. }
  220. if escaped {
  221. sendErrorResponse(w, "Search keywords contain escape character!")
  222. return
  223. }
  224. //OK. Tidy up the results
  225. js, _ := json.Marshal(results)
  226. sendJSONResponse(w, string(js))
  227. } else {
  228. //Recursive keyword
  229. results := []fs.FileData{}
  230. var err error = nil
  231. if casesensitve == "true" {
  232. //Require case sensitive match
  233. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  234. if strings.Contains(filepath.Base(path), keyword) {
  235. //This is a matching file
  236. if !fs.IsInsideHiddenFolder(path) {
  237. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  238. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  239. }
  240. }
  241. return nil
  242. })
  243. } else {
  244. //Require general match
  245. keywordLower := strings.ToLower(keyword)
  246. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  247. if strings.Contains(strings.ToLower(filepath.Base(path)), keywordLower) {
  248. //This is a matching file
  249. if !fs.IsInsideHiddenFolder(path) {
  250. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  251. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  252. }
  253. }
  254. return nil
  255. })
  256. }
  257. if err != nil {
  258. sendErrorResponse(w, err.Error())
  259. return
  260. }
  261. //OK. Tidy up the results
  262. js, _ := json.Marshal(results)
  263. sendJSONResponse(w, string(js))
  264. }
  265. }
  266. /*
  267. Handle low-memory upload operations
  268. This function is specailly designed to work with low memory devices
  269. (e.g. ZeroPi / Orange Pi Zero with 512MB RAM)
  270. */
  271. func system_fs_handleLowMemoryUpload(w http.ResponseWriter, r *http.Request) {
  272. //Get user info
  273. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  274. if err != nil {
  275. w.WriteHeader(http.StatusUnauthorized)
  276. w.Write([]byte("401 - Unauthorized"))
  277. return
  278. }
  279. //Get filename and upload path
  280. filename, err := mv(r, "filename", false)
  281. if filename == "" || err != nil {
  282. w.WriteHeader(http.StatusInternalServerError)
  283. w.Write([]byte("500 - Invalid filename given"))
  284. return
  285. }
  286. //Get upload target directory
  287. uploadTarget, err := mv(r, "path", false)
  288. if uploadTarget == "" || err != nil {
  289. w.WriteHeader(http.StatusInternalServerError)
  290. w.Write([]byte("500 - Invalid path given"))
  291. return
  292. }
  293. //Check if the user can write to this folder
  294. if !userinfo.CanWrite(uploadTarget) {
  295. //No permission
  296. w.WriteHeader(http.StatusForbidden)
  297. w.Write([]byte("403 - Access Denied"))
  298. return
  299. }
  300. //Translate the upload target directory
  301. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  302. if err != nil {
  303. w.WriteHeader(http.StatusInternalServerError)
  304. w.Write([]byte("500 - Path translation failed"))
  305. return
  306. }
  307. //Generate an UUID for this upload
  308. uploadUUID := uuid.NewV4().String()
  309. uploadFolder := filepath.Join(*tmp_directory, "uploads", uploadUUID)
  310. os.MkdirAll(uploadFolder, 0700)
  311. targetUploadLocation := filepath.Join(realUploadPath, filename)
  312. if !fileExists(realUploadPath) {
  313. os.MkdirAll(realUploadPath, 0755)
  314. }
  315. //Start websocket connection
  316. var upgrader = websocket.Upgrader{}
  317. c, err := upgrader.Upgrade(w, r, nil)
  318. defer c.Close()
  319. //Handle WebSocket upload
  320. blockCounter := 0
  321. chunkName := []string{}
  322. lastChunkArrivalTime := time.Now().Unix()
  323. //Setup a timeout listener, check if connection still active every 1 minute
  324. ticker := time.NewTicker(60 * time.Second)
  325. done := make(chan bool)
  326. go func() {
  327. for {
  328. select {
  329. case <-done:
  330. return
  331. case <-ticker.C:
  332. if time.Now().Unix()-lastChunkArrivalTime > 300 {
  333. //Already 5 minutes without new data arraival. Stop connection
  334. log.Println("Upload WebSocket connection timeout. Disconnecting.")
  335. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  336. time.Sleep(1 * time.Second)
  337. c.Close()
  338. return
  339. }
  340. }
  341. }
  342. }()
  343. totalFileSize := int64(0)
  344. for {
  345. mt, message, err := c.ReadMessage()
  346. if err != nil {
  347. //Connection closed by client. Clear the tmp folder and exit
  348. log.Println("Upload terminated by client. Cleaning tmp folder.")
  349. //Clear the tmp folder
  350. time.Sleep(1 * time.Second)
  351. os.RemoveAll(uploadFolder)
  352. return
  353. }
  354. //The mt should be 2 = binary for file upload and 1 for control syntax
  355. if mt == 1 {
  356. msg := strings.TrimSpace(string(message))
  357. if msg == "done" {
  358. //Start the merging process
  359. log.Println(userinfo.Username + " uploaded a file: " + filepath.Base(targetUploadLocation))
  360. break
  361. } else {
  362. //Unknown operations
  363. }
  364. } else if mt == 2 {
  365. //File block. Save it to tmp folder
  366. chunkFilepath := filepath.Join(uploadFolder, "upld_"+strconv.Itoa(blockCounter))
  367. chunkName = append(chunkName, chunkFilepath)
  368. ioutil.WriteFile(chunkFilepath, message, 0700)
  369. //Update the last upload chunk time
  370. lastChunkArrivalTime = time.Now().Unix()
  371. //Check if the file size is too big
  372. totalFileSize += fs.GetFileSize(chunkFilepath)
  373. if totalFileSize > max_upload_size {
  374. //File too big
  375. c.WriteMessage(1, []byte(`{\"error\":\"File size too large.\"}`))
  376. //Close the connection
  377. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  378. time.Sleep(1 * time.Second)
  379. c.Close()
  380. //Clear the tmp files
  381. os.RemoveAll(uploadFolder)
  382. return
  383. }
  384. blockCounter++
  385. //Request client to send the next chunk
  386. c.WriteMessage(1, []byte("next"))
  387. }
  388. //log.Println("recv:", len(message), "type", mt)
  389. }
  390. //Merge the file
  391. out, err := os.OpenFile(targetUploadLocation, os.O_CREATE|os.O_WRONLY, 0755)
  392. if err != nil {
  393. log.Println("Failed to open file:", err)
  394. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open destination file\"}`))
  395. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  396. time.Sleep(1 * time.Second)
  397. c.Close()
  398. return
  399. }
  400. defer out.Close()
  401. for _, filesrc := range chunkName {
  402. srcChunkReader, err := os.Open(filesrc)
  403. if err != nil {
  404. log.Println("Failed to open Source Chunk", filesrc, " with error ", err.Error())
  405. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open Source Chunk\"}`))
  406. return
  407. }
  408. io.Copy(out, srcChunkReader)
  409. srcChunkReader.Close()
  410. }
  411. //Set owner of the new uploaded file
  412. userinfo.SetOwnerOfFile(targetUploadLocation)
  413. //Return complete signal
  414. c.WriteMessage(1, []byte("OK"))
  415. //Stop the timeout listner
  416. done <- true
  417. //Clear the tmp folder
  418. time.Sleep(1 * time.Second)
  419. err = os.RemoveAll(uploadFolder)
  420. if err != nil {
  421. log.Println(err)
  422. }
  423. //Close WebSocket connection after finished
  424. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  425. time.Sleep(1 * time.Second)
  426. c.Close()
  427. }
  428. /*
  429. Handle FORM POST based upload
  430. This function is design for general SBCs or computers with more than 2GB of RAM
  431. (e.g. Raspberry Pi 4 / Linux Server)
  432. */
  433. func system_fs_handleUpload(w http.ResponseWriter, r *http.Request) {
  434. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  435. if err != nil {
  436. sendErrorResponse(w, "User not logged in")
  437. return
  438. }
  439. username := userinfo.Username
  440. //Limit the max upload size to the user defined size
  441. if max_upload_size != 0 {
  442. r.Body = http.MaxBytesReader(w, r.Body, max_upload_size)
  443. }
  444. //Check if this is running under demo mode. If yes, reject upload
  445. if *demo_mode {
  446. sendErrorResponse(w, "You cannot upload in demo mode")
  447. return
  448. }
  449. //Experimental code: Get the remaining memory and use 1/2 - 10MB of it
  450. //See https://golang.org/pkg/mime/multipart/#Reader.ReadForm for why 10MB
  451. usedRam, totalRam := usage.GetNumericRAMUsage()
  452. autoCalculatedUploadBuf := int64(0)
  453. if usedRam > 0 && totalRam > 0 {
  454. //Do not use all RAM. Use only 80% of it
  455. totalRam = int64(float64(totalRam) * 0.8)
  456. //Use *upload_buf per 1GB rules for upload
  457. usableMemorySpace := totalRam - usedRam - systemReservedUploadMem
  458. autoCalculatedUploadBuf := (usableMemorySpace / (1024 * 1024 * 1024)) * int64(*upload_buf)
  459. //Add the reserve to global reserve memory value
  460. systemReservedUploadMem += autoCalculatedUploadBuf
  461. //Handle file upload
  462. log.Println("*Testing* Upload buffer set to ", autoCalculatedUploadBuf, "MB")
  463. err = r.ParseMultipartForm(int64(autoCalculatedUploadBuf) << 20)
  464. } else {
  465. //Unable to get RAM usage. Use default parser buffer size
  466. err = r.ParseMultipartForm(int64(*upload_buf) << 20)
  467. }
  468. if err != nil {
  469. //Filesize too big
  470. log.Println(err)
  471. sendErrorResponse(w, "File too large")
  472. return
  473. }
  474. file, handler, err := r.FormFile("file")
  475. if err != nil {
  476. log.Println("Error Retrieving File from upload by user: " + username)
  477. sendErrorResponse(w, "Unable to parse file from upload")
  478. return
  479. }
  480. //Get upload target directory
  481. uploadTarget, _ := mv(r, "path", true)
  482. if uploadTarget == "" {
  483. sendErrorResponse(w, "Upload target cannot be empty.")
  484. return
  485. }
  486. //Translate the upload target directory
  487. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  488. if err != nil {
  489. sendErrorResponse(w, "Upload target is invalid or permission denied.")
  490. return
  491. }
  492. storeFilename := handler.Filename //Filename of the uploaded file
  493. destFilepath := filepath.ToSlash(filepath.Clean(realUploadPath)) + "/" + storeFilename
  494. if !fileExists(filepath.Dir(destFilepath)) {
  495. os.MkdirAll(filepath.Dir(destFilepath), 0755)
  496. }
  497. //Check if the upload target is read only.
  498. accmode := userinfo.GetPathAccessPermission(uploadTarget)
  499. if accmode == "readonly" {
  500. sendErrorResponse(w, "The upload target is Read Only.")
  501. return
  502. } else if accmode == "denied" {
  503. sendErrorResponse(w, "Access Denied")
  504. return
  505. }
  506. //Check for storage quota
  507. uploadFileSize := handler.Size
  508. if !userinfo.StorageQuota.HaveSpace(uploadFileSize) {
  509. sendErrorResponse(w, "Storage Quota Full")
  510. return
  511. }
  512. //Prepare the file to be created (uploaded)
  513. destination, err := os.Create(destFilepath)
  514. if err != nil {
  515. sendErrorResponse(w, err.Error())
  516. return
  517. }
  518. defer destination.Close()
  519. defer file.Close()
  520. //Move the file to destination file location
  521. if *enable_asyncFileUpload {
  522. //Use Async upload method
  523. go func(r *http.Request, file multipart.File, destination *os.File, userinfo *user.User) {
  524. //Do the file copying using a buffered reader
  525. buf := make([]byte, *file_opr_buff)
  526. for {
  527. n, err := file.Read(buf)
  528. if err != nil && err != io.EOF {
  529. log.Println(err.Error())
  530. return
  531. }
  532. if n == 0 {
  533. break
  534. }
  535. if _, err := destination.Write(buf[:n]); err != nil {
  536. log.Println(err.Error())
  537. return
  538. }
  539. }
  540. //Clear up buffered files
  541. r.MultipartForm.RemoveAll()
  542. //Set the ownership of file
  543. userinfo.SetOwnerOfFile(destFilepath)
  544. //Perform a GC afterward
  545. runtime.GC()
  546. //Deduce the buffered memory
  547. systemReservedUploadMem -= autoCalculatedUploadBuf
  548. }(r, file, destination, userinfo)
  549. } else {
  550. //Use blocking upload and move method
  551. buf := make([]byte, *file_opr_buff)
  552. for {
  553. n, err := file.Read(buf)
  554. if err != nil && err != io.EOF {
  555. log.Println(err.Error())
  556. return
  557. }
  558. if n == 0 {
  559. break
  560. }
  561. if _, err := destination.Write(buf[:n]); err != nil {
  562. log.Println(err.Error())
  563. return
  564. }
  565. }
  566. //Clear up buffered files
  567. r.MultipartForm.RemoveAll()
  568. //Set the ownership of file
  569. userinfo.SetOwnerOfFile(destFilepath)
  570. }
  571. //Finish up the upload
  572. //fmt.Printf("Uploaded File: %+v\n", handler.Filename)
  573. //fmt.Printf("File Size: %+v\n", handler.Size)
  574. //fmt.Printf("MIME Header: %+v\n", handler.Header)
  575. //fmt.Println("Upload target: " + realUploadPath)
  576. //Fnish upload. Fix the tmp filename
  577. log.Println(username + " uploaded a file: " + handler.Filename)
  578. //Do upload finishing stuff
  579. //Perform a GC
  580. runtime.GC()
  581. //Deduce the buffered memory
  582. systemReservedUploadMem -= autoCalculatedUploadBuf
  583. //Completed
  584. sendOK(w)
  585. return
  586. }
  587. //Validate if the copy and target process will involve file overwriting problem.
  588. func system_fs_validateFileOpr(w http.ResponseWriter, r *http.Request) {
  589. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  590. if err != nil {
  591. sendErrorResponse(w, err.Error())
  592. return
  593. }
  594. vsrcFiles, _ := mv(r, "src", true)
  595. vdestFile, _ := mv(r, "dest", true)
  596. var duplicateFiles []string
  597. //Loop through all files are see if there are duplication during copy and paste
  598. sourceFiles := []string{}
  599. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  600. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  601. if err != nil {
  602. sendErrorResponse(w, "Source file JSON parse error.")
  603. return
  604. }
  605. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  606. for _, file := range sourceFiles {
  607. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(file))
  608. if fileExists(rdestFile + filepath.Base(rsrcFile)) {
  609. //File exists already.
  610. vpath, _ := userinfo.RealPathToVirtualPath(rsrcFile)
  611. duplicateFiles = append(duplicateFiles, vpath)
  612. }
  613. }
  614. jsonString, _ := json.Marshal(duplicateFiles)
  615. sendJSONResponse(w, string(jsonString))
  616. return
  617. }
  618. //Scan all directory and get trash file and send back results with WebSocket
  619. func system_fs_WebSocketScanTrashBin(w http.ResponseWriter, r *http.Request) {
  620. //Get and check user permission
  621. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  622. if err != nil {
  623. sendErrorResponse(w, "User not logged in")
  624. return
  625. }
  626. //Upgrade to websocket
  627. var upgrader = websocket.Upgrader{}
  628. c, err := upgrader.Upgrade(w, r, nil)
  629. if err != nil {
  630. w.WriteHeader(http.StatusInternalServerError)
  631. w.Write([]byte("500 - " + err.Error()))
  632. log.Print("Websocket Upgrade Error:", err.Error())
  633. return
  634. }
  635. //Start Scanning
  636. scanningRoots := []string{}
  637. //Get all roots to scan
  638. for _, storage := range userinfo.GetAllFileSystemHandler() {
  639. storageRoot := storage.Path
  640. scanningRoots = append(scanningRoots, storageRoot)
  641. }
  642. for _, rootPath := range scanningRoots {
  643. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  644. oneLevelUpper := filepath.Base(filepath.Dir(path))
  645. if oneLevelUpper == ".trash" {
  646. //This is a trashbin dir.
  647. file := path
  648. //Parse the trashFile struct
  649. timestamp := filepath.Ext(file)[1:]
  650. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  651. originalExt := filepath.Ext(filepath.Base(originalName))
  652. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  653. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  654. rawsize := fs.GetFileSize(file)
  655. timestampInt64, _ := StringToInt64(timestamp)
  656. removeTimeDate := time.Unix(timestampInt64, 0)
  657. if IsDir(file) {
  658. originalExt = ""
  659. }
  660. thisTrashFileObject := trashedFile{
  661. Filename: filepath.Base(file),
  662. Filepath: virtualFilepath,
  663. FileExt: originalExt,
  664. IsDir: IsDir(file),
  665. Filesize: int64(rawsize),
  666. RemoveTimestamp: timestampInt64,
  667. RemoveDate: timeToString(removeTimeDate),
  668. OriginalPath: virtualOrgPath,
  669. OriginalFilename: originalName,
  670. }
  671. //Send out the result as JSON string
  672. js, _ := json.Marshal(thisTrashFileObject)
  673. err := c.WriteMessage(1, js)
  674. if err != nil {
  675. //Connection already closed
  676. return err
  677. }
  678. }
  679. return nil
  680. })
  681. if err != nil {
  682. //Scan or client connection error (Connection closed?)
  683. return
  684. }
  685. }
  686. //Close connection after finished
  687. c.Close()
  688. }
  689. //Scan all the directory and get trash files within the system
  690. func system_fs_scanTrashBin(w http.ResponseWriter, r *http.Request) {
  691. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  692. if err != nil {
  693. sendErrorResponse(w, err.Error())
  694. return
  695. }
  696. username := userinfo.Username
  697. results := []trashedFile{}
  698. files, err := system_fs_listTrash(username)
  699. if err != nil {
  700. sendErrorResponse(w, err.Error())
  701. return
  702. }
  703. //Get information of each files and process it into results
  704. for _, file := range files {
  705. timestamp := filepath.Ext(file)[1:]
  706. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  707. originalExt := filepath.Ext(filepath.Base(originalName))
  708. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  709. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  710. rawsize := fs.GetFileSize(file)
  711. timestampInt64, _ := StringToInt64(timestamp)
  712. removeTimeDate := time.Unix(timestampInt64, 0)
  713. if IsDir(file) {
  714. originalExt = ""
  715. }
  716. results = append(results, trashedFile{
  717. Filename: filepath.Base(file),
  718. Filepath: virtualFilepath,
  719. FileExt: originalExt,
  720. IsDir: IsDir(file),
  721. Filesize: int64(rawsize),
  722. RemoveTimestamp: timestampInt64,
  723. RemoveDate: timeToString(removeTimeDate),
  724. OriginalPath: virtualOrgPath,
  725. OriginalFilename: originalName,
  726. })
  727. }
  728. //Sort the results by date, latest on top
  729. sort.Slice(results[:], func(i, j int) bool {
  730. return results[i].RemoveTimestamp > results[j].RemoveTimestamp
  731. })
  732. //Format and return the json results
  733. jsonString, _ := json.Marshal(results)
  734. sendJSONResponse(w, string(jsonString))
  735. }
  736. //Restore a trashed file to its parent dir
  737. func system_fs_restoreFile(w http.ResponseWriter, r *http.Request) {
  738. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  739. if err != nil {
  740. sendErrorResponse(w, err.Error())
  741. return
  742. }
  743. targetTrashedFile, err := mv(r, "src", true)
  744. if err != nil {
  745. sendErrorResponse(w, "Invalid src given")
  746. return
  747. }
  748. //Translate it to realpath
  749. realpath, _ := userinfo.VirtualPathToRealPath(targetTrashedFile)
  750. if !fileExists(realpath) {
  751. sendErrorResponse(w, "File not exists")
  752. return
  753. }
  754. //Check if this is really a trashed file
  755. if filepath.Base(filepath.Dir(realpath)) != ".trash" {
  756. sendErrorResponse(w, "File not in trashbin")
  757. return
  758. }
  759. //OK to proceed.
  760. targetPath := filepath.ToSlash(filepath.Dir(filepath.Dir(realpath))) + "/" + strings.TrimSuffix(filepath.Base(realpath), filepath.Ext(filepath.Base(realpath)))
  761. //log.Println(targetPath);
  762. os.Rename(realpath, targetPath)
  763. //Check if the parent dir has no more fileds. If yes, remove it
  764. filescounter, _ := filepath.Glob(filepath.Dir(realpath) + "/*")
  765. if len(filescounter) == 0 {
  766. os.Remove(filepath.Dir(realpath))
  767. }
  768. sendOK(w)
  769. }
  770. //Clear all trashed file in the system
  771. func system_fs_clearTrashBin(w http.ResponseWriter, r *http.Request) {
  772. u, err := userHandler.GetUserInfoFromRequest(w, r)
  773. if err != nil {
  774. sendErrorResponse(w, "User not logged in")
  775. return
  776. }
  777. username := u.Username
  778. fileList, err := system_fs_listTrash(username)
  779. if err != nil {
  780. sendErrorResponse(w, "Unable to clear trash: "+err.Error())
  781. return
  782. }
  783. //Get list success. Remove each of them.
  784. for _, file := range fileList {
  785. isOwner := u.IsOwnerOfFile(file)
  786. if isOwner {
  787. //This user own this system. Remove this file from his quota
  788. u.RemoveOwnershipFromFile(file)
  789. }
  790. os.RemoveAll(file)
  791. //Check if its parent directory have no files. If yes, remove the dir itself as well.
  792. filesInThisTrashBin, _ := filepath.Glob(filepath.Dir(file) + "/*")
  793. if len(filesInThisTrashBin) == 0 {
  794. os.Remove(filepath.Dir(file))
  795. }
  796. }
  797. sendOK(w)
  798. }
  799. //Get all trash in a string list
  800. func system_fs_listTrash(username string) ([]string, error) {
  801. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  802. scanningRoots := []string{}
  803. //Get all roots to scan
  804. for _, storage := range userinfo.GetAllFileSystemHandler() {
  805. storageRoot := storage.Path
  806. scanningRoots = append(scanningRoots, storageRoot)
  807. }
  808. files := []string{}
  809. for _, rootPath := range scanningRoots {
  810. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  811. oneLevelUpper := filepath.Base(filepath.Dir(path))
  812. if oneLevelUpper == ".trash" {
  813. //This is a trashbin dir.
  814. files = append(files, path)
  815. }
  816. return nil
  817. })
  818. if err != nil {
  819. return []string{}, errors.New("Failed to scan file system.")
  820. }
  821. }
  822. return files, nil
  823. }
  824. /*
  825. Handle new file or folder functions
  826. Required information
  827. @type {folder / file}
  828. @ext {any that is listed in the template folder}
  829. if no paramter is passed in, default listing all the supported template file
  830. */
  831. func system_fs_handleNewObjects(w http.ResponseWriter, r *http.Request) {
  832. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  833. if err != nil {
  834. sendErrorResponse(w, "User not logged in")
  835. return
  836. }
  837. fileType, _ := mv(r, "type", true) //File creation type, {file, folder}
  838. vsrc, _ := mv(r, "src", true) //Virtual file source folder, do not include filename
  839. filename, _ := mv(r, "filename", true) //Filename for the new file
  840. if fileType == "" && filename == "" {
  841. //List all the supported new filetype
  842. if !fileExists("system/newitem/") {
  843. os.MkdirAll("system/newitem/", 0755)
  844. }
  845. type newItemObject struct {
  846. Desc string
  847. Ext string
  848. }
  849. var newItemList []newItemObject
  850. newItemTemplate, _ := filepath.Glob("system/newitem/*")
  851. for _, file := range newItemTemplate {
  852. thisItem := new(newItemObject)
  853. thisItem.Desc = strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
  854. thisItem.Ext = filepath.Ext(file)[1:]
  855. newItemList = append(newItemList, *thisItem)
  856. }
  857. jsonString, err := json.Marshal(newItemList)
  858. if err != nil {
  859. log.Println("*File System* Unable to parse JSON string for new item list!")
  860. sendErrorResponse(w, "Unable to parse new item list. See server log for more information.")
  861. return
  862. }
  863. sendJSONResponse(w, string(jsonString))
  864. return
  865. } else if fileType != "" && filename != "" {
  866. if vsrc == "" {
  867. sendErrorResponse(w, "Missing paramter: 'src'")
  868. return
  869. }
  870. //Translate the path to realpath
  871. rpath, err := userinfo.VirtualPathToRealPath(vsrc)
  872. if err != nil {
  873. sendErrorResponse(w, "Invalid path given.")
  874. return
  875. }
  876. //Check if directory is readonly
  877. accmode := userinfo.GetPathAccessPermission(vsrc)
  878. if accmode == "readonly" {
  879. sendErrorResponse(w, "This directory is Read Only.")
  880. return
  881. } else if accmode == "denied" {
  882. sendErrorResponse(w, "Access Denied")
  883. return
  884. }
  885. //Check if the file already exists. If yes, fix its filename.
  886. newfilePath := filepath.ToSlash(filepath.Join(rpath, filename))
  887. if fileType == "file" {
  888. for fileExists(newfilePath) {
  889. sendErrorResponse(w, "Given filename already exists.")
  890. return
  891. }
  892. ext := filepath.Ext(filename)
  893. if ext == "" {
  894. //This is a file with no extension.
  895. f, err := os.Create(newfilePath)
  896. if err != nil {
  897. log.Println("*File System* " + err.Error())
  898. sendErrorResponse(w, err.Error())
  899. return
  900. }
  901. f.Close()
  902. } else {
  903. templateFile, _ := filepath.Glob("system/newitem/*" + ext)
  904. if len(templateFile) == 0 {
  905. //This file extension is not in template
  906. f, err := os.Create(newfilePath)
  907. if err != nil {
  908. log.Println("*File System* " + err.Error())
  909. sendErrorResponse(w, err.Error())
  910. return
  911. }
  912. f.Close()
  913. } else {
  914. //Copy file from templateFile[0] to current dir with the given name
  915. input, _ := ioutil.ReadFile(templateFile[0])
  916. err := ioutil.WriteFile(newfilePath, input, 0755)
  917. if err != nil {
  918. log.Println("*File System* " + err.Error())
  919. sendErrorResponse(w, err.Error())
  920. return
  921. }
  922. }
  923. }
  924. } else if fileType == "folder" {
  925. if fileExists(newfilePath) {
  926. sendErrorResponse(w, "Given folder already exists.")
  927. return
  928. }
  929. //Create the folder at target location
  930. err := os.Mkdir(newfilePath, 0755)
  931. if err != nil {
  932. sendErrorResponse(w, err.Error())
  933. return
  934. }
  935. }
  936. sendJSONResponse(w, "\"OK\"")
  937. } else {
  938. sendErrorResponse(w, "Missing paramter(s).")
  939. return
  940. }
  941. }
  942. /*
  943. Handle file operations via WebSocket
  944. This handler only handle zip, unzip, copy and move. Not other operations.
  945. For other operations, please use the legacy handleOpr endpoint
  946. */
  947. func system_fs_handleWebSocketOpr(w http.ResponseWriter, r *http.Request) {
  948. //Get and check user permission
  949. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  950. if err != nil {
  951. sendErrorResponse(w, "User not logged in")
  952. return
  953. }
  954. operation, _ := mv(r, "opr", false) //Accept copy and move
  955. vsrcFiles, _ := mv(r, "src", false)
  956. vdestFile, _ := mv(r, "dest", false)
  957. existsOpr, _ := mv(r, "existsresp", false)
  958. if existsOpr == "" {
  959. existsOpr = "keep"
  960. }
  961. //Decode the source file list
  962. var sourceFiles []string
  963. tmp := []string{}
  964. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  965. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  966. if err != nil {
  967. log.Println("Source file JSON parse error.", err.Error())
  968. sendErrorResponse(w, "Source file JSON parse error.")
  969. return
  970. }
  971. //Bugged char filtering
  972. for _, src := range sourceFiles {
  973. tmp = append(tmp, strings.ReplaceAll(src, "{{plug_sign}}", "+"))
  974. }
  975. sourceFiles = tmp
  976. vdestFile = strings.ReplaceAll(vdestFile, "{{plug_sign}}", "+")
  977. //Decode the target position
  978. escapedVdest, _ := url.QueryUnescape(vdestFile)
  979. vdestFile = escapedVdest
  980. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  981. //Permission checking
  982. if !userinfo.CanWrite(vdestFile) {
  983. log.Println(vdestFile)
  984. w.WriteHeader(http.StatusForbidden)
  985. w.Write([]byte("403 - Access Denied"))
  986. return
  987. }
  988. //Check if opr is suported
  989. if operation == "move" || operation == "copy" || operation == "zip" || operation == "unzip" {
  990. } else {
  991. log.Println("This file operation is not supported on WebSocket file operations endpoint. Please use the legacy endpoint instead. Received: ", operation)
  992. w.WriteHeader(http.StatusInternalServerError)
  993. w.Write([]byte("500 - Not supported operation"))
  994. return
  995. }
  996. //Upgrade to websocket
  997. var upgrader = websocket.Upgrader{}
  998. c, err := upgrader.Upgrade(w, r, nil)
  999. if err != nil {
  1000. w.WriteHeader(http.StatusInternalServerError)
  1001. w.Write([]byte("500 - " + err.Error()))
  1002. log.Print("Websocket Upgrade Error:", err.Error())
  1003. return
  1004. }
  1005. type ProgressUpdate struct {
  1006. LatestFile string
  1007. Progress int
  1008. Error string
  1009. }
  1010. if operation == "zip" {
  1011. //Zip files
  1012. outputFilename := filepath.Join(rdestFile, filepath.Base(rdestFile)) + ".zip"
  1013. if len(sourceFiles) == 1 {
  1014. //Use the basename of the source file as zip file name
  1015. outputFilename = filepath.Join(rdestFile, filepath.Base(sourceFiles[0])) + ".zip"
  1016. }
  1017. //Translate source Files into real paths
  1018. realSourceFiles := []string{}
  1019. for _, vsrcs := range sourceFiles {
  1020. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1021. if err != nil {
  1022. stopStatus := ProgressUpdate{
  1023. LatestFile: filepath.Base(rsrc),
  1024. Progress: -1,
  1025. Error: "File not exists",
  1026. }
  1027. js, _ := json.Marshal(stopStatus)
  1028. c.WriteMessage(1, js)
  1029. c.Close()
  1030. }
  1031. realSourceFiles = append(realSourceFiles, rsrc)
  1032. }
  1033. //Create the zip file
  1034. fs.ArozZipFileWithProgress(realSourceFiles, outputFilename, false, func(currentFilename string, _ int, _ int, progress float64) {
  1035. currentStatus := ProgressUpdate{
  1036. LatestFile: currentFilename,
  1037. Progress: int(math.Ceil(progress)),
  1038. Error: "",
  1039. }
  1040. js, _ := json.Marshal(currentStatus)
  1041. c.WriteMessage(1, js)
  1042. })
  1043. } else if operation == "unzip" {
  1044. //Check if the target destination exists and writable
  1045. if !userinfo.CanWrite(vdestFile) {
  1046. stopStatus := ProgressUpdate{
  1047. LatestFile: filepath.Base(vdestFile),
  1048. Progress: -1,
  1049. Error: "Access Denied: No Write Permission",
  1050. }
  1051. js, _ := json.Marshal(stopStatus)
  1052. c.WriteMessage(1, js)
  1053. c.Close()
  1054. }
  1055. //Create the destination folder
  1056. os.MkdirAll(rdestFile, 0755)
  1057. //Convert the src files into realpaths
  1058. realSourceFiles := []string{}
  1059. for _, vsrcs := range sourceFiles {
  1060. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1061. if err != nil {
  1062. stopStatus := ProgressUpdate{
  1063. LatestFile: filepath.Base(rsrc),
  1064. Progress: -1,
  1065. Error: "File not exists",
  1066. }
  1067. js, _ := json.Marshal(stopStatus)
  1068. c.WriteMessage(1, js)
  1069. c.Close()
  1070. }
  1071. realSourceFiles = append(realSourceFiles, rsrc)
  1072. }
  1073. //Unzip the files
  1074. fs.ArozUnzipFileWithProgress(realSourceFiles, rdestFile, func(currentFile string, filecount int, totalfile int, progress float64) {
  1075. //Generate the status update struct
  1076. currentStatus := ProgressUpdate{
  1077. LatestFile: filepath.Base(currentFile),
  1078. Progress: int(math.Ceil(progress)),
  1079. Error: "",
  1080. }
  1081. js, _ := json.Marshal(currentStatus)
  1082. c.WriteMessage(1, js)
  1083. })
  1084. } else {
  1085. //Other operations that allow multiple source files to handle one by one
  1086. for i := 0; i < len(sourceFiles); i++ {
  1087. vsrcFile := sourceFiles[i]
  1088. rsrcFile, _ := userinfo.VirtualPathToRealPath(vsrcFile)
  1089. //c.WriteMessage(1, message)
  1090. if !fileExists(rsrcFile) {
  1091. //This source file not exists. Report Error and Stop
  1092. stopStatus := ProgressUpdate{
  1093. LatestFile: filepath.Base(rsrcFile),
  1094. Progress: -1,
  1095. Error: "File not exists",
  1096. }
  1097. js, _ := json.Marshal(stopStatus)
  1098. c.WriteMessage(1, js)
  1099. c.Close()
  1100. return
  1101. }
  1102. if operation == "move" {
  1103. err := fs.FileMove(rsrcFile, rdestFile, existsOpr, false, func(progress int, currentFile string) {
  1104. //Multply child progress to parent progress
  1105. blockRatio := float64(100) / float64(len(sourceFiles))
  1106. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1107. //Construct return struct
  1108. currentStatus := ProgressUpdate{
  1109. LatestFile: filepath.Base(currentFile),
  1110. Progress: int(overallRatio),
  1111. Error: "",
  1112. }
  1113. js, _ := json.Marshal(currentStatus)
  1114. c.WriteMessage(1, js)
  1115. })
  1116. //Handle move starting error
  1117. if err != nil {
  1118. stopStatus := ProgressUpdate{
  1119. LatestFile: filepath.Base(rsrcFile),
  1120. Progress: -1,
  1121. Error: err.Error(),
  1122. }
  1123. js, _ := json.Marshal(stopStatus)
  1124. c.WriteMessage(1, js)
  1125. c.Close()
  1126. return
  1127. }
  1128. } else if operation == "copy" {
  1129. err := fs.FileCopy(rsrcFile, rdestFile, existsOpr, func(progress int, currentFile string) {
  1130. //Multply child progress to parent progress
  1131. blockRatio := float64(100) / float64(len(sourceFiles))
  1132. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1133. //Construct return struct
  1134. currentStatus := ProgressUpdate{
  1135. LatestFile: filepath.Base(currentFile),
  1136. Progress: int(overallRatio),
  1137. Error: "",
  1138. }
  1139. js, _ := json.Marshal(currentStatus)
  1140. c.WriteMessage(1, js)
  1141. })
  1142. //Handle Copy starting error
  1143. if err != nil {
  1144. stopStatus := ProgressUpdate{
  1145. LatestFile: filepath.Base(rsrcFile),
  1146. Progress: -1,
  1147. Error: err.Error(),
  1148. }
  1149. js, _ := json.Marshal(stopStatus)
  1150. c.WriteMessage(1, js)
  1151. c.Close()
  1152. return
  1153. }
  1154. }
  1155. }
  1156. }
  1157. //Close WebSocket connection after finished
  1158. time.Sleep(1 * time.Second)
  1159. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  1160. c.Close()
  1161. }
  1162. /*
  1163. Handle file operations
  1164. Support {move, copy, delete, recycle, rename}
  1165. */
  1166. //Handle file operations.
  1167. func system_fs_handleOpr(w http.ResponseWriter, r *http.Request) {
  1168. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1169. if err != nil {
  1170. sendErrorResponse(w, "User not logged in")
  1171. return
  1172. }
  1173. operation, _ := mv(r, "opr", true)
  1174. vsrcFiles, _ := mv(r, "src", true)
  1175. vdestFile, _ := mv(r, "dest", true)
  1176. vnfilenames, _ := mv(r, "new", true) //Only use when rename or create new file / folder
  1177. //Check if operation valid.
  1178. if operation == "" {
  1179. //Undefined operations.
  1180. sendErrorResponse(w, "Undefined operations paramter: Missing 'opr' in request header.")
  1181. return
  1182. }
  1183. //As the user can pass in multiple source files at the same time, parse sourceFiles from json string
  1184. var sourceFiles []string
  1185. //This line is required in order to allow passing of special charaters
  1186. decodedSourceFiles := system_fs_specialURIDecode(vsrcFiles)
  1187. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  1188. if err != nil {
  1189. sendErrorResponse(w, "Source file JSON parse error.")
  1190. return
  1191. }
  1192. //Check if new filenames are also valid. If yes, translate it into string array
  1193. var newFilenames []string
  1194. if vnfilenames != "" {
  1195. vnfilenames, _ := url.QueryUnescape(vnfilenames)
  1196. err = json.Unmarshal([]byte(vnfilenames), &newFilenames)
  1197. if err != nil {
  1198. sendErrorResponse(w, "Unable to parse JSON for new filenames")
  1199. return
  1200. }
  1201. }
  1202. if operation == "zip" {
  1203. //Zip operation. Parse the real filepath list
  1204. rsrcFiles := []string{}
  1205. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1206. for _, vsrcFile := range sourceFiles {
  1207. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1208. if fileExists(rsrcFile) {
  1209. rsrcFiles = append(rsrcFiles, rsrcFile)
  1210. }
  1211. }
  1212. zipFilename := rdestFile
  1213. if fs.IsDir(rdestFile) {
  1214. //Append the filename to it
  1215. if len(rsrcFiles) == 1 {
  1216. zipFilename = filepath.Join(rdestFile, strings.TrimSuffix(filepath.Base(rsrcFiles[0]), filepath.Ext(filepath.Base(rsrcFiles[0])))+".zip")
  1217. } else if len(rsrcFiles) > 1 {
  1218. zipFilename = filepath.Join(rdestFile, filepath.Base(filepath.Dir(rsrcFiles[0]))+".zip")
  1219. }
  1220. }
  1221. //Create a zip file at target location
  1222. err := fs.ArozZipFile(rsrcFiles, zipFilename, false)
  1223. if err != nil {
  1224. sendErrorResponse(w, err.Error())
  1225. return
  1226. }
  1227. } else {
  1228. //For operations that is handled file by file
  1229. for i, vsrcFile := range sourceFiles {
  1230. //Convert the virtual path to realpath on disk
  1231. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1232. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1233. //Check if the source file exists
  1234. if !fileExists(rsrcFile) {
  1235. /*
  1236. Special edge case handler:
  1237. There might be edge case that files are stored in URIEncoded methods
  1238. e.g. abc def.mp3 --> abc%20cdf.mp3
  1239. In this case, this logic statement should be able to handle this
  1240. */
  1241. edgeCaseFilename := filepath.Join(filepath.Dir(rsrcFile), system_fs_specialURIEncode(filepath.Base(rsrcFile)))
  1242. if fileExists(edgeCaseFilename) {
  1243. rsrcFile = edgeCaseFilename
  1244. } else {
  1245. sendErrorResponse(w, "Source file not exists.")
  1246. return
  1247. }
  1248. }
  1249. if operation == "rename" {
  1250. //Check if the usage is correct.
  1251. if vdestFile != "" {
  1252. sendErrorResponse(w, "Rename only accept 'src' and 'new'. Please use move if you want to move a file.")
  1253. return
  1254. }
  1255. //Check if new name paramter is passed in.
  1256. if len(newFilenames) == 0 {
  1257. sendErrorResponse(w, "Missing paramter (JSON string): 'new'")
  1258. return
  1259. }
  1260. //Check if the source filenames and new filenanmes match
  1261. if len(newFilenames) != len(sourceFiles) {
  1262. sendErrorResponse(w, "New filenames do not match with source filename's length.")
  1263. return
  1264. }
  1265. //Check if the target dir is not readonly
  1266. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1267. if accmode == "readonly" {
  1268. sendErrorResponse(w, "This directory is Read Only.")
  1269. return
  1270. } else if accmode == "denied" {
  1271. sendErrorResponse(w, "Access Denied")
  1272. return
  1273. }
  1274. thisFilename := newFilenames[i]
  1275. //Check if the name already exists. If yes, return false
  1276. if fileExists(filepath.Dir(rsrcFile) + "/" + thisFilename) {
  1277. sendErrorResponse(w, "File already exists")
  1278. return
  1279. }
  1280. //Everything is ok. Rename the file.
  1281. targetNewName := filepath.Dir(rsrcFile) + "/" + thisFilename
  1282. err = os.Rename(rsrcFile, targetNewName)
  1283. if err != nil {
  1284. sendErrorResponse(w, err.Error())
  1285. return
  1286. }
  1287. } else if operation == "move" {
  1288. //File move operation. Check if the source file / dir and target directory exists
  1289. /*
  1290. Example usage from file explorer
  1291. $.ajax({
  1292. type: 'POST',
  1293. url: `/system/file_system/fileOpr`,
  1294. data: {opr: "move" ,src: JSON.stringify(fileList), dest: targetDir},
  1295. success: function(data){
  1296. if (data.error !== undefined){
  1297. msgbox("remove",data.error);
  1298. }else{
  1299. //OK, do something
  1300. }
  1301. }
  1302. });
  1303. */
  1304. if !fileExists(rsrcFile) {
  1305. sendErrorResponse(w, "Source file not exists")
  1306. return
  1307. }
  1308. //Check if the source file is read only.
  1309. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1310. if accmode == "readonly" {
  1311. sendErrorResponse(w, "This source file is Read Only.")
  1312. return
  1313. } else if accmode == "denied" {
  1314. sendErrorResponse(w, "Access Denied")
  1315. return
  1316. }
  1317. if rdestFile == "" {
  1318. sendErrorResponse(w, "Undefined dest location.")
  1319. return
  1320. }
  1321. //Get exists overwrite mode
  1322. existsOpr, _ := mv(r, "existsresp", true)
  1323. //Check if use fast move instead
  1324. //Check if the source and destination folder are under the same root. If yes, use os.Rename for faster move operations
  1325. underSameRoot := false
  1326. //Check if the two files are under the same user root path
  1327. srcAbs, _ := filepath.Abs(rsrcFile)
  1328. destAbs, _ := filepath.Abs(rdestFile)
  1329. //Check other storage path and see if they are under the same root
  1330. for _, rootPath := range userinfo.GetAllFileSystemHandler() {
  1331. thisRoot := rootPath.Path
  1332. thisRootAbs, err := filepath.Abs(thisRoot)
  1333. if err != nil {
  1334. continue
  1335. }
  1336. if strings.Contains(srcAbs, thisRootAbs) && strings.Contains(destAbs, thisRootAbs) {
  1337. underSameRoot = true
  1338. }
  1339. }
  1340. //Updates 19-10-2020: Added ownership management to file move and copy
  1341. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1342. err = fs.FileMove(rsrcFile, rdestFile, existsOpr, underSameRoot, nil)
  1343. if err != nil {
  1344. sendErrorResponse(w, err.Error())
  1345. //Restore the ownership if remove failed
  1346. userinfo.SetOwnerOfFile(rsrcFile)
  1347. return
  1348. }
  1349. //Set user to own the new file
  1350. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1351. } else if operation == "copy" {
  1352. //Copy file. See move example and change 'opr' to 'copy'
  1353. if !fileExists(rsrcFile) {
  1354. sendErrorResponse(w, "Source file not exists")
  1355. return
  1356. }
  1357. //Check if the desintation is read only.
  1358. if !userinfo.CanWrite(vdestFile) {
  1359. sendErrorResponse(w, "Access Denied.")
  1360. return
  1361. }
  1362. if !fileExists(rdestFile) {
  1363. if fileExists(filepath.Dir(rdestFile)) {
  1364. //User pass in the whole path for the folder. Report error usecase.
  1365. sendErrorResponse(w, "Dest location should be an existing folder instead of the full path of the copied file.")
  1366. return
  1367. }
  1368. sendErrorResponse(w, "Dest folder not found")
  1369. return
  1370. }
  1371. existsOpr, _ := mv(r, "existsresp", true)
  1372. //Check if the user have space for the extra file
  1373. if !userinfo.StorageQuota.HaveSpace(fs.GetFileSize(rdestFile)) {
  1374. sendErrorResponse(w, "Storage Quota Full")
  1375. return
  1376. }
  1377. err = fs.FileCopy(rsrcFile, rdestFile, existsOpr, nil)
  1378. if err != nil {
  1379. sendErrorResponse(w, err.Error())
  1380. return
  1381. }
  1382. //Set user to own this file
  1383. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1384. } else if operation == "delete" {
  1385. //Delete the file permanently
  1386. if !fileExists(rsrcFile) {
  1387. //Check if it is a non escapted file instead
  1388. sendErrorResponse(w, "Source file not exists")
  1389. return
  1390. }
  1391. //Check if the desintation is read only.
  1392. /*
  1393. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1394. if accmode == "readonly" {
  1395. sendErrorResponse(w, "This directory is Read Only.")
  1396. return
  1397. } else if accmode == "denied" {
  1398. sendErrorResponse(w, "Access Denied")
  1399. return
  1400. }
  1401. */
  1402. if !userinfo.CanWrite(vsrcFile) {
  1403. sendErrorResponse(w, "Access Denied.")
  1404. return
  1405. }
  1406. //Check if the user own this file
  1407. isOwner := userinfo.IsOwnerOfFile(rsrcFile)
  1408. if isOwner {
  1409. //This user own this system. Remove this file from his quota
  1410. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1411. }
  1412. //Check if this file has any cached files. If yes, remove it
  1413. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1414. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1415. }
  1416. //Clear the cache folder if there is no files inside
  1417. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1418. if len(fc) == 0 {
  1419. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1420. }
  1421. os.RemoveAll(rsrcFile)
  1422. } else if operation == "recycle" {
  1423. //Put it into a subfolder named trash and allow it to to be removed later
  1424. if !fileExists(rsrcFile) {
  1425. //Check if it is a non escapted file instead
  1426. sendErrorResponse(w, "Source file not exists")
  1427. return
  1428. }
  1429. //Check if the upload target is read only.
  1430. //Updates 20 Jan 2021: Replace with CanWrite handler
  1431. /*
  1432. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1433. if accmode == "readonly" {
  1434. sendErrorResponse(w, "This directory is Read Only.")
  1435. return
  1436. } else if accmode == "denied" {
  1437. sendErrorResponse(w, "Access Denied")
  1438. return
  1439. }*/
  1440. if !userinfo.CanWrite(vsrcFile) {
  1441. sendErrorResponse(w, "Access Denied.")
  1442. return
  1443. }
  1444. //Check if this file has any cached files. If yes, remove it
  1445. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1446. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1447. }
  1448. //Clear the cache folder if there is no files inside
  1449. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1450. if len(fc) == 0 {
  1451. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1452. }
  1453. //Create a trash directory for this folder
  1454. trashDir := filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.trash/"
  1455. os.MkdirAll(trashDir, 0755)
  1456. hidden.HideFile(trashDir)
  1457. os.Rename(rsrcFile, trashDir+filepath.Base(rsrcFile)+"."+Int64ToString(GetUnixTime()))
  1458. } else if operation == "unzip" {
  1459. //Unzip the file to destination
  1460. //Check if the user can write to the target dest file
  1461. if userinfo.CanWrite(string(vdestFile)) == false {
  1462. sendErrorResponse(w, "Access Denied.")
  1463. return
  1464. }
  1465. //Make the rdest directory if not exists
  1466. if !fileExists(rdestFile) {
  1467. err = os.MkdirAll(rdestFile, 0755)
  1468. if err != nil {
  1469. sendErrorResponse(w, err.Error())
  1470. return
  1471. }
  1472. }
  1473. //OK! Unzip to destination
  1474. err := fs.Unzip(rsrcFile, rdestFile)
  1475. if err != nil {
  1476. sendErrorResponse(w, err.Error())
  1477. return
  1478. }
  1479. } else {
  1480. sendErrorResponse(w, "Unknown file opeartion given.")
  1481. return
  1482. }
  1483. }
  1484. }
  1485. sendJSONResponse(w, "\"OK\"")
  1486. return
  1487. }
  1488. //Allow systems to store key value pairs in the database as preferences.
  1489. func system_fs_handleUserPreference(w http.ResponseWriter, r *http.Request) {
  1490. username, err := authAgent.GetUserName(w, r)
  1491. if err != nil {
  1492. sendErrorResponse(w, "User not logged in")
  1493. return
  1494. }
  1495. key, _ := mv(r, "key", false)
  1496. value, _ := mv(r, "value", false)
  1497. remove, _ := mv(r, "remove", false)
  1498. if key != "" && value == "" && remove == "" {
  1499. //Get mode. Read the prefernece with given key
  1500. result := ""
  1501. err := sysdb.Read("fs", "pref/"+key+"/"+username, &result)
  1502. if err != nil {
  1503. sendJSONResponse(w, "{\"error\":\"Key not found.\"}")
  1504. return
  1505. }
  1506. sendTextResponse(w, result)
  1507. } else if key != "" && value == "" && remove == "true" {
  1508. //Remove mode. Delete this key from sysdb
  1509. err := sysdb.Delete("fs", "pref/"+key+"/"+username)
  1510. if err != nil {
  1511. sendErrorResponse(w, err.Error())
  1512. }
  1513. sendOK(w)
  1514. } else if key != "" && value != "" {
  1515. //Set mode. Set the preference with given key
  1516. if len(value) > 1024 {
  1517. //Size too big. Reject storage
  1518. sendErrorResponse(w, "Preference value too long. Preference value can only store maximum 1024 characters.")
  1519. return
  1520. }
  1521. sysdb.Write("fs", "pref/"+key+"/"+username, value)
  1522. sendOK(w)
  1523. }
  1524. }
  1525. func system_fs_removeUserPreferences(username string) {
  1526. entries, err := sysdb.ListTable("fs")
  1527. if err != nil {
  1528. return
  1529. }
  1530. for _, keypairs := range entries {
  1531. if strings.Contains(string(keypairs[0]), "pref/") && strings.Contains(string(keypairs[0]), "/"+username) {
  1532. //Remove this preference
  1533. sysdb.Delete("fs", string(keypairs[0]))
  1534. }
  1535. }
  1536. }
  1537. func system_fs_listDrives(w http.ResponseWriter, r *http.Request) {
  1538. if authAgent.CheckAuth(r) == false {
  1539. sendErrorResponse(w, "User not logged in")
  1540. return
  1541. }
  1542. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1543. type driveInfo struct {
  1544. Drivepath string
  1545. DriveFreeSpace uint64
  1546. DriveTotalSpace uint64
  1547. DriveAvailSpace uint64
  1548. }
  1549. var drives []driveInfo
  1550. if runtime.GOOS == "windows" {
  1551. //Under windows
  1552. for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
  1553. f, err := os.Open(string(drive) + ":\\")
  1554. if err == nil {
  1555. thisdrive := new(driveInfo)
  1556. thisdrive.Drivepath = string(drive) + ":\\"
  1557. free, total, avail := storage.GetDriveCapacity(string(drive) + ":\\")
  1558. thisdrive.DriveFreeSpace = free
  1559. thisdrive.DriveTotalSpace = total
  1560. thisdrive.DriveAvailSpace = avail
  1561. drives = append(drives, *thisdrive)
  1562. f.Close()
  1563. }
  1564. }
  1565. } else {
  1566. //Under linux environment
  1567. //Append all the virtual directories root as root instead
  1568. storageDevices := []string{}
  1569. for _, fshandler := range userinfo.GetAllFileSystemHandler() {
  1570. storageDevices = append(storageDevices, fshandler.Path)
  1571. }
  1572. //List all storage information of each devices
  1573. for _, dev := range storageDevices {
  1574. thisdrive := new(driveInfo)
  1575. thisdrive.Drivepath = filepath.Base(dev)
  1576. free, total, avail := storage.GetDriveCapacity(string(dev))
  1577. thisdrive.DriveFreeSpace = free
  1578. thisdrive.DriveTotalSpace = total
  1579. thisdrive.DriveAvailSpace = avail
  1580. drives = append(drives, *thisdrive)
  1581. }
  1582. }
  1583. jsonString, _ := json.Marshal(drives)
  1584. sendJSONResponse(w, string(jsonString))
  1585. }
  1586. func system_fs_listRoot(w http.ResponseWriter, r *http.Request) {
  1587. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1588. if err != nil {
  1589. sendErrorResponse(w, err.Error())
  1590. return
  1591. }
  1592. username := userinfo.Username
  1593. userRoot, _ := mv(r, "user", false)
  1594. if userRoot == "true" {
  1595. type fileObject struct {
  1596. Filename string
  1597. Filepath string
  1598. IsDir bool
  1599. }
  1600. //List the root media folders under user:/
  1601. filesInUserRoot := []fileObject{}
  1602. filesInRoot, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(*root_directory)) + "/users/" + username + "/*")
  1603. for _, file := range filesInRoot {
  1604. thisFile := new(fileObject)
  1605. thisFile.Filename = filepath.Base(file)
  1606. thisFile.Filepath, _ = userinfo.RealPathToVirtualPath(file)
  1607. thisFile.IsDir = IsDir(file)
  1608. filesInUserRoot = append(filesInUserRoot, *thisFile)
  1609. }
  1610. jsonString, _ := json.Marshal(filesInUserRoot)
  1611. sendJSONResponse(w, string(jsonString))
  1612. } else {
  1613. type rootObject struct {
  1614. RootName string
  1615. RootPath string
  1616. }
  1617. var roots []rootObject
  1618. for _, store := range userinfo.GetAllFileSystemHandler() {
  1619. var thisDevice = new(rootObject)
  1620. thisDevice.RootName = store.Name
  1621. thisDevice.RootPath = store.UUID + ":/"
  1622. roots = append(roots, *thisDevice)
  1623. }
  1624. jsonString, _ := json.Marshal(roots)
  1625. sendJSONResponse(w, string(jsonString))
  1626. }
  1627. }
  1628. /*
  1629. Special Glob for handling path with [ or ] inside.
  1630. You can also pass in normal path for globing if you are not sure.
  1631. */
  1632. func system_fs_specialGlob(path string) ([]string, error) {
  1633. files, err := filepath.Glob(path)
  1634. if err != nil {
  1635. return []string{}, err
  1636. }
  1637. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  1638. if len(files) == 0 {
  1639. //Handle reverse check. Replace all [ and ] with *
  1640. newSearchPath := strings.ReplaceAll(path, "[", "?")
  1641. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  1642. //Scan with all the similar structure except [ and ]
  1643. tmpFilelist, _ := filepath.Glob(newSearchPath)
  1644. for _, file := range tmpFilelist {
  1645. file = filepath.ToSlash(file)
  1646. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  1647. files = append(files, file)
  1648. }
  1649. }
  1650. }
  1651. }
  1652. //Convert all filepaths to slash
  1653. for i := 0; i < len(files); i++ {
  1654. files[i] = filepath.ToSlash(files[i])
  1655. }
  1656. return files, nil
  1657. }
  1658. func system_fs_specialURIDecode(inputPath string) string {
  1659. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  1660. inputPath, _ = url.QueryUnescape(inputPath)
  1661. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  1662. return inputPath
  1663. }
  1664. func system_fs_specialURIEncode(inputPath string) string {
  1665. inputPath = strings.ReplaceAll(inputPath, " ", "{{space_sign}}")
  1666. inputPath, _ = url.QueryUnescape(inputPath)
  1667. inputPath = strings.ReplaceAll(inputPath, "{{space_sign}}", "%20")
  1668. return inputPath
  1669. }
  1670. func system_fs_matchFileExt(inputFilename string, extArray []string) bool {
  1671. inputExt := filepath.Ext(inputFilename)
  1672. if stringInSlice(inputExt, extArray) {
  1673. return true
  1674. }
  1675. return false
  1676. }
  1677. //Handle file properties request
  1678. func system_fs_getFileProperties(w http.ResponseWriter, r *http.Request) {
  1679. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1680. if err != nil {
  1681. sendErrorResponse(w, err.Error())
  1682. return
  1683. }
  1684. vpath, err := mv(r, "path", true)
  1685. if err != nil {
  1686. sendErrorResponse(w, "path not defined")
  1687. return
  1688. }
  1689. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1690. if err != nil {
  1691. sendErrorResponse(w, err.Error())
  1692. return
  1693. }
  1694. fileStat, err := os.Stat(rpath)
  1695. if err != nil {
  1696. sendErrorResponse(w, err.Error())
  1697. return
  1698. }
  1699. type fileProperties struct {
  1700. VirtualPath string
  1701. StoragePath string
  1702. Basename string
  1703. VirtualDirname string
  1704. StorageDirname string
  1705. Ext string
  1706. MimeType string
  1707. Filesize int64
  1708. Permission string
  1709. LastModTime string
  1710. LastModUnix int64
  1711. IsDirectory bool
  1712. Owner string
  1713. }
  1714. mime := "text/directory"
  1715. if !fileStat.IsDir() {
  1716. m, _, err := fs.GetMime(rpath)
  1717. if err != nil {
  1718. mime = ""
  1719. }
  1720. mime = m
  1721. }
  1722. filesize := fileStat.Size()
  1723. //Get file overall size if this is folder
  1724. if fileStat.IsDir() {
  1725. var size int64
  1726. filepath.Walk(rpath, func(_ string, info os.FileInfo, err error) error {
  1727. if err != nil {
  1728. return err
  1729. }
  1730. if !info.IsDir() {
  1731. size += info.Size()
  1732. }
  1733. return err
  1734. })
  1735. filesize = size
  1736. }
  1737. //Get file owner
  1738. owner := userinfo.GetFileOwner(rpath)
  1739. if owner == "" {
  1740. owner = "Unknown"
  1741. }
  1742. result := fileProperties{
  1743. VirtualPath: vpath,
  1744. StoragePath: filepath.Clean(rpath),
  1745. Basename: filepath.Base(rpath),
  1746. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1747. StorageDirname: filepath.ToSlash(filepath.Dir(rpath)),
  1748. Ext: filepath.Ext(rpath),
  1749. MimeType: mime,
  1750. Filesize: filesize,
  1751. Permission: fileStat.Mode().Perm().String(),
  1752. LastModTime: timeToString(fileStat.ModTime()),
  1753. LastModUnix: fileStat.ModTime().Unix(),
  1754. IsDirectory: fileStat.IsDir(),
  1755. Owner: owner,
  1756. }
  1757. jsonString, _ := json.Marshal(result)
  1758. sendJSONResponse(w, string(jsonString))
  1759. }
  1760. /*
  1761. List directory in the given path
  1762. Usage: Pass in dir like the following examples:
  1763. AOR:/Desktop <= Open /user/{username}/Desktop
  1764. S1:/ <= Open {uuid=S1}/
  1765. */
  1766. func system_fs_handleList(w http.ResponseWriter, r *http.Request) {
  1767. currentDir, _ := mv(r, "dir", true)
  1768. //Commented this line to handle dirname that contains "+" sign
  1769. //currentDir, _ = url.QueryUnescape(currentDir)
  1770. sortMode, _ := mv(r, "sort", true)
  1771. showHidden, _ := mv(r, "showHidden", true)
  1772. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1773. if err != nil {
  1774. //user not logged in. Redirect to login page.
  1775. sendErrorResponse(w, "User not logged in")
  1776. return
  1777. }
  1778. if currentDir == "" {
  1779. sendErrorResponse(w, "Invalid dir given.")
  1780. return
  1781. }
  1782. //Pad a slash at the end of currentDir if not exists
  1783. if currentDir[len(currentDir)-1:] != "/" {
  1784. currentDir = currentDir + "/"
  1785. }
  1786. //Convert the virutal path to realpath
  1787. realpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1788. if err != nil {
  1789. sendErrorResponse(w, "Error. Unable to parse path. "+err.Error())
  1790. return
  1791. }
  1792. if !fileExists(realpath) {
  1793. userRoot, _ := userinfo.VirtualPathToRealPath("user:/")
  1794. if filepath.Clean(realpath) == filepath.Clean(userRoot) {
  1795. //Initiate user folder (Initiaed in user object)
  1796. userinfo.GetHomeDirectory()
  1797. } else {
  1798. //Folder not exists
  1799. sendJSONResponse(w, "{\"error\":\"Folder not exists\"}")
  1800. return
  1801. }
  1802. }
  1803. if sortMode == "" {
  1804. sortMode = "default"
  1805. }
  1806. //Check for really special exception in where the path contains [ or ] which cannot be handled via Golang Glob function
  1807. files, _ := system_fs_specialGlob(filepath.Clean(realpath) + "/*")
  1808. var parsedFilelist []fs.FileData
  1809. for _, v := range files {
  1810. if showHidden != "true" && filepath.Base(v)[:1] == "." {
  1811. //Skipping hidden files
  1812. continue
  1813. }
  1814. rawsize := fs.GetFileSize(v)
  1815. modtime, _ := fs.GetModTime(v)
  1816. thisFile := fs.FileData{
  1817. Filename: filepath.Base(v),
  1818. Filepath: currentDir + filepath.Base(v),
  1819. Realpath: v,
  1820. IsDir: IsDir(v),
  1821. Filesize: rawsize,
  1822. Displaysize: fs.GetFileDisplaySize(rawsize, 2),
  1823. ModTime: modtime,
  1824. IsShared: shareManager.FileIsShared(v),
  1825. }
  1826. parsedFilelist = append(parsedFilelist, thisFile)
  1827. }
  1828. //Sort the filelist
  1829. if sortMode == "default" {
  1830. //Sort by name, convert filename to window sorting methods
  1831. sort.Slice(parsedFilelist, func(i, j int) bool {
  1832. return strings.ToLower(parsedFilelist[i].Filename) < strings.ToLower(parsedFilelist[j].Filename)
  1833. })
  1834. } else if sortMode == "reverse" {
  1835. //Sort by reverse name
  1836. sort.Slice(parsedFilelist, func(i, j int) bool {
  1837. return strings.ToLower(parsedFilelist[i].Filename) > strings.ToLower(parsedFilelist[j].Filename)
  1838. })
  1839. } else if sortMode == "smallToLarge" {
  1840. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize < parsedFilelist[j].Filesize })
  1841. } else if sortMode == "largeToSmall" {
  1842. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize > parsedFilelist[j].Filesize })
  1843. } else if sortMode == "mostRecent" {
  1844. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime > parsedFilelist[j].ModTime })
  1845. } else if sortMode == "leastRecent" {
  1846. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime < parsedFilelist[j].ModTime })
  1847. }
  1848. jsonString, _ := json.Marshal(parsedFilelist)
  1849. sendJSONResponse(w, string(jsonString))
  1850. }
  1851. //Handle getting a hash from a given contents in the given path
  1852. func system_fs_handleDirHash(w http.ResponseWriter, r *http.Request) {
  1853. currentDir, err := mv(r, "dir", true)
  1854. if err != nil {
  1855. sendErrorResponse(w, "Invalid dir given")
  1856. return
  1857. }
  1858. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1859. if err != nil {
  1860. sendErrorResponse(w, "User not logged in")
  1861. return
  1862. }
  1863. rpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1864. if err != nil {
  1865. sendErrorResponse(w, "Invalid dir given")
  1866. return
  1867. }
  1868. //Get a list of files in this directory
  1869. currentDir = filepath.ToSlash(filepath.Clean(rpath)) + "/"
  1870. filesInDir, err := system_fs_specialGlob(currentDir + "*")
  1871. if err != nil {
  1872. sendErrorResponse(w, err.Error())
  1873. return
  1874. }
  1875. filenames := []string{}
  1876. for _, file := range filesInDir {
  1877. if len(filepath.Base(file)) > 0 && string([]rune(filepath.Base(file))[0]) != "." {
  1878. //Ignore hidden files
  1879. filenames = append(filenames, filepath.Base(file))
  1880. }
  1881. }
  1882. sort.Strings(filenames)
  1883. //Build a hash base on the filelist
  1884. h := sha256.New()
  1885. h.Write([]byte(strings.Join(filenames, ",")))
  1886. sendTextResponse(w, hex.EncodeToString((h.Sum(nil))))
  1887. }
  1888. /*
  1889. File zipping and unzipping functions
  1890. */
  1891. //Handle all zip related API
  1892. func system_fs_zipHandler(w http.ResponseWriter, r *http.Request) {
  1893. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1894. if err != nil {
  1895. sendErrorResponse(w, err.Error())
  1896. return
  1897. }
  1898. opr, err := mv(r, "opr", true)
  1899. if err != nil {
  1900. sendErrorResponse(w, "Invalid opr or opr not defined")
  1901. return
  1902. }
  1903. vsrc, _ := mv(r, "src", true)
  1904. if vsrc == "" {
  1905. sendErrorResponse(w, "Invalid src paramter")
  1906. return
  1907. }
  1908. vdest, _ := mv(r, "dest", true)
  1909. rdest := ""
  1910. //Convert source path from JSON string to object
  1911. virtualSourcePaths := []string{}
  1912. err = json.Unmarshal([]byte(vsrc), &virtualSourcePaths)
  1913. if err != nil {
  1914. sendErrorResponse(w, err.Error())
  1915. return
  1916. }
  1917. //Check each of the path
  1918. realSourcePaths := []string{}
  1919. for _, vpath := range virtualSourcePaths {
  1920. thisrpath, err := userinfo.VirtualPathToRealPath(vpath)
  1921. if err != nil || !fileExists(thisrpath) {
  1922. sendErrorResponse(w, "File not exists: "+vpath)
  1923. return
  1924. }
  1925. realSourcePaths = append(realSourcePaths, thisrpath)
  1926. }
  1927. ///Convert dest to real if given
  1928. if vdest != "" {
  1929. realdest, _ := userinfo.VirtualPathToRealPath(vdest)
  1930. rdest = realdest
  1931. }
  1932. //This function will be deprecate soon in ArozOS 1.120
  1933. log.Println("*DEPRECATE* zipHandler will be deprecating soon! Please use fileOpr endpoint")
  1934. if opr == "zip" {
  1935. //Check if destination location exists
  1936. if rdest == "" || !fileExists(filepath.Dir(rdest)) {
  1937. sendErrorResponse(w, "Invalid dest location")
  1938. return
  1939. }
  1940. //OK. Create the zip at the desired location
  1941. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1942. if err != nil {
  1943. sendErrorResponse(w, err.Error())
  1944. return
  1945. }
  1946. sendOK(w)
  1947. } else if opr == "tmpzip" {
  1948. //Zip to tmp folder
  1949. userTmpFolder, _ := userinfo.VirtualPathToRealPath("tmp:/")
  1950. filename := Int64ToString(GetUnixTime()) + ".zip"
  1951. rdest := filepath.ToSlash(filepath.Clean(userTmpFolder)) + "/" + filename
  1952. log.Println(realSourcePaths, rdest)
  1953. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1954. if err != nil {
  1955. sendErrorResponse(w, err.Error())
  1956. return
  1957. }
  1958. //Send the tmp filename to the user
  1959. sendTextResponse(w, "tmp:/"+filename)
  1960. } else if opr == "inspect" {
  1961. } else if opr == "unzip" {
  1962. }
  1963. }
  1964. //Translate path from and to virtual and realpath
  1965. func system_fs_handlePathTranslate(w http.ResponseWriter, r *http.Request) {
  1966. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1967. if err != nil {
  1968. sendErrorResponse(w, err.Error())
  1969. return
  1970. }
  1971. path, err := mv(r, "path", false)
  1972. if err != nil {
  1973. sendErrorResponse(w, "Invalid path given")
  1974. return
  1975. }
  1976. rpath, err := userinfo.VirtualPathToRealPath(path)
  1977. if err != nil {
  1978. //Try to convert it to virtualPath
  1979. vpath, err := userinfo.RealPathToVirtualPath(path)
  1980. if err != nil {
  1981. sendErrorResponse(w, "Unknown path given")
  1982. } else {
  1983. jsonstring, _ := json.Marshal(vpath)
  1984. sendJSONResponse(w, string(jsonstring))
  1985. }
  1986. } else {
  1987. abrpath, _ := filepath.Abs(rpath)
  1988. jsonstring, _ := json.Marshal([]string{rpath, filepath.ToSlash(abrpath)})
  1989. sendJSONResponse(w, string(jsonstring))
  1990. }
  1991. }
  1992. //Handle cache rendering with websocket pipeline
  1993. func system_fs_handleCacheRender(w http.ResponseWriter, r *http.Request) {
  1994. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1995. vpath, err := mv(r, "folder", false)
  1996. if err != nil {
  1997. sendErrorResponse(w, "Invalid folder paramter")
  1998. return
  1999. }
  2000. //Convert vpath to realpath
  2001. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2002. if err != nil {
  2003. sendErrorResponse(w, err.Error())
  2004. return
  2005. }
  2006. //Perform cache rendering
  2007. thumbRenderHandler.HandleLoadCache(w, r, rpath)
  2008. }
  2009. //Handle file thumbnail caching
  2010. func system_fs_handleFolderCache(w http.ResponseWriter, r *http.Request) {
  2011. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2012. vfolderpath, err := mv(r, "folder", false)
  2013. if err != nil {
  2014. sendErrorResponse(w, "folder not defined")
  2015. return
  2016. }
  2017. rpath, err := userinfo.VirtualPathToRealPath(vfolderpath)
  2018. if err != nil {
  2019. sendErrorResponse(w, err.Error())
  2020. return
  2021. }
  2022. thumbRenderHandler.BuildCacheForFolder(rpath)
  2023. sendOK(w)
  2024. }
  2025. //Handle setting and loading of file permission on Linux
  2026. func system_fs_handleFilePermission(w http.ResponseWriter, r *http.Request) {
  2027. file, err := mv(r, "file", true)
  2028. if err != nil {
  2029. sendErrorResponse(w, "Invalid file")
  2030. return
  2031. }
  2032. //Translate the file to real path
  2033. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2034. if err != nil {
  2035. sendErrorResponse(w, "User not logged in")
  2036. return
  2037. }
  2038. rpath, err := userinfo.VirtualPathToRealPath(file)
  2039. if err != nil {
  2040. sendErrorResponse(w, err.Error())
  2041. return
  2042. }
  2043. newMode, _ := mv(r, "mode", true)
  2044. if newMode == "" {
  2045. //Read the file mode
  2046. //Check if the file exists
  2047. if !fileExists(rpath) {
  2048. sendErrorResponse(w, "File not exists!")
  2049. return
  2050. }
  2051. //Read the file permission
  2052. filePermission, err := fsp.GetFilePermissions(rpath)
  2053. if err != nil {
  2054. sendErrorResponse(w, err.Error())
  2055. return
  2056. }
  2057. //Send the file permission to client
  2058. js, _ := json.Marshal(filePermission)
  2059. sendJSONResponse(w, string(js))
  2060. } else {
  2061. //Set the file mode
  2062. //Check if the file exists
  2063. if !fileExists(rpath) {
  2064. sendErrorResponse(w, "File not exists!")
  2065. return
  2066. }
  2067. //Check if windows. If yes, ignore this request
  2068. if runtime.GOOS == "windows" {
  2069. sendErrorResponse(w, "Windows host not supported")
  2070. return
  2071. }
  2072. //Check if this user has permission to change the file permission
  2073. //Aka user must be 1. This is his own folder or 2. Admin
  2074. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(file)
  2075. if fsh.Hierarchy == "user" {
  2076. //Always ok as this is owned by the user
  2077. } else if fsh.Hierarchy == "public" {
  2078. //Require admin
  2079. if userinfo.IsAdmin() == false {
  2080. sendErrorResponse(w, "Permission Denied")
  2081. return
  2082. }
  2083. } else {
  2084. //Not implemeneted. Require admin
  2085. if userinfo.IsAdmin() == false {
  2086. sendErrorResponse(w, "Permission Denied")
  2087. return
  2088. }
  2089. }
  2090. //Be noted that if the system is not running in sudo mode,
  2091. //File permission change might not works.
  2092. err := fsp.SetFilePermisson(rpath, newMode)
  2093. if err != nil {
  2094. sendErrorResponse(w, err.Error())
  2095. return
  2096. } else {
  2097. sendOK(w)
  2098. }
  2099. }
  2100. }
  2101. //Check if the given filepath is and must inside the given directory path.
  2102. //You can pass both as relative
  2103. func system_fs_checkFileInDirectory(filesourcepath string, directory string) bool {
  2104. filepathAbs, err := filepath.Abs(filesourcepath)
  2105. if err != nil {
  2106. return false
  2107. }
  2108. directoryAbs, err := filepath.Abs(directory)
  2109. if err != nil {
  2110. return false
  2111. }
  2112. //Check if the filepathabs contain directoryAbs
  2113. if strings.Contains(filepathAbs, directoryAbs) {
  2114. return true
  2115. } else {
  2116. return false
  2117. }
  2118. }
  2119. //Clear the old files inside the tmp file
  2120. func system_fs_clearOldTmpFiles() {
  2121. filesToBeDelete := []string{}
  2122. tmpAbs, _ := filepath.Abs(*tmp_directory)
  2123. filepath.Walk(*tmp_directory, func(path string, info os.FileInfo, err error) error {
  2124. if filepath.Base(path) != "aofs.db" && filepath.Base(path) != "aofs.db.lock" {
  2125. //Check if root folders. Do not delete root folders
  2126. parentAbs, _ := filepath.Abs(filepath.Dir(path))
  2127. if tmpAbs == parentAbs {
  2128. //Root folder. Do not remove
  2129. return nil
  2130. }
  2131. //Get its modification time
  2132. modTime, err := fs.GetModTime(path)
  2133. if err != nil {
  2134. return nil
  2135. }
  2136. //Check if mod time is more than 24 hours ago
  2137. if time.Now().Unix()-modTime > int64(*maxTempFileKeepTime) {
  2138. //Delete OK
  2139. filesToBeDelete = append(filesToBeDelete, path)
  2140. }
  2141. }
  2142. return nil
  2143. })
  2144. //Remove all files from the delete list
  2145. for _, fileToBeDelete := range filesToBeDelete {
  2146. os.RemoveAll(fileToBeDelete)
  2147. }
  2148. }