processing_handler.go 8.6 KB

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