file_system.go 84 KB

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