processing_handler.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/imgproxy/imgproxy/v3/config"
  11. "github.com/imgproxy/imgproxy/v3/errorreport"
  12. "github.com/imgproxy/imgproxy/v3/etag"
  13. "github.com/imgproxy/imgproxy/v3/ierrors"
  14. "github.com/imgproxy/imgproxy/v3/imagedata"
  15. "github.com/imgproxy/imgproxy/v3/imagetype"
  16. "github.com/imgproxy/imgproxy/v3/metrics"
  17. "github.com/imgproxy/imgproxy/v3/options"
  18. "github.com/imgproxy/imgproxy/v3/processing"
  19. "github.com/imgproxy/imgproxy/v3/router"
  20. "github.com/imgproxy/imgproxy/v3/security"
  21. "github.com/imgproxy/imgproxy/v3/vips"
  22. )
  23. var (
  24. processingSem chan struct{}
  25. headerVaryValue string
  26. )
  27. type fallbackImageUsedCtxKey struct{}
  28. func initProcessingHandler() {
  29. processingSem = make(chan struct{}, config.Concurrency)
  30. vary := make([]string, 0)
  31. if config.EnableWebpDetection || config.EnforceWebp {
  32. vary = append(vary, "Accept")
  33. }
  34. if config.EnableClientHints {
  35. vary = append(vary, "DPR", "Viewport-Width", "Width")
  36. }
  37. headerVaryValue = strings.Join(vary, ", ")
  38. }
  39. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, resultData *imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData *imagedata.ImageData) {
  40. var contentDisposition string
  41. if len(po.Filename) > 0 {
  42. contentDisposition = resultData.Type.ContentDisposition(po.Filename)
  43. } else {
  44. contentDisposition = resultData.Type.ContentDispositionFromURL(originURL)
  45. }
  46. rw.Header().Set("Content-Type", resultData.Type.Mime())
  47. rw.Header().Set("Content-Disposition", contentDisposition)
  48. if po.Dpr != 1 {
  49. rw.Header().Set("Content-DPR", strconv.FormatFloat(po.Dpr, 'f', 2, 32))
  50. }
  51. if config.SetCanonicalHeader {
  52. if strings.HasPrefix(originURL, "https://") || strings.HasPrefix(originURL, "http://") {
  53. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, originURL)
  54. rw.Header().Set("Link", linkHeader)
  55. }
  56. }
  57. var cacheControl, expires string
  58. if config.CacheControlPassthrough && originData.Headers != nil {
  59. if val, ok := originData.Headers["Cache-Control"]; ok {
  60. cacheControl = val
  61. }
  62. if val, ok := originData.Headers["Expires"]; ok {
  63. expires = val
  64. }
  65. }
  66. if len(cacheControl) == 0 && len(expires) == 0 {
  67. cacheControl = fmt.Sprintf("max-age=%d, public", config.TTL)
  68. expires = time.Now().Add(time.Second * time.Duration(config.TTL)).Format(http.TimeFormat)
  69. }
  70. if len(cacheControl) > 0 {
  71. rw.Header().Set("Cache-Control", cacheControl)
  72. }
  73. if len(expires) > 0 {
  74. rw.Header().Set("Expires", expires)
  75. }
  76. if len(headerVaryValue) > 0 {
  77. rw.Header().Set("Vary", headerVaryValue)
  78. }
  79. if config.EnableDebugHeaders {
  80. rw.Header().Set("X-Origin-Content-Length", strconv.Itoa(len(originData.Data)))
  81. }
  82. rw.Header().Set("Content-Length", strconv.Itoa(len(resultData.Data)))
  83. statusCode := 200
  84. if getFallbackImageUsed(r.Context()) {
  85. statusCode = config.FallbackImageHTTPCode
  86. }
  87. rw.WriteHeader(statusCode)
  88. rw.Write(resultData.Data)
  89. router.LogResponse(
  90. reqID, r, statusCode, nil,
  91. log.Fields{
  92. "image_url": originURL,
  93. "processing_options": po,
  94. },
  95. )
  96. }
  97. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string) {
  98. rw.WriteHeader(304)
  99. router.LogResponse(
  100. reqID, r, 304, nil,
  101. log.Fields{
  102. "image_url": originURL,
  103. "processing_options": po,
  104. },
  105. )
  106. }
  107. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  108. ctx, timeoutCancel := context.WithTimeout(r.Context(), time.Duration(config.WriteTimeout)*time.Second)
  109. defer timeoutCancel()
  110. var metricsCancel context.CancelFunc
  111. ctx, metricsCancel, rw = metrics.StartRequest(ctx, rw, r)
  112. defer metricsCancel()
  113. path := r.RequestURI
  114. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  115. path = path[:queryStart]
  116. }
  117. if len(config.PathPrefix) > 0 {
  118. path = strings.TrimPrefix(path, config.PathPrefix)
  119. }
  120. path = strings.TrimPrefix(path, "/")
  121. signature := ""
  122. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  123. signature = path[:signatureEnd]
  124. path = path[signatureEnd:]
  125. } else {
  126. panic(ierrors.New(404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL"))
  127. }
  128. if err := security.VerifySignature(signature, path); err != nil {
  129. panic(ierrors.New(403, err.Error(), "Forbidden"))
  130. }
  131. po, imageURL, err := options.ParsePath(path, r.Header)
  132. if err != nil {
  133. panic(err)
  134. }
  135. if !security.VerifySourceURL(imageURL) {
  136. panic(ierrors.New(404, fmt.Sprintf("Source URL is not allowed: %s", imageURL), "Invalid source"))
  137. }
  138. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  139. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  140. panic(ierrors.New(
  141. 422,
  142. fmt.Sprintf("Resulting image format is not supported: %s", po.Format),
  143. "Invalid URL",
  144. ))
  145. }
  146. imgRequestHeader := make(http.Header)
  147. var etagHandler etag.Handler
  148. if config.ETagEnabled {
  149. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  150. if etagHandler.SetActualProcessingOptions(po) {
  151. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  152. imgRequestHeader.Set("If-None-Match", imgEtag)
  153. }
  154. }
  155. }
  156. // The heavy part start here, so we need to restrict concurrency
  157. select {
  158. case processingSem <- struct{}{}:
  159. case <-ctx.Done():
  160. // We don't actually need to check timeout here,
  161. // but it's an easy way to check if this is an actual timeout
  162. // or the request was cancelled
  163. router.CheckTimeout(ctx)
  164. }
  165. defer func() { <-processingSem }()
  166. originData, err := func() (*imagedata.ImageData, error) {
  167. defer metrics.StartDownloadingSegment(ctx)()
  168. return imagedata.Download(imageURL, "source image", imgRequestHeader)
  169. }()
  170. switch {
  171. case err == nil:
  172. defer originData.Close()
  173. case ierrors.StatusCode(err) == http.StatusNotModified:
  174. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  175. respondWithNotModified(reqID, r, rw, po, imageURL)
  176. return
  177. default:
  178. if ierr, ok := err.(*ierrors.Error); !ok || ierr.Unexpected {
  179. errorreport.Report(err, r)
  180. }
  181. metrics.SendError(ctx, "download", err)
  182. if imagedata.FallbackImage == nil {
  183. panic(err)
  184. }
  185. log.Warningf("Could not load image %s. Using fallback image. %s", imageURL, err.Error())
  186. r = r.WithContext(setFallbackImageUsedCtx(r.Context()))
  187. originData = imagedata.FallbackImage
  188. }
  189. router.CheckTimeout(ctx)
  190. if config.ETagEnabled && !getFallbackImageUsed(ctx) {
  191. imgDataMatch := etagHandler.SetActualImageData(originData)
  192. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  193. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  194. respondWithNotModified(reqID, r, rw, po, imageURL)
  195. return
  196. }
  197. }
  198. router.CheckTimeout(ctx)
  199. if originData.Type == po.Format || po.Format == imagetype.Unknown {
  200. // Don't process SVG
  201. if originData.Type == imagetype.SVG {
  202. respondWithImage(reqID, r, rw, originData, po, imageURL, originData)
  203. return
  204. }
  205. if len(po.SkipProcessingFormats) > 0 {
  206. for _, f := range po.SkipProcessingFormats {
  207. if f == originData.Type {
  208. respondWithImage(reqID, r, rw, originData, po, imageURL, originData)
  209. return
  210. }
  211. }
  212. }
  213. }
  214. if !vips.SupportsLoad(originData.Type) {
  215. panic(ierrors.New(
  216. 422,
  217. fmt.Sprintf("Source image format is not supported: %s", originData.Type),
  218. "Invalid URL",
  219. ))
  220. }
  221. // At this point we can't allow requested format to be SVG as we can't save SVGs
  222. if po.Format == imagetype.SVG {
  223. panic(ierrors.New(422, "Resulting image format is not supported: svg", "Invalid URL"))
  224. }
  225. resultData, err := func() (*imagedata.ImageData, error) {
  226. defer metrics.StartProcessingSegment(ctx)()
  227. return processing.ProcessImage(ctx, originData, po)
  228. }()
  229. if err != nil {
  230. metrics.SendError(ctx, "processing", err)
  231. panic(err)
  232. }
  233. defer resultData.Close()
  234. router.CheckTimeout(ctx)
  235. respondWithImage(reqID, r, rw, resultData, po, imageURL, originData)
  236. }
  237. func setFallbackImageUsedCtx(ctx context.Context) context.Context {
  238. return context.WithValue(ctx, fallbackImageUsedCtxKey{}, true)
  239. }
  240. func getFallbackImageUsed(ctx context.Context) bool {
  241. result, _ := ctx.Value(fallbackImageUsedCtxKey{}).(bool)
  242. return result
  243. }