Debian Codegraph @

modules/caddyhttp/encode/encode.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package encode implements an encoder middleware for Caddy. The initial
16 // enhancements related to Accept-Encoding, minimum content length, and
17 // buffer/writer pools were adapted from https://github.com/xi2/httpgzip
18 // then modified heavily to accommodate modular encoders and fix bugs.
19 // Code borrowed from that repository is Copyright (c) 2015 The Httpgzip Authors.
20 package encode
21
22 import (
23 "cmp"
24 "fmt"
25 "io"
26 "math"
27 "net/http"
28 "slices"
29 "strconv"
30 "strings"
31 "sync"
32
33 "github.com/caddyserver/caddy/v2"
34 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
35 )
36
37 func init() {
38 caddy.RegisterModule(Encode{})
39 }
40
41 // Encode is a middleware which can encode responses.
42 type Encode struct {
43 // Selection of compression algorithms to choose from. The best one
44 // will be chosen based on the client's Accept-Encoding header.
45 EncodingsRaw caddy.ModuleMap `json:"encodings,omitempty" caddy:"namespace=http.encoders"`
46
47 // If the client has no strong preference, choose these encodings in order.
48 Prefer []string `json:"prefer,omitempty"`
49
50 // Only encode responses that are at least this many bytes long.
51 MinLength int `json:"minimum_length,omitempty"`
52
53 // Only encode responses that match against this ResponseMatcher.
54 // The default is a collection of text-based Content-Type headers.
55 Matcher *caddyhttp.ResponseMatcher `json:"match,omitempty"`
56
57 writerPools map[string]*sync.Pool // TODO: these pools do not get reused through config reloads...
58 }
59
60 // CaddyModule returns the Caddy module information.
61 func (Encode) CaddyModule() caddy.ModuleInfo {
62 return caddy.ModuleInfo{
63 ID: "http.handlers.encode",
64 New: func() caddy.Module { return new(Encode) },
65 }
66 }
67
68 // Provision provisions enc.
69 func (enc *Encode) Provision(ctx caddy.Context) error {
70 mods, err := ctx.LoadModule(enc, "EncodingsRaw")
71 if err != nil {
72 return fmt.Errorf("loading encoder modules: %v", err)
73 }
74 for modName, modIface := range mods.(map[string]any) {
75 err = enc.addEncoding(modIface.(Encoding))
76 if err != nil {
77 return fmt.Errorf("adding encoding %s: %v", modName, err)
78 }
79 }
80 if enc.MinLength == 0 {
81 enc.MinLength = defaultMinLength
82 }
83
84 if enc.Matcher == nil {
85 // common text-based content types
86 // list based on https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression/#compression-between-cloudflare-and-website-visitors
87 enc.Matcher = &caddyhttp.ResponseMatcher{
88 Headers: http.Header{
89 "Content-Type": []string{
90 "application/atom+xml*",
91 "application/eot*",
92 "application/font*",
93 "application/geo+json*",
94 "application/graphql+json*",
95 "application/graphql-response+json*",
96 "application/javascript*",
97 "application/json*",
98 "application/ld+json*",
99 "application/manifest+json*",
100 "application/opentype*",
101 "application/otf*",
102 "application/rss+xml*",
103 "application/truetype*",
104 "application/ttf*",
105 "application/vnd.api+json*",
106 "application/vnd.ms-fontobject*",
107 "application/wasm*",
108 "application/x-httpd-cgi*",
109 "application/x-javascript*",
110 "application/x-opentype*",
111 "application/x-otf*",
112 "application/x-perl*",
113 "application/x-protobuf*",
114 "application/x-ttf*",
115 "application/xhtml+xml*",
116 "application/xml*",
117 "font/ttf*",
118 "font/otf*",
119 "image/svg+xml*",
120 "image/vnd.microsoft.icon*",
121 "image/x-icon*",
122 "multipart/bag*",
123 "multipart/mixed*",
124 "text/*",
125 },
126 },
127 }
128 }
129
130 if len(enc.Prefer) == 0 {
131 for _, encName := range []string{"zstd", "br", "gzip"} {
132 if _, ok := enc.writerPools[encName]; ok {
133 enc.Prefer = append(enc.Prefer, encName)
134 }
135 }
136 }
137
138 return nil
139 }
140
141 // Validate ensures that enc's configuration is valid.
142 func (enc *Encode) Validate() error {
143 check := make(map[string]bool)
144 for _, encName := range enc.Prefer {
145 if _, ok := enc.writerPools[encName]; !ok {
146 return fmt.Errorf("encoding %s not enabled", encName)
147 }
148
149 if _, ok := check[encName]; ok {
150 return fmt.Errorf("encoding %s is duplicated in prefer", encName)
151 }
152 check[encName] = true
153 }
154
155 return nil
156 }
157
158 func isEncodeAllowed(h http.Header) bool {
159 return !strings.Contains(h.Get("Cache-Control"), "no-transform")
160 }
161
162 func (enc *Encode) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
163 if isEncodeAllowed(r.Header) {
164 for _, encName := range AcceptedEncodings(r, enc.Prefer) {
165 if _, ok := enc.writerPools[encName]; !ok {
166 continue // encoding not offered
167 }
168 w = enc.openResponseWriter(encName, w, r.Method == http.MethodConnect)
169 defer w.(*responseWriter).Close()
170
171 // to comply with RFC 9110 section 8.8.3(.3), we modify the Etag when encoding
172 // by appending a hyphen and the encoder name; the problem is, the client will
173 // send back that Etag in an If-None-Match header, but upstream handlers that set
174 // the Etag in the first place don't know that we appended to their Etag! so here
175 // we have to strip our addition so the upstream handlers can still honor client
176 // caches without knowing about our changes...
177 if etag := r.Header.Get("If-None-Match"); etag != "" && !strings.HasPrefix(etag, "W/") {
178 ourSuffix := "-" + encName + `"`
179 if before, ok := strings.CutSuffix(etag, ourSuffix); ok {
180 etag = before + `"`
181 r.Header.Set("If-None-Match", etag)
182 }
183 }
184
185 break
186 }
187 }
188
189 err := next.ServeHTTP(w, r)
190 // If there was an error, disable encoding completely
191 // This prevents corruption when handle_errors processes the response
192 if err != nil {
193 if ew, ok := w.(*responseWriter); ok {
194 ew.disabled = true
195 }
196 }
197
198 return err
199 }
200
201 func (enc *Encode) addEncoding(e Encoding) error {
202 ae := e.AcceptEncoding()
203 if ae == "" {
204 return fmt.Errorf("encoder does not specify an Accept-Encoding value")
205 }
206 if _, ok := enc.writerPools[ae]; ok {
207 return fmt.Errorf("encoder already added: %s", ae)
208 }
209 if enc.writerPools == nil {
210 enc.writerPools = make(map[string]*sync.Pool)
211 }
212 enc.writerPools[ae] = &sync.Pool{
213 New: func() any {
214 return e.NewEncoder()
215 },
216 }
217 return nil
218 }
219
220 // openResponseWriter creates a new response writer that may (or may not)
221 // encode the response with encodingName. The returned response writer MUST
222 // be closed after the handler completes.
223 func (enc *Encode) openResponseWriter(encodingName string, w http.ResponseWriter, isConnect bool) *responseWriter {
224 var rw responseWriter
225 return enc.initResponseWriter(&rw, encodingName, w, isConnect)
226 }
227
228 // initResponseWriter initializes the responseWriter instance
229 // allocated in openResponseWriter, enabling mid-stack inlining.
230 func (enc *Encode) initResponseWriter(rw *responseWriter, encodingName string, wrappedRW http.ResponseWriter, isConnect bool) *responseWriter {
231 if rww, ok := wrappedRW.(*caddyhttp.ResponseWriterWrapper); ok {
232 rw.ResponseWriter = rww
233 } else {
234 rw.ResponseWriter = &caddyhttp.ResponseWriterWrapper{ResponseWriter: wrappedRW}
235 }
236 rw.encodingName = encodingName
237 rw.config = enc
238 rw.isConnect = isConnect
239
240 return rw
241 }
242
243 // responseWriter writes to an underlying response writer
244 // using the encoding represented by encodingName and
245 // configured by config.
246 type responseWriter struct {
247 http.ResponseWriter
248 encodingName string
249 w Encoder
250 config *Encode
251 statusCode int
252 wroteHeader bool
253 isConnect bool
254 disabled bool // disable encoding (for error responses)
255 }
256
257 // WriteHeader stores the status to write when the time comes
258 // to actually write the header.
259 func (rw *responseWriter) WriteHeader(status int) {
260 rw.statusCode = status
261
262 // See #5849 and RFC 9110 section 15.4.5 (https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4.5) - 304
263 // Not Modified must have certain headers set as if it was a 200 response, and according to the issue
264 // we would miss the Vary header in this case when compression was also enabled; note that we set this
265 // header in the responseWriter.init() method but that is only called if we are writing a response body
266 if status == http.StatusNotModified && !hasVaryValue(rw.Header(), "Accept-Encoding") {
267 rw.Header().Add("Vary", "Accept-Encoding")
268 }
269
270 // write status immediately if status is 2xx and the request is CONNECT
271 // since it means the response is successful.
272 // see: https://github.com/caddyserver/caddy/issues/6733#issuecomment-2525058845
273 if rw.isConnect && 200 <= status && status <= 299 {
274 rw.ResponseWriter.WriteHeader(status)
275 rw.wroteHeader = true
276 }
277
278 // write status immediately when status code is informational
279 // see: https://caddy.community/t/disappear-103-early-hints-response-with-encode-enable-caddy-v2-7-6/23081/5
280 if 100 <= status && status <= 199 {
281 rw.ResponseWriter.WriteHeader(status)
282 }
283 }
284
285 // Match determines, if encoding should be done based on the ResponseMatcher.
286 func (enc *Encode) Match(rw *responseWriter) bool {
287 return enc.Matcher.Match(rw.statusCode, rw.Header())
288 }
289
290 // FlushError is an alternative Flush returning an error. It delays the actual Flush of the underlying
291 // ResponseWriterWrapper until headers were written.
292 func (rw *responseWriter) FlushError() error {
293 // WriteHeader wasn't called and is a CONNECT request, treat it as a success.
294 // otherwise, wait until header is written.
295 if rw.isConnect && !rw.wroteHeader && rw.statusCode == 0 {
296 rw.WriteHeader(http.StatusOK)
297 }
298
299 if !rw.wroteHeader {
300 // flushing the underlying ResponseWriter will write header and status code,
301 // but we need to delay that until we can determine if we must encode and
302 // therefore add the Content-Encoding header; this happens in the first call
303 // to rw.Write (see bug in #4314)
304 return nil
305 }
306 // also flushes the encoder, if any
307 // see: https://github.com/jjiang-stripe/caddy-slow-gzip
308 if rw.w != nil {
309 err := rw.w.Flush()
310 if err != nil {
311 return err
312 }
313 }
314 //nolint:bodyclose
315 return http.NewResponseController(rw.ResponseWriter).Flush()
316 }
317
318 // Write writes to the response. If the response qualifies,
319 // it is encoded using the encoder, which is initialized
320 // if not done so already.
321 func (rw *responseWriter) Write(p []byte) (int, error) {
322 // ignore zero data writes, probably head request
323 if len(p) == 0 {
324 return 0, nil
325 }
326
327 // WriteHeader wasn't called and is a CONNECT request, treat it as a success.
328 // otherwise, determine if the response should be compressed.
329 if rw.isConnect && !rw.wroteHeader && rw.statusCode == 0 {
330 rw.WriteHeader(http.StatusOK)
331 }
332
333 // sniff content-type and determine content-length
334 if !rw.wroteHeader && rw.config.MinLength > 0 {
335 var gtMinLength bool
336 if len(p) > rw.config.MinLength {
337 gtMinLength = true
338 } else if cl, err := strconv.Atoi(rw.Header().Get("Content-Length")); err == nil && cl > rw.config.MinLength {
339 gtMinLength = true
340 }
341
342 if gtMinLength {
343 if rw.Header().Get("Content-Type") == "" {
344 rw.Header().Set("Content-Type", http.DetectContentType(p))
345 }
346 rw.init()
347 }
348 }
349
350 // before we write to the response, we need to make
351 // sure the header is written exactly once; we do
352 // that by checking if a status code has been set,
353 // and if so, that means we haven't written the
354 // header OR the default status code will be written
355 // by the standard library
356 if !rw.wroteHeader {
357 if rw.statusCode != 0 {
358 rw.ResponseWriter.WriteHeader(rw.statusCode)
359 }
360 rw.wroteHeader = true
361 }
362
363 if rw.w != nil {
364 return rw.w.Write(p)
365 } else {
366 return rw.ResponseWriter.Write(p)
367 }
368 }
369
370 // used to mask ReadFrom method
371 type writerOnly struct {
372 io.Writer
373 }
374
375 // copied from stdlib
376 const sniffLen = 512
377
378 // ReadFrom will try to use sendfile to copy from the reader to the response writer.
379 // It's only used if the response writer implements io.ReaderFrom and the data can't be compressed.
380 // It's based on the standard library HTTP/1.1 response writer implementation.
381 // https://github.com/golang/go/blob/f4e3ec3dbe3b8e04a058d266adf8e048bab563f2/src/net/http/server.go#L586
382 func (rw *responseWriter) ReadFrom(r io.Reader) (int64, error) {
383 rf, ok := rw.ResponseWriter.(io.ReaderFrom)
384 // sendfile can't be used anyway
385 if !ok {
386 // mask ReadFrom to avoid infinite recursion
387 return io.Copy(writerOnly{rw}, r)
388 }
389
390 var ns int64
391 // try to sniff the content type and determine if the response should be compressed
392 if !rw.wroteHeader && rw.config.MinLength > 0 {
393 var (
394 err error
395 buf [sniffLen]byte
396 )
397 // mask ReadFrom to let Write determine if the response should be compressed
398 ns, err = io.CopyBuffer(writerOnly{rw}, io.LimitReader(r, sniffLen), buf[:])
399 if err != nil || ns < sniffLen {
400 return ns, err
401 }
402 }
403
404 // the response will be compressed, no sendfile support
405 if rw.w != nil {
406 nr, err := io.Copy(rw.w, r)
407 return nr + ns, err
408 }
409 nr, err := rf.ReadFrom(r)
410 return nr + ns, err
411 }
412
413 // Close writes any remaining buffered response and
414 // deallocates any active resources.
415 func (rw *responseWriter) Close() error {
416 // didn't write, probably head request
417 if !rw.wroteHeader {
418 cl, err := strconv.Atoi(rw.Header().Get("Content-Length"))
419 if err == nil && cl > rw.config.MinLength {
420 rw.init()
421 }
422
423 // issue #5059, don't write status code if not set explicitly.
424 if rw.statusCode != 0 {
425 rw.ResponseWriter.WriteHeader(rw.statusCode)
426 }
427 rw.wroteHeader = true
428 }
429
430 var err error
431 if rw.w != nil {
432 err = rw.w.Close()
433 rw.w.Reset(nil)
434 rw.config.writerPools[rw.encodingName].Put(rw.w)
435 rw.w = nil
436 }
437 return err
438 }
439
440 // Unwrap returns the underlying ResponseWriter.
441 func (rw *responseWriter) Unwrap() http.ResponseWriter {
442 return rw.ResponseWriter
443 }
444
445 // init should be called before we write a response, if rw.buf has contents.
446 func (rw *responseWriter) init() {
447 // Don't initialize encoder for error responses
448 // This prevents response corruption when handle_errors is used
449 if rw.disabled {
450 return
451 }
452
453 hdr := rw.Header()
454
455 if hdr.Get("Content-Encoding") == "" && isEncodeAllowed(hdr) &&
456 rw.config.Match(rw) {
457 rw.w = rw.config.writerPools[rw.encodingName].Get().(Encoder)
458 rw.w.Reset(rw.ResponseWriter)
459 hdr.Del("Content-Length") // https://github.com/golang/go/issues/14975
460 hdr.Set("Content-Encoding", rw.encodingName)
461 if !hasVaryValue(hdr, "Accept-Encoding") {
462 hdr.Add("Vary", "Accept-Encoding")
463 }
464 hdr.Del("Accept-Ranges") // we don't know ranges for dynamically-encoded content
465
466 // strong ETags need to be distinct depending on the encoding ("selected representation")
467 // see RFC 9110 section 8.8.3.3:
468 // https://www.rfc-editor.org/rfc/rfc9110.html#name-example-entity-tags-varying
469 // I don't know a great way to do this... how about appending? That's a neat trick!
470 // (We have to strip the value we append from If-None-Match headers before
471 // sending subsequent requests back upstream, however, since upstream handlers
472 // don't know about our appending to their Etag since they've already done their work)
473 if etag := hdr.Get("Etag"); etag != "" && !strings.HasPrefix(etag, "W/") {
474 etag = fmt.Sprintf(`%s-%s"`, strings.TrimSuffix(etag, `"`), rw.encodingName)
475 hdr.Set("Etag", etag)
476 }
477 }
478 }
479
480 func hasVaryValue(hdr http.Header, target string) bool {
481 for _, vary := range hdr.Values("Vary") {
482 for val := range strings.SplitSeq(vary, ",") {
483 if strings.EqualFold(strings.TrimSpace(val), target) {
484 return true
485 }
486 }
487 }
488 return false
489 }
490
491 // AcceptedEncodings returns the list of encodings that the
492 // client supports, in descending order of preference.
493 // The client preference via q-factor and the server
494 // preference via Prefer setting are taken into account. If
495 // the Sec-WebSocket-Key header is present then non-identity
496 // encodings are not considered. See
497 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.
498 func AcceptedEncodings(r *http.Request, preferredOrder []string) []string {
499 acceptEncHeader := r.Header.Get("Accept-Encoding")
500 websocketKey := r.Header.Get("Sec-WebSocket-Key")
501 if acceptEncHeader == "" {
502 return []string{}
503 }
504
505 prefs := []encodingPreference{}
506
507 for accepted := range strings.SplitSeq(acceptEncHeader, ",") {
508 parts := strings.Split(accepted, ";")
509 encName := strings.ToLower(strings.TrimSpace(parts[0]))
510
511 // determine q-factor
512 qFactor := 1.0
513 if len(parts) > 1 {
514 qFactorStr := strings.ToLower(strings.TrimSpace(parts[1]))
515 if strings.HasPrefix(qFactorStr, "q=") {
516 if qFactorFloat, err := strconv.ParseFloat(qFactorStr[2:], 32); err == nil {
517 if qFactorFloat >= 0 && qFactorFloat <= 1 {
518 qFactor = qFactorFloat
519 }
520 }
521 }
522 }
523
524 // encodings with q-factor of 0 are not accepted;
525 // use a small threshold to account for float precision
526 if qFactor < 0.00001 {
527 continue
528 }
529
530 // don't encode WebSocket handshakes
531 if websocketKey != "" && encName != "identity" {
532 continue
533 }
534
535 // set server preference
536 prefOrder := slices.Index(preferredOrder, encName)
537 if prefOrder > -1 {
538 prefOrder = len(preferredOrder) - prefOrder
539 }
540
541 prefs = append(prefs, encodingPreference{
542 encoding: encName,
543 q: qFactor,
544 preferOrder: prefOrder,
545 })
546 }
547
548 // sort preferences by descending q-factor first, then by preferOrder
549 slices.SortStableFunc(prefs, func(a, b encodingPreference) int {
550 if math.Abs(a.q-b.q) < 0.00001 {
551 return cmp.Compare(b.preferOrder, a.preferOrder)
552 }
553 return cmp.Compare(b.q, a.q)
554 })
555
556 prefEncNames := make([]string, len(prefs))
557 for i := range prefs {
558 prefEncNames[i] = prefs[i].encoding
559 }
560
561 return prefEncNames
562 }
563
564 // encodingPreference pairs an encoding with its q-factor.
565 type encodingPreference struct {
566 encoding string
567 q float64
568 preferOrder int
569 }
570
571 // Encoder is a type which can encode a stream of data.
572 type Encoder interface {
573 io.WriteCloser
574 Reset(io.Writer)
575 Flush() error // encoder by default buffers data to maximize compressing rate
576 }
577
578 // Encoding is a type which can create encoders of its kind
579 // and return the name used in the Accept-Encoding header.
580 type Encoding interface {
581 AcceptEncoding() string
582 NewEncoder() Encoder
583 }
584
585 // Precompressed is a type which returns filename suffix of precompressed
586 // file and Accept-Encoding header to use when serving this file.
587 type Precompressed interface {
588 AcceptEncoding() string
589 Suffix() string
590 }
591
592 // defaultMinLength is the minimum length at which to compress content.
593 const defaultMinLength = 512
594
595 // Interface guards
596 var (
597 _ caddy.Provisioner = (*Encode)(nil)
598 _ caddy.Validator = (*Encode)(nil)
599 _ caddyhttp.MiddlewareHandler = (*Encode)(nil)
600 )