file_system.go 78 KB

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