processing_handler.go 10 KB

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