processing_handler.go 8.0 KB

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