file_system.go 77 KB

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