processing_handler.go 9.8 KB

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