processing_handler.go 11 KB

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