share.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. package share
  2. /*
  3. Arozos File Share Manager
  4. author: tobychui
  5. This module handle file share request and other stuffs
  6. */
  7. import (
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "image"
  12. "image/color"
  13. "image/draw"
  14. "image/jpeg"
  15. "io"
  16. "io/fs"
  17. "io/ioutil"
  18. "log"
  19. "math"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "path/filepath"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/golang/freetype"
  28. "github.com/nfnt/resize"
  29. uuid "github.com/satori/go.uuid"
  30. "github.com/valyala/fasttemplate"
  31. "imuslab.com/arozos/mod/auth"
  32. "imuslab.com/arozos/mod/common"
  33. filesystem "imuslab.com/arozos/mod/filesystem"
  34. "imuslab.com/arozos/mod/filesystem/metadata"
  35. "imuslab.com/arozos/mod/share/shareEntry"
  36. "imuslab.com/arozos/mod/user"
  37. )
  38. type Options struct {
  39. AuthAgent *auth.AuthAgent
  40. UserHandler *user.UserHandler
  41. ShareEntryTable *shareEntry.ShareEntryTable
  42. HostName string
  43. TmpFolder string
  44. }
  45. type Manager struct {
  46. options Options
  47. }
  48. //Create a new Share Manager
  49. func NewShareManager(options Options) *Manager {
  50. //Return a new manager object
  51. return &Manager{
  52. options: options,
  53. }
  54. }
  55. func (s *Manager) HandleOPGServing(w http.ResponseWriter, r *http.Request, shareID string) {
  56. shareEntry := s.GetShareObjectFromUUID(shareID)
  57. if shareEntry == nil {
  58. //This share is not valid
  59. http.NotFound(w, r)
  60. return
  61. }
  62. //Overlap and generate opg
  63. //Load in base template
  64. baseTemplate, err := os.Open("./system/share/default_opg.png")
  65. if err != nil {
  66. fmt.Println("[share/opg] " + err.Error())
  67. http.NotFound(w, r)
  68. return
  69. }
  70. base, _, err := image.Decode(baseTemplate)
  71. if err != nil {
  72. fmt.Println("[share/opg] " + err.Error())
  73. http.NotFound(w, r)
  74. return
  75. }
  76. //Create base canvas
  77. rx := image.Rectangle{image.Point{0, 0}, base.Bounds().Size()}
  78. resultopg := image.NewRGBA(rx)
  79. draw.Draw(resultopg, base.Bounds(), base, image.Point{0, 0}, draw.Src)
  80. //Append filename to the image
  81. fontBytes, err := ioutil.ReadFile("./system/share/fonts/TaipeiSansTCBeta-Light.ttf")
  82. if err != nil {
  83. fmt.Println("[share/opg] " + err.Error())
  84. http.NotFound(w, r)
  85. return
  86. }
  87. utf8Font, err := freetype.ParseFont(fontBytes)
  88. if err != nil {
  89. fmt.Println("[share/opg] " + err.Error())
  90. http.NotFound(w, r)
  91. return
  92. }
  93. fontSize := float64(42)
  94. ctx := freetype.NewContext()
  95. ctx.SetDPI(72)
  96. ctx.SetFont(utf8Font)
  97. ctx.SetFontSize(fontSize)
  98. ctx.SetClip(resultopg.Bounds())
  99. ctx.SetDst(resultopg)
  100. ctx.SetSrc(image.NewUniform(color.RGBA{255, 255, 255, 255}))
  101. //Check if we need to split the filename into two lines
  102. filename := filepath.Base(shareEntry.FileRealPath)
  103. filenameOnly := strings.TrimSuffix(filename, filepath.Ext(filename))
  104. fs := filesystem.GetFileSize(shareEntry.FileRealPath)
  105. shareMeta := filepath.Ext(shareEntry.FileRealPath) + " / " + filesystem.GetFileDisplaySize(fs, 2)
  106. if isDir(shareEntry.FileRealPath) {
  107. fs, fc := filesystem.GetDirctorySize(shareEntry.FileRealPath, false)
  108. shareMeta = strconv.Itoa(fc) + " items / " + filesystem.GetFileDisplaySize(fs, 2)
  109. }
  110. if len([]rune(filename)) > 20 {
  111. //Split into lines
  112. lines := []string{}
  113. for i := 0; i < len([]rune(filenameOnly)); i += 20 {
  114. endPos := int(math.Min(float64(len([]rune(filenameOnly))), float64(i+20)))
  115. lines = append(lines, string([]rune(filenameOnly)[i:endPos]))
  116. }
  117. for j, line := range lines {
  118. pt := freetype.Pt(100, (j+1)*60+int(ctx.PointToFixed(fontSize)>>6))
  119. _, err = ctx.DrawString(line, pt)
  120. if err != nil {
  121. fmt.Println("[share/opg] " + err.Error())
  122. return
  123. }
  124. }
  125. fontSize = 36
  126. ctx.SetFontSize(fontSize)
  127. pt := freetype.Pt(100, (len(lines)+1)*60+int(ctx.PointToFixed(fontSize)>>6))
  128. _, err = ctx.DrawString(shareMeta, pt)
  129. if err != nil {
  130. fmt.Println("[share/opg] " + err.Error())
  131. http.NotFound(w, r)
  132. return
  133. }
  134. } else {
  135. //One liner
  136. pt := freetype.Pt(100, 60+int(ctx.PointToFixed(fontSize)>>6))
  137. _, err = ctx.DrawString(filenameOnly, pt)
  138. if err != nil {
  139. fmt.Println("[share/opg] " + err.Error())
  140. http.NotFound(w, r)
  141. return
  142. }
  143. fontSize = 36
  144. ctx.SetFontSize(fontSize)
  145. pt = freetype.Pt(100, 120+int(ctx.PointToFixed(fontSize)>>6))
  146. _, err = ctx.DrawString(shareMeta, pt)
  147. if err != nil {
  148. fmt.Println("[share/opg] " + err.Error())
  149. http.NotFound(w, r)
  150. return
  151. }
  152. }
  153. //Get thumbnail
  154. ownerinfo, err := s.options.UserHandler.GetUserInfoFromUsername(shareEntry.Owner)
  155. if err != nil {
  156. fmt.Println("[share/opg] " + err.Error())
  157. http.NotFound(w, r)
  158. return
  159. }
  160. fsh, err := ownerinfo.GetFileSystemHandlerFromVirtualPath(shareEntry.FileVirtualPath)
  161. if err != nil {
  162. fmt.Println("[share/opg] " + err.Error())
  163. http.NotFound(w, r)
  164. return
  165. }
  166. rpath, _ := fsh.FileSystemAbstraction.VirtualPathToRealPath(shareEntry.FileVirtualPath, shareEntry.Owner)
  167. cacheFileImagePath, err := metadata.GetCacheFilePath(fsh, rpath)
  168. if err == nil {
  169. //We got a thumbnail for this file. Render it as well
  170. thumbnailFile, err := os.Open(cacheFileImagePath)
  171. if err != nil {
  172. fmt.Println("[share/opg] " + err.Error())
  173. http.NotFound(w, r)
  174. return
  175. }
  176. thumb, _, err := image.Decode(thumbnailFile)
  177. if err != nil {
  178. fmt.Println("[share/opg] " + err.Error())
  179. http.NotFound(w, r)
  180. return
  181. }
  182. resizedThumb := resize.Resize(250, 0, thumb, resize.Lanczos3)
  183. draw.Draw(resultopg, resultopg.Bounds(), resizedThumb, image.Point{-(resultopg.Bounds().Dx() - resizedThumb.Bounds().Dx() - 90), -60}, draw.Over)
  184. } else if isDir(shareEntry.FileRealPath) {
  185. //Is directory but no thumbnail. Use default foldr share thumbnail
  186. thumbnailFile, err := os.Open("./system/share/folder.png")
  187. if err != nil {
  188. fmt.Println("[share/opg] " + err.Error())
  189. http.NotFound(w, r)
  190. return
  191. }
  192. thumb, _, err := image.Decode(thumbnailFile)
  193. if err != nil {
  194. fmt.Println("[share/opg] " + err.Error())
  195. http.NotFound(w, r)
  196. return
  197. }
  198. resizedThumb := resize.Resize(250, 0, thumb, resize.Lanczos3)
  199. draw.Draw(resultopg, resultopg.Bounds(), resizedThumb, image.Point{-(resultopg.Bounds().Dx() - resizedThumb.Bounds().Dx() - 90), -60}, draw.Over)
  200. }
  201. w.Header().Set("Content-Type", "image/jpeg")
  202. jpeg.Encode(w, resultopg, nil)
  203. }
  204. //Main function for handle share. Must be called with http.HandleFunc (No auth)
  205. func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
  206. //New download method variables
  207. subpathElements := []string{}
  208. directDownload := false
  209. directServe := false
  210. relpath := ""
  211. id, err := mv(r, "id", false)
  212. if err != nil {
  213. //ID is not defined in the URL paramter. New ID defination is based on the subpath content
  214. requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
  215. subpathElements = strings.Split(requestURI[1:], "/")
  216. if len(subpathElements) == 2 {
  217. //E.g. /share/{id} => Show the download page
  218. id = subpathElements[1]
  219. //Check if there is missing / at the end. Redirect if true
  220. if r.URL.Path[len(r.URL.Path)-1:] != "/" {
  221. http.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
  222. return
  223. }
  224. } else if len(subpathElements) >= 3 {
  225. //E.g. /share/download/{uuid} or /share/preview/{uuid}
  226. id = subpathElements[2]
  227. if subpathElements[1] == "download" {
  228. directDownload = true
  229. //Check if this contain a subpath
  230. if len(subpathElements) > 3 {
  231. relpath = strings.Join(subpathElements[3:], "/")
  232. }
  233. } else if subpathElements[1] == "preview" {
  234. directServe = true
  235. } else if len(subpathElements) == 3 {
  236. //Check if the last element is the filename
  237. if strings.Contains(subpathElements[2], ".") {
  238. //Share link contain filename. Redirect to share interface
  239. http.Redirect(w, r, "./", http.StatusTemporaryRedirect)
  240. return
  241. } else {
  242. //Incorrect operation type
  243. w.WriteHeader(http.StatusBadRequest)
  244. w.Header().Set("Content-Type", "text/plain") // this
  245. w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
  246. return
  247. }
  248. } else if len(subpathElements) >= 4 {
  249. if subpathElements[1] == "opg" {
  250. //Handle serving opg preview image, usually with
  251. // /share/opg/{req.timestamp}/{uuid}
  252. s.HandleOPGServing(w, r, subpathElements[3])
  253. return
  254. }
  255. //Invalid operation type
  256. w.WriteHeader(http.StatusBadRequest)
  257. w.Header().Set("Content-Type", "text/plain") // this
  258. w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
  259. return
  260. }
  261. } else if len(subpathElements) == 1 {
  262. //ID is missing. Serve the id input page
  263. content, err := ioutil.ReadFile("system/share/index.html")
  264. if err != nil {
  265. //Handling index not found. Is server updated correctly?
  266. w.WriteHeader(http.StatusInternalServerError)
  267. w.Write([]byte("500 - Internal Server Error"))
  268. return
  269. }
  270. t := fasttemplate.New(string(content), "{{", "}}")
  271. s := t.ExecuteString(map[string]interface{}{
  272. "hostname": s.options.HostName,
  273. })
  274. w.Write([]byte(s))
  275. return
  276. } else {
  277. http.NotFound(w, r)
  278. return
  279. }
  280. } else {
  281. //Parse and redirect to new share path
  282. download, _ := mv(r, "download", false)
  283. if download == "true" {
  284. directDownload = true
  285. }
  286. serve, _ := mv(r, "serve", false)
  287. if serve == "true" {
  288. directServe = true
  289. }
  290. relpath, _ = mv(r, "rel", false)
  291. redirectURL := "./" + id + "/"
  292. if directDownload == true {
  293. redirectURL = "./download/" + id + "/"
  294. }
  295. http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
  296. return
  297. }
  298. //Check if id exists
  299. val, ok := s.options.ShareEntryTable.UrlToFileMap.Load(id)
  300. if ok {
  301. //Parse the option structure
  302. shareOption := val.(*shareEntry.ShareOption)
  303. //Check for permission
  304. if shareOption.Permission == "anyone" {
  305. //OK to proceed
  306. } else if shareOption.Permission == "signedin" {
  307. if !s.options.AuthAgent.CheckAuth(r) {
  308. //Redirect to login page
  309. if directDownload || directServe {
  310. w.WriteHeader(http.StatusUnauthorized)
  311. w.Write([]byte("401 - Unauthorized"))
  312. } else {
  313. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  314. }
  315. return
  316. } else {
  317. //Ok to proccedd
  318. }
  319. } else if shareOption.Permission == "samegroup" {
  320. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  321. if err != nil {
  322. if directDownload || directServe {
  323. w.WriteHeader(http.StatusUnauthorized)
  324. w.Write([]byte("401 - Unauthorized"))
  325. } else {
  326. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  327. }
  328. return
  329. }
  330. //Check if all the user groups are inside the share owner groups
  331. valid := true
  332. thisUsersGroupByName := []string{}
  333. for _, pg := range thisuserinfo.PermissionGroup {
  334. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  335. }
  336. for _, allowedpg := range shareOption.Accessibles {
  337. if inArray(thisUsersGroupByName, allowedpg) {
  338. //This required group is inside this user's group. OK
  339. } else {
  340. //This required group is not inside user's group. Reject
  341. valid = false
  342. }
  343. }
  344. if !valid {
  345. //Serve permission denied page
  346. if directDownload || directServe {
  347. w.WriteHeader(http.StatusForbidden)
  348. w.Write([]byte("401 - Forbidden"))
  349. } else {
  350. ServePermissionDeniedPage(w)
  351. }
  352. return
  353. }
  354. } else if shareOption.Permission == "users" {
  355. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  356. if err != nil {
  357. //User not logged in. Redirect to login page
  358. if directDownload || directServe {
  359. w.WriteHeader(http.StatusUnauthorized)
  360. w.Write([]byte("401 - Unauthorized"))
  361. } else {
  362. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  363. }
  364. return
  365. }
  366. //Check if username in the allowed user list
  367. if !inArray(shareOption.Accessibles, thisuserinfo.Username) && shareOption.Owner != thisuserinfo.Username {
  368. //Serve permission denied page
  369. if directDownload || directServe {
  370. w.WriteHeader(http.StatusForbidden)
  371. w.Write([]byte("401 - Forbidden"))
  372. } else {
  373. ServePermissionDeniedPage(w)
  374. }
  375. return
  376. }
  377. } else if shareOption.Permission == "groups" {
  378. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  379. if err != nil {
  380. //User not logged in. Redirect to login page
  381. if directDownload || directServe {
  382. w.WriteHeader(http.StatusUnauthorized)
  383. w.Write([]byte("401 - Unauthorized"))
  384. } else {
  385. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  386. }
  387. return
  388. }
  389. allowAccess := false
  390. thisUsersGroupByName := []string{}
  391. for _, pg := range thisuserinfo.PermissionGroup {
  392. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  393. }
  394. for _, thisUserPg := range thisUsersGroupByName {
  395. if inArray(shareOption.Accessibles, thisUserPg) {
  396. allowAccess = true
  397. }
  398. }
  399. if !allowAccess {
  400. //Serve permission denied page
  401. if directDownload || directServe {
  402. w.WriteHeader(http.StatusForbidden)
  403. w.Write([]byte("401 - Forbidden"))
  404. } else {
  405. ServePermissionDeniedPage(w)
  406. }
  407. return
  408. }
  409. } else {
  410. //Unsupported mode. Show notfound
  411. http.NotFound(w, r)
  412. return
  413. }
  414. //Resolve the fsh from the entry
  415. owner, err := s.options.UserHandler.GetUserInfoFromUsername(shareOption.Owner)
  416. if err != nil {
  417. w.WriteHeader(http.StatusForbidden)
  418. w.Write([]byte("401 - Share account not exists"))
  419. return
  420. }
  421. targetFsh, err := owner.GetFileSystemHandlerFromVirtualPath(shareOption.FileVirtualPath)
  422. if err != nil {
  423. w.WriteHeader(http.StatusInternalServerError)
  424. w.Write([]byte("500 - Unable to load Shared File"))
  425. return
  426. }
  427. targetFshAbs := targetFsh.FileSystemAbstraction
  428. fileRuntimeAbsPath, _ := targetFshAbs.VirtualPathToRealPath(shareOption.FileVirtualPath, owner.Username)
  429. if !targetFshAbs.FileExists(fileRuntimeAbsPath) {
  430. http.NotFound(w, r)
  431. return
  432. }
  433. //Serve the download page
  434. if targetFshAbs.IsDir(fileRuntimeAbsPath) {
  435. //This share is a folder
  436. type File struct {
  437. Filename string
  438. RelPath string
  439. Filesize string
  440. IsDir bool
  441. }
  442. if directDownload {
  443. if relpath != "" {
  444. //User specified a specific file within the directory. Escape the relpath
  445. targetFilepath := filepath.Join(fileRuntimeAbsPath, relpath)
  446. //Check if file exists
  447. if !targetFshAbs.FileExists(targetFilepath) {
  448. http.NotFound(w, r)
  449. return
  450. }
  451. //Validate the absolute path to prevent path escape
  452. reqPath := filepath.ToSlash(filepath.Clean(targetFilepath))
  453. rootPath, _ := targetFshAbs.VirtualPathToRealPath(shareOption.FileVirtualPath, shareOption.Owner)
  454. if !strings.HasPrefix(reqPath, rootPath) {
  455. //Directory escape detected
  456. w.WriteHeader(http.StatusBadRequest)
  457. w.Write([]byte("400 - Bad Request: Invalid relative path"))
  458. return
  459. }
  460. //Serve the target file
  461. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(targetFilepath)), "+", "%20"))
  462. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  463. //http.ServeFile(w, r, targetFilepath)
  464. f, _ := targetFshAbs.ReadStream(targetFilepath)
  465. io.Copy(w, f)
  466. f.Close()
  467. } else {
  468. //Download this folder as zip
  469. //Create a zip using ArOZ Zipper, tmp zip files are located under tmp/share-cache/*.zip
  470. tmpFolder := s.options.TmpFolder
  471. tmpFolder = filepath.Join(tmpFolder, "share-cache")
  472. os.MkdirAll(tmpFolder, 0755)
  473. targetZipFilename := filepath.Join(tmpFolder, filepath.Base(fileRuntimeAbsPath)) + ".zip"
  474. //Check if the target fs require buffer
  475. zippingSource := shareOption.FileRealPath
  476. localBuff := ""
  477. if targetFsh.RequireBuffer {
  478. //Buffer all the required files for zipping
  479. localBuff = filepath.Join(tmpFolder, uuid.NewV4().String(), filepath.Base(fileRuntimeAbsPath))
  480. os.MkdirAll(localBuff, 0755)
  481. //Buffer all files into tmp folder
  482. targetFshAbs.Walk(fileRuntimeAbsPath, func(path string, info fs.FileInfo, err error) error {
  483. relPath := strings.TrimPrefix(filepath.ToSlash(path), filepath.ToSlash(fileRuntimeAbsPath))
  484. localPath := filepath.Join(localBuff, relPath)
  485. if info.IsDir() {
  486. os.MkdirAll(localPath, 0755)
  487. } else {
  488. f, err := targetFshAbs.ReadStream(path)
  489. if err != nil {
  490. log.Println("[Share] Buffer and zip download operation failed: ", err)
  491. }
  492. dest, err := os.OpenFile(localPath, os.O_CREATE|os.O_WRONLY, 0775)
  493. if err != nil {
  494. log.Println("[Share] Buffer and zip download operation failed: ", err)
  495. }
  496. _, err = io.Copy(dest, f)
  497. if err != nil {
  498. log.Println("[Share] Buffer and zip download operation failed: ", err)
  499. }
  500. f.Close()
  501. }
  502. return nil
  503. })
  504. zippingSource = localBuff
  505. }
  506. //Build a filelist
  507. err := filesystem.ArozZipFile([]string{zippingSource}, targetZipFilename, false)
  508. if err != nil {
  509. //Failed to create zip file
  510. w.WriteHeader(http.StatusInternalServerError)
  511. w.Write([]byte("500 - Internal Server Error: Zip file creation failed"))
  512. log.Println("Failed to create zip file for share download: " + err.Error())
  513. return
  514. }
  515. //Serve thje zip file
  516. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20")+".zip")
  517. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  518. http.ServeFile(w, r, targetZipFilename)
  519. //Remove the buffer file if exists
  520. if targetFsh.RequireBuffer {
  521. os.RemoveAll(filepath.Dir(localBuff))
  522. }
  523. }
  524. } else if directServe {
  525. //Folder provide no direct serve method.
  526. w.WriteHeader(http.StatusBadRequest)
  527. w.Write([]byte("400 - Cannot preview folder type shares"))
  528. return
  529. } else {
  530. //Show download page. Do not allow serving
  531. content, err := ioutil.ReadFile("./system/share/downloadPageFolder.html")
  532. if err != nil {
  533. http.NotFound(w, r)
  534. return
  535. }
  536. //Get file size
  537. fsize, fcount := targetFsh.GetDirctorySizeFromRealPath(fileRuntimeAbsPath, false)
  538. //Build the tree list of the folder
  539. treeList := map[string][]File{}
  540. err = targetFshAbs.Walk(filepath.Clean(fileRuntimeAbsPath), func(file string, info os.FileInfo, err error) error {
  541. if err != nil {
  542. //If error skip this
  543. return nil
  544. }
  545. if filepath.Base(file)[:1] != "." {
  546. fileSize := targetFshAbs.GetFileSize(file)
  547. if targetFshAbs.IsDir(file) {
  548. fileSize, _ = targetFsh.GetDirctorySizeFromRealPath(file, false)
  549. }
  550. relPath, err := filepath.Rel(fileRuntimeAbsPath, file)
  551. if err != nil {
  552. relPath = ""
  553. }
  554. relPath = filepath.ToSlash(filepath.Clean(relPath))
  555. relDir := filepath.ToSlash(filepath.Dir(relPath))
  556. if relPath == "." {
  557. //The root file object. Skip this
  558. return nil
  559. }
  560. treeList[relDir] = append(treeList[relDir], File{
  561. Filename: filepath.Base(file),
  562. RelPath: filepath.ToSlash(relPath),
  563. Filesize: filesystem.GetFileDisplaySize(fileSize, 2),
  564. IsDir: targetFshAbs.IsDir(file),
  565. })
  566. }
  567. return nil
  568. })
  569. if err != nil {
  570. w.WriteHeader(http.StatusInternalServerError)
  571. w.Write([]byte("500 - Internal Server Error"))
  572. return
  573. }
  574. tl, _ := json.Marshal(treeList)
  575. //Get modification time
  576. fmodtime, _ := targetFshAbs.GetModTime(fileRuntimeAbsPath)
  577. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  578. t := fasttemplate.New(string(content), "{{", "}}")
  579. s := t.ExecuteString(map[string]interface{}{
  580. "hostname": s.options.HostName,
  581. "host": r.Host,
  582. "reqid": id,
  583. "mime": "application/x-directory",
  584. "size": filesystem.GetFileDisplaySize(fsize, 2),
  585. "filecount": strconv.Itoa(fcount),
  586. "modtime": timeString,
  587. "downloadurl": "../../share/download/" + id,
  588. "filename": filepath.Base(fileRuntimeAbsPath),
  589. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  590. "requri": "//" + r.Host + r.URL.Path,
  591. "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
  592. "treelist": tl,
  593. "downloaduuid": id,
  594. })
  595. w.Write([]byte(s))
  596. return
  597. }
  598. } else {
  599. //This share is a file
  600. if directDownload {
  601. //Serve the file directly
  602. w.Header().Set("Content-Disposition", "attachment; filename=\""+filepath.Base(shareOption.FileVirtualPath)+"\"")
  603. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  604. f, _ := targetFshAbs.ReadStream(fileRuntimeAbsPath)
  605. io.Copy(w, f)
  606. f.Close()
  607. } else if directServe {
  608. w.Header().Set("Access-Control-Allow-Origin", "*")
  609. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  610. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  611. f, _ := targetFshAbs.ReadStream(fileRuntimeAbsPath)
  612. io.Copy(w, f)
  613. f.Close()
  614. } else {
  615. //Serve the download page
  616. content, err := ioutil.ReadFile("./system/share/downloadPage.html")
  617. if err != nil {
  618. http.NotFound(w, r)
  619. return
  620. }
  621. //Get file mime type
  622. mime, ext, err := filesystem.GetMime(fileRuntimeAbsPath)
  623. if err != nil {
  624. mime = "Unknown"
  625. }
  626. //Load the preview template
  627. templateRoot := "./system/share/"
  628. previewTemplate := ""
  629. if ext == ".mp4" || ext == ".webm" {
  630. previewTemplate = filepath.Join(templateRoot, "video.html")
  631. } else if ext == ".mp3" || ext == ".wav" || ext == ".flac" || ext == ".ogg" {
  632. previewTemplate = filepath.Join(templateRoot, "audio.html")
  633. } else if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" {
  634. previewTemplate = filepath.Join(templateRoot, "image.html")
  635. } else if ext == ".pdf" {
  636. previewTemplate = filepath.Join(templateRoot, "iframe.html")
  637. } else {
  638. //Format do not support preview. Use the default.html
  639. previewTemplate = filepath.Join(templateRoot, "default.html")
  640. }
  641. tp, err := ioutil.ReadFile(previewTemplate)
  642. if err != nil {
  643. tp = []byte("")
  644. }
  645. //Merge two templates
  646. content = []byte(strings.ReplaceAll(string(content), "{{previewer}}", string(tp)))
  647. //Get file size
  648. fsize := targetFshAbs.GetFileSize(fileRuntimeAbsPath)
  649. //Get modification time
  650. fmodtime, _ := targetFshAbs.GetModTime(fileRuntimeAbsPath)
  651. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  652. //Check if ext match with filepath ext
  653. displayExt := ext
  654. if ext != filepath.Ext(fileRuntimeAbsPath) {
  655. displayExt = filepath.Ext(fileRuntimeAbsPath) + " (" + ext + ")"
  656. }
  657. t := fasttemplate.New(string(content), "{{", "}}")
  658. s := t.ExecuteString(map[string]interface{}{
  659. "hostname": s.options.HostName,
  660. "host": r.Host,
  661. "reqid": id,
  662. "requri": "//" + r.Host + r.URL.Path,
  663. "mime": mime,
  664. "ext": displayExt,
  665. "size": filesystem.GetFileDisplaySize(fsize, 2),
  666. "modtime": timeString,
  667. "downloadurl": "../../share/download/" + id + "/" + filepath.Base(fileRuntimeAbsPath),
  668. "preview_url": "/share/preview/" + id + "/",
  669. "filename": filepath.Base(fileRuntimeAbsPath),
  670. "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
  671. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  672. })
  673. w.Write([]byte(s))
  674. return
  675. }
  676. }
  677. } else {
  678. //This share not exists
  679. if directDownload {
  680. //Send 404 header
  681. http.NotFound(w, r)
  682. return
  683. } else {
  684. //Send not found page
  685. content, err := ioutil.ReadFile("./system/share/notfound.html")
  686. if err != nil {
  687. http.NotFound(w, r)
  688. return
  689. }
  690. t := fasttemplate.New(string(content), "{{", "}}")
  691. s := t.ExecuteString(map[string]interface{}{
  692. "hostname": s.options.HostName,
  693. "reqid": id,
  694. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  695. })
  696. w.Write([]byte(s))
  697. return
  698. }
  699. }
  700. }
  701. //Check if a file is shared
  702. func (s *Manager) HandleShareCheck(w http.ResponseWriter, r *http.Request) {
  703. //Get the vpath from paramters
  704. vpath, err := mv(r, "path", true)
  705. if err != nil {
  706. sendErrorResponse(w, "Invalid path given")
  707. return
  708. }
  709. //Get userinfo
  710. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  711. if err != nil {
  712. sendErrorResponse(w, "User not logged in")
  713. return
  714. }
  715. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  716. pathHash := shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
  717. type Result struct {
  718. IsShared bool
  719. ShareUUID *shareEntry.ShareOption
  720. }
  721. //Check if share exists
  722. shareExists := s.options.ShareEntryTable.FileIsShared(pathHash)
  723. if !shareExists {
  724. //Share not exists
  725. js, _ := json.Marshal(Result{
  726. IsShared: false,
  727. ShareUUID: &shareEntry.ShareOption{},
  728. })
  729. sendJSONResponse(w, string(js))
  730. } else {
  731. //Share exists
  732. thisSharedInfo := s.options.ShareEntryTable.GetShareObjectFromPathHash(pathHash)
  733. js, _ := json.Marshal(Result{
  734. IsShared: true,
  735. ShareUUID: thisSharedInfo,
  736. })
  737. sendJSONResponse(w, string(js))
  738. }
  739. }
  740. //Create new share from the given path
  741. func (s *Manager) HandleCreateNewShare(w http.ResponseWriter, r *http.Request) {
  742. //Get the vpath from paramters
  743. vpath, err := mv(r, "path", true)
  744. if err != nil {
  745. sendErrorResponse(w, "Invalid path given")
  746. return
  747. }
  748. //Get userinfo
  749. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  750. if err != nil {
  751. sendErrorResponse(w, "User not logged in")
  752. return
  753. }
  754. //Get the target fsh that this vpath come from
  755. vpathSourceFsh := userinfo.GetRootFSHFromVpathInUserScope(vpath)
  756. if vpathSourceFsh == nil {
  757. sendErrorResponse(w, "Invalid vpath given")
  758. return
  759. }
  760. share, err := s.CreateNewShare(userinfo, vpathSourceFsh, vpath)
  761. if err != nil {
  762. sendErrorResponse(w, err.Error())
  763. return
  764. }
  765. js, _ := json.Marshal(share)
  766. sendJSONResponse(w, string(js))
  767. }
  768. // Handle Share Edit.
  769. // For allowing groups / users, use the following syntax
  770. // groups:group1,group2,group3
  771. // users:user1,user2,user3
  772. // For basic modes, use the following keywords
  773. // anyone / signedin / samegroup
  774. // anyone: Anyone who has the link
  775. // signedin: Anyone logged in to this system
  776. // samegroup: The requesting user has the same (or more) user group as the share owner
  777. func (s *Manager) HandleEditShare(w http.ResponseWriter, r *http.Request) {
  778. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  779. if err != nil {
  780. sendErrorResponse(w, "User not logged in")
  781. return
  782. }
  783. uuid, err := mv(r, "uuid", true)
  784. if err != nil {
  785. sendErrorResponse(w, "Invalid path given")
  786. return
  787. }
  788. shareMode, _ := mv(r, "mode", true)
  789. if shareMode == "" {
  790. shareMode = "signedin"
  791. }
  792. //Check if share exists
  793. so := s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
  794. if so == nil {
  795. //This share url not exists
  796. sendErrorResponse(w, "Share UUID not exists")
  797. return
  798. }
  799. //Check if the user has permission to edit this share
  800. if !s.CanModifyShareEntry(userinfo, so.FileVirtualPath) {
  801. common.SendErrorResponse(w, "Permission Denied")
  802. return
  803. }
  804. //Validate and extract the storage mode
  805. ok, sharetype, settings := validateShareModes(shareMode)
  806. if !ok {
  807. sendErrorResponse(w, "Invalid share setting")
  808. return
  809. }
  810. //Analysis the sharetype
  811. if sharetype == "anyone" || sharetype == "signedin" || sharetype == "samegroup" {
  812. //Basic types.
  813. so.Permission = sharetype
  814. if sharetype == "samegroup" {
  815. //Write user groups into accessible (Must be all match inorder to allow access)
  816. userpg := []string{}
  817. for _, pg := range userinfo.PermissionGroup {
  818. userpg = append(userpg, pg.Name)
  819. }
  820. so.Accessibles = userpg
  821. }
  822. //Write changes to database
  823. s.options.ShareEntryTable.Database.Write("share", uuid, so)
  824. } else if sharetype == "groups" || sharetype == "users" {
  825. //Username or group is listed = ok
  826. so.Permission = sharetype
  827. so.Accessibles = settings
  828. //Write changes to database
  829. s.options.ShareEntryTable.Database.Write("share", uuid, so)
  830. }
  831. sendOK(w)
  832. }
  833. func (s *Manager) HandleDeleteShare(w http.ResponseWriter, r *http.Request) {
  834. //Get the vpath from paramters
  835. vpath, err := mv(r, "path", true)
  836. if err != nil {
  837. sendErrorResponse(w, "Invalid path given")
  838. return
  839. }
  840. //Get userinfo
  841. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  842. if err != nil {
  843. sendErrorResponse(w, "User not logged in")
  844. return
  845. }
  846. //Delete the share setting
  847. err = s.DeleteShare(userinfo, vpath)
  848. if err != nil {
  849. sendErrorResponse(w, err.Error())
  850. } else {
  851. sendOK(w)
  852. }
  853. }
  854. func (s *Manager) HandleListAllShares(w http.ResponseWriter, r *http.Request) {
  855. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  856. if err != nil {
  857. common.SendErrorResponse(w, "User not logged in")
  858. return
  859. }
  860. fshId, _ := common.Mv(r, "fsh", false)
  861. results := []*shareEntry.ShareOption{}
  862. if fshId == "" {
  863. //List all
  864. allFsh := userinfo.GetAllFileSystemHandler()
  865. for _, thisFsh := range allFsh {
  866. allShares := s.ListAllShareByFshId(thisFsh.UUID, userinfo)
  867. for _, thisShare := range allShares {
  868. if s.ShareIsValid(thisShare) {
  869. results = append(results, thisShare)
  870. }
  871. }
  872. }
  873. } else {
  874. //List fsh onlya
  875. targetFsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(fshId)
  876. if err != nil {
  877. common.SendErrorResponse(w, err.Error())
  878. return
  879. }
  880. sharesInThisFsh := s.ListAllShareByFshId(targetFsh.UUID, userinfo)
  881. for _, thisShare := range sharesInThisFsh {
  882. if s.ShareIsValid(thisShare) {
  883. results = append(results, thisShare)
  884. }
  885. }
  886. }
  887. js, _ := json.Marshal(results)
  888. common.SendJSONResponse(w, string(js))
  889. }
  890. //Craete a new file or folder share
  891. func (s *Manager) CreateNewShare(userinfo *user.User, srcFsh *filesystem.FileSystemHandler, vpath string) (*shareEntry.ShareOption, error) {
  892. //Translate the vpath to realpath
  893. return s.options.ShareEntryTable.CreateNewShare(srcFsh, vpath, userinfo.Username, userinfo.GetUserPermissionGroupNames())
  894. }
  895. func ServePermissionDeniedPage(w http.ResponseWriter) {
  896. w.WriteHeader(http.StatusForbidden)
  897. pageContent := []byte("Permissioned Denied")
  898. if fileExists("system/share/permissionDenied.html") {
  899. content, err := ioutil.ReadFile("system/share/permissionDenied.html")
  900. if err == nil {
  901. pageContent = content
  902. }
  903. }
  904. w.Write([]byte(pageContent))
  905. }
  906. /*
  907. Validate Share Mode string
  908. will return
  909. 1. bool => Is valid
  910. 2. permission type: {basic / groups / users}
  911. 3. mode string
  912. */
  913. func validateShareModes(mode string) (bool, string, []string) {
  914. // user:a,b,c,d
  915. validModes := []string{"anyone", "signedin", "samegroup"}
  916. if inArray(validModes, mode) {
  917. //Standard modes
  918. return true, mode, []string{}
  919. } else if len(mode) > 7 && mode[:7] == "groups:" {
  920. //Handle custom group case like groups:a,b,c,d
  921. groupList := mode[7:]
  922. if len(groupList) > 0 {
  923. groups := strings.Split(groupList, ",")
  924. return true, "groups", groups
  925. } else {
  926. //Invalid configuration
  927. return false, "groups", []string{}
  928. }
  929. } else if len(mode) > 6 && mode[:6] == "users:" {
  930. //Handle custom usersname like users:a,b,c,d
  931. userList := mode[6:]
  932. if len(userList) > 0 {
  933. users := strings.Split(userList, ",")
  934. return true, "users", users
  935. } else {
  936. //Invalid configuration
  937. return false, "users", []string{}
  938. }
  939. }
  940. return false, "", []string{}
  941. }
  942. func (s *Manager) ListAllShareByFshId(fshId string, userinfo *user.User) []*shareEntry.ShareOption {
  943. results := []*shareEntry.ShareOption{}
  944. s.options.ShareEntryTable.FileToUrlMap.Range(func(k, v interface{}) bool {
  945. thisShareOption := v.(*shareEntry.ShareOption)
  946. if (!userinfo.IsAdmin() && thisShareOption.IsAccessibleBy(userinfo.Username, userinfo.GetUserPermissionGroupNames())) || userinfo.IsAdmin() {
  947. id, _, _ := filesystem.GetIDFromVirtualPath(thisShareOption.FileVirtualPath)
  948. if id == fshId {
  949. results = append(results, thisShareOption)
  950. }
  951. }
  952. return true
  953. })
  954. return results
  955. }
  956. func (s *Manager) ShareIsValid(thisShareOption *shareEntry.ShareOption) bool {
  957. vpath := thisShareOption.FileVirtualPath
  958. userinfo, _ := s.options.UserHandler.GetUserInfoFromUsername(thisShareOption.Owner)
  959. fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  960. if err != nil {
  961. return false
  962. }
  963. fshAbs := fsh.FileSystemAbstraction
  964. rpath, _ := fshAbs.VirtualPathToRealPath(vpath, userinfo.Username)
  965. if !fshAbs.FileExists(rpath) {
  966. return false
  967. }
  968. return true
  969. }
  970. func (s *Manager) GetPathHashFromShare(thisShareOption *shareEntry.ShareOption) (string, error) {
  971. vpath := thisShareOption.FileVirtualPath
  972. userinfo, _ := s.options.UserHandler.GetUserInfoFromUsername(thisShareOption.Owner)
  973. fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  974. if err != nil {
  975. return "", err
  976. }
  977. pathHash := shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
  978. return pathHash, nil
  979. }
  980. //Check and clear shares that its pointinf files no longe exists
  981. func (s *Manager) ValidateAndClearShares() {
  982. //Iterate through all shares within the system
  983. s.options.ShareEntryTable.FileToUrlMap.Range(func(k, v interface{}) bool {
  984. thisShareOption := v.(*shareEntry.ShareOption)
  985. pathHash, err := s.GetPathHashFromShare(thisShareOption)
  986. if err != nil {
  987. //Unable to resolve path hash. Filesystem handler is gone?
  988. //s.options.ShareEntryTable.RemoveShareByUUID(thisShareOption.UUID)
  989. return true
  990. }
  991. if !s.ShareIsValid(thisShareOption) {
  992. //This share source file don't exists anymore. Remove it
  993. s.options.ShareEntryTable.RemoveShareByPathHash(pathHash)
  994. log.Println("*Share* Removing share to file: " + thisShareOption.FileRealPath + " as it no longer exists")
  995. }
  996. return true
  997. })
  998. }
  999. //Check if the user has the permission to modify this share entry
  1000. func (s *Manager) CanModifyShareEntry(userinfo *user.User, vpath string) bool {
  1001. shareEntry := s.GetShareObjectFromUserAndVpath(userinfo, vpath)
  1002. if shareEntry == nil {
  1003. //Share entry not found
  1004. return false
  1005. }
  1006. //Check if the user is the share owner or the user is admin
  1007. if userinfo.IsAdmin() {
  1008. return true
  1009. } else if userinfo.Username == shareEntry.Owner {
  1010. return true
  1011. }
  1012. return false
  1013. }
  1014. func (s *Manager) DeleteShare(userinfo *user.User, vpath string) error {
  1015. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1016. if !s.CanModifyShareEntry(userinfo, vpath) {
  1017. return errors.New("Permission denied")
  1018. }
  1019. return s.options.ShareEntryTable.DeleteShareByPathHash(ps)
  1020. }
  1021. func (s *Manager) GetShareUUIDFromUserAndVpath(userinfo *user.User, vpath string) string {
  1022. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1023. return s.options.ShareEntryTable.GetShareUUIDFromPathHash(ps)
  1024. }
  1025. func (s *Manager) GetShareObjectFromUserAndVpath(userinfo *user.User, vpath string) *shareEntry.ShareOption {
  1026. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1027. return s.options.ShareEntryTable.GetShareObjectFromPathHash(ps)
  1028. }
  1029. func (s *Manager) GetShareObjectFromUUID(uuid string) *shareEntry.ShareOption {
  1030. return s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
  1031. }
  1032. func (s *Manager) FileIsShared(userinfo *user.User, vpath string) bool {
  1033. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1034. return s.options.ShareEntryTable.FileIsShared(ps)
  1035. }
  1036. func (s *Manager) RemoveShareByUUID(userinfo *user.User, uuid string) error {
  1037. shareObject := s.GetShareObjectFromUUID(uuid)
  1038. if shareObject == nil {
  1039. return errors.New("Share entry not found")
  1040. }
  1041. if !s.CanModifyShareEntry(userinfo, shareObject.FileVirtualPath) {
  1042. return errors.New("Permission denied")
  1043. }
  1044. return s.options.ShareEntryTable.RemoveShareByUUID(uuid)
  1045. }
  1046. func getPathHashFromUsernameAndVpath(userinfo *user.User, vpath string) string {
  1047. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  1048. return shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
  1049. }