file_system.go 69 KB

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