file_system.go 79 KB

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