processing_handler.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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/svg"
  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. var ttl int
  43. if config.CacheControlPassthrough && originHeaders != nil {
  44. if val, ok := originHeaders["Cache-Control"]; ok {
  45. cacheControl = val
  46. }
  47. if val, ok := originHeaders["Expires"]; ok {
  48. expires = val
  49. }
  50. }
  51. if len(cacheControl) == 0 && len(expires) == 0 {
  52. ttl = config.TTL
  53. if _, ok := originHeaders["Fallback-Image"]; ok && config.FallbackImageTTL > 0 {
  54. ttl = config.FallbackImageTTL
  55. }
  56. cacheControl = fmt.Sprintf("max-age=%d, public", ttl)
  57. expires = time.Now().Add(time.Second * time.Duration(ttl)).Format(http.TimeFormat)
  58. }
  59. if len(cacheControl) > 0 {
  60. rw.Header().Set("Cache-Control", cacheControl)
  61. }
  62. if len(expires) > 0 {
  63. rw.Header().Set("Expires", expires)
  64. }
  65. }
  66. func setVary(rw http.ResponseWriter) {
  67. if len(headerVaryValue) > 0 {
  68. rw.Header().Set("Vary", headerVaryValue)
  69. }
  70. }
  71. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData *imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData *imagedata.ImageData) {
  72. var contentDisposition string
  73. if len(po.Filename) > 0 {
  74. contentDisposition = resultData.Type.ContentDisposition(po.Filename, po.ReturnAttachment)
  75. } else {
  76. contentDisposition = resultData.Type.ContentDispositionFromURL(originURL, po.ReturnAttachment)
  77. }
  78. rw.Header().Set("Content-Type", resultData.Type.Mime())
  79. rw.Header().Set("Content-Disposition", contentDisposition)
  80. if po.Dpr != 1 {
  81. rw.Header().Set("Content-DPR", strconv.FormatFloat(po.Dpr, 'f', 2, 32))
  82. }
  83. if config.SetCanonicalHeader {
  84. if strings.HasPrefix(originURL, "https://") || strings.HasPrefix(originURL, "http://") {
  85. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, originURL)
  86. rw.Header().Set("Link", linkHeader)
  87. }
  88. }
  89. setCacheControl(rw, originData.Headers)
  90. setVary(rw)
  91. if config.EnableDebugHeaders {
  92. rw.Header().Set("X-Origin-Content-Length", strconv.Itoa(len(originData.Data)))
  93. rw.Header().Set("X-Origin-Width", resultData.Headers["X-Origin-Width"])
  94. rw.Header().Set("X-Origin-Height", resultData.Headers["X-Origin-Height"])
  95. rw.Header().Set("X-Result-Width", resultData.Headers["X-Result-Width"])
  96. rw.Header().Set("X-Result-Height", resultData.Headers["X-Result-Height"])
  97. }
  98. rw.Header().Set("Content-Length", strconv.Itoa(len(resultData.Data)))
  99. rw.WriteHeader(statusCode)
  100. rw.Write(resultData.Data)
  101. router.LogResponse(
  102. reqID, r, statusCode, nil,
  103. log.Fields{
  104. "image_url": originURL,
  105. "processing_options": po,
  106. },
  107. )
  108. }
  109. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders map[string]string) {
  110. setCacheControl(rw, originHeaders)
  111. setVary(rw)
  112. rw.WriteHeader(304)
  113. router.LogResponse(
  114. reqID, r, 304, nil,
  115. log.Fields{
  116. "image_url": originURL,
  117. "processing_options": po,
  118. },
  119. )
  120. }
  121. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  122. ctx := r.Context()
  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. statusCode := http.StatusOK
  177. originData, err := func() (*imagedata.ImageData, error) {
  178. defer metrics.StartDownloadingSegment(ctx)()
  179. var cookieJar *cookiejar.Jar
  180. if config.CookiePassthrough {
  181. if cookieJar, err = cookies.JarFromRequest(r); err != nil {
  182. panic(err)
  183. }
  184. }
  185. return imagedata.Download(imageURL, "source image", imgRequestHeader, cookieJar)
  186. }()
  187. if err == nil {
  188. defer originData.Close()
  189. } else if nmErr, ok := err.(*imagedata.ErrorNotModified); ok && config.ETagEnabled {
  190. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  191. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers)
  192. return
  193. } else {
  194. ierr, ierrok := err.(*ierrors.Error)
  195. if ierrok {
  196. statusCode = ierr.StatusCode
  197. }
  198. if config.ReportDownloadingErrors && (!ierrok || ierr.Unexpected) {
  199. errorreport.Report(err, r)
  200. }
  201. metrics.SendError(ctx, "download", err)
  202. if imagedata.FallbackImage == nil {
  203. panic(err)
  204. }
  205. log.Warningf("Could not load image %s. Using fallback image. %s", imageURL, err.Error())
  206. if config.FallbackImageHTTPCode > 0 {
  207. statusCode = config.FallbackImageHTTPCode
  208. }
  209. originData = imagedata.FallbackImage
  210. }
  211. router.CheckTimeout(ctx)
  212. if config.ETagEnabled && statusCode == http.StatusOK {
  213. imgDataMatch := etagHandler.SetActualImageData(originData)
  214. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  215. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  216. respondWithNotModified(reqID, r, rw, po, imageURL, originData.Headers)
  217. return
  218. }
  219. }
  220. router.CheckTimeout(ctx)
  221. if originData.Type == po.Format || po.Format == imagetype.Unknown {
  222. // Don't process SVG
  223. if originData.Type == imagetype.SVG {
  224. if config.SanitizeSvg {
  225. sanitized, svgErr := svg.Satitize(originData.Data)
  226. if svgErr != nil {
  227. panic(svgErr)
  228. }
  229. // Since we'll replace origin data, it's better to close it to return
  230. // it's buffer to the pool
  231. originData.Close()
  232. originData = &imagedata.ImageData{
  233. Data: sanitized,
  234. Type: imagetype.SVG,
  235. }
  236. }
  237. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  238. return
  239. }
  240. if len(po.SkipProcessingFormats) > 0 {
  241. for _, f := range po.SkipProcessingFormats {
  242. if f == originData.Type {
  243. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  244. return
  245. }
  246. }
  247. }
  248. }
  249. if !vips.SupportsLoad(originData.Type) {
  250. panic(ierrors.New(
  251. 422,
  252. fmt.Sprintf("Source image format is not supported: %s", originData.Type),
  253. "Invalid URL",
  254. ))
  255. }
  256. // At this point we can't allow requested format to be SVG as we can't save SVGs
  257. if po.Format == imagetype.SVG {
  258. panic(ierrors.New(422, "Resulting image format is not supported: svg", "Invalid URL"))
  259. }
  260. resultData, err := func() (*imagedata.ImageData, error) {
  261. defer metrics.StartProcessingSegment(ctx)()
  262. return processing.ProcessImage(ctx, originData, po)
  263. }()
  264. if err != nil {
  265. metrics.SendError(ctx, "processing", err)
  266. panic(err)
  267. }
  268. defer resultData.Close()
  269. router.CheckTimeout(ctx)
  270. respondWithImage(reqID, r, rw, statusCode, resultData, po, imageURL, originData)
  271. }