file_system.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497
  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. //Use *upload_buf per 1GB rules for upload
  455. usableMemorySpace := totalRam - usedRam - systemReservedUploadMem
  456. autoCalculatedUploadBuf := int64((float64(usableMemorySpace) / float64(1024*1024*1024)) * float64(*upload_buf))
  457. //Add the reserve to global reserve memory value
  458. systemReservedUploadMem += autoCalculatedUploadBuf
  459. //Handle file upload
  460. log.Println("*Testing* Upload buffer set to ", autoCalculatedUploadBuf, "MB")
  461. err = r.ParseMultipartForm(int64(autoCalculatedUploadBuf) << 20)
  462. } else {
  463. //Unable to get RAM usage. Use default parser buffer size
  464. err = r.ParseMultipartForm(int64(*upload_buf) << 20)
  465. }
  466. if err != nil {
  467. //Filesize too big
  468. log.Println(err)
  469. sendErrorResponse(w, "File too large")
  470. return
  471. }
  472. file, handler, err := r.FormFile("file")
  473. if err != nil {
  474. log.Println("Error Retrieving File from upload by user: " + username)
  475. sendErrorResponse(w, "Unable to parse file from upload")
  476. return
  477. }
  478. //Get upload target directory
  479. uploadTarget, _ := mv(r, "path", true)
  480. if uploadTarget == "" {
  481. sendErrorResponse(w, "Upload target cannot be empty.")
  482. return
  483. }
  484. //Translate the upload target directory
  485. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  486. if err != nil {
  487. sendErrorResponse(w, "Upload target is invalid or permission denied.")
  488. return
  489. }
  490. storeFilename := handler.Filename //Filename of the uploaded file
  491. destFilepath := filepath.ToSlash(filepath.Clean(realUploadPath)) + "/" + storeFilename
  492. if !fileExists(filepath.Dir(destFilepath)) {
  493. os.MkdirAll(filepath.Dir(destFilepath), 0755)
  494. }
  495. //Check if the upload target is read only.
  496. accmode := userinfo.GetPathAccessPermission(uploadTarget)
  497. if accmode == "readonly" {
  498. sendErrorResponse(w, "The upload target is Read Only.")
  499. return
  500. } else if accmode == "denied" {
  501. sendErrorResponse(w, "Access Denied")
  502. return
  503. }
  504. //Check for storage quota
  505. uploadFileSize := handler.Size
  506. if !userinfo.StorageQuota.HaveSpace(uploadFileSize) {
  507. sendErrorResponse(w, "Storage Quota Full")
  508. return
  509. }
  510. //Prepare the file to be created (uploaded)
  511. destination, err := os.Create(destFilepath)
  512. if err != nil {
  513. sendErrorResponse(w, err.Error())
  514. return
  515. }
  516. defer destination.Close()
  517. defer file.Close()
  518. //Move the file to destination file location
  519. if *enable_asyncFileUpload {
  520. //Use Async upload method
  521. go func(r *http.Request, file multipart.File, destination *os.File, userinfo *user.User) {
  522. //Do the file copying using a buffered reader
  523. buf := make([]byte, *file_opr_buff)
  524. for {
  525. n, err := file.Read(buf)
  526. if err != nil && err != io.EOF {
  527. log.Println(err.Error())
  528. return
  529. }
  530. if n == 0 {
  531. break
  532. }
  533. if _, err := destination.Write(buf[:n]); err != nil {
  534. log.Println(err.Error())
  535. return
  536. }
  537. }
  538. //Clear up buffered files
  539. r.MultipartForm.RemoveAll()
  540. //Set the ownership of file
  541. userinfo.SetOwnerOfFile(destFilepath)
  542. //Perform a GC afterward
  543. runtime.GC()
  544. //Deduce the buffered memory
  545. systemReservedUploadMem -= autoCalculatedUploadBuf
  546. }(r, file, destination, userinfo)
  547. } else {
  548. //Use blocking upload and move method
  549. buf := make([]byte, *file_opr_buff)
  550. for {
  551. n, err := file.Read(buf)
  552. if err != nil && err != io.EOF {
  553. log.Println(err.Error())
  554. return
  555. }
  556. if n == 0 {
  557. break
  558. }
  559. if _, err := destination.Write(buf[:n]); err != nil {
  560. log.Println(err.Error())
  561. return
  562. }
  563. }
  564. //Clear up buffered files
  565. r.MultipartForm.RemoveAll()
  566. //Set the ownership of file
  567. userinfo.SetOwnerOfFile(destFilepath)
  568. }
  569. //Finish up the upload
  570. //fmt.Printf("Uploaded File: %+v\n", handler.Filename)
  571. //fmt.Printf("File Size: %+v\n", handler.Size)
  572. //fmt.Printf("MIME Header: %+v\n", handler.Header)
  573. //fmt.Println("Upload target: " + realUploadPath)
  574. //Fnish upload. Fix the tmp filename
  575. log.Println(username + " uploaded a file: " + handler.Filename)
  576. //Do upload finishing stuff
  577. //Perform a GC
  578. runtime.GC()
  579. //Deduce the buffered memory
  580. systemReservedUploadMem -= autoCalculatedUploadBuf
  581. //Completed
  582. sendOK(w)
  583. return
  584. }
  585. //Validate if the copy and target process will involve file overwriting problem.
  586. func system_fs_validateFileOpr(w http.ResponseWriter, r *http.Request) {
  587. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  588. if err != nil {
  589. sendErrorResponse(w, err.Error())
  590. return
  591. }
  592. vsrcFiles, _ := mv(r, "src", true)
  593. vdestFile, _ := mv(r, "dest", true)
  594. var duplicateFiles []string
  595. //Loop through all files are see if there are duplication during copy and paste
  596. sourceFiles := []string{}
  597. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  598. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  599. if err != nil {
  600. sendErrorResponse(w, "Source file JSON parse error.")
  601. return
  602. }
  603. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  604. for _, file := range sourceFiles {
  605. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(file))
  606. if fileExists(rdestFile + filepath.Base(rsrcFile)) {
  607. //File exists already.
  608. vpath, _ := userinfo.RealPathToVirtualPath(rsrcFile)
  609. duplicateFiles = append(duplicateFiles, vpath)
  610. }
  611. }
  612. jsonString, _ := json.Marshal(duplicateFiles)
  613. sendJSONResponse(w, string(jsonString))
  614. return
  615. }
  616. //Scan all directory and get trash file and send back results with WebSocket
  617. func system_fs_WebSocketScanTrashBin(w http.ResponseWriter, r *http.Request) {
  618. //Get and check user permission
  619. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  620. if err != nil {
  621. sendErrorResponse(w, "User not logged in")
  622. return
  623. }
  624. //Upgrade to websocket
  625. var upgrader = websocket.Upgrader{}
  626. c, err := upgrader.Upgrade(w, r, nil)
  627. if err != nil {
  628. w.WriteHeader(http.StatusInternalServerError)
  629. w.Write([]byte("500 - " + err.Error()))
  630. log.Print("Websocket Upgrade Error:", err.Error())
  631. return
  632. }
  633. //Start Scanning
  634. scanningRoots := []string{}
  635. //Get all roots to scan
  636. for _, storage := range userinfo.GetAllFileSystemHandler() {
  637. storageRoot := storage.Path
  638. scanningRoots = append(scanningRoots, storageRoot)
  639. }
  640. for _, rootPath := range scanningRoots {
  641. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  642. oneLevelUpper := filepath.Base(filepath.Dir(path))
  643. if oneLevelUpper == ".trash" {
  644. //This is a trashbin dir.
  645. file := path
  646. //Parse the trashFile struct
  647. timestamp := filepath.Ext(file)[1:]
  648. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  649. originalExt := filepath.Ext(filepath.Base(originalName))
  650. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  651. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  652. rawsize := fs.GetFileSize(file)
  653. timestampInt64, _ := StringToInt64(timestamp)
  654. removeTimeDate := time.Unix(timestampInt64, 0)
  655. if IsDir(file) {
  656. originalExt = ""
  657. }
  658. thisTrashFileObject := trashedFile{
  659. Filename: filepath.Base(file),
  660. Filepath: virtualFilepath,
  661. FileExt: originalExt,
  662. IsDir: IsDir(file),
  663. Filesize: int64(rawsize),
  664. RemoveTimestamp: timestampInt64,
  665. RemoveDate: timeToString(removeTimeDate),
  666. OriginalPath: virtualOrgPath,
  667. OriginalFilename: originalName,
  668. }
  669. //Send out the result as JSON string
  670. js, _ := json.Marshal(thisTrashFileObject)
  671. err := c.WriteMessage(1, js)
  672. if err != nil {
  673. //Connection already closed
  674. return err
  675. }
  676. }
  677. return nil
  678. })
  679. if err != nil {
  680. //Scan or client connection error (Connection closed?)
  681. return
  682. }
  683. }
  684. //Close connection after finished
  685. c.Close()
  686. }
  687. //Scan all the directory and get trash files within the system
  688. func system_fs_scanTrashBin(w http.ResponseWriter, r *http.Request) {
  689. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  690. if err != nil {
  691. sendErrorResponse(w, err.Error())
  692. return
  693. }
  694. username := userinfo.Username
  695. results := []trashedFile{}
  696. files, err := system_fs_listTrash(username)
  697. if err != nil {
  698. sendErrorResponse(w, err.Error())
  699. return
  700. }
  701. //Get information of each files and process it into results
  702. for _, file := range files {
  703. timestamp := filepath.Ext(file)[1:]
  704. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  705. originalExt := filepath.Ext(filepath.Base(originalName))
  706. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  707. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  708. rawsize := fs.GetFileSize(file)
  709. timestampInt64, _ := StringToInt64(timestamp)
  710. removeTimeDate := time.Unix(timestampInt64, 0)
  711. if IsDir(file) {
  712. originalExt = ""
  713. }
  714. results = append(results, trashedFile{
  715. Filename: filepath.Base(file),
  716. Filepath: virtualFilepath,
  717. FileExt: originalExt,
  718. IsDir: IsDir(file),
  719. Filesize: int64(rawsize),
  720. RemoveTimestamp: timestampInt64,
  721. RemoveDate: timeToString(removeTimeDate),
  722. OriginalPath: virtualOrgPath,
  723. OriginalFilename: originalName,
  724. })
  725. }
  726. //Sort the results by date, latest on top
  727. sort.Slice(results[:], func(i, j int) bool {
  728. return results[i].RemoveTimestamp > results[j].RemoveTimestamp
  729. })
  730. //Format and return the json results
  731. jsonString, _ := json.Marshal(results)
  732. sendJSONResponse(w, string(jsonString))
  733. }
  734. //Restore a trashed file to its parent dir
  735. func system_fs_restoreFile(w http.ResponseWriter, r *http.Request) {
  736. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  737. if err != nil {
  738. sendErrorResponse(w, err.Error())
  739. return
  740. }
  741. targetTrashedFile, err := mv(r, "src", true)
  742. if err != nil {
  743. sendErrorResponse(w, "Invalid src given")
  744. return
  745. }
  746. //Translate it to realpath
  747. realpath, _ := userinfo.VirtualPathToRealPath(targetTrashedFile)
  748. if !fileExists(realpath) {
  749. sendErrorResponse(w, "File not exists")
  750. return
  751. }
  752. //Check if this is really a trashed file
  753. if filepath.Base(filepath.Dir(realpath)) != ".trash" {
  754. sendErrorResponse(w, "File not in trashbin")
  755. return
  756. }
  757. //OK to proceed.
  758. targetPath := filepath.ToSlash(filepath.Dir(filepath.Dir(realpath))) + "/" + strings.TrimSuffix(filepath.Base(realpath), filepath.Ext(filepath.Base(realpath)))
  759. //log.Println(targetPath);
  760. os.Rename(realpath, targetPath)
  761. //Check if the parent dir has no more fileds. If yes, remove it
  762. filescounter, _ := filepath.Glob(filepath.Dir(realpath) + "/*")
  763. if len(filescounter) == 0 {
  764. os.Remove(filepath.Dir(realpath))
  765. }
  766. sendOK(w)
  767. }
  768. //Clear all trashed file in the system
  769. func system_fs_clearTrashBin(w http.ResponseWriter, r *http.Request) {
  770. u, err := userHandler.GetUserInfoFromRequest(w, r)
  771. if err != nil {
  772. sendErrorResponse(w, "User not logged in")
  773. return
  774. }
  775. username := u.Username
  776. fileList, err := system_fs_listTrash(username)
  777. if err != nil {
  778. sendErrorResponse(w, "Unable to clear trash: "+err.Error())
  779. return
  780. }
  781. //Get list success. Remove each of them.
  782. for _, file := range fileList {
  783. isOwner := u.IsOwnerOfFile(file)
  784. if isOwner {
  785. //This user own this system. Remove this file from his quota
  786. u.RemoveOwnershipFromFile(file)
  787. }
  788. os.RemoveAll(file)
  789. //Check if its parent directory have no files. If yes, remove the dir itself as well.
  790. filesInThisTrashBin, _ := filepath.Glob(filepath.Dir(file) + "/*")
  791. if len(filesInThisTrashBin) == 0 {
  792. os.Remove(filepath.Dir(file))
  793. }
  794. }
  795. sendOK(w)
  796. }
  797. //Get all trash in a string list
  798. func system_fs_listTrash(username string) ([]string, error) {
  799. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  800. scanningRoots := []string{}
  801. //Get all roots to scan
  802. for _, storage := range userinfo.GetAllFileSystemHandler() {
  803. storageRoot := storage.Path
  804. scanningRoots = append(scanningRoots, storageRoot)
  805. }
  806. files := []string{}
  807. for _, rootPath := range scanningRoots {
  808. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  809. oneLevelUpper := filepath.Base(filepath.Dir(path))
  810. if oneLevelUpper == ".trash" {
  811. //This is a trashbin dir.
  812. files = append(files, path)
  813. }
  814. return nil
  815. })
  816. if err != nil {
  817. return []string{}, errors.New("Failed to scan file system.")
  818. }
  819. }
  820. return files, nil
  821. }
  822. /*
  823. Handle new file or folder functions
  824. Required information
  825. @type {folder / file}
  826. @ext {any that is listed in the template folder}
  827. if no paramter is passed in, default listing all the supported template file
  828. */
  829. func system_fs_handleNewObjects(w http.ResponseWriter, r *http.Request) {
  830. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  831. if err != nil {
  832. sendErrorResponse(w, "User not logged in")
  833. return
  834. }
  835. fileType, _ := mv(r, "type", true) //File creation type, {file, folder}
  836. vsrc, _ := mv(r, "src", true) //Virtual file source folder, do not include filename
  837. filename, _ := mv(r, "filename", true) //Filename for the new file
  838. if fileType == "" && filename == "" {
  839. //List all the supported new filetype
  840. if !fileExists("system/newitem/") {
  841. os.MkdirAll("system/newitem/", 0755)
  842. }
  843. type newItemObject struct {
  844. Desc string
  845. Ext string
  846. }
  847. var newItemList []newItemObject
  848. newItemTemplate, _ := filepath.Glob("system/newitem/*")
  849. for _, file := range newItemTemplate {
  850. thisItem := new(newItemObject)
  851. thisItem.Desc = strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
  852. thisItem.Ext = filepath.Ext(file)[1:]
  853. newItemList = append(newItemList, *thisItem)
  854. }
  855. jsonString, err := json.Marshal(newItemList)
  856. if err != nil {
  857. log.Println("*File System* Unable to parse JSON string for new item list!")
  858. sendErrorResponse(w, "Unable to parse new item list. See server log for more information.")
  859. return
  860. }
  861. sendJSONResponse(w, string(jsonString))
  862. return
  863. } else if fileType != "" && filename != "" {
  864. if vsrc == "" {
  865. sendErrorResponse(w, "Missing paramter: 'src'")
  866. return
  867. }
  868. //Translate the path to realpath
  869. rpath, err := userinfo.VirtualPathToRealPath(vsrc)
  870. if err != nil {
  871. sendErrorResponse(w, "Invalid path given.")
  872. return
  873. }
  874. //Check if directory is readonly
  875. accmode := userinfo.GetPathAccessPermission(vsrc)
  876. if accmode == "readonly" {
  877. sendErrorResponse(w, "This directory is Read Only.")
  878. return
  879. } else if accmode == "denied" {
  880. sendErrorResponse(w, "Access Denied")
  881. return
  882. }
  883. //Check if the file already exists. If yes, fix its filename.
  884. newfilePath := filepath.ToSlash(filepath.Join(rpath, filename))
  885. if fileType == "file" {
  886. for fileExists(newfilePath) {
  887. sendErrorResponse(w, "Given filename already exists.")
  888. return
  889. }
  890. ext := filepath.Ext(filename)
  891. if ext == "" {
  892. //This is a file with no extension.
  893. f, err := os.Create(newfilePath)
  894. if err != nil {
  895. log.Println("*File System* " + err.Error())
  896. sendErrorResponse(w, err.Error())
  897. return
  898. }
  899. f.Close()
  900. } else {
  901. templateFile, _ := filepath.Glob("system/newitem/*" + ext)
  902. if len(templateFile) == 0 {
  903. //This file extension is not in template
  904. f, err := os.Create(newfilePath)
  905. if err != nil {
  906. log.Println("*File System* " + err.Error())
  907. sendErrorResponse(w, err.Error())
  908. return
  909. }
  910. f.Close()
  911. } else {
  912. //Copy file from templateFile[0] to current dir with the given name
  913. input, _ := ioutil.ReadFile(templateFile[0])
  914. err := ioutil.WriteFile(newfilePath, input, 0755)
  915. if err != nil {
  916. log.Println("*File System* " + err.Error())
  917. sendErrorResponse(w, err.Error())
  918. return
  919. }
  920. }
  921. }
  922. } else if fileType == "folder" {
  923. if fileExists(newfilePath) {
  924. sendErrorResponse(w, "Given folder already exists.")
  925. return
  926. }
  927. //Create the folder at target location
  928. err := os.Mkdir(newfilePath, 0755)
  929. if err != nil {
  930. sendErrorResponse(w, err.Error())
  931. return
  932. }
  933. }
  934. sendJSONResponse(w, "\"OK\"")
  935. } else {
  936. sendErrorResponse(w, "Missing paramter(s).")
  937. return
  938. }
  939. }
  940. /*
  941. Handle file operations via WebSocket
  942. This handler only handle zip, unzip, copy and move. Not other operations.
  943. For other operations, please use the legacy handleOpr endpoint
  944. */
  945. func system_fs_handleWebSocketOpr(w http.ResponseWriter, r *http.Request) {
  946. //Get and check user permission
  947. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  948. if err != nil {
  949. sendErrorResponse(w, "User not logged in")
  950. return
  951. }
  952. operation, _ := mv(r, "opr", false) //Accept copy and move
  953. vsrcFiles, _ := mv(r, "src", false)
  954. vdestFile, _ := mv(r, "dest", false)
  955. existsOpr, _ := mv(r, "existsresp", false)
  956. if existsOpr == "" {
  957. existsOpr = "keep"
  958. }
  959. //Decode the source file list
  960. var sourceFiles []string
  961. tmp := []string{}
  962. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  963. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  964. if err != nil {
  965. log.Println("Source file JSON parse error.", err.Error())
  966. sendErrorResponse(w, "Source file JSON parse error.")
  967. return
  968. }
  969. //Bugged char filtering
  970. for _, src := range sourceFiles {
  971. tmp = append(tmp, strings.ReplaceAll(src, "{{plug_sign}}", "+"))
  972. }
  973. sourceFiles = tmp
  974. vdestFile = strings.ReplaceAll(vdestFile, "{{plug_sign}}", "+")
  975. //Decode the target position
  976. escapedVdest, _ := url.QueryUnescape(vdestFile)
  977. vdestFile = escapedVdest
  978. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  979. //Permission checking
  980. if !userinfo.CanWrite(vdestFile) {
  981. log.Println(vdestFile)
  982. w.WriteHeader(http.StatusForbidden)
  983. w.Write([]byte("403 - Access Denied"))
  984. return
  985. }
  986. //Check if opr is suported
  987. if operation == "move" || operation == "copy" || operation == "zip" || operation == "unzip" {
  988. } else {
  989. log.Println("This file operation is not supported on WebSocket file operations endpoint. Please use the legacy endpoint instead. Received: ", operation)
  990. w.WriteHeader(http.StatusInternalServerError)
  991. w.Write([]byte("500 - Not supported operation"))
  992. return
  993. }
  994. //Upgrade to websocket
  995. var upgrader = websocket.Upgrader{}
  996. c, err := upgrader.Upgrade(w, r, nil)
  997. if err != nil {
  998. w.WriteHeader(http.StatusInternalServerError)
  999. w.Write([]byte("500 - " + err.Error()))
  1000. log.Print("Websocket Upgrade Error:", err.Error())
  1001. return
  1002. }
  1003. type ProgressUpdate struct {
  1004. LatestFile string
  1005. Progress int
  1006. Error string
  1007. }
  1008. if operation == "zip" {
  1009. //Zip files
  1010. outputFilename := filepath.Join(rdestFile, filepath.Base(rdestFile)) + ".zip"
  1011. if len(sourceFiles) == 1 {
  1012. //Use the basename of the source file as zip file name
  1013. outputFilename = filepath.Join(rdestFile, filepath.Base(sourceFiles[0])) + ".zip"
  1014. }
  1015. //Translate source Files into real paths
  1016. realSourceFiles := []string{}
  1017. for _, vsrcs := range sourceFiles {
  1018. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1019. if err != nil {
  1020. stopStatus := ProgressUpdate{
  1021. LatestFile: filepath.Base(rsrc),
  1022. Progress: -1,
  1023. Error: "File not exists",
  1024. }
  1025. js, _ := json.Marshal(stopStatus)
  1026. c.WriteMessage(1, js)
  1027. c.Close()
  1028. }
  1029. realSourceFiles = append(realSourceFiles, rsrc)
  1030. }
  1031. //Create the zip file
  1032. fs.ArozZipFileWithProgress(realSourceFiles, outputFilename, false, func(currentFilename string, _ int, _ int, progress float64) {
  1033. currentStatus := ProgressUpdate{
  1034. LatestFile: currentFilename,
  1035. Progress: int(math.Ceil(progress)),
  1036. Error: "",
  1037. }
  1038. js, _ := json.Marshal(currentStatus)
  1039. c.WriteMessage(1, js)
  1040. })
  1041. } else if operation == "unzip" {
  1042. //Check if the target destination exists and writable
  1043. if !userinfo.CanWrite(vdestFile) {
  1044. stopStatus := ProgressUpdate{
  1045. LatestFile: filepath.Base(vdestFile),
  1046. Progress: -1,
  1047. Error: "Access Denied: No Write Permission",
  1048. }
  1049. js, _ := json.Marshal(stopStatus)
  1050. c.WriteMessage(1, js)
  1051. c.Close()
  1052. }
  1053. //Create the destination folder
  1054. os.MkdirAll(rdestFile, 0755)
  1055. //Convert the src files into realpaths
  1056. realSourceFiles := []string{}
  1057. for _, vsrcs := range sourceFiles {
  1058. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1059. if err != nil {
  1060. stopStatus := ProgressUpdate{
  1061. LatestFile: filepath.Base(rsrc),
  1062. Progress: -1,
  1063. Error: "File not exists",
  1064. }
  1065. js, _ := json.Marshal(stopStatus)
  1066. c.WriteMessage(1, js)
  1067. c.Close()
  1068. }
  1069. realSourceFiles = append(realSourceFiles, rsrc)
  1070. }
  1071. //Unzip the files
  1072. fs.ArozUnzipFileWithProgress(realSourceFiles, rdestFile, func(currentFile string, filecount int, totalfile int, progress float64) {
  1073. //Generate the status update struct
  1074. currentStatus := ProgressUpdate{
  1075. LatestFile: filepath.Base(currentFile),
  1076. Progress: int(math.Ceil(progress)),
  1077. Error: "",
  1078. }
  1079. js, _ := json.Marshal(currentStatus)
  1080. c.WriteMessage(1, js)
  1081. })
  1082. } else {
  1083. //Other operations that allow multiple source files to handle one by one
  1084. for i := 0; i < len(sourceFiles); i++ {
  1085. vsrcFile := sourceFiles[i]
  1086. rsrcFile, _ := userinfo.VirtualPathToRealPath(vsrcFile)
  1087. //c.WriteMessage(1, message)
  1088. if !fileExists(rsrcFile) {
  1089. //This source file not exists. Report Error and Stop
  1090. stopStatus := ProgressUpdate{
  1091. LatestFile: filepath.Base(rsrcFile),
  1092. Progress: -1,
  1093. Error: "File not exists",
  1094. }
  1095. js, _ := json.Marshal(stopStatus)
  1096. c.WriteMessage(1, js)
  1097. c.Close()
  1098. return
  1099. }
  1100. if operation == "move" {
  1101. err := fs.FileMove(rsrcFile, rdestFile, existsOpr, false, func(progress int, currentFile string) {
  1102. //Multply child progress to parent progress
  1103. blockRatio := float64(100) / float64(len(sourceFiles))
  1104. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1105. //Construct return struct
  1106. currentStatus := ProgressUpdate{
  1107. LatestFile: filepath.Base(currentFile),
  1108. Progress: int(overallRatio),
  1109. Error: "",
  1110. }
  1111. js, _ := json.Marshal(currentStatus)
  1112. c.WriteMessage(1, js)
  1113. })
  1114. //Handle move starting error
  1115. if err != nil {
  1116. stopStatus := ProgressUpdate{
  1117. LatestFile: filepath.Base(rsrcFile),
  1118. Progress: -1,
  1119. Error: err.Error(),
  1120. }
  1121. js, _ := json.Marshal(stopStatus)
  1122. c.WriteMessage(1, js)
  1123. c.Close()
  1124. return
  1125. }
  1126. } else if operation == "copy" {
  1127. err := fs.FileCopy(rsrcFile, rdestFile, existsOpr, func(progress int, currentFile string) {
  1128. //Multply child progress to parent progress
  1129. blockRatio := float64(100) / float64(len(sourceFiles))
  1130. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1131. //Construct return struct
  1132. currentStatus := ProgressUpdate{
  1133. LatestFile: filepath.Base(currentFile),
  1134. Progress: int(overallRatio),
  1135. Error: "",
  1136. }
  1137. js, _ := json.Marshal(currentStatus)
  1138. c.WriteMessage(1, js)
  1139. })
  1140. //Handle Copy starting error
  1141. if err != nil {
  1142. stopStatus := ProgressUpdate{
  1143. LatestFile: filepath.Base(rsrcFile),
  1144. Progress: -1,
  1145. Error: err.Error(),
  1146. }
  1147. js, _ := json.Marshal(stopStatus)
  1148. c.WriteMessage(1, js)
  1149. c.Close()
  1150. return
  1151. }
  1152. }
  1153. }
  1154. }
  1155. //Close WebSocket connection after finished
  1156. time.Sleep(1 * time.Second)
  1157. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  1158. c.Close()
  1159. }
  1160. /*
  1161. Handle file operations
  1162. Support {move, copy, delete, recycle, rename}
  1163. */
  1164. //Handle file operations.
  1165. func system_fs_handleOpr(w http.ResponseWriter, r *http.Request) {
  1166. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1167. if err != nil {
  1168. sendErrorResponse(w, "User not logged in")
  1169. return
  1170. }
  1171. operation, _ := mv(r, "opr", true)
  1172. vsrcFiles, _ := mv(r, "src", true)
  1173. vdestFile, _ := mv(r, "dest", true)
  1174. vnfilenames, _ := mv(r, "new", true) //Only use when rename or create new file / folder
  1175. //Check if operation valid.
  1176. if operation == "" {
  1177. //Undefined operations.
  1178. sendErrorResponse(w, "Undefined operations paramter: Missing 'opr' in request header.")
  1179. return
  1180. }
  1181. //As the user can pass in multiple source files at the same time, parse sourceFiles from json string
  1182. var sourceFiles []string
  1183. //This line is required in order to allow passing of special charaters
  1184. decodedSourceFiles := system_fs_specialURIDecode(vsrcFiles)
  1185. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  1186. if err != nil {
  1187. sendErrorResponse(w, "Source file JSON parse error.")
  1188. return
  1189. }
  1190. //Check if new filenames are also valid. If yes, translate it into string array
  1191. var newFilenames []string
  1192. if vnfilenames != "" {
  1193. vnfilenames, _ := url.QueryUnescape(vnfilenames)
  1194. err = json.Unmarshal([]byte(vnfilenames), &newFilenames)
  1195. if err != nil {
  1196. sendErrorResponse(w, "Unable to parse JSON for new filenames")
  1197. return
  1198. }
  1199. }
  1200. if operation == "zip" {
  1201. //Zip operation. Parse the real filepath list
  1202. rsrcFiles := []string{}
  1203. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1204. for _, vsrcFile := range sourceFiles {
  1205. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1206. if fileExists(rsrcFile) {
  1207. rsrcFiles = append(rsrcFiles, rsrcFile)
  1208. }
  1209. }
  1210. zipFilename := rdestFile
  1211. if fs.IsDir(rdestFile) {
  1212. //Append the filename to it
  1213. if len(rsrcFiles) == 1 {
  1214. zipFilename = filepath.Join(rdestFile, strings.TrimSuffix(filepath.Base(rsrcFiles[0]), filepath.Ext(filepath.Base(rsrcFiles[0])))+".zip")
  1215. } else if len(rsrcFiles) > 1 {
  1216. zipFilename = filepath.Join(rdestFile, filepath.Base(filepath.Dir(rsrcFiles[0]))+".zip")
  1217. }
  1218. }
  1219. //Create a zip file at target location
  1220. err := fs.ArozZipFile(rsrcFiles, zipFilename, false)
  1221. if err != nil {
  1222. sendErrorResponse(w, err.Error())
  1223. return
  1224. }
  1225. } else {
  1226. //For operations that is handled file by file
  1227. for i, vsrcFile := range sourceFiles {
  1228. //Convert the virtual path to realpath on disk
  1229. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1230. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1231. //Check if the source file exists
  1232. if !fileExists(rsrcFile) {
  1233. /*
  1234. Special edge case handler:
  1235. There might be edge case that files are stored in URIEncoded methods
  1236. e.g. abc def.mp3 --> abc%20cdf.mp3
  1237. In this case, this logic statement should be able to handle this
  1238. */
  1239. edgeCaseFilename := filepath.Join(filepath.Dir(rsrcFile), system_fs_specialURIEncode(filepath.Base(rsrcFile)))
  1240. if fileExists(edgeCaseFilename) {
  1241. rsrcFile = edgeCaseFilename
  1242. } else {
  1243. sendErrorResponse(w, "Source file not exists.")
  1244. return
  1245. }
  1246. }
  1247. if operation == "rename" {
  1248. //Check if the usage is correct.
  1249. if vdestFile != "" {
  1250. sendErrorResponse(w, "Rename only accept 'src' and 'new'. Please use move if you want to move a file.")
  1251. return
  1252. }
  1253. //Check if new name paramter is passed in.
  1254. if len(newFilenames) == 0 {
  1255. sendErrorResponse(w, "Missing paramter (JSON string): 'new'")
  1256. return
  1257. }
  1258. //Check if the source filenames and new filenanmes match
  1259. if len(newFilenames) != len(sourceFiles) {
  1260. sendErrorResponse(w, "New filenames do not match with source filename's length.")
  1261. return
  1262. }
  1263. //Check if the target dir is not readonly
  1264. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1265. if accmode == "readonly" {
  1266. sendErrorResponse(w, "This directory is Read Only.")
  1267. return
  1268. } else if accmode == "denied" {
  1269. sendErrorResponse(w, "Access Denied")
  1270. return
  1271. }
  1272. thisFilename := newFilenames[i]
  1273. //Check if the name already exists. If yes, return false
  1274. if fileExists(filepath.Dir(rsrcFile) + "/" + thisFilename) {
  1275. sendErrorResponse(w, "File already exists")
  1276. return
  1277. }
  1278. //Everything is ok. Rename the file.
  1279. targetNewName := filepath.Dir(rsrcFile) + "/" + thisFilename
  1280. err = os.Rename(rsrcFile, targetNewName)
  1281. if err != nil {
  1282. sendErrorResponse(w, err.Error())
  1283. return
  1284. }
  1285. } else if operation == "move" {
  1286. //File move operation. Check if the source file / dir and target directory exists
  1287. /*
  1288. Example usage from file explorer
  1289. $.ajax({
  1290. type: 'POST',
  1291. url: `/system/file_system/fileOpr`,
  1292. data: {opr: "move" ,src: JSON.stringify(fileList), dest: targetDir},
  1293. success: function(data){
  1294. if (data.error !== undefined){
  1295. msgbox("remove",data.error);
  1296. }else{
  1297. //OK, do something
  1298. }
  1299. }
  1300. });
  1301. */
  1302. if !fileExists(rsrcFile) {
  1303. sendErrorResponse(w, "Source file not exists")
  1304. return
  1305. }
  1306. //Check if the source file is read only.
  1307. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1308. if accmode == "readonly" {
  1309. sendErrorResponse(w, "This source file is Read Only.")
  1310. return
  1311. } else if accmode == "denied" {
  1312. sendErrorResponse(w, "Access Denied")
  1313. return
  1314. }
  1315. if rdestFile == "" {
  1316. sendErrorResponse(w, "Undefined dest location.")
  1317. return
  1318. }
  1319. //Get exists overwrite mode
  1320. existsOpr, _ := mv(r, "existsresp", true)
  1321. //Check if use fast move instead
  1322. //Check if the source and destination folder are under the same root. If yes, use os.Rename for faster move operations
  1323. underSameRoot := false
  1324. //Check if the two files are under the same user root path
  1325. srcAbs, _ := filepath.Abs(rsrcFile)
  1326. destAbs, _ := filepath.Abs(rdestFile)
  1327. //Check other storage path and see if they are under the same root
  1328. for _, rootPath := range userinfo.GetAllFileSystemHandler() {
  1329. thisRoot := rootPath.Path
  1330. thisRootAbs, err := filepath.Abs(thisRoot)
  1331. if err != nil {
  1332. continue
  1333. }
  1334. if strings.Contains(srcAbs, thisRootAbs) && strings.Contains(destAbs, thisRootAbs) {
  1335. underSameRoot = true
  1336. }
  1337. }
  1338. //Updates 19-10-2020: Added ownership management to file move and copy
  1339. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1340. err = fs.FileMove(rsrcFile, rdestFile, existsOpr, underSameRoot, nil)
  1341. if err != nil {
  1342. sendErrorResponse(w, err.Error())
  1343. //Restore the ownership if remove failed
  1344. userinfo.SetOwnerOfFile(rsrcFile)
  1345. return
  1346. }
  1347. //Set user to own the new file
  1348. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1349. } else if operation == "copy" {
  1350. //Copy file. See move example and change 'opr' to 'copy'
  1351. if !fileExists(rsrcFile) {
  1352. sendErrorResponse(w, "Source file not exists")
  1353. return
  1354. }
  1355. //Check if the desintation is read only.
  1356. if !userinfo.CanWrite(vdestFile) {
  1357. sendErrorResponse(w, "Access Denied.")
  1358. return
  1359. }
  1360. if !fileExists(rdestFile) {
  1361. if fileExists(filepath.Dir(rdestFile)) {
  1362. //User pass in the whole path for the folder. Report error usecase.
  1363. sendErrorResponse(w, "Dest location should be an existing folder instead of the full path of the copied file.")
  1364. return
  1365. }
  1366. sendErrorResponse(w, "Dest folder not found")
  1367. return
  1368. }
  1369. existsOpr, _ := mv(r, "existsresp", true)
  1370. //Check if the user have space for the extra file
  1371. if !userinfo.StorageQuota.HaveSpace(fs.GetFileSize(rdestFile)) {
  1372. sendErrorResponse(w, "Storage Quota Full")
  1373. return
  1374. }
  1375. err = fs.FileCopy(rsrcFile, rdestFile, existsOpr, nil)
  1376. if err != nil {
  1377. sendErrorResponse(w, err.Error())
  1378. return
  1379. }
  1380. //Set user to own this file
  1381. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1382. } else if operation == "delete" {
  1383. //Delete the file permanently
  1384. if !fileExists(rsrcFile) {
  1385. //Check if it is a non escapted file instead
  1386. sendErrorResponse(w, "Source file not exists")
  1387. return
  1388. }
  1389. //Check if the desintation is read only.
  1390. /*
  1391. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1392. if accmode == "readonly" {
  1393. sendErrorResponse(w, "This directory is Read Only.")
  1394. return
  1395. } else if accmode == "denied" {
  1396. sendErrorResponse(w, "Access Denied")
  1397. return
  1398. }
  1399. */
  1400. if !userinfo.CanWrite(vsrcFile) {
  1401. sendErrorResponse(w, "Access Denied.")
  1402. return
  1403. }
  1404. //Check if the user own this file
  1405. isOwner := userinfo.IsOwnerOfFile(rsrcFile)
  1406. if isOwner {
  1407. //This user own this system. Remove this file from his quota
  1408. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1409. }
  1410. //Check if this file has any cached files. If yes, remove it
  1411. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1412. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1413. }
  1414. //Clear the cache folder if there is no files inside
  1415. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1416. if len(fc) == 0 {
  1417. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1418. }
  1419. os.RemoveAll(rsrcFile)
  1420. } else if operation == "recycle" {
  1421. //Put it into a subfolder named trash and allow it to to be removed later
  1422. if !fileExists(rsrcFile) {
  1423. //Check if it is a non escapted file instead
  1424. sendErrorResponse(w, "Source file not exists")
  1425. return
  1426. }
  1427. //Check if the upload target is read only.
  1428. //Updates 20 Jan 2021: Replace with CanWrite handler
  1429. /*
  1430. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1431. if accmode == "readonly" {
  1432. sendErrorResponse(w, "This directory is Read Only.")
  1433. return
  1434. } else if accmode == "denied" {
  1435. sendErrorResponse(w, "Access Denied")
  1436. return
  1437. }*/
  1438. if !userinfo.CanWrite(vsrcFile) {
  1439. sendErrorResponse(w, "Access Denied.")
  1440. return
  1441. }
  1442. //Check if this file has any cached files. If yes, remove it
  1443. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1444. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1445. }
  1446. //Clear the cache folder if there is no files inside
  1447. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1448. if len(fc) == 0 {
  1449. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1450. }
  1451. //Create a trash directory for this folder
  1452. trashDir := filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.trash/"
  1453. os.MkdirAll(trashDir, 0755)
  1454. hidden.HideFile(trashDir)
  1455. os.Rename(rsrcFile, trashDir+filepath.Base(rsrcFile)+"."+Int64ToString(GetUnixTime()))
  1456. } else if operation == "unzip" {
  1457. //Unzip the file to destination
  1458. //Check if the user can write to the target dest file
  1459. if userinfo.CanWrite(string(vdestFile)) == false {
  1460. sendErrorResponse(w, "Access Denied.")
  1461. return
  1462. }
  1463. //Make the rdest directory if not exists
  1464. if !fileExists(rdestFile) {
  1465. err = os.MkdirAll(rdestFile, 0755)
  1466. if err != nil {
  1467. sendErrorResponse(w, err.Error())
  1468. return
  1469. }
  1470. }
  1471. //OK! Unzip to destination
  1472. err := fs.Unzip(rsrcFile, rdestFile)
  1473. if err != nil {
  1474. sendErrorResponse(w, err.Error())
  1475. return
  1476. }
  1477. } else {
  1478. sendErrorResponse(w, "Unknown file opeartion given.")
  1479. return
  1480. }
  1481. }
  1482. }
  1483. sendJSONResponse(w, "\"OK\"")
  1484. return
  1485. }
  1486. //Allow systems to store key value pairs in the database as preferences.
  1487. func system_fs_handleUserPreference(w http.ResponseWriter, r *http.Request) {
  1488. username, err := authAgent.GetUserName(w, r)
  1489. if err != nil {
  1490. sendErrorResponse(w, "User not logged in")
  1491. return
  1492. }
  1493. key, _ := mv(r, "key", false)
  1494. value, _ := mv(r, "value", false)
  1495. remove, _ := mv(r, "remove", false)
  1496. if key != "" && value == "" && remove == "" {
  1497. //Get mode. Read the prefernece with given key
  1498. result := ""
  1499. err := sysdb.Read("fs", "pref/"+key+"/"+username, &result)
  1500. if err != nil {
  1501. sendJSONResponse(w, "{\"error\":\"Key not found.\"}")
  1502. return
  1503. }
  1504. sendTextResponse(w, result)
  1505. } else if key != "" && value == "" && remove == "true" {
  1506. //Remove mode. Delete this key from sysdb
  1507. err := sysdb.Delete("fs", "pref/"+key+"/"+username)
  1508. if err != nil {
  1509. sendErrorResponse(w, err.Error())
  1510. }
  1511. sendOK(w)
  1512. } else if key != "" && value != "" {
  1513. //Set mode. Set the preference with given key
  1514. if len(value) > 1024 {
  1515. //Size too big. Reject storage
  1516. sendErrorResponse(w, "Preference value too long. Preference value can only store maximum 1024 characters.")
  1517. return
  1518. }
  1519. sysdb.Write("fs", "pref/"+key+"/"+username, value)
  1520. sendOK(w)
  1521. }
  1522. }
  1523. func system_fs_removeUserPreferences(username string) {
  1524. entries, err := sysdb.ListTable("fs")
  1525. if err != nil {
  1526. return
  1527. }
  1528. for _, keypairs := range entries {
  1529. if strings.Contains(string(keypairs[0]), "pref/") && strings.Contains(string(keypairs[0]), "/"+username) {
  1530. //Remove this preference
  1531. sysdb.Delete("fs", string(keypairs[0]))
  1532. }
  1533. }
  1534. }
  1535. func system_fs_listDrives(w http.ResponseWriter, r *http.Request) {
  1536. if authAgent.CheckAuth(r) == false {
  1537. sendErrorResponse(w, "User not logged in")
  1538. return
  1539. }
  1540. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1541. type driveInfo struct {
  1542. Drivepath string
  1543. DriveFreeSpace uint64
  1544. DriveTotalSpace uint64
  1545. DriveAvailSpace uint64
  1546. }
  1547. var drives []driveInfo
  1548. if runtime.GOOS == "windows" {
  1549. //Under windows
  1550. for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
  1551. f, err := os.Open(string(drive) + ":\\")
  1552. if err == nil {
  1553. thisdrive := new(driveInfo)
  1554. thisdrive.Drivepath = string(drive) + ":\\"
  1555. free, total, avail := storage.GetDriveCapacity(string(drive) + ":\\")
  1556. thisdrive.DriveFreeSpace = free
  1557. thisdrive.DriveTotalSpace = total
  1558. thisdrive.DriveAvailSpace = avail
  1559. drives = append(drives, *thisdrive)
  1560. f.Close()
  1561. }
  1562. }
  1563. } else {
  1564. //Under linux environment
  1565. //Append all the virtual directories root as root instead
  1566. storageDevices := []string{}
  1567. for _, fshandler := range userinfo.GetAllFileSystemHandler() {
  1568. storageDevices = append(storageDevices, fshandler.Path)
  1569. }
  1570. //List all storage information of each devices
  1571. for _, dev := range storageDevices {
  1572. thisdrive := new(driveInfo)
  1573. thisdrive.Drivepath = filepath.Base(dev)
  1574. free, total, avail := storage.GetDriveCapacity(string(dev))
  1575. thisdrive.DriveFreeSpace = free
  1576. thisdrive.DriveTotalSpace = total
  1577. thisdrive.DriveAvailSpace = avail
  1578. drives = append(drives, *thisdrive)
  1579. }
  1580. }
  1581. jsonString, _ := json.Marshal(drives)
  1582. sendJSONResponse(w, string(jsonString))
  1583. }
  1584. func system_fs_listRoot(w http.ResponseWriter, r *http.Request) {
  1585. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1586. if err != nil {
  1587. sendErrorResponse(w, err.Error())
  1588. return
  1589. }
  1590. username := userinfo.Username
  1591. userRoot, _ := mv(r, "user", false)
  1592. if userRoot == "true" {
  1593. type fileObject struct {
  1594. Filename string
  1595. Filepath string
  1596. IsDir bool
  1597. }
  1598. //List the root media folders under user:/
  1599. filesInUserRoot := []fileObject{}
  1600. filesInRoot, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(*root_directory)) + "/users/" + username + "/*")
  1601. for _, file := range filesInRoot {
  1602. thisFile := new(fileObject)
  1603. thisFile.Filename = filepath.Base(file)
  1604. thisFile.Filepath, _ = userinfo.RealPathToVirtualPath(file)
  1605. thisFile.IsDir = IsDir(file)
  1606. filesInUserRoot = append(filesInUserRoot, *thisFile)
  1607. }
  1608. jsonString, _ := json.Marshal(filesInUserRoot)
  1609. sendJSONResponse(w, string(jsonString))
  1610. } else {
  1611. type rootObject struct {
  1612. RootName string
  1613. RootPath string
  1614. }
  1615. var roots []rootObject
  1616. for _, store := range userinfo.GetAllFileSystemHandler() {
  1617. var thisDevice = new(rootObject)
  1618. thisDevice.RootName = store.Name
  1619. thisDevice.RootPath = store.UUID + ":/"
  1620. roots = append(roots, *thisDevice)
  1621. }
  1622. jsonString, _ := json.Marshal(roots)
  1623. sendJSONResponse(w, string(jsonString))
  1624. }
  1625. }
  1626. /*
  1627. Special Glob for handling path with [ or ] inside.
  1628. You can also pass in normal path for globing if you are not sure.
  1629. */
  1630. func system_fs_specialGlob(path string) ([]string, error) {
  1631. files, err := filepath.Glob(path)
  1632. if err != nil {
  1633. return []string{}, err
  1634. }
  1635. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  1636. if len(files) == 0 {
  1637. //Handle reverse check. Replace all [ and ] with *
  1638. newSearchPath := strings.ReplaceAll(path, "[", "?")
  1639. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  1640. //Scan with all the similar structure except [ and ]
  1641. tmpFilelist, _ := filepath.Glob(newSearchPath)
  1642. for _, file := range tmpFilelist {
  1643. file = filepath.ToSlash(file)
  1644. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  1645. files = append(files, file)
  1646. }
  1647. }
  1648. }
  1649. }
  1650. //Convert all filepaths to slash
  1651. for i := 0; i < len(files); i++ {
  1652. files[i] = filepath.ToSlash(files[i])
  1653. }
  1654. return files, nil
  1655. }
  1656. func system_fs_specialURIDecode(inputPath string) string {
  1657. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  1658. inputPath, _ = url.QueryUnescape(inputPath)
  1659. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  1660. return inputPath
  1661. }
  1662. func system_fs_specialURIEncode(inputPath string) string {
  1663. inputPath = strings.ReplaceAll(inputPath, " ", "{{space_sign}}")
  1664. inputPath, _ = url.QueryUnescape(inputPath)
  1665. inputPath = strings.ReplaceAll(inputPath, "{{space_sign}}", "%20")
  1666. return inputPath
  1667. }
  1668. func system_fs_matchFileExt(inputFilename string, extArray []string) bool {
  1669. inputExt := filepath.Ext(inputFilename)
  1670. if stringInSlice(inputExt, extArray) {
  1671. return true
  1672. }
  1673. return false
  1674. }
  1675. //Handle file properties request
  1676. func system_fs_getFileProperties(w http.ResponseWriter, r *http.Request) {
  1677. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1678. if err != nil {
  1679. sendErrorResponse(w, err.Error())
  1680. return
  1681. }
  1682. vpath, err := mv(r, "path", true)
  1683. if err != nil {
  1684. sendErrorResponse(w, "path not defined")
  1685. return
  1686. }
  1687. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1688. if err != nil {
  1689. sendErrorResponse(w, err.Error())
  1690. return
  1691. }
  1692. fileStat, err := os.Stat(rpath)
  1693. if err != nil {
  1694. sendErrorResponse(w, err.Error())
  1695. return
  1696. }
  1697. type fileProperties struct {
  1698. VirtualPath string
  1699. StoragePath string
  1700. Basename string
  1701. VirtualDirname string
  1702. StorageDirname string
  1703. Ext string
  1704. MimeType string
  1705. Filesize int64
  1706. Permission string
  1707. LastModTime string
  1708. LastModUnix int64
  1709. IsDirectory bool
  1710. Owner string
  1711. }
  1712. mime := "text/directory"
  1713. if !fileStat.IsDir() {
  1714. m, _, err := fs.GetMime(rpath)
  1715. if err != nil {
  1716. mime = ""
  1717. }
  1718. mime = m
  1719. }
  1720. filesize := fileStat.Size()
  1721. //Get file overall size if this is folder
  1722. if fileStat.IsDir() {
  1723. var size int64
  1724. filepath.Walk(rpath, func(_ string, info os.FileInfo, err error) error {
  1725. if err != nil {
  1726. return err
  1727. }
  1728. if !info.IsDir() {
  1729. size += info.Size()
  1730. }
  1731. return err
  1732. })
  1733. filesize = size
  1734. }
  1735. //Get file owner
  1736. owner := userinfo.GetFileOwner(rpath)
  1737. if owner == "" {
  1738. owner = "Unknown"
  1739. }
  1740. result := fileProperties{
  1741. VirtualPath: vpath,
  1742. StoragePath: filepath.Clean(rpath),
  1743. Basename: filepath.Base(rpath),
  1744. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1745. StorageDirname: filepath.ToSlash(filepath.Dir(rpath)),
  1746. Ext: filepath.Ext(rpath),
  1747. MimeType: mime,
  1748. Filesize: filesize,
  1749. Permission: fileStat.Mode().Perm().String(),
  1750. LastModTime: timeToString(fileStat.ModTime()),
  1751. LastModUnix: fileStat.ModTime().Unix(),
  1752. IsDirectory: fileStat.IsDir(),
  1753. Owner: owner,
  1754. }
  1755. jsonString, _ := json.Marshal(result)
  1756. sendJSONResponse(w, string(jsonString))
  1757. }
  1758. /*
  1759. List directory in the given path
  1760. Usage: Pass in dir like the following examples:
  1761. AOR:/Desktop <= Open /user/{username}/Desktop
  1762. S1:/ <= Open {uuid=S1}/
  1763. */
  1764. func system_fs_handleList(w http.ResponseWriter, r *http.Request) {
  1765. currentDir, _ := mv(r, "dir", true)
  1766. //Commented this line to handle dirname that contains "+" sign
  1767. //currentDir, _ = url.QueryUnescape(currentDir)
  1768. sortMode, _ := mv(r, "sort", true)
  1769. showHidden, _ := mv(r, "showHidden", true)
  1770. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1771. if err != nil {
  1772. //user not logged in. Redirect to login page.
  1773. sendErrorResponse(w, "User not logged in")
  1774. return
  1775. }
  1776. if currentDir == "" {
  1777. sendErrorResponse(w, "Invalid dir given.")
  1778. return
  1779. }
  1780. //Pad a slash at the end of currentDir if not exists
  1781. if currentDir[len(currentDir)-1:] != "/" {
  1782. currentDir = currentDir + "/"
  1783. }
  1784. //Convert the virutal path to realpath
  1785. realpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1786. if err != nil {
  1787. sendErrorResponse(w, "Error. Unable to parse path. "+err.Error())
  1788. return
  1789. }
  1790. if !fileExists(realpath) {
  1791. userRoot, _ := userinfo.VirtualPathToRealPath("user:/")
  1792. if filepath.Clean(realpath) == filepath.Clean(userRoot) {
  1793. //Initiate user folder (Initiaed in user object)
  1794. userinfo.GetHomeDirectory()
  1795. } else {
  1796. //Folder not exists
  1797. sendJSONResponse(w, "{\"error\":\"Folder not exists\"}")
  1798. return
  1799. }
  1800. }
  1801. if sortMode == "" {
  1802. sortMode = "default"
  1803. }
  1804. //Check for really special exception in where the path contains [ or ] which cannot be handled via Golang Glob function
  1805. files, _ := system_fs_specialGlob(filepath.Clean(realpath) + "/*")
  1806. var parsedFilelist []fs.FileData
  1807. for _, v := range files {
  1808. if showHidden != "true" && filepath.Base(v)[:1] == "." {
  1809. //Skipping hidden files
  1810. continue
  1811. }
  1812. rawsize := fs.GetFileSize(v)
  1813. modtime, _ := fs.GetModTime(v)
  1814. thisFile := fs.FileData{
  1815. Filename: filepath.Base(v),
  1816. Filepath: currentDir + filepath.Base(v),
  1817. Realpath: v,
  1818. IsDir: IsDir(v),
  1819. Filesize: rawsize,
  1820. Displaysize: fs.GetFileDisplaySize(rawsize, 2),
  1821. ModTime: modtime,
  1822. IsShared: shareManager.FileIsShared(v),
  1823. }
  1824. parsedFilelist = append(parsedFilelist, thisFile)
  1825. }
  1826. //Sort the filelist
  1827. if sortMode == "default" {
  1828. //Sort by name, convert filename to window sorting methods
  1829. sort.Slice(parsedFilelist, func(i, j int) bool {
  1830. return strings.ToLower(parsedFilelist[i].Filename) < strings.ToLower(parsedFilelist[j].Filename)
  1831. })
  1832. } else if sortMode == "reverse" {
  1833. //Sort by reverse name
  1834. sort.Slice(parsedFilelist, func(i, j int) bool {
  1835. return strings.ToLower(parsedFilelist[i].Filename) > strings.ToLower(parsedFilelist[j].Filename)
  1836. })
  1837. } else if sortMode == "smallToLarge" {
  1838. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize < parsedFilelist[j].Filesize })
  1839. } else if sortMode == "largeToSmall" {
  1840. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize > parsedFilelist[j].Filesize })
  1841. } else if sortMode == "mostRecent" {
  1842. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime > parsedFilelist[j].ModTime })
  1843. } else if sortMode == "leastRecent" {
  1844. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime < parsedFilelist[j].ModTime })
  1845. }
  1846. jsonString, _ := json.Marshal(parsedFilelist)
  1847. sendJSONResponse(w, string(jsonString))
  1848. }
  1849. //Handle getting a hash from a given contents in the given path
  1850. func system_fs_handleDirHash(w http.ResponseWriter, r *http.Request) {
  1851. currentDir, err := mv(r, "dir", true)
  1852. if err != nil {
  1853. sendErrorResponse(w, "Invalid dir given")
  1854. return
  1855. }
  1856. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1857. if err != nil {
  1858. sendErrorResponse(w, "User not logged in")
  1859. return
  1860. }
  1861. rpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1862. if err != nil {
  1863. sendErrorResponse(w, "Invalid dir given")
  1864. return
  1865. }
  1866. //Get a list of files in this directory
  1867. currentDir = filepath.ToSlash(filepath.Clean(rpath)) + "/"
  1868. filesInDir, err := system_fs_specialGlob(currentDir + "*")
  1869. if err != nil {
  1870. sendErrorResponse(w, err.Error())
  1871. return
  1872. }
  1873. filenames := []string{}
  1874. for _, file := range filesInDir {
  1875. if len(filepath.Base(file)) > 0 && string([]rune(filepath.Base(file))[0]) != "." {
  1876. //Ignore hidden files
  1877. filenames = append(filenames, filepath.Base(file))
  1878. }
  1879. }
  1880. sort.Strings(filenames)
  1881. //Build a hash base on the filelist
  1882. h := sha256.New()
  1883. h.Write([]byte(strings.Join(filenames, ",")))
  1884. sendTextResponse(w, hex.EncodeToString((h.Sum(nil))))
  1885. }
  1886. /*
  1887. File zipping and unzipping functions
  1888. */
  1889. //Handle all zip related API
  1890. func system_fs_zipHandler(w http.ResponseWriter, r *http.Request) {
  1891. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1892. if err != nil {
  1893. sendErrorResponse(w, err.Error())
  1894. return
  1895. }
  1896. opr, err := mv(r, "opr", true)
  1897. if err != nil {
  1898. sendErrorResponse(w, "Invalid opr or opr not defined")
  1899. return
  1900. }
  1901. vsrc, _ := mv(r, "src", true)
  1902. if vsrc == "" {
  1903. sendErrorResponse(w, "Invalid src paramter")
  1904. return
  1905. }
  1906. vdest, _ := mv(r, "dest", true)
  1907. rdest := ""
  1908. //Convert source path from JSON string to object
  1909. virtualSourcePaths := []string{}
  1910. err = json.Unmarshal([]byte(vsrc), &virtualSourcePaths)
  1911. if err != nil {
  1912. sendErrorResponse(w, err.Error())
  1913. return
  1914. }
  1915. //Check each of the path
  1916. realSourcePaths := []string{}
  1917. for _, vpath := range virtualSourcePaths {
  1918. thisrpath, err := userinfo.VirtualPathToRealPath(vpath)
  1919. if err != nil || !fileExists(thisrpath) {
  1920. sendErrorResponse(w, "File not exists: "+vpath)
  1921. return
  1922. }
  1923. realSourcePaths = append(realSourcePaths, thisrpath)
  1924. }
  1925. ///Convert dest to real if given
  1926. if vdest != "" {
  1927. realdest, _ := userinfo.VirtualPathToRealPath(vdest)
  1928. rdest = realdest
  1929. }
  1930. //This function will be deprecate soon in ArozOS 1.120
  1931. log.Println("*DEPRECATE* zipHandler will be deprecating soon! Please use fileOpr endpoint")
  1932. if opr == "zip" {
  1933. //Check if destination location exists
  1934. if rdest == "" || !fileExists(filepath.Dir(rdest)) {
  1935. sendErrorResponse(w, "Invalid dest location")
  1936. return
  1937. }
  1938. //OK. Create the zip at the desired location
  1939. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1940. if err != nil {
  1941. sendErrorResponse(w, err.Error())
  1942. return
  1943. }
  1944. sendOK(w)
  1945. } else if opr == "tmpzip" {
  1946. //Zip to tmp folder
  1947. userTmpFolder, _ := userinfo.VirtualPathToRealPath("tmp:/")
  1948. filename := Int64ToString(GetUnixTime()) + ".zip"
  1949. rdest := filepath.ToSlash(filepath.Clean(userTmpFolder)) + "/" + filename
  1950. log.Println(realSourcePaths, rdest)
  1951. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1952. if err != nil {
  1953. sendErrorResponse(w, err.Error())
  1954. return
  1955. }
  1956. //Send the tmp filename to the user
  1957. sendTextResponse(w, "tmp:/"+filename)
  1958. } else if opr == "inspect" {
  1959. } else if opr == "unzip" {
  1960. }
  1961. }
  1962. //Translate path from and to virtual and realpath
  1963. func system_fs_handlePathTranslate(w http.ResponseWriter, r *http.Request) {
  1964. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1965. if err != nil {
  1966. sendErrorResponse(w, err.Error())
  1967. return
  1968. }
  1969. path, err := mv(r, "path", false)
  1970. if err != nil {
  1971. sendErrorResponse(w, "Invalid path given")
  1972. return
  1973. }
  1974. rpath, err := userinfo.VirtualPathToRealPath(path)
  1975. if err != nil {
  1976. //Try to convert it to virtualPath
  1977. vpath, err := userinfo.RealPathToVirtualPath(path)
  1978. if err != nil {
  1979. sendErrorResponse(w, "Unknown path given")
  1980. } else {
  1981. jsonstring, _ := json.Marshal(vpath)
  1982. sendJSONResponse(w, string(jsonstring))
  1983. }
  1984. } else {
  1985. abrpath, _ := filepath.Abs(rpath)
  1986. jsonstring, _ := json.Marshal([]string{rpath, filepath.ToSlash(abrpath)})
  1987. sendJSONResponse(w, string(jsonstring))
  1988. }
  1989. }
  1990. //Handle cache rendering with websocket pipeline
  1991. func system_fs_handleCacheRender(w http.ResponseWriter, r *http.Request) {
  1992. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1993. vpath, err := mv(r, "folder", false)
  1994. if err != nil {
  1995. sendErrorResponse(w, "Invalid folder paramter")
  1996. return
  1997. }
  1998. //Convert vpath to realpath
  1999. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2000. if err != nil {
  2001. sendErrorResponse(w, err.Error())
  2002. return
  2003. }
  2004. //Perform cache rendering
  2005. thumbRenderHandler.HandleLoadCache(w, r, rpath)
  2006. }
  2007. //Handle file thumbnail caching
  2008. func system_fs_handleFolderCache(w http.ResponseWriter, r *http.Request) {
  2009. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2010. vfolderpath, err := mv(r, "folder", false)
  2011. if err != nil {
  2012. sendErrorResponse(w, "folder not defined")
  2013. return
  2014. }
  2015. rpath, err := userinfo.VirtualPathToRealPath(vfolderpath)
  2016. if err != nil {
  2017. sendErrorResponse(w, err.Error())
  2018. return
  2019. }
  2020. thumbRenderHandler.BuildCacheForFolder(rpath)
  2021. sendOK(w)
  2022. }
  2023. //Handle setting and loading of file permission on Linux
  2024. func system_fs_handleFilePermission(w http.ResponseWriter, r *http.Request) {
  2025. file, err := mv(r, "file", true)
  2026. if err != nil {
  2027. sendErrorResponse(w, "Invalid file")
  2028. return
  2029. }
  2030. //Translate the file to real path
  2031. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2032. if err != nil {
  2033. sendErrorResponse(w, "User not logged in")
  2034. return
  2035. }
  2036. rpath, err := userinfo.VirtualPathToRealPath(file)
  2037. if err != nil {
  2038. sendErrorResponse(w, err.Error())
  2039. return
  2040. }
  2041. newMode, _ := mv(r, "mode", true)
  2042. if newMode == "" {
  2043. //Read the file mode
  2044. //Check if the file exists
  2045. if !fileExists(rpath) {
  2046. sendErrorResponse(w, "File not exists!")
  2047. return
  2048. }
  2049. //Read the file permission
  2050. filePermission, err := fsp.GetFilePermissions(rpath)
  2051. if err != nil {
  2052. sendErrorResponse(w, err.Error())
  2053. return
  2054. }
  2055. //Send the file permission to client
  2056. js, _ := json.Marshal(filePermission)
  2057. sendJSONResponse(w, string(js))
  2058. } else {
  2059. //Set the file mode
  2060. //Check if the file exists
  2061. if !fileExists(rpath) {
  2062. sendErrorResponse(w, "File not exists!")
  2063. return
  2064. }
  2065. //Check if windows. If yes, ignore this request
  2066. if runtime.GOOS == "windows" {
  2067. sendErrorResponse(w, "Windows host not supported")
  2068. return
  2069. }
  2070. //Check if this user has permission to change the file permission
  2071. //Aka user must be 1. This is his own folder or 2. Admin
  2072. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(file)
  2073. if fsh.Hierarchy == "user" {
  2074. //Always ok as this is owned by the user
  2075. } else if fsh.Hierarchy == "public" {
  2076. //Require admin
  2077. if userinfo.IsAdmin() == false {
  2078. sendErrorResponse(w, "Permission Denied")
  2079. return
  2080. }
  2081. } else {
  2082. //Not implemeneted. Require admin
  2083. if userinfo.IsAdmin() == false {
  2084. sendErrorResponse(w, "Permission Denied")
  2085. return
  2086. }
  2087. }
  2088. //Be noted that if the system is not running in sudo mode,
  2089. //File permission change might not works.
  2090. err := fsp.SetFilePermisson(rpath, newMode)
  2091. if err != nil {
  2092. sendErrorResponse(w, err.Error())
  2093. return
  2094. } else {
  2095. sendOK(w)
  2096. }
  2097. }
  2098. }
  2099. //Check if the given filepath is and must inside the given directory path.
  2100. //You can pass both as relative
  2101. func system_fs_checkFileInDirectory(filesourcepath string, directory string) bool {
  2102. filepathAbs, err := filepath.Abs(filesourcepath)
  2103. if err != nil {
  2104. return false
  2105. }
  2106. directoryAbs, err := filepath.Abs(directory)
  2107. if err != nil {
  2108. return false
  2109. }
  2110. //Check if the filepathabs contain directoryAbs
  2111. if strings.Contains(filepathAbs, directoryAbs) {
  2112. return true
  2113. } else {
  2114. return false
  2115. }
  2116. }
  2117. //Clear the old files inside the tmp file
  2118. func system_fs_clearOldTmpFiles() {
  2119. filesToBeDelete := []string{}
  2120. tmpAbs, _ := filepath.Abs(*tmp_directory)
  2121. filepath.Walk(*tmp_directory, func(path string, info os.FileInfo, err error) error {
  2122. if filepath.Base(path) != "aofs.db" && filepath.Base(path) != "aofs.db.lock" {
  2123. //Check if root folders. Do not delete root folders
  2124. parentAbs, _ := filepath.Abs(filepath.Dir(path))
  2125. if tmpAbs == parentAbs {
  2126. //Root folder. Do not remove
  2127. return nil
  2128. }
  2129. //Get its modification time
  2130. modTime, err := fs.GetModTime(path)
  2131. if err != nil {
  2132. return nil
  2133. }
  2134. //Check if mod time is more than 24 hours ago
  2135. if time.Now().Unix()-modTime > int64(*maxTempFileKeepTime) {
  2136. //Delete OK
  2137. filesToBeDelete = append(filesToBeDelete, path)
  2138. }
  2139. }
  2140. return nil
  2141. })
  2142. //Remove all files from the delete list
  2143. for _, fileToBeDelete := range filesToBeDelete {
  2144. os.RemoveAll(fileToBeDelete)
  2145. }
  2146. }