file_system.go 76 KB

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