processing_handler.go 8.5 KB

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