file_system.go 79 KB

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