file_system.go 80 KB

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