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