processing_handler.go 7.1 KB

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