file_system.go 101 KB

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