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.

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