processing_handler.go 8.3 KB

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