gitea源码

serve.go 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package httplib
  4. import (
  5. "bytes"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. charsetModule "code.gitea.io/gitea/modules/charset"
  17. "code.gitea.io/gitea/modules/container"
  18. "code.gitea.io/gitea/modules/httpcache"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/typesniffer"
  22. "code.gitea.io/gitea/modules/util"
  23. "github.com/klauspost/compress/gzhttp"
  24. )
  25. type ServeHeaderOptions struct {
  26. ContentType string // defaults to "application/octet-stream"
  27. ContentTypeCharset string
  28. ContentLength *int64
  29. Disposition string // defaults to "attachment"
  30. Filename string
  31. CacheIsPublic bool
  32. CacheDuration time.Duration // defaults to 5 minutes
  33. LastModified time.Time
  34. }
  35. // ServeSetHeaders sets necessary content serve headers
  36. func ServeSetHeaders(w http.ResponseWriter, opts *ServeHeaderOptions) {
  37. header := w.Header()
  38. skipCompressionExts := container.SetOf(".gz", ".bz2", ".zip", ".xz", ".zst", ".deb", ".apk", ".jar", ".png", ".jpg", ".webp")
  39. if skipCompressionExts.Contains(strings.ToLower(path.Ext(opts.Filename))) {
  40. w.Header().Add(gzhttp.HeaderNoCompression, "1")
  41. }
  42. contentType := typesniffer.MimeTypeApplicationOctetStream
  43. if opts.ContentType != "" {
  44. if opts.ContentTypeCharset != "" {
  45. contentType = opts.ContentType + "; charset=" + strings.ToLower(opts.ContentTypeCharset)
  46. } else {
  47. contentType = opts.ContentType
  48. }
  49. }
  50. header.Set("Content-Type", contentType)
  51. header.Set("X-Content-Type-Options", "nosniff")
  52. if opts.ContentLength != nil {
  53. header.Set("Content-Length", strconv.FormatInt(*opts.ContentLength, 10))
  54. }
  55. if opts.Filename != "" {
  56. disposition := opts.Disposition
  57. if disposition == "" {
  58. disposition = "attachment"
  59. }
  60. backslashEscapedName := strings.ReplaceAll(strings.ReplaceAll(opts.Filename, `\`, `\\`), `"`, `\"`) // \ -> \\, " -> \"
  61. header.Set("Content-Disposition", fmt.Sprintf(`%s; filename="%s"; filename*=UTF-8''%s`, disposition, backslashEscapedName, url.PathEscape(opts.Filename)))
  62. header.Set("Access-Control-Expose-Headers", "Content-Disposition")
  63. }
  64. httpcache.SetCacheControlInHeader(header, &httpcache.CacheControlOptions{
  65. IsPublic: opts.CacheIsPublic,
  66. MaxAge: opts.CacheDuration,
  67. NoTransform: true,
  68. })
  69. if !opts.LastModified.IsZero() {
  70. // http.TimeFormat required a UTC time, refer to https://pkg.go.dev/net/http#TimeFormat
  71. header.Set("Last-Modified", opts.LastModified.UTC().Format(http.TimeFormat))
  72. }
  73. }
  74. // ServeData download file from io.Reader
  75. func setServeHeadersByFile(r *http.Request, w http.ResponseWriter, mineBuf []byte, opts *ServeHeaderOptions) {
  76. // do not set "Content-Length", because the length could only be set by callers, and it needs to support range requests
  77. sniffedType := typesniffer.DetectContentType(mineBuf)
  78. // the "render" parameter came from year 2016: 638dd24c, it doesn't have clear meaning, so I think it could be removed later
  79. isPlain := sniffedType.IsText() || r.FormValue("render") != ""
  80. if setting.MimeTypeMap.Enabled {
  81. fileExtension := strings.ToLower(filepath.Ext(opts.Filename))
  82. opts.ContentType = setting.MimeTypeMap.Map[fileExtension]
  83. }
  84. if opts.ContentType == "" {
  85. if sniffedType.IsBrowsableBinaryType() {
  86. opts.ContentType = sniffedType.GetMimeType()
  87. } else if isPlain {
  88. opts.ContentType = "text/plain"
  89. } else {
  90. opts.ContentType = typesniffer.MimeTypeApplicationOctetStream
  91. }
  92. }
  93. if isPlain {
  94. charset, err := charsetModule.DetectEncoding(mineBuf)
  95. if err != nil {
  96. log.Error("Detect raw file %s charset failed: %v, using by default utf-8", opts.Filename, err)
  97. charset = "utf-8"
  98. }
  99. opts.ContentTypeCharset = strings.ToLower(charset)
  100. }
  101. isSVG := sniffedType.IsSvgImage()
  102. // serve types that can present a security risk with CSP
  103. if isSVG {
  104. w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox")
  105. } else if sniffedType.IsPDF() {
  106. // no sandbox attribute for pdf as it breaks rendering in at least safari. this
  107. // should generally be safe as scripts inside PDF can not escape the PDF document
  108. // see https://bugs.chromium.org/p/chromium/issues/detail?id=413851 for more discussion
  109. w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'")
  110. }
  111. opts.Disposition = "inline"
  112. if isSVG && !setting.UI.SVG.Enabled {
  113. opts.Disposition = "attachment"
  114. }
  115. ServeSetHeaders(w, opts)
  116. }
  117. const mimeDetectionBufferLen = 1024
  118. func ServeContentByReader(r *http.Request, w http.ResponseWriter, size int64, reader io.Reader, opts *ServeHeaderOptions) {
  119. buf := make([]byte, mimeDetectionBufferLen)
  120. n, err := util.ReadAtMost(reader, buf)
  121. if err != nil {
  122. http.Error(w, "serve content: unable to pre-read", http.StatusRequestedRangeNotSatisfiable)
  123. return
  124. }
  125. if n >= 0 {
  126. buf = buf[:n]
  127. }
  128. setServeHeadersByFile(r, w, buf, opts)
  129. // reset the reader to the beginning
  130. reader = io.MultiReader(bytes.NewReader(buf), reader)
  131. rangeHeader := r.Header.Get("Range")
  132. // if no size or no supported range, serve as 200 (complete response)
  133. if size <= 0 || !strings.HasPrefix(rangeHeader, "bytes=") {
  134. if size >= 0 {
  135. w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
  136. }
  137. _, _ = io.Copy(w, reader) // just like http.ServeContent, not necessary to handle the error
  138. return
  139. }
  140. // do our best to support the minimal "Range" request (no support for multiple range: "Range: bytes=0-50, 100-150")
  141. //
  142. // GET /...
  143. // Range: bytes=0-1023
  144. //
  145. // HTTP/1.1 206 Partial Content
  146. // Content-Range: bytes 0-1023/146515
  147. // Content-Length: 1024
  148. _, rangeParts, _ := strings.Cut(rangeHeader, "=")
  149. rangeBytesStart, rangeBytesEnd, found := strings.Cut(rangeParts, "-")
  150. start, err := strconv.ParseInt(rangeBytesStart, 10, 64)
  151. if start < 0 || start >= size {
  152. err = errors.New("invalid start range")
  153. }
  154. if err != nil {
  155. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  156. return
  157. }
  158. end, err := strconv.ParseInt(rangeBytesEnd, 10, 64)
  159. if rangeBytesEnd == "" && found {
  160. err = nil
  161. end = size - 1
  162. }
  163. if end >= size {
  164. end = size - 1
  165. }
  166. if end < start {
  167. err = errors.New("invalid end range")
  168. }
  169. if err != nil {
  170. http.Error(w, err.Error(), http.StatusBadRequest)
  171. return
  172. }
  173. partialLength := end - start + 1
  174. w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, size))
  175. w.Header().Set("Content-Length", strconv.FormatInt(partialLength, 10))
  176. if _, err = io.CopyN(io.Discard, reader, start); err != nil {
  177. http.Error(w, "serve content: unable to skip", http.StatusInternalServerError)
  178. return
  179. }
  180. w.WriteHeader(http.StatusPartialContent)
  181. _, _ = io.CopyN(w, reader, partialLength) // just like http.ServeContent, not necessary to handle the error
  182. }
  183. func ServeContentByReadSeeker(r *http.Request, w http.ResponseWriter, modTime *time.Time, reader io.ReadSeeker, opts *ServeHeaderOptions) {
  184. buf := make([]byte, mimeDetectionBufferLen)
  185. n, err := util.ReadAtMost(reader, buf)
  186. if err != nil {
  187. http.Error(w, "serve content: unable to read", http.StatusInternalServerError)
  188. return
  189. }
  190. if _, err = reader.Seek(0, io.SeekStart); err != nil {
  191. http.Error(w, "serve content: unable to seek", http.StatusInternalServerError)
  192. return
  193. }
  194. if n >= 0 {
  195. buf = buf[:n]
  196. }
  197. setServeHeadersByFile(r, w, buf, opts)
  198. if modTime == nil {
  199. modTime = &time.Time{}
  200. }
  201. http.ServeContent(w, r, opts.Filename, *modTime, reader)
  202. }