processing_handler.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. rw.Header().Set("X-Origin-Width", resultData.Headers["X-Origin-Width"])
  82. rw.Header().Set("X-Origin-Height", resultData.Headers["X-Origin-Height"])
  83. }
  84. rw.Header().Set("Content-Length", strconv.Itoa(len(resultData.Data)))
  85. statusCode := 200
  86. if getFallbackImageUsed(r.Context()) {
  87. statusCode = config.FallbackImageHTTPCode
  88. }
  89. rw.WriteHeader(statusCode)
  90. rw.Write(resultData.Data)
  91. router.LogResponse(
  92. reqID, r, statusCode, nil,
  93. log.Fields{
  94. "image_url": originURL,
  95. "processing_options": po,
  96. },
  97. )
  98. }
  99. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string) {
  100. rw.WriteHeader(304)
  101. router.LogResponse(
  102. reqID, r, 304, nil,
  103. log.Fields{
  104. "image_url": originURL,
  105. "processing_options": po,
  106. },
  107. )
  108. }
  109. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  110. ctx, timeoutCancel := context.WithTimeout(r.Context(), time.Duration(config.WriteTimeout)*time.Second)
  111. defer timeoutCancel()
  112. var metricsCancel context.CancelFunc
  113. ctx, metricsCancel, rw = metrics.StartRequest(ctx, rw, r)
  114. defer metricsCancel()
  115. path := r.RequestURI
  116. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  117. path = path[:queryStart]
  118. }
  119. if len(config.PathPrefix) > 0 {
  120. path = strings.TrimPrefix(path, config.PathPrefix)
  121. }
  122. path = strings.TrimPrefix(path, "/")
  123. signature := ""
  124. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  125. signature = path[:signatureEnd]
  126. path = path[signatureEnd:]
  127. } else {
  128. panic(ierrors.New(404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL"))
  129. }
  130. if err := security.VerifySignature(signature, path); err != nil {
  131. panic(ierrors.New(403, err.Error(), "Forbidden"))
  132. }
  133. po, imageURL, err := options.ParsePath(path, r.Header)
  134. if err != nil {
  135. panic(err)
  136. }
  137. if !security.VerifySourceURL(imageURL) {
  138. panic(ierrors.New(404, fmt.Sprintf("Source URL is not allowed: %s", imageURL), "Invalid source"))
  139. }
  140. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  141. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  142. panic(ierrors.New(
  143. 422,
  144. fmt.Sprintf("Resulting image format is not supported: %s", po.Format),
  145. "Invalid URL",
  146. ))
  147. }
  148. imgRequestHeader := make(http.Header)
  149. var etagHandler etag.Handler
  150. if config.ETagEnabled {
  151. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  152. if etagHandler.SetActualProcessingOptions(po) {
  153. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  154. imgRequestHeader.Set("If-None-Match", imgEtag)
  155. }
  156. }
  157. }
  158. // The heavy part start here, so we need to restrict concurrency
  159. select {
  160. case processingSem <- struct{}{}:
  161. case <-ctx.Done():
  162. // We don't actually need to check timeout here,
  163. // but it's an easy way to check if this is an actual timeout
  164. // or the request was cancelled
  165. router.CheckTimeout(ctx)
  166. }
  167. defer func() { <-processingSem }()
  168. originData, err := func() (*imagedata.ImageData, error) {
  169. defer metrics.StartDownloadingSegment(ctx)()
  170. return imagedata.Download(imageURL, "source image", imgRequestHeader)
  171. }()
  172. switch {
  173. case err == nil:
  174. defer originData.Close()
  175. case ierrors.StatusCode(err) == http.StatusNotModified:
  176. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  177. respondWithNotModified(reqID, r, rw, po, imageURL)
  178. return
  179. default:
  180. if ierr, ok := err.(*ierrors.Error); !ok || ierr.Unexpected {
  181. errorreport.Report(err, r)
  182. }
  183. metrics.SendError(ctx, "download", err)
  184. if imagedata.FallbackImage == nil {
  185. panic(err)
  186. }
  187. log.Warningf("Could not load image %s. Using fallback image. %s", imageURL, err.Error())
  188. r = r.WithContext(setFallbackImageUsedCtx(r.Context()))
  189. originData = imagedata.FallbackImage
  190. }
  191. router.CheckTimeout(ctx)
  192. if config.ETagEnabled && !getFallbackImageUsed(ctx) {
  193. imgDataMatch := etagHandler.SetActualImageData(originData)
  194. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  195. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  196. respondWithNotModified(reqID, r, rw, po, imageURL)
  197. return
  198. }
  199. }
  200. router.CheckTimeout(ctx)
  201. if originData.Type == po.Format || po.Format == imagetype.Unknown {
  202. // Don't process SVG
  203. if originData.Type == imagetype.SVG {
  204. respondWithImage(reqID, r, rw, originData, po, imageURL, originData)
  205. return
  206. }
  207. if len(po.SkipProcessingFormats) > 0 {
  208. for _, f := range po.SkipProcessingFormats {
  209. if f == originData.Type {
  210. respondWithImage(reqID, r, rw, originData, po, imageURL, originData)
  211. return
  212. }
  213. }
  214. }
  215. }
  216. if !vips.SupportsLoad(originData.Type) {
  217. panic(ierrors.New(
  218. 422,
  219. fmt.Sprintf("Source image format is not supported: %s", originData.Type),
  220. "Invalid URL",
  221. ))
  222. }
  223. // At this point we can't allow requested format to be SVG as we can't save SVGs
  224. if po.Format == imagetype.SVG {
  225. panic(ierrors.New(422, "Resulting image format is not supported: svg", "Invalid URL"))
  226. }
  227. resultData, err := func() (*imagedata.ImageData, error) {
  228. defer metrics.StartProcessingSegment(ctx)()
  229. return processing.ProcessImage(ctx, originData, po)
  230. }()
  231. if err != nil {
  232. metrics.SendError(ctx, "processing", err)
  233. panic(err)
  234. }
  235. defer resultData.Close()
  236. router.CheckTimeout(ctx)
  237. respondWithImage(reqID, r, rw, resultData, po, imageURL, originData)
  238. }
  239. func setFallbackImageUsedCtx(ctx context.Context) context.Context {
  240. return context.WithValue(ctx, fallbackImageUsedCtxKey{}, true)
  241. }
  242. func getFallbackImageUsed(ctx context.Context) bool {
  243. result, _ := ctx.Value(fallbackImageUsedCtxKey{}).(bool)
  244. return result
  245. }