file_system.go 78 KB

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