file_system.go 82 KB

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