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