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.

public.go 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. // Copyright 2016 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package public
  4. import (
  5. "bytes"
  6. "io"
  7. "net/http"
  8. "os"
  9. "path"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/modules/assetfs"
  13. "code.gitea.io/gitea/modules/container"
  14. "code.gitea.io/gitea/modules/httpcache"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. )
  19. func CustomAssets() *assetfs.Layer {
  20. return assetfs.Local("custom", setting.CustomPath, "public")
  21. }
  22. func AssetFS() *assetfs.LayeredFS {
  23. return assetfs.Layered(CustomAssets(), BuiltinAssets())
  24. }
  25. // AssetsHandlerFunc implements the static handler for serving custom or original assets.
  26. func AssetsHandlerFunc(prefix string) http.HandlerFunc {
  27. assetFS := AssetFS()
  28. prefix = strings.TrimSuffix(prefix, "/") + "/"
  29. return func(resp http.ResponseWriter, req *http.Request) {
  30. subPath := req.URL.Path
  31. if !strings.HasPrefix(subPath, prefix) {
  32. return
  33. }
  34. subPath = strings.TrimPrefix(subPath, prefix)
  35. if req.Method != "GET" && req.Method != "HEAD" {
  36. resp.WriteHeader(http.StatusNotFound)
  37. return
  38. }
  39. if handleRequest(resp, req, assetFS, subPath) {
  40. return
  41. }
  42. resp.WriteHeader(http.StatusNotFound)
  43. }
  44. }
  45. // parseAcceptEncoding parse Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5 as compress methods
  46. func parseAcceptEncoding(val string) container.Set[string] {
  47. parts := strings.Split(val, ";")
  48. types := make(container.Set[string])
  49. for _, v := range strings.Split(parts[0], ",") {
  50. types.Add(strings.TrimSpace(v))
  51. }
  52. return types
  53. }
  54. // setWellKnownContentType will set the Content-Type if the file is a well-known type.
  55. // See the comments of detectWellKnownMimeType
  56. func setWellKnownContentType(w http.ResponseWriter, file string) {
  57. mimeType := detectWellKnownMimeType(path.Ext(file))
  58. if mimeType != "" {
  59. w.Header().Set("Content-Type", mimeType)
  60. }
  61. }
  62. func handleRequest(w http.ResponseWriter, req *http.Request, fs http.FileSystem, file string) bool {
  63. // actually, fs (http.FileSystem) is designed to be a safe interface, relative paths won't bypass its parent directory, it's also fine to do a clean here
  64. f, err := fs.Open(util.PathJoinRelX("assets", file))
  65. if err != nil {
  66. if os.IsNotExist(err) {
  67. return false
  68. }
  69. w.WriteHeader(http.StatusInternalServerError)
  70. log.Error("[Static] Open %q failed: %v", file, err)
  71. return true
  72. }
  73. defer f.Close()
  74. fi, err := f.Stat()
  75. if err != nil {
  76. w.WriteHeader(http.StatusInternalServerError)
  77. log.Error("[Static] %q exists, but fails to open: %v", file, err)
  78. return true
  79. }
  80. // Try to serve index file
  81. if fi.IsDir() {
  82. w.WriteHeader(http.StatusNotFound)
  83. return true
  84. }
  85. serveContent(w, req, fi, fi.ModTime(), f)
  86. return true
  87. }
  88. type GzipBytesProvider interface {
  89. GzipBytes() []byte
  90. }
  91. // serveContent serve http content
  92. func serveContent(w http.ResponseWriter, req *http.Request, fi os.FileInfo, modtime time.Time, content io.ReadSeeker) {
  93. setWellKnownContentType(w, fi.Name())
  94. encodings := parseAcceptEncoding(req.Header.Get("Accept-Encoding"))
  95. if encodings.Contains("gzip") {
  96. // try to provide gzip content directly from bindata (provided by vfsgen۰CompressedFileInfo)
  97. if compressed, ok := fi.(GzipBytesProvider); ok {
  98. rdGzip := bytes.NewReader(compressed.GzipBytes())
  99. // all gzipped static files (from bindata) are managed by Gitea, so we can make sure every file has the correct ext name
  100. // then we can get the correct Content-Type, we do not need to do http.DetectContentType on the decompressed data
  101. if w.Header().Get("Content-Type") == "" {
  102. w.Header().Set("Content-Type", "application/octet-stream")
  103. }
  104. w.Header().Set("Content-Encoding", "gzip")
  105. httpcache.ServeContentWithCacheControl(w, req, fi.Name(), modtime, rdGzip)
  106. return
  107. }
  108. }
  109. httpcache.ServeContentWithCacheControl(w, req, fi.Name(), modtime, content)
  110. return
  111. }