Debian Codegraph @

modules/caddyhttp/reverseproxy/reverseproxy.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 reverseproxy
16
17 import (
18 "bytes"
19 "context"
20 "crypto/rand"
21 "encoding/base64"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "net"
27 "net/http"
28 "net/http/httptrace"
29 "net/netip"
30 "net/textproto"
31 "net/url"
32 "strconv"
33 "strings"
34 "sync"
35 "sync/atomic"
36 "time"
37
38 "go.uber.org/zap"
39 "go.uber.org/zap/zapcore"
40 "golang.org/x/net/http/httpguts"
41
42 "github.com/caddyserver/caddy/v2"
43 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
44 "github.com/caddyserver/caddy/v2/modules/caddyevents"
45 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
46 "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
47 "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite"
48 )
49
50 // inFlightRequests uses sync.Map with atomic.Int64 for lock-free updates on the hot path
51 var inFlightRequests sync.Map
52
53 func incInFlightRequest(address string) {
54 v, _ := inFlightRequests.LoadOrStore(address, new(atomic.Int64))
55 v.(*atomic.Int64).Add(1)
56 }
57
58 func decInFlightRequest(address string) {
59 if v, ok := inFlightRequests.Load(address); ok {
60 if v.(*atomic.Int64).Add(-1) <= 0 {
61 inFlightRequests.Delete(address)
62 }
63 }
64 }
65
66 func getInFlightRequests() map[string]int64 {
67 copyMap := make(map[string]int64)
68 inFlightRequests.Range(func(key, value any) bool {
69 copyMap[key.(string)] = value.(*atomic.Int64).Load()
70 return true
71 })
72 return copyMap
73 }
74
75 func init() {
76 caddy.RegisterModule(Handler{})
77 }
78
79 // Handler implements a highly configurable and production-ready reverse proxy.
80 //
81 // Upon proxying, this module sets the following placeholders (which can be used
82 // both within and after this handler; for example, in response headers):
83 //
84 // Placeholder | Description
85 // ------------|-------------
86 // `{http.reverse_proxy.upstream.address}` | The full address to the upstream as given in the config
87 // `{http.reverse_proxy.upstream.hostport}` | The host:port of the upstream
88 // `{http.reverse_proxy.upstream.host}` | The host of the upstream
89 // `{http.reverse_proxy.upstream.port}` | The port of the upstream
90 // `{http.reverse_proxy.upstream.requests}` | The approximate current number of requests to the upstream
91 // `{http.reverse_proxy.upstream.max_requests}` | The maximum approximate number of requests allowed to the upstream
92 // `{http.reverse_proxy.upstream.fails}` | The number of recent failed requests to the upstream
93 // `{http.reverse_proxy.upstream.latency}` | How long it took the proxy upstream to write the response header.
94 // `{http.reverse_proxy.upstream.latency_ms}` | Same as 'latency', but in milliseconds.
95 // `{http.reverse_proxy.upstream.duration}` | Time spent proxying to the upstream, including writing response body to client.
96 // `{http.reverse_proxy.upstream.duration_ms}` | Same as 'upstream.duration', but in milliseconds.
97 // `{http.reverse_proxy.duration}` | Total time spent proxying, including selecting an upstream, retries, and writing response.
98 // `{http.reverse_proxy.duration_ms}` | Same as 'duration', but in milliseconds.
99 // `{http.reverse_proxy.retries}` | The number of retries actually performed to communicate with an upstream.
100 type Handler struct {
101 // Configures the method of transport for the proxy. A transport
102 // is what performs the actual "round trip" to the backend.
103 // The default transport is plaintext HTTP.
104 TransportRaw json.RawMessage `json:"transport,omitempty" caddy:"namespace=http.reverse_proxy.transport inline_key=protocol"`
105
106 // A circuit breaker may be used to relieve pressure on a backend
107 // that is beginning to exhibit symptoms of stress or latency.
108 // By default, there is no circuit breaker.
109 CBRaw json.RawMessage `json:"circuit_breaker,omitempty" caddy:"namespace=http.reverse_proxy.circuit_breakers inline_key=type"`
110
111 // Load balancing distributes load/requests between backends.
112 LoadBalancing *LoadBalancing `json:"load_balancing,omitempty"`
113
114 // Health checks update the status of backends, whether they are
115 // up or down. Down backends will not be proxied to.
116 HealthChecks *HealthChecks `json:"health_checks,omitempty"`
117
118 // Upstreams is the static list of backends to proxy to.
119 Upstreams UpstreamPool `json:"upstreams,omitempty"`
120
121 // A module for retrieving the list of upstreams dynamically. Dynamic
122 // upstreams are retrieved at every iteration of the proxy loop for
123 // each request (i.e. before every proxy attempt within every request).
124 // Active health checks do not work on dynamic upstreams, and passive
125 // health checks are only effective on dynamic upstreams if the proxy
126 // server is busy enough that concurrent requests to the same backends
127 // are continuous. Instead of health checks for dynamic upstreams, it
128 // is recommended that the dynamic upstream module only return available
129 // backends in the first place.
130 DynamicUpstreamsRaw json.RawMessage `json:"dynamic_upstreams,omitempty" caddy:"namespace=http.reverse_proxy.upstreams inline_key=source"`
131
132 // Adjusts how often to flush the response buffer. By default,
133 // no periodic flushing is done. A negative value disables
134 // response buffering, and flushes immediately after each
135 // write to the client. This option is ignored when the upstream's
136 // response is recognized as a streaming response, or if its
137 // content length is -1; for such responses, writes are flushed
138 // to the client immediately.
139 FlushInterval caddy.Duration `json:"flush_interval,omitempty"`
140
141 // A list of IP ranges (supports CIDR notation) from which
142 // X-Forwarded-* header values should be trusted. By default,
143 // no proxies are trusted, so existing values will be ignored
144 // when setting these headers. If the proxy is trusted, then
145 // existing values will be used when constructing the final
146 // header values.
147 TrustedProxies []string `json:"trusted_proxies,omitempty"`
148
149 // Headers manipulates headers between Caddy and the backend.
150 // By default, all headers are passed-thru without changes,
151 // with the exceptions of special hop-by-hop headers.
152 //
153 // X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host
154 // are also set implicitly.
155 Headers *headers.Handler `json:"headers,omitempty"`
156
157 // If nonzero, the entire request body up to this size will be read
158 // and buffered in memory before being proxied to the backend. This
159 // should be avoided if at all possible for performance reasons, but
160 // could be useful if the backend is intolerant of read latency or
161 // chunked encodings.
162 RequestBuffers int64 `json:"request_buffers,omitempty"`
163
164 // If nonzero, the entire response body up to this size will be read
165 // and buffered in memory before being proxied to the client. This
166 // should be avoided if at all possible for performance reasons, but
167 // could be useful if the backend has tighter memory constraints.
168 ResponseBuffers int64 `json:"response_buffers,omitempty"`
169
170 // If nonzero, streaming requests such as WebSockets will be
171 // forcibly closed at the end of the timeout. Default: no timeout.
172 StreamTimeout caddy.Duration `json:"stream_timeout,omitempty"`
173
174 // The size of the buffer used for each direction of streaming
175 // requests such as WebSockets. If zero, the default size is 32 KiB.
176 // This only affects upgraded bidirectional streams, not normal
177 // request or response buffering.
178 StreamBufferSize int `json:"stream_buffer_size,omitempty"`
179
180 // If nonzero, streaming requests such as WebSockets will not be
181 // closed when the proxy config is unloaded, and instead the stream
182 // will remain open until the delay is complete. In other words,
183 // enabling this prevents streams from closing when Caddy's config
184 // is reloaded. Enabling this may be a good idea to avoid a thundering
185 // herd of reconnecting clients which had their connections closed
186 // by the previous config closing. Default: no delay.
187 StreamCloseDelay caddy.Duration `json:"stream_close_delay,omitempty"`
188
189 // If configured, rewrites the copy of the upstream request.
190 // Allows changing the request method and URI (path and query).
191 // Since the rewrite is applied to the copy, it does not persist
192 // past the reverse proxy handler.
193 // If the method is changed to `GET` or `HEAD`, the request body
194 // will not be copied to the backend. This allows a later request
195 // handler -- either in a `handle_response` route, or after -- to
196 // read the body.
197 // By default, no rewrite is performed, and the method and URI
198 // from the incoming request is used as-is for proxying.
199 Rewrite *rewrite.Rewrite `json:"rewrite,omitempty"`
200
201 // List of handlers and their associated matchers to evaluate
202 // after successful roundtrips. The first handler that matches
203 // the response from a backend will be invoked. The response
204 // body from the backend will not be written to the client;
205 // it is up to the handler to finish handling the response.
206 // If passive health checks are enabled, any errors from the
207 // handler chain will not affect the health status of the
208 // backend.
209 //
210 // Three new placeholders are available in this handler chain:
211 // - `{http.reverse_proxy.status_code}` The status code from the response
212 // - `{http.reverse_proxy.status_text}` The status text from the response
213 // - `{http.reverse_proxy.header.*}` The headers from the response
214 HandleResponse []caddyhttp.ResponseHandler `json:"handle_response,omitempty"`
215
216 // If set, the proxy will write very detailed logs about its
217 // inner workings. Enable this only when debugging, as it
218 // will produce a lot of output.
219 //
220 // EXPERIMENTAL: This feature is subject to change or removal.
221 VerboseLogs bool `json:"verbose_logs,omitempty"`
222
223 Transport http.RoundTripper `json:"-"`
224 CB CircuitBreaker `json:"-"`
225 DynamicUpstreams UpstreamSource `json:"-"`
226
227 // transportHeaderOps is a set of header operations provided
228 // by the transport at provision time, if the transport
229 // implements TransportHeaderOpsProvider. These ops are
230 // applied before any user-configured header ops so the
231 // user can override transport defaults.
232 transportHeaderOps *headers.HeaderOps
233
234 // Holds the parsed CIDR ranges from TrustedProxies
235 trustedProxies []netip.Prefix
236
237 // Holds the named response matchers from the Caddyfile while adapting
238 responseMatchers map[string]caddyhttp.ResponseMatcher
239
240 // Holds the handle_response Caddyfile tokens while adapting
241 handleResponseSegments []*caddyfile.Dispenser
242
243 // Stores upgraded requests (hijacked connections) for proper cleanup
244 connections map[io.ReadWriteCloser]openConnection
245 connectionsCloseTimer *time.Timer
246 connectionsMu *sync.Mutex
247
248 ctx caddy.Context
249 logger *zap.Logger
250 events *caddyevents.App
251 }
252
253 // CaddyModule returns the Caddy module information.
254 func (Handler) CaddyModule() caddy.ModuleInfo {
255 return caddy.ModuleInfo{
256 ID: "http.handlers.reverse_proxy",
257 New: func() caddy.Module { return new(Handler) },
258 }
259 }
260
261 // Provision ensures that h is set up properly before use.
262 func (h *Handler) Provision(ctx caddy.Context) error {
263 eventAppIface, err := ctx.App("events")
264 if err != nil {
265 return fmt.Errorf("getting events app: %v", err)
266 }
267 h.events = eventAppIface.(*caddyevents.App)
268 h.ctx = ctx
269 h.logger = ctx.Logger()
270 h.connections = make(map[io.ReadWriteCloser]openConnection)
271 h.connectionsMu = new(sync.Mutex)
272
273 // warn about unsafe buffering config
274 if h.RequestBuffers == -1 || h.ResponseBuffers == -1 {
275 h.logger.Warn("UNLIMITED BUFFERING: buffering is enabled without any cap on buffer size, which can result in OOM crashes")
276 }
277
278 // start by loading modules
279 if h.TransportRaw != nil {
280 mod, err := ctx.LoadModule(h, "TransportRaw")
281 if err != nil {
282 return fmt.Errorf("loading transport: %v", err)
283 }
284 h.Transport = mod.(http.RoundTripper)
285
286 // set default buffer sizes if applicable
287 if bt, ok := h.Transport.(BufferedTransport); ok {
288 reqBuffers, respBuffers := bt.DefaultBufferSizes()
289 if h.RequestBuffers == 0 {
290 h.RequestBuffers = reqBuffers
291 }
292 if h.ResponseBuffers == 0 {
293 h.ResponseBuffers = respBuffers
294 }
295 }
296 }
297 if h.LoadBalancing != nil && h.LoadBalancing.SelectionPolicyRaw != nil {
298 mod, err := ctx.LoadModule(h.LoadBalancing, "SelectionPolicyRaw")
299 if err != nil {
300 return fmt.Errorf("loading load balancing selection policy: %s", err)
301 }
302 h.LoadBalancing.SelectionPolicy = mod.(Selector)
303 }
304 if h.CBRaw != nil {
305 mod, err := ctx.LoadModule(h, "CBRaw")
306 if err != nil {
307 return fmt.Errorf("loading circuit breaker: %s", err)
308 }
309 h.CB = mod.(CircuitBreaker)
310 }
311 if h.DynamicUpstreamsRaw != nil {
312 mod, err := ctx.LoadModule(h, "DynamicUpstreamsRaw")
313 if err != nil {
314 return fmt.Errorf("loading upstream source module: %v", err)
315 }
316 h.DynamicUpstreams = mod.(UpstreamSource)
317 }
318
319 // parse trusted proxy CIDRs ahead of time
320 for _, str := range h.TrustedProxies {
321 if strings.Contains(str, "/") {
322 ipNet, err := netip.ParsePrefix(str)
323 if err != nil {
324 return fmt.Errorf("parsing CIDR expression: '%s': %v", str, err)
325 }
326 h.trustedProxies = append(h.trustedProxies, ipNet)
327 } else {
328 ipAddr, err := netip.ParseAddr(str)
329 if err != nil {
330 return fmt.Errorf("invalid IP address: '%s': %v", str, err)
331 }
332 ipNew := netip.PrefixFrom(ipAddr, ipAddr.BitLen())
333 h.trustedProxies = append(h.trustedProxies, ipNew)
334 }
335 }
336
337 // ensure any embedded headers handler module gets provisioned
338 // (see https://caddy.community/t/set-cookie-manipulation-in-reverse-proxy/7666?u=matt
339 // for what happens if we forget to provision it)
340 if h.Headers != nil {
341 err := h.Headers.Provision(ctx)
342 if err != nil {
343 return fmt.Errorf("provisioning embedded headers handler: %v", err)
344 }
345 }
346
347 if h.Rewrite != nil {
348 err := h.Rewrite.Provision(ctx)
349 if err != nil {
350 return fmt.Errorf("provisioning rewrite: %v", err)
351 }
352 }
353
354 // set up transport
355 if h.Transport == nil {
356 t := &HTTPTransport{}
357 err := t.Provision(ctx)
358 if err != nil {
359 return fmt.Errorf("provisioning default transport: %v", err)
360 }
361 h.Transport = t
362 }
363
364 // If the transport can provide header ops, cache them now so we don't
365 // have to compute them per-request. Provision the HeaderOps if present
366 // so any runtime artifacts (like precompiled regex) are prepared.
367 if tph, ok := h.Transport.(RequestHeaderOpsTransport); ok {
368 h.transportHeaderOps = tph.RequestHeaderOps()
369 if h.transportHeaderOps != nil {
370 if err := h.transportHeaderOps.Provision(ctx); err != nil {
371 return fmt.Errorf("provisioning transport header ops: %v", err)
372 }
373 }
374 }
375
376 // set up load balancing
377 if h.LoadBalancing == nil {
378 h.LoadBalancing = new(LoadBalancing)
379 }
380 if h.LoadBalancing.SelectionPolicy == nil {
381 h.LoadBalancing.SelectionPolicy = RandomSelection{}
382 }
383 if h.LoadBalancing.TryDuration > 0 && h.LoadBalancing.TryInterval == 0 {
384 // a non-zero try_duration with a zero try_interval
385 // will always spin the CPU for try_duration if the
386 // upstream is local or low-latency; avoid that by
387 // defaulting to a sane wait period between attempts
388 h.LoadBalancing.TryInterval = caddy.Duration(250 * time.Millisecond)
389 }
390 lbMatcherSets, err := ctx.LoadModule(h.LoadBalancing, "RetryMatchRaw")
391 if err != nil {
392 return err
393 }
394 err = h.LoadBalancing.RetryMatch.FromInterface(lbMatcherSets)
395 if err != nil {
396 return err
397 }
398
399 // set up upstreams
400 for _, u := range h.Upstreams {
401 h.provisionUpstream(u, false)
402 }
403
404 if h.HealthChecks != nil {
405 // set defaults on passive health checks, if necessary
406 if h.HealthChecks.Passive != nil {
407 h.HealthChecks.Passive.logger = h.logger.Named("health_checker.passive")
408 if h.HealthChecks.Passive.MaxFails == 0 {
409 h.HealthChecks.Passive.MaxFails = 1
410 }
411 }
412
413 // if active health checks are enabled, configure them and start a worker
414 if h.HealthChecks.Active != nil {
415 err := h.HealthChecks.Active.Provision(ctx, h)
416 if err != nil {
417 return err
418 }
419
420 if h.HealthChecks.Active.IsEnabled() {
421 go h.activeHealthChecker()
422 }
423 }
424 }
425
426 // set up any response routes
427 for i, rh := range h.HandleResponse {
428 err := rh.Provision(ctx)
429 if err != nil {
430 return fmt.Errorf("provisioning response handler %d: %v", i, err)
431 }
432 }
433
434 upstreamHealthyUpdater := newMetricsUpstreamsHealthyUpdater(h, ctx)
435 upstreamHealthyUpdater.init()
436
437 return nil
438 }
439
440 // Cleanup cleans up the resources made by h.
441 func (h *Handler) Cleanup() error {
442 err := h.cleanupConnections()
443
444 // remove hosts from our config from the pool
445 for _, upstream := range h.Upstreams {
446 _, _ = hosts.Delete(upstream.String())
447 }
448
449 return err
450 }
451
452 // bodyNopCloserIfNotRead wraps a request body to prevent closing if not read, i.e., when
453 // dialing to upstream fails.
454 // It will close the body as normal if the body is read.
455 type bodyNopCloserIfNotRead struct {
456 io.ReadCloser
457 read int // tracks the number of bytes read, -1 when first Read returns 0, io.EOF
458 }
459
460 func (b *bodyNopCloserIfNotRead) Read(p []byte) (int, error) {
461 if b.read == -1 {
462 return 0, io.EOF
463 }
464 n, err := b.ReadCloser.Read(p)
465 // first Read returns 0, io.EOF
466 if b.read == 0 && n == 0 && err == io.EOF {
467 b.read = -1
468 } else {
469 b.read += n
470 }
471 return n, err
472 }
473
474 func (b *bodyNopCloserIfNotRead) Close() error {
475 // don't close the body
476 if b.read == 0 {
477 return nil
478 }
479 // close as usual, when -1, any read will return EOF as the original read will do
480 // in other cases, the read will fail as body is closed because we do not want partial bodies to be sent to the upstream
481 // users can buffer the entire request body to allow the request to be resent
482 return b.ReadCloser.Close()
483 }
484
485 func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
486 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
487
488 // prepare the request for proxying; this is needed only once
489 clonedReq, err := h.prepareRequest(r, repl)
490 if err != nil {
491 return caddyhttp.Error(http.StatusInternalServerError,
492 fmt.Errorf("preparing request for upstream round-trip: %v", err))
493 }
494
495 // websocket over http2 or http3 if extended connect is enabled, assuming backend doesn't support this, the request will be modified to http1.1 upgrade
496 // Both use the same upgrade mechanism: server advertizes extended connect support, and client sends the pseudo header :protocol in a CONNECT request
497 // The quic-go http3 implementation also puts :protocol in r.Proto for CONNECT requests (quic-go/http3/headers.go@70-72,185,203)
498 // TODO: once we can reliably detect backend support this, it can be removed for those backends
499 if (r.ProtoMajor == 2 && r.Method == http.MethodConnect && r.Header.Get(":protocol") == "websocket") ||
500 (r.ProtoMajor == 3 && r.Method == http.MethodConnect && r.Proto == "websocket") {
501 clonedReq.Header.Del(":protocol")
502 // keep the body for later use. http1.1 upgrade uses http.NoBody
503 caddyhttp.SetVar(clonedReq.Context(), "extended_connect_websocket_body", clonedReq.Body)
504 clonedReq.Body = http.NoBody
505 clonedReq.Method = http.MethodGet
506 clonedReq.Header.Set("Upgrade", "websocket")
507 clonedReq.Header.Set("Connection", "Upgrade")
508 key := make([]byte, 16)
509 _, randErr := rand.Read(key)
510 if randErr != nil {
511 return randErr
512 }
513 clonedReq.Header["Sec-WebSocket-Key"] = []string{base64.StdEncoding.EncodeToString(key)}
514 }
515
516 // we will need the original headers and Host value if
517 // header operations are configured; this is so that each
518 // retry can apply the modifications, because placeholders
519 // may be used which depend on the selected upstream for
520 // their values
521 reqHost := clonedReq.Host
522 reqHeader := clonedReq.Header
523
524 // If the request contained a body, wrap it in io.NopCloser
525 // to prevent Go's transport from closing it on dial errors.
526 // cloneRequest does a shallow copy, so clonedReq.Body and
527 // r.Body share the same io.ReadCloser — a dial-failure Close()
528 // would kill the original body for all subsequent retry
529 // attempts or subsequent handlers. The real body is closed by
530 // the HTTP server when the handler returns.
531 //
532 // If the body was already fully buffered (via request_buffers),
533 // we also extract the buffer so the retry loop can replay it
534 // from the beginning on each attempt. (see #6259, #7546, #7713)
535 var bufferedReqBody *bytes.Buffer
536 if clonedReq.Body != nil {
537 if reqBodyBuf, ok := clonedReq.Body.(bodyReadCloser); ok && reqBodyBuf.body == nil && reqBodyBuf.buf != nil {
538 bufferedReqBody = reqBodyBuf.buf
539 reqBodyBuf.buf = nil
540 clonedReq.Body = io.NopCloser(bytes.NewReader(bufferedReqBody.Bytes()))
541 defer func() {
542 bufferedReqBody.Reset()
543 bufPool.Put(bufferedReqBody)
544 }()
545 } else {
546 clonedReq.Body = &bodyNopCloserIfNotRead{ReadCloser: clonedReq.Body}
547 }
548 }
549
550 start := time.Now()
551 defer func() {
552 // total proxying duration, including time spent on LB and retries
553 repl.Set("http.reverse_proxy.duration", time.Since(start))
554 repl.Set("http.reverse_proxy.duration_ms", time.Since(start).Seconds()*1e3) // multiply seconds to preserve decimal (see #4666)
555 }()
556
557 // in the proxy loop, each iteration is an attempt to proxy the request,
558 // and because we may retry some number of times, carry over the error
559 // from previous tries because of the nuances of load balancing & retries
560 var proxyErr error
561 var retries int
562 for {
563 // if the request body was buffered (and only the entire body, hence no body
564 // set to read from after the buffer), make reading from the body idempotent
565 // and reusable, so if a backend partially or fully reads the body but then
566 // produces an error, the request can be repeated to the next backend with
567 // the full body (retries should only happen for idempotent requests) (see #6259)
568 if bufferedReqBody != nil {
569 clonedReq.Body = io.NopCloser(bytes.NewReader(bufferedReqBody.Bytes()))
570 }
571
572 var done bool
573 done, proxyErr = h.proxyLoopIteration(clonedReq, r, w, proxyErr, start, retries, repl, reqHeader, reqHost, next)
574 if done {
575 break
576 }
577 if h.VerboseLogs {
578 var lbWait time.Duration
579 if h.LoadBalancing != nil {
580 lbWait = time.Duration(h.LoadBalancing.TryInterval)
581 }
582 if c := h.logger.Check(zapcore.DebugLevel, "retrying"); c != nil {
583 c.Write(zap.Error(proxyErr), zap.Duration("after", lbWait))
584 }
585 }
586 retries++
587 }
588
589 // number of retries actually performed
590 repl.Set("http.reverse_proxy.retries", retries)
591
592 if proxyErr != nil {
593 return statusError(proxyErr)
594 }
595
596 return nil
597 }
598
599 // proxyLoopIteration implements an iteration of the proxy loop. Despite the enormous amount of local state
600 // that has to be passed in, we brought this into its own method so that we could run defer more easily.
601 // It returns true when the loop is done and should break; false otherwise. The error value returned should
602 // be assigned to the proxyErr value for the next iteration of the loop (or the error handled after break).
603 func (h *Handler) proxyLoopIteration(r *http.Request, origReq *http.Request, w http.ResponseWriter, proxyErr error, start time.Time, retries int,
604 repl *caddy.Replacer, reqHeader http.Header, reqHost string, next caddyhttp.Handler,
605 ) (bool, error) {
606 // get the updated list of upstreams
607 upstreams := h.Upstreams
608 if h.DynamicUpstreams != nil {
609 if retries > 0 {
610 // after a failure (and thus during a retry), give dynamic upstream modules an opportunity
611 // to purge their relevant cache entries so we don't keep retrying bad upstreams
612 if cachingDynamicUpstreams, ok := h.DynamicUpstreams.(CachingUpstreamSource); ok {
613 if err := cachingDynamicUpstreams.ResetCache(r); err != nil {
614 if c := h.logger.Check(zapcore.ErrorLevel, "failed clearing dynamic upstream source's cache"); c != nil {
615 c.Write(zap.Error(err))
616 }
617 }
618 }
619 }
620 dUpstreams, err := h.DynamicUpstreams.GetUpstreams(r)
621 if err != nil {
622 if c := h.logger.Check(zapcore.ErrorLevel, "failed getting dynamic upstreams; falling back to static upstreams"); c != nil {
623 c.Write(zap.Error(err))
624 }
625 } else {
626 upstreams = dUpstreams
627 for _, dUp := range dUpstreams {
628 h.provisionUpstream(dUp, true)
629 }
630 if c := h.logger.Check(zapcore.DebugLevel, "provisioned dynamic upstreams"); c != nil {
631 c.Write(zap.Int("count", len(dUpstreams)))
632 }
633 }
634 }
635
636 // choose an available upstream
637 upstream := h.LoadBalancing.SelectionPolicy.Select(upstreams, r, w)
638 if upstream == nil {
639 if proxyErr == nil {
640 proxyErr = caddyhttp.Error(http.StatusServiceUnavailable, errNoUpstream)
641 }
642 if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r, h.logger) {
643 return true, proxyErr
644 }
645 return false, proxyErr
646 }
647
648 // the dial address may vary per-request if placeholders are
649 // used, so perform those replacements here; the resulting
650 // DialInfo struct should have valid network address syntax
651 dialInfo, err := upstream.fillDialInfo(repl)
652 if err != nil {
653 return true, fmt.Errorf("making dial info: %v", err)
654 }
655
656 if c := h.logger.Check(zapcore.DebugLevel, "selected upstream"); c != nil {
657 c.Write(
658 zap.String("dial", dialInfo.Address),
659 zap.Int("total_upstreams", len(upstreams)),
660 )
661 }
662
663 // attach to the request information about how to dial the upstream;
664 // this is necessary because the information cannot be sufficiently
665 // or satisfactorily represented in a URL
666 caddyhttp.SetVar(r.Context(), dialInfoVarKey, dialInfo)
667
668 // set placeholders with information about this upstream
669 repl.Set("http.reverse_proxy.upstream.address", dialInfo.String())
670 repl.Set("http.reverse_proxy.upstream.hostport", dialInfo.Address)
671 repl.Set("http.reverse_proxy.upstream.host", dialInfo.Host)
672 repl.Set("http.reverse_proxy.upstream.port", dialInfo.Port)
673 repl.Set("http.reverse_proxy.upstream.requests", upstream.Host.NumRequests())
674 repl.Set("http.reverse_proxy.upstream.max_requests", upstream.MaxRequests)
675 repl.Set("http.reverse_proxy.upstream.fails", upstream.Host.Fails())
676
677 // mutate request headers according to this upstream;
678 // because we're in a retry loop, we have to copy headers
679 // (and the r.Host value) from the original so that each
680 // retry is identical to the first. If either transport or
681 // user ops exist, apply them in order (transport first,
682 // then user, so user's config wins).
683 var userOps *headers.HeaderOps
684 if h.Headers != nil {
685 userOps = h.Headers.Request
686 }
687 transportOps := h.transportHeaderOps
688 if transportOps != nil || userOps != nil {
689 r.Header = make(http.Header)
690 copyHeader(r.Header, reqHeader)
691 r.Host = reqHost
692 if transportOps != nil {
693 transportOps.ApplyToRequest(r)
694 }
695 if userOps != nil {
696 userOps.ApplyToRequest(r)
697 }
698 }
699
700 // proxy the request to that upstream
701 proxyErr = h.reverseProxy(w, r, origReq, repl, dialInfo, next)
702 if proxyErr == nil || errors.Is(proxyErr, context.Canceled) {
703 // context.Canceled happens when the downstream client
704 // cancels the request, which is not our failure
705 return true, nil
706 }
707
708 // if the roundtrip was successful, don't retry the request or
709 // ding the health status of the upstream (an error can still
710 // occur after the roundtrip if, for example, a response handler
711 // after the roundtrip returns an error)
712 if succ, ok := proxyErr.(roundtripSucceededError); ok {
713 return true, succ.error
714 }
715
716 // remember this failure (if enabled); response-based retries
717 // are not counted as failures since the upstream did respond
718 // successfully - only the response content triggered a retry
719 if _, isRetryableResponse := proxyErr.(retryableResponseError); !isRetryableResponse {
720 h.countFailure(upstream)
721 }
722
723 // if we've tried long enough, break
724 if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r, h.logger) {
725 return true, proxyErr
726 }
727
728 return false, proxyErr
729 }
730
731 // Mapping of the canonical form of the headers, to the RFC 6455 form,
732 // i.e. `WebSocket` with uppercase 'S'.
733 var websocketHeaderMapping = map[string]string{
734 "Sec-Websocket-Accept": "Sec-WebSocket-Accept",
735 "Sec-Websocket-Extensions": "Sec-WebSocket-Extensions",
736 "Sec-Websocket-Key": "Sec-WebSocket-Key",
737 "Sec-Websocket-Protocol": "Sec-WebSocket-Protocol",
738 "Sec-Websocket-Version": "Sec-WebSocket-Version",
739 }
740
741 // normalizeWebsocketHeaders ensures we use the standard casing as per
742 // RFC 6455, i.e. `WebSocket` with uppercase 'S'. Most servers don't
743 // care about this difference (read headers case insensitively), but
744 // some do, so this maximizes compatibility with upstreams.
745 // See https://github.com/caddyserver/caddy/pull/6621
746 func normalizeWebsocketHeaders(header http.Header) {
747 for k, rk := range websocketHeaderMapping {
748 if v, ok := header[k]; ok {
749 delete(header, k)
750 header[rk] = v
751 }
752 }
753 }
754
755 // prepareRequest clones req so that it can be safely modified without
756 // changing the original request or introducing data races. It then
757 // modifies it so that it is ready to be proxied, except for directing
758 // to a specific upstream. This method adjusts headers and other relevant
759 // properties of the cloned request and should be done just once (before
760 // proxying) regardless of proxy retries. This assumes that no mutations
761 // of the cloned request are performed by h during or after proxying.
762 func (h Handler) prepareRequest(req *http.Request, repl *caddy.Replacer) (*http.Request, error) {
763 req = cloneRequest(req)
764
765 // if enabled, perform rewrites on the cloned request; if
766 // the method is GET or HEAD, prevent the request body
767 // from being copied to the upstream
768 if h.Rewrite != nil {
769 changed := h.Rewrite.Rewrite(req, repl)
770 if changed && (h.Rewrite.Method == "GET" || h.Rewrite.Method == "HEAD") {
771 req.ContentLength = 0
772 req.Body = nil
773 }
774 }
775
776 // if enabled, buffer client request; this should only be
777 // enabled if the upstream requires it and does not work
778 // with "slow clients" (gunicorn, etc.) - this obviously
779 // has a perf overhead and makes the proxy at risk of
780 // exhausting memory and more susceptible to slowloris
781 // attacks, so it is strongly recommended to only use this
782 // feature if absolutely required, if read timeouts are
783 // set, and if body size is limited
784 if h.RequestBuffers != 0 && req.Body != nil {
785 var readBytes int64
786 req.Body, readBytes = h.bufferedBody(req.Body, h.RequestBuffers)
787 // set Content-Length when body is fully buffered
788 if b, ok := req.Body.(bodyReadCloser); ok && b.body == nil {
789 req.ContentLength = readBytes
790 req.Header.Set("Content-Length", strconv.FormatInt(req.ContentLength, 10))
791 }
792 }
793
794 if req.ContentLength == 0 {
795 req.Body = nil // Issue golang/go#16036: nil Body for http.Transport retries
796 }
797
798 req.Close = false
799
800 // if User-Agent is not set by client, then explicitly
801 // disable it so it's not set to default value by std lib
802 if _, ok := req.Header["User-Agent"]; !ok {
803 req.Header.Set("User-Agent", "")
804 }
805
806 // Indicate if request has been conveyed in early data.
807 // RFC 8470: "An intermediary that forwards a request prior to the
808 // completion of the TLS handshake with its client MUST send it with
809 // the Early-Data header field set to “1” (i.e., it adds it if not
810 // present in the request). An intermediary MUST use the Early-Data
811 // header field if the request might have been subject to a replay and
812 // might already have been forwarded by it or another instance
813 // (see Section 6.2)."
814 if req.TLS != nil && !req.TLS.HandshakeComplete {
815 req.Header.Set("Early-Data", "1")
816 }
817
818 reqUpgradeType := upgradeType(req.Header)
819 removeConnectionHeaders(req.Header)
820
821 // Remove hop-by-hop headers to the backend. Especially
822 // important is "Connection" because we want a persistent
823 // connection, regardless of what the client sent to us.
824 // Issue golang/go#46313: don't skip if field is empty.
825 for _, h := range hopHeaders {
826 // Issue golang/go#21096: tell backend applications that care about trailer support
827 // that we support trailers. (We do, but we don't go out of our way to
828 // advertise that unless the incoming client request thought it was worth
829 // mentioning.)
830 if h == "Te" && httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") {
831 req.Header.Set("Te", "trailers")
832 continue
833 }
834 req.Header.Del(h)
835 }
836
837 // After stripping all the hop-by-hop connection headers above, add back any
838 // necessary for protocol upgrades, such as for websockets.
839 if reqUpgradeType != "" {
840 req.Header.Set("Connection", "Upgrade")
841 req.Header.Set("Upgrade", reqUpgradeType)
842 normalizeWebsocketHeaders(req.Header)
843 }
844
845 // Set up the PROXY protocol info
846 address := caddyhttp.GetVar(req.Context(), caddyhttp.ClientIPVarKey).(string)
847 addrPort, err := netip.ParseAddrPort(address)
848 if err != nil {
849 // OK; probably didn't have a port
850 addr, err := netip.ParseAddr(address)
851 if err != nil {
852 // Doesn't seem like a valid ip address at all
853 } else {
854 // Ok, only the port was missing
855 addrPort = netip.AddrPortFrom(addr, 0)
856 }
857 }
858 proxyProtocolInfo := ProxyProtocolInfo{AddrPort: addrPort}
859 caddyhttp.SetVar(req.Context(), proxyProtocolInfoVarKey, proxyProtocolInfo)
860
861 // some of the outbound requests require h1 (e.g. websocket)
862 // https://github.com/golang/go/blob/4837fbe4145cd47b43eed66fee9eed9c2b988316/src/net/http/request.go#L1579
863 if isWebsocket(req) {
864 caddyhttp.SetVar(req.Context(), tlsH1OnlyVarKey, true)
865 }
866
867 // Add the supported X-Forwarded-* headers
868 err = h.addForwardedHeaders(req)
869 if err != nil {
870 return nil, err
871 }
872
873 // Via header(s)
874 req.Header.Add("Via", fmt.Sprintf("%d.%d Caddy", req.ProtoMajor, req.ProtoMinor))
875
876 return req, nil
877 }
878
879 // addForwardedHeaders adds the de-facto standard X-Forwarded-*
880 // headers to the request before it is sent upstream.
881 //
882 // These headers are security sensitive, so care is taken to only
883 // use existing values for these headers from the incoming request
884 // if the client IP is trusted (i.e. coming from a trusted proxy
885 // sitting in front of this server). If the request didn't have
886 // the headers at all, then they will be added with the values
887 // that we can glean from the request.
888 func (h Handler) addForwardedHeaders(req *http.Request) error {
889 // Check if the client is a trusted proxy
890 trusted := caddyhttp.GetVar(req.Context(), caddyhttp.TrustedProxyVarKey).(bool)
891
892 var clientIP string
893
894 if req.RemoteAddr == "@" {
895 // For Unix socket connections, RemoteAddr is "@" which cannot
896 // be parsed as host:port. If untrusted, strip forwarded headers
897 // for security. If trusted, there is no peer IP to append to
898 // X-Forwarded-For, so clientIP stays empty.
899 if !trusted {
900 req.Header.Del("X-Forwarded-For")
901 req.Header.Del("X-Forwarded-Proto")
902 req.Header.Del("X-Forwarded-Host")
903 return nil
904 }
905 } else {
906 // Parse the remote IP, ignore the error as non-fatal,
907 // but the remote IP is required to continue, so we
908 // just return early. This should probably never happen
909 // though, unless some other module manipulated the request's
910 // remote address and used an invalid value.
911 var err error
912 clientIP, _, err = net.SplitHostPort(req.RemoteAddr)
913 if err != nil {
914 // Remove the `X-Forwarded-*` headers to avoid upstreams
915 // potentially trusting a header that came from the client
916 req.Header.Del("X-Forwarded-For")
917 req.Header.Del("X-Forwarded-Proto")
918 req.Header.Del("X-Forwarded-Host")
919 return nil
920 }
921
922 // Client IP may contain a zone if IPv6, so we need
923 // to pull that out before parsing the IP
924 clientIP, _, _ = strings.Cut(clientIP, "%")
925 ipAddr, err := netip.ParseAddr(clientIP)
926
927 // If ParseAddr fails (e.g. non-IP network like SCION), we cannot check
928 // if it is a trusted proxy by IP range. In this case, we ignore the
929 // error and treat the connection as untrusted (or retain existing status).
930 if err == nil {
931 for _, ipRange := range h.trustedProxies {
932 if ipRange.Contains(ipAddr) {
933 trusted = true
934 break
935 }
936 }
937 }
938 }
939
940 // If we aren't the first proxy, and the proxy is trusted,
941 // retain prior X-Forwarded-For information as a comma+space
942 // separated list and fold multiple headers into one.
943 prior, ok, omit := allHeaderValues(req.Header, "X-Forwarded-For")
944 if !omit {
945 if trusted && ok && prior != "" {
946 if clientIP != "" {
947 req.Header.Set("X-Forwarded-For", prior+", "+clientIP)
948 } else {
949 req.Header.Set("X-Forwarded-For", prior)
950 }
951 } else if clientIP != "" {
952 req.Header.Set("X-Forwarded-For", clientIP)
953 }
954 }
955
956 // Set X-Forwarded-Proto; many backend apps expect this,
957 // so that they can properly craft URLs with the right
958 // scheme to match the original request
959 proto := "https"
960 if req.TLS == nil {
961 proto = "http"
962 }
963 prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Proto")
964 if trusted && ok && prior != "" {
965 proto = prior
966 }
967 if !omit {
968 req.Header.Set("X-Forwarded-Proto", proto)
969 }
970
971 // Set X-Forwarded-Host; often this is redundant because
972 // we pass through the request Host as-is, but in situations
973 // where we proxy over HTTPS, the user may need to override
974 // Host themselves, so it's helpful to send the original too.
975 host := req.Host
976 prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Host")
977 if trusted && ok && prior != "" {
978 host = prior
979 }
980 if !omit {
981 req.Header.Set("X-Forwarded-Host", host)
982 }
983
984 return nil
985 }
986
987 // reverseProxy performs a round-trip to the given backend and processes the response with the client.
988 // (This method is mostly the beginning of what was borrowed from the net/http/httputil package in the
989 // Go standard library which was used as the foundation.)
990 func (h *Handler) reverseProxy(rw http.ResponseWriter, req *http.Request, origReq *http.Request, repl *caddy.Replacer, di DialInfo, next caddyhttp.Handler) error {
991 _ = di.Upstream.Host.countRequest(1)
992
993 // Increment the in-flight request count
994 incInFlightRequest(di.Address)
995
996 //nolint:errcheck
997 defer func() {
998 di.Upstream.Host.countRequest(-1)
999 // Decrement the in-flight request count
1000 decInFlightRequest(di.Address)
1001 }()
1002
1003 // point the request to this upstream
1004 h.directRequest(req, di)
1005
1006 server := req.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server)
1007 shouldLogCredentials := server.Logs != nil && server.Logs.ShouldLogCredentials
1008
1009 // Forward 1xx status codes, backported from https://github.com/golang/go/pull/53164
1010 var (
1011 roundTripMutex sync.Mutex
1012 roundTripDone bool
1013 )
1014 trace := &httptrace.ClientTrace{
1015 Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
1016 roundTripMutex.Lock()
1017 defer roundTripMutex.Unlock()
1018 if roundTripDone {
1019 // If RoundTrip has returned, don't try to further modify
1020 // the ResponseWriter's header map.
1021 return nil
1022 }
1023 h := rw.Header()
1024 copyHeader(h, http.Header(header))
1025 rw.WriteHeader(code)
1026
1027 // Clear headers coming from the backend
1028 // (it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses)
1029 clear(h)
1030
1031 return nil
1032 },
1033 }
1034 req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
1035
1036 // do the round-trip
1037 start := time.Now()
1038 res, err := h.Transport.RoundTrip(req)
1039 duration := time.Since(start)
1040
1041 // record that the round trip is done for the 1xx response handler
1042 roundTripMutex.Lock()
1043 roundTripDone = true
1044 roundTripMutex.Unlock()
1045
1046 // emit debug log with values we know are safe,
1047 // or if there is no error, emit fuller log entry
1048 logger := h.logger.With(
1049 zap.String("upstream", di.Upstream.String()),
1050 zap.Duration("duration", duration),
1051 zap.Object("request", caddyhttp.LoggableHTTPRequest{
1052 Request: req,
1053 ShouldLogCredentials: shouldLogCredentials,
1054 }),
1055 )
1056
1057 const logMessage = "upstream roundtrip"
1058
1059 if err != nil {
1060 if c := logger.Check(zapcore.DebugLevel, logMessage); c != nil {
1061 c.Write(zap.Error(err))
1062 }
1063 return err
1064 }
1065 if c := logger.Check(zapcore.DebugLevel, logMessage); c != nil {
1066 c.Write(
1067 zap.Object("headers", caddyhttp.LoggableHTTPHeader{
1068 Header: res.Header,
1069 ShouldLogCredentials: shouldLogCredentials,
1070 }),
1071 zap.Int("status", res.StatusCode),
1072 )
1073 }
1074
1075 // duration until upstream wrote response headers (roundtrip duration)
1076 repl.Set("http.reverse_proxy.upstream.latency", duration)
1077 repl.Set("http.reverse_proxy.upstream.latency_ms", duration.Seconds()*1e3) // multiply seconds to preserve decimal (see #4666)
1078
1079 // update circuit breaker on current conditions
1080 if di.Upstream.cb != nil {
1081 di.Upstream.cb.RecordMetric(res.StatusCode, duration)
1082 }
1083
1084 // perform passive health checks (if enabled)
1085 if h.HealthChecks != nil && h.HealthChecks.Passive != nil {
1086 // strike if the status code matches one that is "bad"
1087 for _, badStatus := range h.HealthChecks.Passive.UnhealthyStatus {
1088 if caddyhttp.StatusCodeMatches(res.StatusCode, badStatus) {
1089 h.countFailure(di.Upstream)
1090 }
1091 }
1092
1093 // strike if the roundtrip took too long
1094 if h.HealthChecks.Passive.UnhealthyLatency > 0 &&
1095 duration >= time.Duration(h.HealthChecks.Passive.UnhealthyLatency) {
1096 h.countFailure(di.Upstream)
1097 }
1098 }
1099
1100 // if enabled, buffer the response body
1101 if h.ResponseBuffers != 0 {
1102 res.Body, _ = h.bufferedBody(res.Body, h.ResponseBuffers)
1103 }
1104
1105 // set response placeholders so they can be used in retry match
1106 // expressions and handle_response routes; clear stale header
1107 // placeholders from a previous attempt first so they don't
1108 // leak into the next retry evaluation
1109 repl.DeleteByPrefix("http.reverse_proxy.header.")
1110 for field, value := range res.Header {
1111 repl.Set("http.reverse_proxy.header."+field, strings.Join(value, ","))
1112 }
1113 repl.Set("http.reverse_proxy.status_code", res.StatusCode)
1114 repl.Set("http.reverse_proxy.status_text", res.Status)
1115
1116 // check if the response matches a retry match entry; if so,
1117 // close the body and return a retryable error so the request
1118 // is retried with the next upstream. Only evaluate matcher sets
1119 // that contain at least one expression matcher, since those are
1120 // the ones that can reference response data ({rp.status_code},
1121 // {rp.header.*}). Pure request-only matchers (method, path, etc.)
1122 // are skipped to avoid retrying every response that matches a
1123 // request condition
1124 if h.LoadBalancing != nil && len(h.LoadBalancing.RetryMatch) > 0 {
1125 for _, matcherSet := range h.LoadBalancing.RetryMatch {
1126 if !matcherSetHasExpressionMatcher(matcherSet) {
1127 continue
1128 }
1129 match, err := matcherSet.MatchWithError(req)
1130 if err != nil {
1131 h.logger.Error("error matching request for retry", zap.Error(err))
1132 break
1133 }
1134 if match {
1135 res.Body.Close()
1136 return retryableResponseError{
1137 error: fmt.Errorf("upstream response matched retry_match (status %d)", res.StatusCode),
1138 statusCode: res.StatusCode,
1139 }
1140 }
1141 }
1142 }
1143
1144 // see if any response handler is configured for this response from the backend
1145 for i, rh := range h.HandleResponse {
1146 if rh.Match != nil && !rh.Match.Match(res.StatusCode, res.Header) {
1147 continue
1148 }
1149
1150 // if configured to only change the status code,
1151 // do that then continue regular proxy response
1152 if statusCodeStr := rh.StatusCode.String(); statusCodeStr != "" {
1153 statusCode, err := strconv.Atoi(repl.ReplaceAll(statusCodeStr, ""))
1154 if err != nil {
1155 return caddyhttp.Error(http.StatusInternalServerError, err)
1156 }
1157 if statusCode != 0 {
1158 res.StatusCode = statusCode
1159 }
1160 break
1161 }
1162
1163 if c := logger.Check(zapcore.DebugLevel, "handling response"); c != nil {
1164 c.Write(zap.Int("handler", i))
1165 }
1166
1167 // we make some data available via request context to child routes
1168 // so that they may inherit some options and functions from the
1169 // handler, and be able to copy the response.
1170 // we use the original request here, so that any routes from 'next'
1171 // see the original request rather than the proxy cloned request.
1172 hrc := &handleResponseContext{
1173 handler: h,
1174 response: res,
1175 start: start,
1176 logger: logger,
1177 }
1178 ctx := origReq.Context()
1179 ctx = context.WithValue(ctx, proxyHandleResponseContextCtxKey, hrc)
1180
1181 // pass the request through the response handler routes
1182 routeErr := rh.Routes.Compile(next).ServeHTTP(rw, origReq.WithContext(ctx))
1183
1184 // close the response body afterwards, since we don't need it anymore;
1185 // either a route had 'copy_response' which already consumed the body,
1186 // or some other terminal handler ran which doesn't need the response
1187 // body after that point (e.g. 'file_server' for X-Accel-Redirect flow),
1188 // or we fell through to subsequent handlers past this proxy
1189 // (e.g. forward auth's 2xx response flow).
1190 if !hrc.isFinalized {
1191 res.Body.Close()
1192 }
1193
1194 // wrap any route error in roundtripSucceededError so caller knows that
1195 // the roundtrip was successful and to not retry
1196 if routeErr != nil {
1197 return roundtripSucceededError{routeErr}
1198 }
1199
1200 // we're done handling the response, and we don't want to
1201 // fall through to the default finalize/copy behaviour
1202 return nil
1203 }
1204
1205 // copy the response body and headers back to the upstream client
1206 return h.finalizeResponse(rw, req, res, repl, start, logger)
1207 }
1208
1209 // finalizeResponse prepares and copies the response.
1210 func (h *Handler) finalizeResponse(
1211 rw http.ResponseWriter,
1212 req *http.Request,
1213 res *http.Response,
1214 repl *caddy.Replacer,
1215 start time.Time,
1216 logger *zap.Logger,
1217 ) error {
1218 // deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
1219 if res.StatusCode == http.StatusSwitchingProtocols {
1220 var wg sync.WaitGroup
1221 h.handleUpgradeResponse(logger, &wg, rw, req, res)
1222 wg.Wait()
1223 return nil
1224 }
1225
1226 removeConnectionHeaders(res.Header)
1227
1228 for _, h := range hopHeaders {
1229 res.Header.Del(h)
1230 }
1231
1232 // delete our Server header and use Via instead (see #6275)
1233 rw.Header().Del("Server")
1234 var protoPrefix string
1235 if !strings.HasPrefix(strings.ToUpper(res.Proto), "HTTP/") {
1236 protoPrefix = res.Proto[:strings.Index(res.Proto, "/")+1]
1237 }
1238 rw.Header().Add("Via", fmt.Sprintf("%s%d.%d Caddy", protoPrefix, res.ProtoMajor, res.ProtoMinor))
1239
1240 // apply any response header operations
1241 if h.Headers != nil && h.Headers.Response != nil {
1242 if h.Headers.Response.Require == nil ||
1243 h.Headers.Response.Require.Match(res.StatusCode, res.Header) {
1244 h.Headers.Response.ApplyTo(res.Header, repl)
1245 }
1246 }
1247
1248 copyHeader(rw.Header(), res.Header)
1249
1250 // The "Trailer" header isn't included in the Transport's response,
1251 // at least for *http.Transport. Build it up from Trailer.
1252 announcedTrailers := len(res.Trailer)
1253 if announcedTrailers > 0 {
1254 trailerKeys := make([]string, 0, len(res.Trailer))
1255 for k := range res.Trailer {
1256 trailerKeys = append(trailerKeys, k)
1257 }
1258 rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
1259 }
1260
1261 rw.WriteHeader(res.StatusCode)
1262 if h.VerboseLogs {
1263 logger.Debug("wrote header")
1264 }
1265
1266 err := h.copyResponse(rw, res.Body, h.flushInterval(req, res), logger)
1267 errClose := res.Body.Close() // close now, instead of defer, to populate res.Trailer
1268 if h.VerboseLogs || errClose != nil {
1269 if c := logger.Check(zapcore.DebugLevel, "closed response body from upstream"); c != nil {
1270 c.Write(zap.Error(errClose))
1271 }
1272 }
1273 if err != nil {
1274 // we're streaming the response and we've already written headers, so
1275 // there's nothing an error handler can do to recover at this point;
1276 // we'll just log the error and abort the stream here and panic just as
1277 // the standard lib's proxy to propagate the stream error.
1278 // see issue https://github.com/caddyserver/caddy/issues/5951
1279 if c := logger.Check(zapcore.WarnLevel, "aborting with incomplete response"); c != nil {
1280 c.Write(zap.Error(err))
1281 }
1282 // no extra logging from stdlib
1283 panic(http.ErrAbortHandler)
1284 }
1285
1286 if len(res.Trailer) > 0 {
1287 // Force chunking if we saw a response trailer.
1288 // This prevents net/http from calculating the length for short
1289 // bodies and adding a Content-Length.
1290 //nolint:bodyclose
1291 http.NewResponseController(rw).Flush()
1292 }
1293
1294 // total duration spent proxying, including writing response body
1295 repl.Set("http.reverse_proxy.upstream.duration", time.Since(start))
1296 repl.Set("http.reverse_proxy.upstream.duration_ms", time.Since(start).Seconds()*1e3)
1297
1298 if len(res.Trailer) == announcedTrailers {
1299 copyHeader(rw.Header(), res.Trailer)
1300 return nil
1301 }
1302
1303 for k, vv := range res.Trailer {
1304 k = http.TrailerPrefix + k
1305 for _, v := range vv {
1306 rw.Header().Add(k, v)
1307 }
1308 }
1309
1310 if h.VerboseLogs {
1311 logger.Debug("response finalized")
1312 }
1313
1314 return nil
1315 }
1316
1317 // tryAgain takes the time that the handler was initially invoked,
1318 // the amount of retries already performed, as well as any error
1319 // currently obtained, and the request being tried, and returns
1320 // true if another attempt should be made at proxying the request.
1321 // If true is returned, it has already blocked long enough before
1322 // the next retry (i.e. no more sleeping is needed). If false is
1323 // returned, the handler should stop trying to proxy the request.
1324 func (lb LoadBalancing) tryAgain(ctx caddy.Context, start time.Time, retries int, proxyErr error, req *http.Request, logger *zap.Logger) bool {
1325 // no retries are configured
1326 if lb.TryDuration == 0 && lb.Retries == 0 {
1327 return false
1328 }
1329
1330 // if we've tried long enough, break
1331 if lb.TryDuration > 0 && time.Since(start) >= time.Duration(lb.TryDuration) {
1332 return false
1333 }
1334
1335 // if we've reached the retry limit, break
1336 if lb.Retries > 0 && retries >= lb.Retries {
1337 return false
1338 }
1339
1340 // if the error occurred while dialing (i.e. a connection
1341 // could not even be established to the upstream), then it
1342 // should be safe to retry, since without a connection, no
1343 // HTTP request can be transmitted; but if the error is not
1344 // specifically a dialer error, we need to be careful
1345 if proxyErr != nil {
1346 _, isDialError := proxyErr.(DialError)
1347 _, isRetryableResponse := proxyErr.(retryableResponseError)
1348 herr, isHandlerError := proxyErr.(caddyhttp.HandlerError)
1349
1350 // if the error occurred after a connection was established,
1351 // we have to assume the upstream received the request, and
1352 // retries need to be carefully decided, because some requests
1353 // are not idempotent; retryableResponseError is excluded here
1354 // because its retry decision was already made in reverseProxy()
1355 // when the response matchers were evaluated
1356 if !isDialError && !isRetryableResponse && (!isHandlerError || !errors.Is(herr, errNoUpstream)) {
1357 if lb.RetryMatch == nil && req.Method != "GET" {
1358 // by default, don't retry requests if they aren't GET
1359 return false
1360 }
1361
1362 // set transport error flag so CEL expressions can use
1363 // {rp.is_transport_error} to decide whether to retry
1364 repl, _ := req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
1365 if repl != nil {
1366 repl.Set("http.reverse_proxy.is_transport_error", true)
1367 defer repl.Delete("http.reverse_proxy.is_transport_error")
1368 }
1369
1370 match, err := lb.RetryMatch.AnyMatchWithError(req)
1371 if err != nil {
1372 logger.Error("error matching request for retry", zap.Error(err))
1373 return false
1374 }
1375 if !match {
1376 return false
1377 }
1378 }
1379 }
1380
1381 // fast path; if the interval is zero, we don't need to wait
1382 if lb.TryInterval == 0 {
1383 return true
1384 }
1385
1386 // otherwise, wait and try the next available host
1387 timer := time.NewTimer(time.Duration(lb.TryInterval))
1388 select {
1389 case <-timer.C:
1390 return true
1391 case <-ctx.Done():
1392 if !timer.Stop() {
1393 // if the timer has been stopped then read from the channel
1394 <-timer.C
1395 }
1396 return false
1397 }
1398 }
1399
1400 // directRequest modifies only req.URL so that it points to the upstream
1401 // in the given DialInfo. It must modify ONLY the request URL.
1402 func (h *Handler) directRequest(req *http.Request, di DialInfo) {
1403 // we need a host, so set the upstream's host address
1404 reqHost := di.Address
1405
1406 // if the port equates to the scheme, strip the port because
1407 // it's weird to make a request like http://example.com:80/.
1408 if (req.URL.Scheme == "http" && di.Port == "80") ||
1409 (req.URL.Scheme == "https" && di.Port == "443") {
1410 reqHost = di.Host
1411 }
1412
1413 // add client address to the host to let transport differentiate requests from different clients
1414 if ppt, ok := h.Transport.(ProxyProtocolTransport); ok && ppt.ProxyProtocolEnabled() {
1415 if proxyProtocolInfo, ok := caddyhttp.GetVar(req.Context(), proxyProtocolInfoVarKey).(ProxyProtocolInfo); ok {
1416 // encode the request so it plays well with h2 transport, it's unnecessary for h1 but anyway
1417 // The issue is that h2 transport will use the address to determine if new connections are needed
1418 // to roundtrip requests but the without escaping, new connections are constantly created and closed until
1419 // file descriptors are exhausted.
1420 // see: https://github.com/caddyserver/caddy/issues/7529
1421 reqHost = url.QueryEscape(proxyProtocolInfo.AddrPort.String() + "->" + reqHost)
1422 }
1423 }
1424
1425 req.URL.Host = reqHost
1426 }
1427
1428 func (h Handler) provisionUpstream(upstream *Upstream, dynamic bool) {
1429 // create or get the host representation for this upstream;
1430 // dynamic upstreams are tracked in a separate map with last-seen
1431 // timestamps so their health state persists across requests without
1432 // being reference-counted (and thus discarded between requests).
1433 if dynamic {
1434 upstream.fillDynamicHost()
1435 } else {
1436 upstream.fillHost()
1437 }
1438
1439 // give it the circuit breaker, if any
1440 upstream.cb = h.CB
1441
1442 // if the passive health checker has a non-zero UnhealthyRequestCount
1443 // but the upstream has no MaxRequests set (they are the same thing,
1444 // but the passive health checker is a default value for upstreams
1445 // without MaxRequests), copy the value into this upstream, since the
1446 // value in the upstream (MaxRequests) is what is used during
1447 // availability checks
1448 if h.HealthChecks != nil &&
1449 h.HealthChecks.Passive != nil &&
1450 h.HealthChecks.Passive.UnhealthyRequestCount > 0 &&
1451 upstream.MaxRequests == 0 {
1452 upstream.MaxRequests = h.HealthChecks.Passive.UnhealthyRequestCount
1453 }
1454
1455 // upstreams need independent access to the passive
1456 // health check policy because passive health checks
1457 // run without access to h.
1458 if h.HealthChecks != nil {
1459 upstream.healthCheckPolicy = h.HealthChecks.Passive
1460 }
1461 }
1462
1463 // bufferedBody reads originalBody into a buffer with maximum size of limit (-1 for unlimited),
1464 // then returns a reader for the buffer along with how many bytes were buffered. Always close
1465 // the return value when done with it, just like if it was the original body! If limit is 0
1466 // (which it shouldn't be), this function returns its input; i.e. is a no-op, for safety.
1467 // Otherwise, it returns bodyReadCloser, the original body will be closed and body will be nil
1468 // if it's explicitly configured to buffer all or EOF is reached when reading.
1469 // TODO: the error during reading is discarded if the limit is negative, should the error be propagated
1470 // to upstream/downstream?
1471 func (h Handler) bufferedBody(originalBody io.ReadCloser, limit int64) (io.ReadCloser, int64) {
1472 if limit == 0 {
1473 return originalBody, 0
1474 }
1475 var written int64
1476 buf := bufPool.Get().(*bytes.Buffer)
1477 buf.Reset()
1478 if limit > 0 {
1479 var err error
1480 written, err = io.CopyN(buf, originalBody, limit)
1481 if (err != nil && err != io.EOF) || written == limit {
1482 return bodyReadCloser{
1483 Reader: io.MultiReader(buf, originalBody),
1484 buf: buf,
1485 body: originalBody,
1486 }, written
1487 }
1488 } else {
1489 written, _ = io.Copy(buf, originalBody)
1490 }
1491 originalBody.Close() // no point in keeping it open
1492 return bodyReadCloser{
1493 Reader: buf,
1494 buf: buf,
1495 }, written
1496 }
1497
1498 // cloneRequest makes a semi-deep clone of origReq.
1499 //
1500 // Most of this code is borrowed from the Go stdlib reverse proxy,
1501 // but we make a shallow-ish clone the request (deep clone only
1502 // the headers and URL) so we can avoid manipulating the original
1503 // request when using it to proxy upstream. This prevents request
1504 // corruption and data races.
1505 func cloneRequest(origReq *http.Request) *http.Request {
1506 req := new(http.Request)
1507 *req = *origReq
1508 if origReq.URL != nil {
1509 newURL := new(url.URL)
1510 *newURL = *origReq.URL
1511 if origReq.URL.User != nil {
1512 newURL.User = new(url.Userinfo)
1513 *newURL.User = *origReq.URL.User
1514 }
1515 // sanitize the request URL; we expect it to not contain the
1516 // scheme and host since those should be determined by r.TLS
1517 // and r.Host respectively, but some clients may include it
1518 // in the request-line, which is technically valid in HTTP,
1519 // but breaks reverseproxy behaviour, overriding how the
1520 // dialer will behave. See #4237 for context.
1521 newURL.Scheme = ""
1522 newURL.Host = ""
1523 req.URL = newURL
1524 }
1525 if origReq.Header != nil {
1526 req.Header = origReq.Header.Clone()
1527 }
1528 if origReq.Trailer != nil {
1529 req.Trailer = origReq.Trailer.Clone()
1530 }
1531 return req
1532 }
1533
1534 func copyHeader(dst, src http.Header) {
1535 for k, vv := range src {
1536 for _, v := range vv {
1537 dst.Add(k, v)
1538 }
1539 }
1540 }
1541
1542 // allHeaderValues gets all values for a given header field,
1543 // joined by a comma and space if more than one is set. If the
1544 // header field is nil, then the omit is true, meaning some
1545 // earlier logic in the server wanted to prevent this header from
1546 // getting written at all. If the header is empty, then ok is
1547 // false. Callers should still check that the value is not empty
1548 // (the header field may be set but have an empty value).
1549 func allHeaderValues(h http.Header, field string) (value string, ok bool, omit bool) {
1550 values, ok := h[http.CanonicalHeaderKey(field)]
1551 if ok && values == nil {
1552 return "", true, true
1553 }
1554 if len(values) == 0 {
1555 return "", false, false
1556 }
1557 return strings.Join(values, ", "), true, false
1558 }
1559
1560 // lastHeaderValue gets the last value for a given header field
1561 // if more than one is set. If the header field is nil, then
1562 // the omit is true, meaning some earlier logic in the server
1563 // wanted to prevent this header from getting written at all.
1564 // If the header is empty, then ok is false. Callers should
1565 // still check that the value is not empty (the header field
1566 // may be set but have an empty value).
1567 func lastHeaderValue(h http.Header, field string) (value string, ok bool, omit bool) {
1568 values, ok := h[http.CanonicalHeaderKey(field)]
1569 if ok && values == nil {
1570 return "", true, true
1571 }
1572 if len(values) == 0 {
1573 return "", false, false
1574 }
1575 return values[len(values)-1], true, false
1576 }
1577
1578 func upgradeType(h http.Header) string {
1579 if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
1580 return ""
1581 }
1582 return strings.ToLower(h.Get("Upgrade"))
1583 }
1584
1585 // removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h.
1586 // See RFC 7230, section 6.1
1587 func removeConnectionHeaders(h http.Header) {
1588 for _, f := range h["Connection"] {
1589 for sf := range strings.SplitSeq(f, ",") {
1590 if sf = textproto.TrimString(sf); sf != "" {
1591 h.Del(sf)
1592 }
1593 }
1594 }
1595 }
1596
1597 // statusError returns an error value that has a status code.
1598 func statusError(err error) error {
1599 // if a response-based retry was exhausted, use the actual upstream
1600 // status code instead of a generic 502
1601 if rre, ok := err.(retryableResponseError); ok {
1602 return caddyhttp.Error(rre.statusCode, err)
1603 }
1604
1605 // errors proxying usually mean there is a problem with the upstream(s)
1606 statusCode := http.StatusBadGateway
1607
1608 // timeout errors have a standard status code (see issue #4823)
1609 if err, ok := err.(net.Error); ok && err.Timeout() {
1610 statusCode = http.StatusGatewayTimeout
1611 }
1612
1613 // if the client canceled the request (usually this means they closed
1614 // the connection, so they won't see any response), we can report it
1615 // as a client error (4xx) and not a server error (5xx); unfortunately
1616 // the Go standard library, at least at time of writing in late 2020,
1617 // obnoxiously wraps the exported, standard context.Canceled error with
1618 // an unexported garbage value that we have to do a substring check for:
1619 // https://github.com/golang/go/blob/6965b01ea248cabb70c3749fd218b36089a21efb/src/net/net.go#L416-L430
1620 if errors.Is(err, context.Canceled) || strings.Contains(err.Error(), "operation was canceled") {
1621 // regrettably, there is no standard error code for "client closed connection", but
1622 // for historical reasons we can use a code that a lot of people are already using;
1623 // using 5xx is problematic for users; see #3748
1624 statusCode = 499
1625 }
1626 return caddyhttp.Error(statusCode, err)
1627 }
1628
1629 // LoadBalancing has parameters related to load balancing.
1630 type LoadBalancing struct {
1631 // A selection policy is how to choose an available backend.
1632 // The default policy is random selection.
1633 SelectionPolicyRaw json.RawMessage `json:"selection_policy,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"`
1634
1635 // How many times to retry selecting available backends for each
1636 // request if the next available host is down. If try_duration is
1637 // also configured, then retries may stop early if the duration
1638 // is reached. By default, retries are disabled (zero).
1639 Retries int `json:"retries,omitempty"`
1640
1641 // How long to try selecting available backends for each request
1642 // if the next available host is down. Clients will wait for up
1643 // to this long while the load balancer tries to find an available
1644 // upstream host. If retries is also configured, tries may stop
1645 // early if the maximum retries is reached. By default, retries
1646 // are disabled (zero duration).
1647 TryDuration caddy.Duration `json:"try_duration,omitempty"`
1648
1649 // How long to wait between selecting the next host from the pool.
1650 // Default is 250ms if try_duration is enabled, otherwise zero. Only
1651 // relevant when a request to an upstream host fails. Be aware that
1652 // setting this to 0 with a non-zero try_duration can cause the CPU
1653 // to spin if all backends are down and latency is very low.
1654 TryInterval caddy.Duration `json:"try_interval,omitempty"`
1655
1656 // A list of matcher sets that controls retry behavior. Matcher sets
1657 // without expression matchers (e.g. method, path) restrict which
1658 // requests are retried on transport errors - if unspecified, only
1659 // GET requests will be retried. Matcher sets with CEL expression
1660 // matchers are evaluated against upstream responses and can
1661 // reference {rp.status_code}, {rp.header.*}, and
1662 // {rp.is_transport_error}. Dial errors are always retried
1663 // regardless of this setting. Retries use the next available
1664 // upstream per the load balancing policy
1665 RetryMatchRaw caddyhttp.RawMatcherSets `json:"retry_match,omitempty" caddy:"namespace=http.matchers"`
1666
1667 SelectionPolicy Selector `json:"-"`
1668 RetryMatch caddyhttp.MatcherSets `json:"-"`
1669 }
1670
1671 // Selector selects an available upstream from the pool.
1672 type Selector interface {
1673 Select(UpstreamPool, *http.Request, http.ResponseWriter) *Upstream
1674 }
1675
1676 // UpstreamSource gets the list of upstreams that can be used when
1677 // proxying a request. Returned upstreams will be load balanced and
1678 // health-checked. This should be a very fast function -- instant
1679 // if possible -- and the return value must be as stable as possible.
1680 // In other words, the list of upstreams should ideally not change much
1681 // across successive calls. If the list of upstreams changes or the
1682 // ordering is not stable, load balancing will suffer. This function
1683 // may be called during each retry, multiple times per request, and as
1684 // such, needs to be instantaneous. The returned slice will not be
1685 // modified.
1686 //
1687 // For upstream sources that cache results, implement the
1688 // [CachingUpstreamSource] interface for optimal performance.
1689 type UpstreamSource interface {
1690 GetUpstreams(*http.Request) ([]*Upstream, error)
1691 }
1692
1693 // CachingUpstreamSource is an upstream source that caches its upstreams.
1694 // The relevant cache entry can be cleared/reset for a given request during
1695 // retries if a request fails. This can help ensure that failing backends
1696 // are not retried.
1697 //
1698 // EXPERIMENTAL: Subject to change.
1699 type CachingUpstreamSource interface {
1700 UpstreamSource
1701
1702 // ResetCache clears any cache entry related to the given request.
1703 // The next time GetUpstreams is called, it should have new upstream
1704 // information for the given request.
1705 ResetCache(*http.Request) error
1706 }
1707
1708 // Hop-by-hop headers. These are removed when sent to the backend.
1709 // As of RFC 7230, hop-by-hop headers are required to appear in the
1710 // Connection header field. These are the headers defined by the
1711 // obsoleted RFC 2616 (section 13.5.1) and are used for backward
1712 // compatibility.
1713 var hopHeaders = []string{
1714 "Alt-Svc",
1715 "Connection",
1716 "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
1717 "Keep-Alive",
1718 "Proxy-Authenticate",
1719 "Proxy-Authorization",
1720 "Te", // canonicalized version of "TE"
1721 "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
1722 "Transfer-Encoding",
1723 "Upgrade",
1724 }
1725
1726 // DialError is an error that specifically occurs
1727 // in a call to Dial or DialContext.
1728 type DialError struct{ error }
1729
1730 // TLSTransport is implemented by transports
1731 // that are capable of using TLS.
1732 type TLSTransport interface {
1733 // TLSEnabled returns true if the transport
1734 // has TLS enabled, false otherwise.
1735 TLSEnabled() bool
1736
1737 // EnableTLS enables TLS within the transport
1738 // if it is not already, using the provided
1739 // value as a basis for the TLS config.
1740 EnableTLS(base *TLSConfig) error
1741 }
1742
1743 // H2CTransport is implemented by transports
1744 // that are capable of using h2c.
1745 type H2CTransport interface {
1746 EnableH2C() error
1747 }
1748
1749 // ProxyProtocolTransport is implemented by transports
1750 // that are capable of using proxy protocol.
1751 type ProxyProtocolTransport interface {
1752 ProxyProtocolEnabled() bool
1753 }
1754
1755 // HealthCheckSchemeOverriderTransport is implemented by transports
1756 // that can override the scheme used for health checks.
1757 type HealthCheckSchemeOverriderTransport interface {
1758 OverrideHealthCheckScheme(base *url.URL, port string)
1759 }
1760
1761 // BufferedTransport is implemented by transports
1762 // that needs to buffer requests and/or responses.
1763 type BufferedTransport interface {
1764 // DefaultBufferSizes returns the default buffer sizes
1765 // for requests and responses, respectively if buffering isn't enabled.
1766 DefaultBufferSizes() (int64, int64)
1767 }
1768
1769 // RequestHeaderOpsTransport may be implemented by a transport to provide
1770 // header operations to apply to requests immediately before the RoundTrip.
1771 // For example, overriding the default Host when TLS is enabled.
1772 type RequestHeaderOpsTransport interface {
1773 // RequestHeaderOps allows a transport to provide header operations
1774 // to apply to the request. The transport is asked at provision time
1775 // to return a HeaderOps (or nil) that will be applied before
1776 // user-configured header ops.
1777 RequestHeaderOps() *headers.HeaderOps
1778 }
1779
1780 // matcherSetHasExpressionMatcher reports whether a matcher set contains
1781 // at least one expression matcher. Expression matchers can reference
1782 // response data via placeholders like {rp.status_code}. Matcher sets
1783 // without expression matchers only test request properties and should
1784 // not be evaluated for response-based retry decisions
1785 func matcherSetHasExpressionMatcher(matcherSet caddyhttp.MatcherSet) bool {
1786 for _, m := range matcherSet {
1787 if _, ok := m.(*caddyhttp.MatchExpression); ok {
1788 return true
1789 }
1790 }
1791 return false
1792 }
1793
1794 // roundtripSucceededError is an error type that is returned if the
1795 // roundtrip succeeded, but an error occurred after-the-fact.
1796 type roundtripSucceededError struct{ error }
1797
1798 // retryableResponseError is returned when the upstream response matched
1799 // a retry_match entry, indicating the request should be retried with the
1800 // next upstream. It preserves the original status code so that if retries
1801 // are exhausted, the actual upstream status is reported instead of a
1802 // generic 502
1803 type retryableResponseError struct {
1804 error
1805 statusCode int
1806 }
1807
1808 // bodyReadCloser is a reader that, upon closing, will return
1809 // its buffer to the pool and close the underlying body reader.
1810 type bodyReadCloser struct {
1811 io.Reader
1812 buf *bytes.Buffer
1813 body io.ReadCloser
1814 }
1815
1816 func (brc bodyReadCloser) Close() error {
1817 // Inside this package this will be set to nil for fully-buffered
1818 // requests due to the possibility of retrial.
1819 if brc.buf != nil {
1820 bufPool.Put(brc.buf)
1821 }
1822 // For fully-buffered bodies, body is nil, so Close is a no-op.
1823 if brc.body != nil {
1824 return brc.body.Close()
1825 }
1826 return nil
1827 }
1828
1829 // bufPool is used for buffering requests and responses.
1830 var bufPool = sync.Pool{
1831 New: func() any {
1832 return new(bytes.Buffer)
1833 },
1834 }
1835
1836 // handleResponseContext carries some contextual information about the
1837 // current proxy handling.
1838 type handleResponseContext struct {
1839 // handler is the active proxy handler instance, so that
1840 // routes like copy_response may inherit some config
1841 // options and have access to handler methods.
1842 handler *Handler
1843
1844 // response is the actual response received from the proxy
1845 // roundtrip, to potentially be copied if a copy_response
1846 // handler is in the handle_response routes.
1847 response *http.Response
1848
1849 // start is the time just before the proxy roundtrip was
1850 // performed, used for logging.
1851 start time.Time
1852
1853 // logger is the prepared logger which is used to write logs
1854 // with the request, duration, and selected upstream attached.
1855 logger *zap.Logger
1856
1857 // isFinalized is whether the response has been finalized,
1858 // i.e. copied and closed, to make sure that it doesn't
1859 // happen twice.
1860 isFinalized bool
1861 }
1862
1863 // proxyHandleResponseContextCtxKey is the context key for the active proxy handler
1864 // so that handle_response routes can inherit some config options
1865 // from the proxy handler.
1866 const proxyHandleResponseContextCtxKey caddy.CtxKey = "reverse_proxy_handle_response_context"
1867
1868 // errNoUpstream occurs when there are no upstream available.
1869 var errNoUpstream = fmt.Errorf("no upstreams available")
1870
1871 // Interface guards
1872 var (
1873 _ caddy.Provisioner = (*Handler)(nil)
1874 _ caddy.CleanerUpper = (*Handler)(nil)
1875 _ caddyhttp.MiddlewareHandler = (*Handler)(nil)
1876 )