file_system.go 85 KB

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