file_system.go 82 KB

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