file_system.go 81 KB

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