file_system.go 79 KB

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