processing_handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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/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/imath"
  18. "github.com/imgproxy/imgproxy/v3/metrics"
  19. "github.com/imgproxy/imgproxy/v3/metrics/stats"
  20. "github.com/imgproxy/imgproxy/v3/options"
  21. "github.com/imgproxy/imgproxy/v3/processing"
  22. "github.com/imgproxy/imgproxy/v3/router"
  23. "github.com/imgproxy/imgproxy/v3/security"
  24. "github.com/imgproxy/imgproxy/v3/semaphore"
  25. "github.com/imgproxy/imgproxy/v3/svg"
  26. "github.com/imgproxy/imgproxy/v3/vips"
  27. )
  28. var (
  29. queueSem *semaphore.Semaphore
  30. processingSem *semaphore.Semaphore
  31. headerVaryValue string
  32. )
  33. func initProcessingHandler() {
  34. if config.RequestsQueueSize > 0 {
  35. queueSem = semaphore.New(config.RequestsQueueSize + config.Workers)
  36. }
  37. processingSem = semaphore.New(config.Workers)
  38. vary := make([]string, 0)
  39. if config.EnableWebpDetection || config.EnforceWebp || config.EnableAvifDetection || config.EnforceAvif {
  40. vary = append(vary, "Accept")
  41. }
  42. if config.EnableClientHints {
  43. vary = append(vary, "Sec-CH-DPR", "DPR", "Sec-CH-Width", "Width")
  44. }
  45. headerVaryValue = strings.Join(vary, ", ")
  46. }
  47. func setCacheControl(rw http.ResponseWriter, force *time.Time, originHeaders map[string]string) {
  48. ttl := -1
  49. if _, ok := originHeaders["Fallback-Image"]; ok && config.FallbackImageTTL > 0 {
  50. ttl = config.FallbackImageTTL
  51. }
  52. if force != nil && (ttl < 0 || force.Before(time.Now().Add(time.Duration(ttl)*time.Second))) {
  53. ttl = imath.Min(config.TTL, imath.Max(0, int(time.Until(*force).Seconds())))
  54. }
  55. if config.CacheControlPassthrough && ttl < 0 && originHeaders != nil {
  56. if val, ok := originHeaders["Cache-Control"]; ok && len(val) > 0 {
  57. rw.Header().Set("Cache-Control", val)
  58. return
  59. }
  60. if val, ok := originHeaders["Expires"]; ok && len(val) > 0 {
  61. if t, err := time.Parse(http.TimeFormat, val); err == nil {
  62. ttl = imath.Max(0, int(time.Until(t).Seconds()))
  63. }
  64. }
  65. }
  66. if ttl < 0 {
  67. ttl = config.TTL
  68. }
  69. if ttl > 0 {
  70. rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", ttl))
  71. } else {
  72. rw.Header().Set("Cache-Control", "no-cache")
  73. }
  74. }
  75. func setLastModified(rw http.ResponseWriter, originHeaders map[string]string) {
  76. if config.LastModifiedEnabled {
  77. if val, ok := originHeaders["Last-Modified"]; ok && len(val) != 0 {
  78. rw.Header().Set("Last-Modified", val)
  79. }
  80. }
  81. }
  82. func setVary(rw http.ResponseWriter) {
  83. if len(headerVaryValue) > 0 {
  84. rw.Header().Set("Vary", headerVaryValue)
  85. }
  86. }
  87. func setCanonical(rw http.ResponseWriter, originURL string) {
  88. if config.SetCanonicalHeader {
  89. if strings.HasPrefix(originURL, "https://") || strings.HasPrefix(originURL, "http://") {
  90. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, originURL)
  91. rw.Header().Set("Link", linkHeader)
  92. }
  93. }
  94. }
  95. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, statusCode int, resultData *imagedata.ImageData, po *options.ProcessingOptions, originURL string, originData *imagedata.ImageData) {
  96. var contentDisposition string
  97. if len(po.Filename) > 0 {
  98. contentDisposition = resultData.Type.ContentDisposition(po.Filename, po.ReturnAttachment)
  99. } else {
  100. contentDisposition = resultData.Type.ContentDispositionFromURL(originURL, po.ReturnAttachment)
  101. }
  102. rw.Header().Set("Content-Type", resultData.Type.Mime())
  103. rw.Header().Set("Content-Disposition", contentDisposition)
  104. setCacheControl(rw, po.Expires, originData.Headers)
  105. setLastModified(rw, originData.Headers)
  106. setVary(rw)
  107. setCanonical(rw, originURL)
  108. if config.EnableDebugHeaders {
  109. rw.Header().Set("X-Origin-Content-Length", strconv.Itoa(len(originData.Data)))
  110. rw.Header().Set("X-Origin-Width", resultData.Headers["X-Origin-Width"])
  111. rw.Header().Set("X-Origin-Height", resultData.Headers["X-Origin-Height"])
  112. rw.Header().Set("X-Result-Width", resultData.Headers["X-Result-Width"])
  113. rw.Header().Set("X-Result-Height", resultData.Headers["X-Result-Height"])
  114. }
  115. rw.Header().Set("Content-Security-Policy", "script-src 'none'")
  116. rw.Header().Set("Content-Length", strconv.Itoa(len(resultData.Data)))
  117. rw.WriteHeader(statusCode)
  118. rw.Write(resultData.Data)
  119. router.LogResponse(
  120. reqID, r, statusCode, nil,
  121. log.Fields{
  122. "image_url": originURL,
  123. "processing_options": po,
  124. },
  125. )
  126. }
  127. func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWriter, po *options.ProcessingOptions, originURL string, originHeaders map[string]string) {
  128. setCacheControl(rw, po.Expires, originHeaders)
  129. setVary(rw)
  130. rw.WriteHeader(304)
  131. router.LogResponse(
  132. reqID, r, 304, nil,
  133. log.Fields{
  134. "image_url": originURL,
  135. "processing_options": po,
  136. },
  137. )
  138. }
  139. func sendErr(ctx context.Context, errType string, err error) {
  140. send := true
  141. if ierr, ok := err.(*ierrors.Error); ok {
  142. switch ierr.StatusCode {
  143. case http.StatusServiceUnavailable:
  144. errType = "timeout"
  145. case 499:
  146. // Don't need to send a "request cancelled" error
  147. send = false
  148. }
  149. }
  150. if send {
  151. metrics.SendError(ctx, errType, err)
  152. }
  153. }
  154. func sendErrAndPanic(ctx context.Context, errType string, err error) {
  155. sendErr(ctx, errType, err)
  156. panic(err)
  157. }
  158. func checkErr(ctx context.Context, errType string, err error) {
  159. if err == nil {
  160. return
  161. }
  162. sendErrAndPanic(ctx, errType, err)
  163. }
  164. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  165. stats.IncRequestsInProgress()
  166. defer stats.DecRequestsInProgress()
  167. ctx := r.Context()
  168. if queueSem != nil {
  169. token, acquired := queueSem.TryAcquire()
  170. if !acquired {
  171. panic(ierrors.New(429, "Too many requests", "Too many requests"))
  172. }
  173. defer token.Release()
  174. }
  175. path := r.RequestURI
  176. if queryStart := strings.IndexByte(path, '?'); queryStart >= 0 {
  177. path = path[:queryStart]
  178. }
  179. if len(config.PathPrefix) > 0 {
  180. path = strings.TrimPrefix(path, config.PathPrefix)
  181. }
  182. path = strings.TrimPrefix(path, "/")
  183. signature := ""
  184. if signatureEnd := strings.IndexByte(path, '/'); signatureEnd > 0 {
  185. signature = path[:signatureEnd]
  186. path = path[signatureEnd:]
  187. } else {
  188. sendErrAndPanic(ctx, "path_parsing", ierrors.New(
  189. 404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL",
  190. ))
  191. }
  192. path = fixPath(path)
  193. if err := security.VerifySignature(signature, path); err != nil {
  194. sendErrAndPanic(ctx, "security", ierrors.New(403, err.Error(), "Forbidden"))
  195. }
  196. po, imageURL, err := options.ParsePath(path, r.Header)
  197. checkErr(ctx, "path_parsing", err)
  198. err = security.VerifySourceURL(imageURL)
  199. checkErr(ctx, "security", err)
  200. if po.Raw {
  201. streamOriginImage(ctx, reqID, r, rw, po, imageURL)
  202. return
  203. }
  204. // SVG is a special case. Though saving to svg is not supported, SVG->SVG is.
  205. if !vips.SupportsSave(po.Format) && po.Format != imagetype.Unknown && po.Format != imagetype.SVG {
  206. sendErrAndPanic(ctx, "path_parsing", ierrors.New(
  207. 422,
  208. fmt.Sprintf("Resulting image format is not supported: %s", po.Format),
  209. "Invalid URL",
  210. ))
  211. }
  212. imgRequestHeader := make(http.Header)
  213. var etagHandler etag.Handler
  214. if config.ETagEnabled {
  215. etagHandler.ParseExpectedETag(r.Header.Get("If-None-Match"))
  216. if etagHandler.SetActualProcessingOptions(po) {
  217. if imgEtag := etagHandler.ImageEtagExpected(); len(imgEtag) != 0 {
  218. imgRequestHeader.Set("If-None-Match", imgEtag)
  219. }
  220. }
  221. }
  222. if config.LastModifiedEnabled {
  223. if modifiedSince := r.Header.Get("If-Modified-Since"); len(modifiedSince) != 0 {
  224. imgRequestHeader.Set("If-Modified-Since", modifiedSince)
  225. }
  226. }
  227. // The heavy part start here, so we need to restrict worker number
  228. var processingSemToken *semaphore.Token
  229. func() {
  230. defer metrics.StartQueueSegment(ctx)()
  231. var acquired bool
  232. processingSemToken, acquired = processingSem.Acquire(ctx)
  233. if !acquired {
  234. // We don't actually need to check timeout here,
  235. // but it's an easy way to check if this is an actual timeout
  236. // or the request was canceled
  237. checkErr(ctx, "queue", router.CheckTimeout(ctx))
  238. }
  239. }()
  240. defer processingSemToken.Release()
  241. stats.IncImagesInProgress()
  242. defer stats.DecImagesInProgress()
  243. statusCode := http.StatusOK
  244. originData, err := func() (*imagedata.ImageData, error) {
  245. defer metrics.StartDownloadingSegment(ctx)()
  246. downloadOpts := imagedata.DownloadOptions{
  247. Header: imgRequestHeader,
  248. CookieJar: nil,
  249. }
  250. if config.CookiePassthrough {
  251. downloadOpts.CookieJar, err = cookies.JarFromRequest(r)
  252. checkErr(ctx, "download", err)
  253. }
  254. return imagedata.Download(ctx, imageURL, "source image", downloadOpts, po.SecurityOptions)
  255. }()
  256. if err == nil {
  257. defer originData.Close()
  258. } else if nmErr, ok := err.(*imagedata.ErrorNotModified); ok {
  259. if config.ETagEnabled && len(etagHandler.ImageEtagExpected()) != 0 {
  260. rw.Header().Set("ETag", etagHandler.GenerateExpectedETag())
  261. }
  262. respondWithNotModified(reqID, r, rw, po, imageURL, nmErr.Headers)
  263. return
  264. } else {
  265. // This may be a request timeout error or a request cancelled error.
  266. // Check it before moving further
  267. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  268. ierr := ierrors.Wrap(err, 0)
  269. ierr.Unexpected = ierr.Unexpected || config.ReportDownloadingErrors
  270. sendErr(ctx, "download", ierr)
  271. if imagedata.FallbackImage == nil {
  272. panic(ierr)
  273. }
  274. // We didn't panic, so the error is not reported.
  275. // Report it now
  276. if ierr.Unexpected {
  277. errorreport.Report(ierr, r)
  278. }
  279. log.WithField("request_id", reqID).Warningf("Could not load image %s. Using fallback image. %s", imageURL, ierr.Error())
  280. if config.FallbackImageHTTPCode > 0 {
  281. statusCode = config.FallbackImageHTTPCode
  282. } else {
  283. statusCode = ierr.StatusCode
  284. }
  285. originData = imagedata.FallbackImage
  286. }
  287. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  288. if config.ETagEnabled && statusCode == http.StatusOK {
  289. imgDataMatch := etagHandler.SetActualImageData(originData)
  290. rw.Header().Set("ETag", etagHandler.GenerateActualETag())
  291. if imgDataMatch && etagHandler.ProcessingOptionsMatch() {
  292. respondWithNotModified(reqID, r, rw, po, imageURL, originData.Headers)
  293. return
  294. }
  295. }
  296. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  297. if originData.Type == po.Format || po.Format == imagetype.Unknown {
  298. // Don't process SVG
  299. if originData.Type == imagetype.SVG {
  300. if config.SanitizeSvg {
  301. sanitized, svgErr := svg.Sanitize(originData)
  302. checkErr(ctx, "svg_processing", svgErr)
  303. // Since we'll replace origin data, it's better to close it to return
  304. // it's buffer to the pool
  305. originData.Close()
  306. originData = sanitized
  307. }
  308. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  309. return
  310. }
  311. if len(po.SkipProcessingFormats) > 0 {
  312. for _, f := range po.SkipProcessingFormats {
  313. if f == originData.Type {
  314. respondWithImage(reqID, r, rw, statusCode, originData, po, imageURL, originData)
  315. return
  316. }
  317. }
  318. }
  319. }
  320. if !vips.SupportsLoad(originData.Type) {
  321. sendErrAndPanic(ctx, "processing", ierrors.New(
  322. 422,
  323. fmt.Sprintf("Source image format is not supported: %s", originData.Type),
  324. "Invalid URL",
  325. ))
  326. }
  327. // At this point we can't allow requested format to be SVG as we can't save SVGs
  328. if po.Format == imagetype.SVG {
  329. sendErrAndPanic(ctx, "processing", ierrors.New(
  330. 422, "Resulting image format is not supported: svg", "Invalid URL",
  331. ))
  332. }
  333. // We're going to rasterize SVG. Since librsvg lacks the support of some SVG
  334. // features, we're going to replace them to minimize rendering error
  335. if originData.Type == imagetype.SVG && config.SvgFixUnsupported {
  336. fixed, changed, svgErr := svg.FixUnsupported(originData)
  337. checkErr(ctx, "svg_processing", svgErr)
  338. if changed {
  339. // Since we'll replace origin data, it's better to close it to return
  340. // it's buffer to the pool
  341. originData.Close()
  342. originData = fixed
  343. }
  344. }
  345. resultData, err := func() (*imagedata.ImageData, error) {
  346. defer metrics.StartProcessingSegment(ctx)()
  347. return processing.ProcessImage(ctx, originData, po)
  348. }()
  349. checkErr(ctx, "processing", err)
  350. defer resultData.Close()
  351. checkErr(ctx, "timeout", router.CheckTimeout(ctx))
  352. respondWithImage(reqID, r, rw, statusCode, resultData, po, imageURL, originData)
  353. }