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.

serve.go 6.9KB

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