processing_handler.go 11 KB

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