Contains the Concourse pipeline definition for building a line-server container
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.3 KiB

  1. package main
  2. import (
  3. "io"
  4. "net/http"
  5. "net/url"
  6. "strconv"
  7. "strings"
  8. "github.com/andreimarcu/linx-server/backends"
  9. "github.com/andreimarcu/linx-server/expiry"
  10. "github.com/zenazn/goji/web"
  11. )
  12. func fileServeHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  13. fileName := c.URLParams["name"]
  14. metadata, err := checkFile(fileName)
  15. if err == backends.NotFoundErr {
  16. notFoundHandler(c, w, r)
  17. return
  18. } else if err == backends.BadMetadata {
  19. oopsHandler(c, w, r, RespAUTO, "Corrupt metadata.")
  20. return
  21. } else if err != nil {
  22. oopsHandler(c, w, r, RespAUTO, err.Error())
  23. return
  24. }
  25. if !Config.allowHotlink {
  26. referer := r.Header.Get("Referer")
  27. u, _ := url.Parse(referer)
  28. p, _ := url.Parse(getSiteURL(r))
  29. if referer != "" && !sameOrigin(u, p) {
  30. http.Redirect(w, r, Config.sitePath+fileName, 303)
  31. return
  32. }
  33. }
  34. w.Header().Set("Content-Security-Policy", Config.fileContentSecurityPolicy)
  35. w.Header().Set("Referrer-Policy", Config.fileReferrerPolicy)
  36. _, reader, err := storageBackend.Get(fileName)
  37. if err != nil {
  38. oopsHandler(c, w, r, RespAUTO, err.Error())
  39. }
  40. w.Header().Set("Content-Type", metadata.Mimetype)
  41. w.Header().Set("Content-Length", strconv.FormatInt(metadata.Size, 10))
  42. w.Header().Set("Etag", metadata.Sha256sum)
  43. w.Header().Set("Cache-Control", "max-age=0")
  44. if r.Method != "HEAD" {
  45. defer reader.Close()
  46. if _, err = io.CopyN(w, reader, metadata.Size); err != nil {
  47. oopsHandler(c, w, r, RespAUTO, err.Error())
  48. }
  49. }
  50. }
  51. func staticHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  52. path := r.URL.Path
  53. if path[len(path)-1:] == "/" {
  54. notFoundHandler(c, w, r)
  55. return
  56. } else {
  57. if path == "/favicon.ico" {
  58. path = Config.sitePath + "/static/images/favicon.gif"
  59. }
  60. filePath := strings.TrimPrefix(path, Config.sitePath+"static/")
  61. file, err := staticBox.Open(filePath)
  62. if err != nil {
  63. notFoundHandler(c, w, r)
  64. return
  65. }
  66. w.Header().Set("Etag", timeStartedStr)
  67. w.Header().Set("Cache-Control", "max-age=86400")
  68. http.ServeContent(w, r, filePath, timeStarted, file)
  69. return
  70. }
  71. }
  72. func checkFile(filename string) (metadata backends.Metadata, err error) {
  73. metadata, err = storageBackend.Head(filename)
  74. if err != nil {
  75. return
  76. }
  77. if expiry.IsTsExpired(metadata.Expiry) {
  78. storageBackend.Delete(filename)
  79. err = backends.NotFoundErr
  80. return
  81. }
  82. return
  83. }