file_system.go 72 KB

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