share.go 29 KB

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