file_system.go 78 KB

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