processing_handler.go 8.5 KB

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