file_system.go 74 KB

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