file_system.go 82 KB

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