file_system.go 72 KB

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