file_system.go 85 KB

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