file_system.go 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939
  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)) + "/.cache/*")
  1544. if len(fc) == 0 {
  1545. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.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. //Updates 20 Jan 2021: Replace with CanWrite handler
  1557. /*
  1558. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1559. if accmode == "readonly" {
  1560. sendErrorResponse(w, "This directory is Read Only.")
  1561. return
  1562. } else if accmode == "denied" {
  1563. sendErrorResponse(w, "Access Denied")
  1564. return
  1565. }*/
  1566. if !userinfo.CanWrite(vsrcFile) {
  1567. sendErrorResponse(w, "Access Denied")
  1568. return
  1569. }
  1570. //Check if this file has any cached files. If yes, remove it
  1571. metadata.RemoveCache(rsrcFile)
  1572. //Clear the cache folder if there is no files inside
  1573. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1574. if len(fc) == 0 {
  1575. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1576. }
  1577. //Create a trash directory for this folder
  1578. trashDir := filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.trash/"
  1579. os.MkdirAll(trashDir, 0755)
  1580. hidden.HideFile(trashDir)
  1581. os.Rename(rsrcFile, trashDir+filepath.Base(rsrcFile)+"."+Int64ToString(GetUnixTime()))
  1582. } else if operation == "unzip" {
  1583. //Unzip the file to destination
  1584. //Check if the user can write to the target dest file
  1585. if userinfo.CanWrite(string(vdestFile)) == false {
  1586. sendErrorResponse(w, "Access Denied")
  1587. return
  1588. }
  1589. //Make the rdest directory if not exists
  1590. if !fileExists(rdestFile) {
  1591. err = os.MkdirAll(rdestFile, 0755)
  1592. if err != nil {
  1593. sendErrorResponse(w, err.Error())
  1594. return
  1595. }
  1596. }
  1597. //OK! Unzip to destination
  1598. err := fs.Unzip(rsrcFile, rdestFile)
  1599. if err != nil {
  1600. sendErrorResponse(w, err.Error())
  1601. return
  1602. }
  1603. } else {
  1604. sendErrorResponse(w, "Unknown file opeartion given")
  1605. return
  1606. }
  1607. }
  1608. }
  1609. sendJSONResponse(w, "\"OK\"")
  1610. return
  1611. }
  1612. //Allow systems to store key value pairs in the database as preferences.
  1613. func system_fs_handleUserPreference(w http.ResponseWriter, r *http.Request) {
  1614. username, err := authAgent.GetUserName(w, r)
  1615. if err != nil {
  1616. sendErrorResponse(w, "User not logged in")
  1617. return
  1618. }
  1619. key, _ := mv(r, "key", false)
  1620. value, _ := mv(r, "value", false)
  1621. remove, _ := mv(r, "remove", false)
  1622. if key != "" && value == "" && remove == "" {
  1623. //Get mode. Read the prefernece with given key
  1624. result := ""
  1625. err := sysdb.Read("fs", "pref/"+key+"/"+username, &result)
  1626. if err != nil {
  1627. sendJSONResponse(w, "{\"error\":\"Key not found.\"}")
  1628. return
  1629. }
  1630. sendTextResponse(w, result)
  1631. } else if key != "" && value == "" && remove == "true" {
  1632. //Remove mode. Delete this key from sysdb
  1633. err := sysdb.Delete("fs", "pref/"+key+"/"+username)
  1634. if err != nil {
  1635. sendErrorResponse(w, err.Error())
  1636. }
  1637. sendOK(w)
  1638. } else if key != "" && value != "" {
  1639. //Set mode. Set the preference with given key
  1640. if len(value) > 1024 {
  1641. //Size too big. Reject storage
  1642. sendErrorResponse(w, "Preference value too long. Preference value can only store maximum 1024 characters.")
  1643. return
  1644. }
  1645. sysdb.Write("fs", "pref/"+key+"/"+username, value)
  1646. sendOK(w)
  1647. }
  1648. }
  1649. func system_fs_removeUserPreferences(username string) {
  1650. entries, err := sysdb.ListTable("fs")
  1651. if err != nil {
  1652. return
  1653. }
  1654. for _, keypairs := range entries {
  1655. if strings.Contains(string(keypairs[0]), "pref/") && strings.Contains(string(keypairs[0]), "/"+username) {
  1656. //Remove this preference
  1657. sysdb.Delete("fs", string(keypairs[0]))
  1658. }
  1659. }
  1660. }
  1661. func system_fs_listDrives(w http.ResponseWriter, r *http.Request) {
  1662. if authAgent.CheckAuth(r) == false {
  1663. sendErrorResponse(w, "User not logged in")
  1664. return
  1665. }
  1666. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1667. type driveInfo struct {
  1668. Drivepath string
  1669. DriveFreeSpace uint64
  1670. DriveTotalSpace uint64
  1671. DriveAvailSpace uint64
  1672. }
  1673. var drives []driveInfo
  1674. if runtime.GOOS == "windows" {
  1675. //Under windows
  1676. for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
  1677. f, err := os.Open(string(drive) + ":\\")
  1678. if err == nil {
  1679. thisdrive := new(driveInfo)
  1680. thisdrive.Drivepath = string(drive) + ":\\"
  1681. free, total, avail := storage.GetDriveCapacity(string(drive) + ":\\")
  1682. thisdrive.DriveFreeSpace = free
  1683. thisdrive.DriveTotalSpace = total
  1684. thisdrive.DriveAvailSpace = avail
  1685. drives = append(drives, *thisdrive)
  1686. f.Close()
  1687. }
  1688. }
  1689. } else {
  1690. //Under linux environment
  1691. //Append all the virtual directories root as root instead
  1692. storageDevices := []string{}
  1693. for _, fshandler := range userinfo.GetAllFileSystemHandler() {
  1694. storageDevices = append(storageDevices, fshandler.Path)
  1695. }
  1696. //List all storage information of each devices
  1697. for _, dev := range storageDevices {
  1698. thisdrive := new(driveInfo)
  1699. thisdrive.Drivepath = filepath.Base(dev)
  1700. free, total, avail := storage.GetDriveCapacity(string(dev))
  1701. thisdrive.DriveFreeSpace = free
  1702. thisdrive.DriveTotalSpace = total
  1703. thisdrive.DriveAvailSpace = avail
  1704. drives = append(drives, *thisdrive)
  1705. }
  1706. }
  1707. jsonString, _ := json.Marshal(drives)
  1708. sendJSONResponse(w, string(jsonString))
  1709. }
  1710. func system_fs_listRoot(w http.ResponseWriter, r *http.Request) {
  1711. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1712. if err != nil {
  1713. sendErrorResponse(w, err.Error())
  1714. return
  1715. }
  1716. username := userinfo.Username
  1717. userRoot, _ := mv(r, "user", false)
  1718. if userRoot == "true" {
  1719. type fileObject struct {
  1720. Filename string
  1721. Filepath string
  1722. IsDir bool
  1723. }
  1724. //List the root media folders under user:/
  1725. filesInUserRoot := []fileObject{}
  1726. filesInRoot, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(*root_directory)) + "/users/" + username + "/*")
  1727. for _, file := range filesInRoot {
  1728. thisFile := new(fileObject)
  1729. thisFile.Filename = filepath.Base(file)
  1730. thisFile.Filepath, _ = userinfo.RealPathToVirtualPath(file)
  1731. thisFile.IsDir = IsDir(file)
  1732. filesInUserRoot = append(filesInUserRoot, *thisFile)
  1733. }
  1734. jsonString, _ := json.Marshal(filesInUserRoot)
  1735. sendJSONResponse(w, string(jsonString))
  1736. } else {
  1737. type rootObject struct {
  1738. rootID string //The vroot id
  1739. RootName string //The name of this vroot
  1740. RootPath string //The path of this vroot
  1741. RootBackups bool //If there are backup for this vroot
  1742. }
  1743. roots := []*rootObject{}
  1744. backupRoots := []string{}
  1745. for _, store := range userinfo.GetAllFileSystemHandler() {
  1746. if store.Hierarchy == "user" || store.Hierarchy == "public" {
  1747. //Normal drives
  1748. var thisDevice = new(rootObject)
  1749. thisDevice.RootName = store.Name
  1750. thisDevice.RootPath = store.UUID + ":/"
  1751. thisDevice.rootID = store.UUID
  1752. roots = append(roots, thisDevice)
  1753. } else if store.Hierarchy == "backup" {
  1754. //Backup drive.
  1755. backupRoots = append(backupRoots, store.HierarchyConfig.(hybridBackup.BackupTask).ParentUID)
  1756. } else if store.Hierarchy == "share" {
  1757. //Share emulated drive
  1758. var thisDevice = new(rootObject)
  1759. thisDevice.RootName = store.Name
  1760. thisDevice.RootPath = store.UUID + ":/"
  1761. thisDevice.rootID = store.UUID
  1762. roots = append(roots, thisDevice)
  1763. }
  1764. }
  1765. //Update root configs for backup roots
  1766. for _, backupRoot := range backupRoots {
  1767. //For this backup root, check if the parent root mounted
  1768. for _, root := range roots {
  1769. if root.rootID == backupRoot {
  1770. //Parent root mounted. Label the parent root as "have backup"
  1771. root.RootBackups = true
  1772. }
  1773. }
  1774. }
  1775. jsonString, _ := json.Marshal(roots)
  1776. sendJSONResponse(w, string(jsonString))
  1777. }
  1778. }
  1779. /*
  1780. Special Glob for handling path with [ or ] inside.
  1781. You can also pass in normal path for globing if you are not sure.
  1782. */
  1783. func system_fs_specialGlob(path string) ([]string, error) {
  1784. //Quick fix for foldername containing -] issue
  1785. path = strings.ReplaceAll(path, "[", "[[]")
  1786. files, err := filepath.Glob(path)
  1787. if err != nil {
  1788. return []string{}, err
  1789. }
  1790. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  1791. if len(files) == 0 {
  1792. //Handle reverse check. Replace all [ and ] with *
  1793. newSearchPath := strings.ReplaceAll(path, "[", "?")
  1794. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  1795. //Scan with all the similar structure except [ and ]
  1796. tmpFilelist, _ := filepath.Glob(newSearchPath)
  1797. for _, file := range tmpFilelist {
  1798. file = filepath.ToSlash(file)
  1799. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  1800. files = append(files, file)
  1801. }
  1802. }
  1803. }
  1804. }
  1805. //Convert all filepaths to slash
  1806. for i := 0; i < len(files); i++ {
  1807. files[i] = filepath.ToSlash(files[i])
  1808. }
  1809. return files, nil
  1810. }
  1811. func system_fs_specialURIDecode(inputPath string) string {
  1812. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  1813. inputPath, _ = url.QueryUnescape(inputPath)
  1814. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  1815. return inputPath
  1816. }
  1817. func system_fs_specialURIEncode(inputPath string) string {
  1818. inputPath = strings.ReplaceAll(inputPath, " ", "{{space_sign}}")
  1819. inputPath, _ = url.QueryUnescape(inputPath)
  1820. inputPath = strings.ReplaceAll(inputPath, "{{space_sign}}", "%20")
  1821. return inputPath
  1822. }
  1823. //Handle file properties request
  1824. func system_fs_getFileProperties(w http.ResponseWriter, r *http.Request) {
  1825. type fileProperties struct {
  1826. VirtualPath string
  1827. StoragePath string
  1828. Basename string
  1829. VirtualDirname string
  1830. StorageDirname string
  1831. Ext string
  1832. MimeType string
  1833. Filesize int64
  1834. Permission string
  1835. LastModTime string
  1836. LastModUnix int64
  1837. IsDirectory bool
  1838. Owner string
  1839. }
  1840. result := fileProperties{}
  1841. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1842. if err != nil {
  1843. sendErrorResponse(w, err.Error())
  1844. return
  1845. }
  1846. vpath, err := mv(r, "path", true)
  1847. if err != nil {
  1848. sendErrorResponse(w, "path not defined")
  1849. return
  1850. }
  1851. vrootID, subpath, _ := filesystem.GetIDFromVirtualPath(vpath)
  1852. if vrootID == "share" && subpath == "" {
  1853. result = fileProperties{
  1854. VirtualPath: vpath,
  1855. StoragePath: "(Emulated File System)",
  1856. Basename: "Share",
  1857. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1858. StorageDirname: "N/A",
  1859. Ext: "N/A",
  1860. MimeType: "emulated/fs",
  1861. Filesize: -1,
  1862. Permission: "N/A",
  1863. LastModTime: "N/A",
  1864. LastModUnix: 0,
  1865. IsDirectory: true,
  1866. Owner: "system",
  1867. }
  1868. } else {
  1869. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1870. if err != nil {
  1871. sendErrorResponse(w, err.Error())
  1872. return
  1873. }
  1874. fileStat, err := os.Stat(rpath)
  1875. if err != nil {
  1876. sendErrorResponse(w, err.Error())
  1877. return
  1878. }
  1879. mime := "text/directory"
  1880. if !fileStat.IsDir() {
  1881. m, _, err := fs.GetMime(rpath)
  1882. if err != nil {
  1883. mime = ""
  1884. }
  1885. mime = m
  1886. }
  1887. filesize := fileStat.Size()
  1888. //Get file overall size if this is folder
  1889. if fileStat.IsDir() {
  1890. var size int64
  1891. filepath.Walk(rpath, func(_ string, info os.FileInfo, err error) error {
  1892. if err != nil {
  1893. return err
  1894. }
  1895. if !info.IsDir() {
  1896. size += info.Size()
  1897. }
  1898. return err
  1899. })
  1900. filesize = size
  1901. }
  1902. //Get file owner
  1903. owner := userinfo.GetFileOwner(rpath)
  1904. if owner == "" {
  1905. //Handle special virtual roots
  1906. vrootID, subpath, _ := filesystem.GetIDFromVirtualPath(vpath)
  1907. if vrootID == "share" {
  1908. //Share objects
  1909. shareOption, _ := shareEntryTable.ResolveShareOptionFromShareSubpath(subpath)
  1910. if shareOption != nil {
  1911. owner = shareOption.Owner
  1912. } else {
  1913. owner = "Unknown"
  1914. }
  1915. } else {
  1916. owner = "Unknown"
  1917. }
  1918. }
  1919. result = fileProperties{
  1920. VirtualPath: vpath,
  1921. StoragePath: filepath.Clean(rpath),
  1922. Basename: filepath.Base(rpath),
  1923. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1924. StorageDirname: filepath.ToSlash(filepath.Dir(rpath)),
  1925. Ext: filepath.Ext(rpath),
  1926. MimeType: mime,
  1927. Filesize: filesize,
  1928. Permission: fileStat.Mode().Perm().String(),
  1929. LastModTime: timeToString(fileStat.ModTime()),
  1930. LastModUnix: fileStat.ModTime().Unix(),
  1931. IsDirectory: fileStat.IsDir(),
  1932. Owner: owner,
  1933. }
  1934. }
  1935. jsonString, _ := json.Marshal(result)
  1936. sendJSONResponse(w, string(jsonString))
  1937. }
  1938. /*
  1939. List directory in the given path
  1940. Usage: Pass in dir like the following examples:
  1941. AOR:/Desktop <= Open /user/{username}/Desktop
  1942. S1:/ <= Open {uuid=S1}/
  1943. */
  1944. func system_fs_handleList(w http.ResponseWriter, r *http.Request) {
  1945. currentDir, _ := mv(r, "dir", true)
  1946. //Commented this line to handle dirname that contains "+" sign
  1947. //currentDir, _ = url.QueryUnescape(currentDir)
  1948. sortMode, _ := mv(r, "sort", true)
  1949. showHidden, _ := mv(r, "showHidden", true)
  1950. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1951. if err != nil {
  1952. //user not logged in. Redirect to login page.
  1953. sendErrorResponse(w, "User not logged in")
  1954. return
  1955. }
  1956. if currentDir == "" {
  1957. sendErrorResponse(w, "Invalid dir given.")
  1958. return
  1959. }
  1960. //Pad a slash at the end of currentDir if not exists
  1961. if currentDir[len(currentDir)-1:] != "/" {
  1962. currentDir = currentDir + "/"
  1963. }
  1964. VirtualRootID, subpath, err := fs.GetIDFromVirtualPath(currentDir)
  1965. if err != nil {
  1966. sendErrorResponse(w, "Unable to resolve requested path: "+err.Error())
  1967. return
  1968. }
  1969. var parsedFilelist []fs.FileData
  1970. var realpath string = ""
  1971. //Handle some special virtual file systems / mount points
  1972. if VirtualRootID == "share" && subpath == "" {
  1973. userpgs := userinfo.GetUserPermissionGroupNames()
  1974. files := shareEntryTable.ListRootForUser(userinfo.Username, userpgs)
  1975. parsedFilelist = files
  1976. } else {
  1977. //Normal file systems
  1978. //Convert the virutal path to realpath
  1979. realpath, err = userinfo.VirtualPathToRealPath(currentDir)
  1980. if err != nil {
  1981. sendErrorResponse(w, err.Error())
  1982. return
  1983. }
  1984. if !fileExists(realpath) {
  1985. userRoot, _ := userinfo.VirtualPathToRealPath("user:/")
  1986. if filepath.Clean(realpath) == filepath.Clean(userRoot) {
  1987. //Initiate user folder (Initiaed in user object)
  1988. userinfo.GetHomeDirectory()
  1989. } else if !strings.Contains(filepath.ToSlash(filepath.Clean(currentDir)), "/") {
  1990. //User root not created. Create the root folder
  1991. os.MkdirAll(filepath.Clean(realpath), 0775)
  1992. } else {
  1993. //Folder not exists
  1994. log.Println("[File Explorer] Requested path: ", realpath, " does not exists!")
  1995. sendErrorResponse(w, "Folder not exists")
  1996. return
  1997. }
  1998. }
  1999. if sortMode == "" {
  2000. sortMode = "default"
  2001. }
  2002. //Check for really special exception in where the path contains [ or ] which cannot be handled via Golang Glob function
  2003. files, _ := system_fs_specialGlob(filepath.Clean(realpath) + "/*")
  2004. var shortCutInfo *shortcut.ShortcutData = nil
  2005. for _, v := range files {
  2006. //Check if it is hidden file
  2007. isHidden, _ := hidden.IsHidden(v, false)
  2008. if showHidden != "true" && isHidden {
  2009. //Skipping hidden files
  2010. continue
  2011. }
  2012. //Check if this is an aodb file
  2013. if filepath.Base(v) == "aofs.db" || filepath.Base(v) == "aofs.db.lock" {
  2014. //Database file (reserved)
  2015. continue
  2016. }
  2017. //Check if it is shortcut file. If yes, render a shortcut data struct
  2018. if filepath.Ext(v) == ".shortcut" {
  2019. //This is a shortcut file
  2020. shorcutData, err := shortcut.ReadShortcut(v)
  2021. if err == nil {
  2022. shortCutInfo = shorcutData
  2023. }
  2024. }
  2025. rawsize := fs.GetFileSize(v)
  2026. modtime, _ := fs.GetModTime(v)
  2027. thisFile := fs.FileData{
  2028. Filename: filepath.Base(v),
  2029. Filepath: currentDir + filepath.Base(v),
  2030. Realpath: v,
  2031. IsDir: IsDir(v),
  2032. Filesize: rawsize,
  2033. Displaysize: fs.GetFileDisplaySize(rawsize, 2),
  2034. ModTime: modtime,
  2035. IsShared: shareManager.FileIsShared(v),
  2036. Shortcut: shortCutInfo,
  2037. }
  2038. parsedFilelist = append(parsedFilelist, thisFile)
  2039. }
  2040. }
  2041. //Sort the filelist
  2042. if sortMode == "default" {
  2043. //Sort by name, convert filename to window sorting methods
  2044. sort.Slice(parsedFilelist, func(i, j int) bool {
  2045. return strings.ToLower(parsedFilelist[i].Filename) < strings.ToLower(parsedFilelist[j].Filename)
  2046. })
  2047. } else if sortMode == "reverse" {
  2048. //Sort by reverse name
  2049. sort.Slice(parsedFilelist, func(i, j int) bool {
  2050. return strings.ToLower(parsedFilelist[i].Filename) > strings.ToLower(parsedFilelist[j].Filename)
  2051. })
  2052. } else if sortMode == "smallToLarge" {
  2053. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize < parsedFilelist[j].Filesize })
  2054. } else if sortMode == "largeToSmall" {
  2055. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize > parsedFilelist[j].Filesize })
  2056. } else if sortMode == "mostRecent" {
  2057. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime > parsedFilelist[j].ModTime })
  2058. } else if sortMode == "leastRecent" {
  2059. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime < parsedFilelist[j].ModTime })
  2060. }
  2061. jsonString, _ := json.Marshal(parsedFilelist)
  2062. sendJSONResponse(w, string(jsonString))
  2063. }
  2064. //Handle getting a hash from a given contents in the given path
  2065. func system_fs_handleDirHash(w http.ResponseWriter, r *http.Request) {
  2066. currentDir, err := mv(r, "dir", true)
  2067. if err != nil {
  2068. sendErrorResponse(w, "Invalid dir given")
  2069. return
  2070. }
  2071. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2072. if err != nil {
  2073. sendErrorResponse(w, "User not logged in")
  2074. return
  2075. }
  2076. VirtualRootID, subpath, _ := fs.GetIDFromVirtualPath(currentDir)
  2077. if VirtualRootID == "share" && subpath == "" {
  2078. sendTextResponse(w, hex.EncodeToString([]byte("0")))
  2079. return
  2080. }
  2081. rpath, err := userinfo.VirtualPathToRealPath(currentDir)
  2082. if err != nil {
  2083. sendErrorResponse(w, "Invalid dir given")
  2084. return
  2085. }
  2086. //Get a list of files in this directory
  2087. currentDir = filepath.ToSlash(filepath.Clean(rpath)) + "/"
  2088. filesInDir, err := system_fs_specialGlob(currentDir + "*")
  2089. if err != nil {
  2090. sendErrorResponse(w, err.Error())
  2091. return
  2092. }
  2093. filenames := []string{}
  2094. for _, file := range filesInDir {
  2095. if len(filepath.Base(file)) > 0 && string([]rune(filepath.Base(file))[0]) != "." {
  2096. //Ignore hidden files
  2097. filenames = append(filenames, filepath.Base(file))
  2098. }
  2099. }
  2100. sort.Strings(filenames)
  2101. //Build a hash base on the filelist
  2102. h := sha256.New()
  2103. h.Write([]byte(strings.Join(filenames, ",")))
  2104. sendTextResponse(w, hex.EncodeToString((h.Sum(nil))))
  2105. }
  2106. /*
  2107. File zipping and unzipping functions
  2108. */
  2109. //Handle all zip related API
  2110. func system_fs_zipHandler(w http.ResponseWriter, r *http.Request) {
  2111. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2112. if err != nil {
  2113. sendErrorResponse(w, err.Error())
  2114. return
  2115. }
  2116. opr, err := mv(r, "opr", true)
  2117. if err != nil {
  2118. sendErrorResponse(w, "Invalid opr or opr not defined")
  2119. return
  2120. }
  2121. vsrc, _ := mv(r, "src", true)
  2122. if vsrc == "" {
  2123. sendErrorResponse(w, "Invalid src paramter")
  2124. return
  2125. }
  2126. vdest, _ := mv(r, "dest", true)
  2127. rdest := ""
  2128. //Convert source path from JSON string to object
  2129. virtualSourcePaths := []string{}
  2130. err = json.Unmarshal([]byte(vsrc), &virtualSourcePaths)
  2131. if err != nil {
  2132. sendErrorResponse(w, err.Error())
  2133. return
  2134. }
  2135. //Check each of the path
  2136. realSourcePaths := []string{}
  2137. for _, vpath := range virtualSourcePaths {
  2138. thisrpath, err := userinfo.VirtualPathToRealPath(vpath)
  2139. if err != nil || !fileExists(thisrpath) {
  2140. sendErrorResponse(w, "File not exists: "+vpath)
  2141. return
  2142. }
  2143. realSourcePaths = append(realSourcePaths, thisrpath)
  2144. }
  2145. ///Convert dest to real if given
  2146. if vdest != "" {
  2147. realdest, _ := userinfo.VirtualPathToRealPath(vdest)
  2148. rdest = realdest
  2149. }
  2150. //This function will be deprecate soon in ArozOS 1.120
  2151. log.Println("*DEPRECATE* zipHandler will be deprecating soon! Please use fileOpr endpoint")
  2152. if opr == "zip" {
  2153. //Check if destination location exists
  2154. if rdest == "" || !fileExists(filepath.Dir(rdest)) {
  2155. sendErrorResponse(w, "Invalid dest location")
  2156. return
  2157. }
  2158. //OK. Create the zip at the desired location
  2159. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  2160. if err != nil {
  2161. sendErrorResponse(w, err.Error())
  2162. return
  2163. }
  2164. sendOK(w)
  2165. } else if opr == "tmpzip" {
  2166. //Zip to tmp folder
  2167. userTmpFolder, _ := userinfo.VirtualPathToRealPath("tmp:/")
  2168. filename := Int64ToString(GetUnixTime()) + ".zip"
  2169. rdest := filepath.ToSlash(filepath.Clean(userTmpFolder)) + "/" + filename
  2170. log.Println(realSourcePaths, rdest)
  2171. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  2172. if err != nil {
  2173. sendErrorResponse(w, err.Error())
  2174. return
  2175. }
  2176. //Send the tmp filename to the user
  2177. sendTextResponse(w, "tmp:/"+filename)
  2178. } else if opr == "inspect" {
  2179. } else if opr == "unzip" {
  2180. }
  2181. }
  2182. //Manage file version history
  2183. func system_fs_FileVersionHistory(w http.ResponseWriter, r *http.Request) {
  2184. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2185. if err != nil {
  2186. sendErrorResponse(w, err.Error())
  2187. return
  2188. }
  2189. path, err := mv(r, "path", true)
  2190. if err != nil {
  2191. sendErrorResponse(w, "Invalid path given")
  2192. return
  2193. }
  2194. opr, _ := mv(r, "opr", true)
  2195. rpath, err := userinfo.VirtualPathToRealPath(path)
  2196. if err != nil {
  2197. sendErrorResponse(w, "Unable to translate virtual path")
  2198. return
  2199. }
  2200. if opr == "" {
  2201. //List file history
  2202. fileVersionData, err := localversion.GetFileVersionData(rpath)
  2203. if err != nil {
  2204. sendErrorResponse(w, "Unable to load version information: "+err.Error())
  2205. return
  2206. }
  2207. js, _ := json.Marshal(fileVersionData)
  2208. sendJSONResponse(w, string(js))
  2209. } else if opr == "delete" {
  2210. //Delete file history of given history ID
  2211. historyID, err := mv(r, "histid", true)
  2212. if err != nil {
  2213. sendErrorResponse(w, "Invalid history id given")
  2214. return
  2215. }
  2216. err = localversion.RemoveFileHistory(rpath, historyID)
  2217. if err != nil {
  2218. sendErrorResponse(w, err.Error())
  2219. return
  2220. }
  2221. sendOK(w)
  2222. } else if opr == "deleteAll" {
  2223. //Delete all file history of given vpath
  2224. err = localversion.RemoveAllRelatedFileHistory(rpath)
  2225. if err != nil {
  2226. sendErrorResponse(w, err.Error())
  2227. return
  2228. }
  2229. sendOK(w)
  2230. } else if opr == "restore" {
  2231. //Restore file history of given history ID
  2232. historyID, err := mv(r, "histid", true)
  2233. if err != nil {
  2234. sendErrorResponse(w, "Invalid history id given")
  2235. return
  2236. }
  2237. err = localversion.RestoreFileHistory(rpath, historyID)
  2238. if err != nil {
  2239. sendErrorResponse(w, err.Error())
  2240. return
  2241. }
  2242. sendOK(w)
  2243. } else if opr == "new" {
  2244. //Create a new snapshot of this file
  2245. err = localversion.CreateFileSnapshot(rpath)
  2246. if err != nil {
  2247. sendErrorResponse(w, err.Error())
  2248. return
  2249. }
  2250. sendOK(w)
  2251. } else {
  2252. sendErrorResponse(w, "Unknown opr")
  2253. }
  2254. }
  2255. func system_fs_clearVersionHistories() {
  2256. for _, fsh := range fsHandlers {
  2257. if fsh.Filesystem != "virtual" && !fsh.ReadOnly {
  2258. localversion.CleanExpiredVersionBackups(fsh.Path, 30*86400)
  2259. }
  2260. }
  2261. }
  2262. //Translate path from and to virtual and realpath
  2263. func system_fs_handlePathTranslate(w http.ResponseWriter, r *http.Request) {
  2264. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2265. if err != nil {
  2266. sendErrorResponse(w, err.Error())
  2267. return
  2268. }
  2269. path, err := mv(r, "path", false)
  2270. if err != nil {
  2271. sendErrorResponse(w, "Invalid path given")
  2272. return
  2273. }
  2274. rpath, err := userinfo.VirtualPathToRealPath(path)
  2275. if err != nil {
  2276. //Try to convert it to virtualPath
  2277. vpath, err := userinfo.RealPathToVirtualPath(path)
  2278. if err != nil {
  2279. sendErrorResponse(w, "Unknown path given")
  2280. } else {
  2281. jsonstring, _ := json.Marshal(vpath)
  2282. sendJSONResponse(w, string(jsonstring))
  2283. }
  2284. } else {
  2285. abrpath, _ := filepath.Abs(rpath)
  2286. jsonstring, _ := json.Marshal([]string{rpath, filepath.ToSlash(abrpath)})
  2287. sendJSONResponse(w, string(jsonstring))
  2288. }
  2289. }
  2290. //Handle cache rendering with websocket pipeline
  2291. func system_fs_handleCacheRender(w http.ResponseWriter, r *http.Request) {
  2292. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2293. vpath, err := mv(r, "folder", false)
  2294. if err != nil {
  2295. sendErrorResponse(w, "Invalid folder paramter")
  2296. return
  2297. }
  2298. //Convert vpath to realpath
  2299. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2300. if err != nil {
  2301. sendErrorResponse(w, err.Error())
  2302. return
  2303. }
  2304. //Get folder sort mode
  2305. sortMode := "default"
  2306. folder := filepath.ToSlash(filepath.Clean(vpath))
  2307. if sysdb.KeyExists("fs-sortpref", userinfo.Username+"/"+folder) {
  2308. sysdb.Read("fs-sortpref", userinfo.Username+"/"+folder, &sortMode)
  2309. }
  2310. //Perform cache rendering
  2311. thumbRenderHandler.HandleLoadCache(w, r, rpath, sortMode)
  2312. }
  2313. //Handle loading of one thumbnail
  2314. func system_fs_handleThumbnailLoad(w http.ResponseWriter, r *http.Request) {
  2315. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2316. vpath, err := mv(r, "vpath", false)
  2317. if err != nil {
  2318. sendErrorResponse(w, "vpath not defined")
  2319. return
  2320. }
  2321. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2322. if err != nil {
  2323. sendErrorResponse(w, err.Error())
  2324. return
  2325. }
  2326. byteMode, _ := mv(r, "bytes", false)
  2327. if byteMode == "true" {
  2328. thumbnailBytes, err := thumbRenderHandler.LoadCacheAsBytes(rpath, false)
  2329. if err != nil {
  2330. sendErrorResponse(w, err.Error())
  2331. return
  2332. }
  2333. filetype := http.DetectContentType(thumbnailBytes)
  2334. w.Header().Add("Content-Type", filetype)
  2335. w.Write(thumbnailBytes)
  2336. } else {
  2337. thumbnailPath, err := thumbRenderHandler.LoadCache(rpath, false)
  2338. if err != nil {
  2339. sendErrorResponse(w, err.Error())
  2340. return
  2341. }
  2342. js, _ := json.Marshal(thumbnailPath)
  2343. sendJSONResponse(w, string(js))
  2344. }
  2345. }
  2346. //Handle file thumbnail caching
  2347. func system_fs_handleFolderCache(w http.ResponseWriter, r *http.Request) {
  2348. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2349. vfolderpath, err := mv(r, "folder", false)
  2350. if err != nil {
  2351. sendErrorResponse(w, "folder not defined")
  2352. return
  2353. }
  2354. rpath, err := userinfo.VirtualPathToRealPath(vfolderpath)
  2355. if err != nil {
  2356. sendErrorResponse(w, err.Error())
  2357. return
  2358. }
  2359. thumbRenderHandler.BuildCacheForFolder(rpath)
  2360. sendOK(w)
  2361. }
  2362. //Handle the get and set of sort mode of a particular folder
  2363. func system_fs_handleFolderSortModePreference(w http.ResponseWriter, r *http.Request) {
  2364. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2365. if err != nil {
  2366. sendErrorResponse(w, "User not logged in")
  2367. return
  2368. }
  2369. folder, err := mv(r, "folder", true)
  2370. if err != nil {
  2371. sendErrorResponse(w, "Invalid folder given")
  2372. return
  2373. }
  2374. opr, _ := mv(r, "opr", true)
  2375. folder = filepath.ToSlash(filepath.Clean(folder))
  2376. if opr == "" || opr == "get" {
  2377. sortMode := "default"
  2378. if sysdb.KeyExists("fs-sortpref", userinfo.Username+"/"+folder) {
  2379. sysdb.Read("fs-sortpref", userinfo.Username+"/"+folder, &sortMode)
  2380. }
  2381. js, err := json.Marshal(sortMode)
  2382. if err != nil {
  2383. sendErrorResponse(w, err.Error())
  2384. return
  2385. }
  2386. sendJSONResponse(w, string(js))
  2387. } else if opr == "set" {
  2388. sortMode, err := mv(r, "mode", true)
  2389. if err != nil {
  2390. sendErrorResponse(w, "Invalid sort mode given")
  2391. return
  2392. }
  2393. if !stringInSlice(sortMode, []string{"default", "reverse", "smallToLarge", "largeToSmall", "mostRecent", "leastRecent"}) {
  2394. sendErrorResponse(w, "Not supported sort mode: "+sortMode)
  2395. return
  2396. }
  2397. sysdb.Write("fs-sortpref", userinfo.Username+"/"+folder, sortMode)
  2398. sendOK(w)
  2399. } else {
  2400. sendErrorResponse(w, "Invalid opr mode")
  2401. return
  2402. }
  2403. }
  2404. //Handle setting and loading of file permission on Linux
  2405. func system_fs_handleFilePermission(w http.ResponseWriter, r *http.Request) {
  2406. file, err := mv(r, "file", true)
  2407. if err != nil {
  2408. sendErrorResponse(w, "Invalid file")
  2409. return
  2410. }
  2411. //Translate the file to real path
  2412. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2413. if err != nil {
  2414. sendErrorResponse(w, "User not logged in")
  2415. return
  2416. }
  2417. rpath, err := userinfo.VirtualPathToRealPath(file)
  2418. if err != nil {
  2419. sendErrorResponse(w, err.Error())
  2420. return
  2421. }
  2422. newMode, _ := mv(r, "mode", true)
  2423. if newMode == "" {
  2424. //Read the file mode
  2425. //Check if the file exists
  2426. if !fileExists(rpath) {
  2427. sendErrorResponse(w, "File not exists!")
  2428. return
  2429. }
  2430. //Read the file permission
  2431. filePermission, err := fsp.GetFilePermissions(rpath)
  2432. if err != nil {
  2433. sendErrorResponse(w, err.Error())
  2434. return
  2435. }
  2436. //Send the file permission to client
  2437. js, _ := json.Marshal(filePermission)
  2438. sendJSONResponse(w, string(js))
  2439. } else {
  2440. //Set the file mode
  2441. //Check if the file exists
  2442. if !fileExists(rpath) {
  2443. sendErrorResponse(w, "File not exists!")
  2444. return
  2445. }
  2446. //Check if windows. If yes, ignore this request
  2447. if runtime.GOOS == "windows" {
  2448. sendErrorResponse(w, "Windows host not supported")
  2449. return
  2450. }
  2451. //Check if this user has permission to change the file permission
  2452. //Aka user must be 1. This is his own folder or 2. Admin
  2453. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(file)
  2454. if fsh.Hierarchy == "user" {
  2455. //Always ok as this is owned by the user
  2456. } else if fsh.Hierarchy == "public" {
  2457. //Require admin
  2458. if userinfo.IsAdmin() == false {
  2459. sendErrorResponse(w, "Permission Denied")
  2460. return
  2461. }
  2462. } else {
  2463. //Not implemeneted. Require admin
  2464. if userinfo.IsAdmin() == false {
  2465. sendErrorResponse(w, "Permission Denied")
  2466. return
  2467. }
  2468. }
  2469. //Be noted that if the system is not running in sudo mode,
  2470. //File permission change might not works.
  2471. err := fsp.SetFilePermisson(rpath, newMode)
  2472. if err != nil {
  2473. sendErrorResponse(w, err.Error())
  2474. return
  2475. } else {
  2476. sendOK(w)
  2477. }
  2478. }
  2479. }
  2480. //Check if the given filepath is and must inside the given directory path.
  2481. //You can pass both as relative
  2482. func system_fs_checkFileInDirectory(filesourcepath string, directory string) bool {
  2483. filepathAbs, err := filepath.Abs(filesourcepath)
  2484. if err != nil {
  2485. return false
  2486. }
  2487. directoryAbs, err := filepath.Abs(directory)
  2488. if err != nil {
  2489. return false
  2490. }
  2491. //Check if the filepathabs contain directoryAbs
  2492. if strings.Contains(filepathAbs, directoryAbs) {
  2493. return true
  2494. } else {
  2495. return false
  2496. }
  2497. }
  2498. //Clear the old files inside the tmp file
  2499. func system_fs_clearOldTmpFiles() {
  2500. filesToBeDelete := []string{}
  2501. tmpAbs, _ := filepath.Abs(*tmp_directory)
  2502. filepath.Walk(*tmp_directory, func(path string, info os.FileInfo, err error) error {
  2503. if filepath.Base(path) != "aofs.db" && filepath.Base(path) != "aofs.db.lock" {
  2504. //Check if root folders. Do not delete root folders
  2505. parentAbs, _ := filepath.Abs(filepath.Dir(path))
  2506. if tmpAbs == parentAbs {
  2507. //Root folder. Do not remove
  2508. return nil
  2509. }
  2510. //Get its modification time
  2511. modTime, err := fs.GetModTime(path)
  2512. if err != nil {
  2513. return nil
  2514. }
  2515. //Check if mod time is more than 24 hours ago
  2516. if time.Now().Unix()-modTime > int64(*maxTempFileKeepTime) {
  2517. //Delete OK
  2518. filesToBeDelete = append(filesToBeDelete, path)
  2519. }
  2520. }
  2521. return nil
  2522. })
  2523. //Remove all files from the delete list
  2524. for _, fileToBeDelete := range filesToBeDelete {
  2525. os.RemoveAll(fileToBeDelete)
  2526. }
  2527. }