file_system.go 69 KB

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