file_system.go 78 KB

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