@marcel91200 / caddy Mirror · read-only
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 11, 01:00 UTC

master
go 2,410 lines 88.6 KB
Raw
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 "maps"
27 "net"
28 "net/http"
29 "net/http/httptrace"
30 "net/netip"
31 "net/textproto"
32 "net/url"
33 "slices"
34 "strconv"
35 "strings"
36 "sync"
37 "sync/atomic"
38 "time"
39
40 "github.com/dunglas/httpsfv"
41 "github.com/quic-go/quic-go/http3"
42 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
43 "go.opentelemetry.io/contrib/propagators/autoprop"
44 oteltrace "go.opentelemetry.io/otel/trace"
45 "go.uber.org/zap"
46 "go.uber.org/zap/zapcore"
47 "golang.org/x/net/http/httpguts"
48
49 "github.com/caddyserver/caddy/v2"
50 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
51 "github.com/caddyserver/caddy/v2/modules/caddyevents"
52 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
53 "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
54 "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite"
55 )
56
57 // inFlightRequests uses sync.Map with atomic.Int64 for lock-free updates on the hot path
58 var inFlightRequests sync.Map
59
60 func incInFlightRequest(address string) {
61 v, _ := inFlightRequests.LoadOrStore(address, new(atomic.Int64))
62 v.(*atomic.Int64).Add(1)
63 }
64
65 func decInFlightRequest(address string) {
66 if v, ok := inFlightRequests.Load(address); ok {
67 if v.(*atomic.Int64).Add(-1) <= 0 {
68 inFlightRequests.Delete(address)
69 }
70 }
71 }
72
73 func getInFlightRequests() map[string]int64 {
74 copyMap := make(map[string]int64)
75 inFlightRequests.Range(func(key, value any) bool {
76 copyMap[key.(string)] = value.(*atomic.Int64).Load()
77 return true
78 })
79 return copyMap
80 }
81
82 func init() {
83 caddy.RegisterModule(Handler{})
84 }
85
86 // Handler implements a highly configurable and production-ready reverse proxy.
87 //
88 // Upon proxying, this module sets the following placeholders (which can be used
89 // both within and after this handler; for example, in response headers):
90 //
91 // Placeholder | Description
92 // ------------|-------------
93 // `{http.reverse_proxy.upstream.address}` | The full address to the upstream as given in the config
94 // `{http.reverse_proxy.upstream.hostport}` | The host:port of the upstream
95 // `{http.reverse_proxy.upstream.host}` | The host of the upstream
96 // `{http.reverse_proxy.upstream.port}` | The port of the upstream
97 // `{http.reverse_proxy.upstream.requests}` | The approximate current number of requests to the upstream
98 // `{http.reverse_proxy.upstream.max_requests}` | The maximum approximate number of requests allowed to the upstream
99 // `{http.reverse_proxy.upstream.fails}` | The number of recent failed requests to the upstream
100 // `{http.reverse_proxy.upstream.latency}` | How long it took the proxy upstream to write the response header.
101 // `{http.reverse_proxy.upstream.latency_ms}` | Same as 'latency', but in milliseconds.
102 // `{http.reverse_proxy.upstream.duration}` | Time spent proxying to the upstream, including writing response body to client.
103 // `{http.reverse_proxy.upstream.duration_ms}` | Same as 'upstream.duration', but in milliseconds.
104 // `{http.reverse_proxy.duration}` | Total time spent proxying, including selecting an upstream, retries, and writing response.
105 // `{http.reverse_proxy.duration_ms}` | Same as 'duration', but in milliseconds.
106 // `{http.reverse_proxy.retries}` | The number of retries actually performed to communicate with an upstream.
107 type Handler struct {
108 // Configures the method of transport for the proxy. A transport
109 // is what performs the actual "round trip" to the backend.
110 // The default transport is plaintext HTTP.
111 TransportRaw json.RawMessage `json:"transport,omitempty" caddy:"namespace=http.reverse_proxy.transport inline_key=protocol"`
112
113 // A circuit breaker may be used to relieve pressure on a backend
114 // that is beginning to exhibit symptoms of stress or latency.
115 // By default, there is no circuit breaker.
116 CBRaw json.RawMessage `json:"circuit_breaker,omitempty" caddy:"namespace=http.reverse_proxy.circuit_breakers inline_key=type"`
117
118 // Load balancing distributes load/requests between backends.
119 LoadBalancing *LoadBalancing `json:"load_balancing,omitempty"`
120
121 // Health checks update the status of backends, whether they are
122 // up or down. Down backends will not be proxied to.
123 HealthChecks *HealthChecks `json:"health_checks,omitempty"`
124
125 // Upstreams is the static list of backends to proxy to.
126 Upstreams UpstreamPool `json:"upstreams,omitempty"`
127
128 // A module for retrieving the list of upstreams dynamically. Dynamic
129 // upstreams are retrieved at every iteration of the proxy loop for
130 // each request (i.e. before every proxy attempt within every request).
131 // Active health checks do not work on dynamic upstreams, and passive
132 // health checks are only effective on dynamic upstreams if the proxy
133 // server is busy enough that concurrent requests to the same backends
134 // are continuous. Instead of health checks for dynamic upstreams, it
135 // is recommended that the dynamic upstream module only return available
136 // backends in the first place.
137 DynamicUpstreamsRaw json.RawMessage `json:"dynamic_upstreams,omitempty" caddy:"namespace=http.reverse_proxy.upstreams inline_key=source"`
138
139 // Adjusts how often to flush the response buffer. By default,
140 // no periodic flushing is done. A negative value disables
141 // response buffering, and flushes immediately after each
142 // write to the client. This option is ignored when the upstream's
143 // response is recognized as a streaming response, or if its
144 // content length is -1; for such responses, writes are flushed
145 // to the client immediately.
146 FlushInterval caddy.Duration `json:"flush_interval,omitempty"`
147
148 // A list of IP ranges (supports CIDR notation) from which
149 // X-Forwarded-* header values should be trusted. By default,
150 // no proxies are trusted, so existing values will be ignored
151 // when setting these headers. If the proxy is trusted, then
152 // existing values will be used when constructing the final
153 // header values.
154 TrustedProxies []string `json:"trusted_proxies,omitempty"`
155
156 // Headers manipulates headers between Caddy and the backend.
157 // By default, all headers are passed-thru without changes,
158 // with the exceptions of special hop-by-hop headers.
159 //
160 // X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host
161 // are also set implicitly.
162 Headers *headers.Handler `json:"headers,omitempty"`
163
164 // If nonzero, the entire request body up to this size will be read
165 // and buffered in memory before being proxied to the backend. This
166 // should be avoided if at all possible for performance reasons, but
167 // could be useful if the backend is intolerant of read latency or
168 // chunked encodings. An incremental request with an explicitly configured
169 // buffer receives a 501 response. A transport-supplied default is bypassed
170 // only when the request already meets the transport's framing requirements.
171 RequestBuffers int64 `json:"request_buffers,omitempty"`
172
173 // If nonzero, the entire response body up to this size will be read
174 // and buffered in memory before being proxied to the client. This
175 // should be avoided if at all possible for performance reasons, but
176 // could be useful if the backend has tighter memory constraints. Forwarding
177 // an incremental response with content produces a 501 response whenever
178 // buffering is configured.
179 ResponseBuffers int64 `json:"response_buffers,omitempty"`
180
181 // The name identifying this proxy in the Proxy-Status response header
182 // field (RFC 9209). It has to identify the deployment rather than the
183 // software, so there is no sensible default: a service name
184 // ("ExampleCDN"), a hostname ("proxy-3.example.com") or an IP address
185 // are all appropriate. This is used when Caddy refuses to forward a
186 // message marked Incremental. When empty, no Proxy-Status field is generated.
187 ProxyStatusName string `json:"proxy_status_name,omitempty"`
188
189 // If nonzero, streaming requests such as WebSockets will be
190 // forcibly closed at the end of the timeout. Default: no timeout.
191 StreamTimeout caddy.Duration `json:"stream_timeout,omitempty"`
192
193 // The size of the buffer used for each direction of streaming
194 // requests such as WebSockets. If zero, the default size is 32 KiB.
195 // This only affects upgraded bidirectional streams, not normal
196 // request or response buffering.
197 StreamBufferSize int `json:"stream_buffer_size,omitempty"`
198
199 // If nonzero, streaming requests such as WebSockets will not be
200 // closed when the proxy config is unloaded, and instead the stream
201 // will remain open until the delay is complete. In other words,
202 // enabling this prevents streams from closing when Caddy's config
203 // is reloaded. Enabling this may be a good idea to avoid a thundering
204 // herd of reconnecting clients which had their connections closed
205 // by the previous config closing. Default: no delay.
206 StreamCloseDelay caddy.Duration `json:"stream_close_delay,omitempty"`
207
208 // If true, upgraded connections such as WebSockets are detached from
209 // the handler and retained across config reloads when their upstream
210 // still exists in the new config. Connections using upstreams that are
211 // removed are closed during cleanup. By default this is false, preserving
212 // legacy behavior where upgraded connections are closed on reload
213 // (optionally delayed by stream_close_delay).
214 // Only http1.1 websocket connections are affected, websockets for h2/h3
215 // are not affected. If true, bytes transferred for http1.1 in the access
216 // logs will be zero but those stats can be found in the stream logs for
217 // http1/2/3 regardless if this is enabled.
218 StreamDetached bool `json:"stream_detached,omitempty"`
219
220 // Controls logging behavior for upgraded stream lifecycle events.
221 // If omitted, defaults are used (level=DEBUG, logger_name="http.handlers.reverse_proxy.stream").
222 StreamLogs *StreamLogs `json:"stream_logs,omitempty"`
223
224 // If configured, rewrites the copy of the upstream request.
225 // Allows changing the request method and URI (path and query).
226 // Since the rewrite is applied to the copy, it does not persist
227 // past the reverse proxy handler.
228 // If the method is changed to `GET` or `HEAD`, the request body
229 // will not be copied to the backend. This allows a later request
230 // handler -- either in a `handle_response` route, or after -- to
231 // read the body.
232 // By default, no rewrite is performed, and the method and URI
233 // from the incoming request is used as-is for proxying.
234 Rewrite *rewrite.Rewrite `json:"rewrite,omitempty"`
235
236 // List of handlers and their associated matchers to evaluate
237 // after successful roundtrips. The first handler that matches
238 // the response from a backend will be invoked. The response
239 // body from the backend will not be written to the client;
240 // it is up to the handler to finish handling the response.
241 // If passive health checks are enabled, any errors from the
242 // handler chain will not affect the health status of the
243 // backend.
244 //
245 // Three new placeholders are available in this handler chain:
246 // - `{http.reverse_proxy.status_code}` The status code from the response
247 // - `{http.reverse_proxy.status_text}` The status text from the response
248 // - `{http.reverse_proxy.header.*}` The headers from the response
249 HandleResponse []caddyhttp.ResponseHandler `json:"handle_response,omitempty"`
250
251 // If set, the proxy will write very detailed logs about its
252 // inner workings. Enable this only when debugging, as it
253 // will produce a lot of output.
254 //
255 // EXPERIMENTAL: This feature is subject to change or removal.
256 VerboseLogs bool `json:"verbose_logs,omitempty"`
257
258 Transport http.RoundTripper `json:"-"`
259 CB CircuitBreaker `json:"-"`
260 DynamicUpstreams UpstreamSource `json:"-"`
261
262 // transportHeaderOps is a set of header operations provided
263 // by the transport at provision time, if the transport
264 // implements TransportHeaderOpsProvider. These ops are
265 // applied before any user-configured header ops so the
266 // user can override transport defaults.
267 transportHeaderOps *headers.HeaderOps
268
269 // requestBuffersFromTransport distinguishes a transport default from an
270 // operator-configured buffer. Incremental forwarding may bypass the former
271 // only when the request already meets the transport's framing requirements.
272 requestBuffersFromTransport bool
273
274 // Holds the parsed CIDR ranges from TrustedProxies
275 trustedProxies []netip.Prefix
276
277 // Holds the named response matchers from the Caddyfile while adapting
278 responseMatchers map[string]caddyhttp.ResponseMatcher
279
280 // Holds the handle_response Caddyfile tokens while adapting
281 handleResponseSegments []*caddyfile.Dispenser
282
283 // Tracks hijacked/upgraded connections (WebSocket etc.) so they can be
284 // closed when their upstream is removed from the config.
285 tunnelTracker *tunnelTracker
286
287 // tracedTransport wraps Transport to emit OpenTelemetry client spans
288 // for upstream round trips when the request is being traced.
289 tracedTransport http.RoundTripper
290
291 ctx caddy.Context
292 logger *zap.Logger
293 events *caddyevents.App
294
295 streamLogLevel zapcore.Level
296 streamLogLoggerName string
297 }
298
299 // CaddyModule returns the Caddy module information.
300 func (Handler) CaddyModule() caddy.ModuleInfo {
301 return caddy.ModuleInfo{
302 ID: "http.handlers.reverse_proxy",
303 New: func() caddy.Module { return new(Handler) },
304 }
305 }
306
307 // Provision ensures that h is set up properly before use.
308 func (h *Handler) Provision(ctx caddy.Context) error {
309 eventAppIface, err := ctx.App("events")
310 if err != nil {
311 return fmt.Errorf("getting events app: %v", err)
312 }
313 h.events = eventAppIface.(*caddyevents.App)
314 h.ctx = ctx
315 h.logger = ctx.Logger()
316 h.tunnelTracker = newTunnelTracker(h.logger, time.Duration(h.StreamCloseDelay))
317 h.streamLogLevel = defaultStreamLogLevel
318 h.streamLogLoggerName = defaultStreamLoggerName
319 if h.StreamLogs != nil {
320 if h.StreamLogs.Level != "" {
321 lvl, err := zapcore.ParseLevel(strings.ToLower(strings.TrimSpace(h.StreamLogs.Level)))
322 if err != nil {
323 return fmt.Errorf("invalid stream_logs.level %q: %w", h.StreamLogs.Level, err)
324 }
325 h.streamLogLevel = lvl
326 }
327 if name := strings.TrimSpace(h.StreamLogs.LoggerName); name != "" {
328 h.streamLogLoggerName = name
329 }
330 }
331
332 if h.StreamDetached {
333 registerDetachedTunnelTrackers(h.tunnelTracker)
334 }
335
336 // warn about unsafe buffering config
337 if h.RequestBuffers == -1 || h.ResponseBuffers == -1 {
338 h.logger.Warn("UNLIMITED BUFFERING: buffering is enabled without any cap on buffer size, which can result in OOM crashes")
339 }
340
341 // start by loading modules
342 if h.TransportRaw != nil {
343 mod, err := ctx.LoadModule(h, "TransportRaw")
344 if err != nil {
345 return fmt.Errorf("loading transport: %v", err)
346 }
347 h.Transport = mod.(http.RoundTripper)
348
349 // set default buffer sizes if applicable
350 if bt, ok := h.Transport.(BufferedTransport); ok {
351 reqBuffers, respBuffers := bt.DefaultBufferSizes()
352 if h.RequestBuffers == 0 {
353 h.RequestBuffers = reqBuffers
354 h.requestBuffersFromTransport = reqBuffers != 0
355 }
356 if h.ResponseBuffers == 0 {
357 h.ResponseBuffers = respBuffers
358 }
359 }
360 }
361 if h.LoadBalancing != nil && h.LoadBalancing.SelectionPolicyRaw != nil {
362 mod, err := ctx.LoadModule(h.LoadBalancing, "SelectionPolicyRaw")
363 if err != nil {
364 return fmt.Errorf("loading load balancing selection policy: %s", err)
365 }
366 h.LoadBalancing.SelectionPolicy = mod.(Selector)
367 }
368 if h.CBRaw != nil {
369 mod, err := ctx.LoadModule(h, "CBRaw")
370 if err != nil {
371 return fmt.Errorf("loading circuit breaker: %s", err)
372 }
373 h.CB = mod.(CircuitBreaker)
374 }
375 if h.DynamicUpstreamsRaw != nil {
376 mod, err := ctx.LoadModule(h, "DynamicUpstreamsRaw")
377 if err != nil {
378 return fmt.Errorf("loading upstream source module: %v", err)
379 }
380 h.DynamicUpstreams = mod.(UpstreamSource)
381 }
382
383 // parse trusted proxy CIDRs ahead of time
384 for _, str := range h.TrustedProxies {
385 if strings.Contains(str, "/") {
386 ipNet, err := netip.ParsePrefix(str)
387 if err != nil {
388 return fmt.Errorf("parsing CIDR expression: '%s': %v", str, err)
389 }
390 h.trustedProxies = append(h.trustedProxies, ipNet)
391 } else {
392 ipAddr, err := netip.ParseAddr(str)
393 if err != nil {
394 return fmt.Errorf("invalid IP address: '%s': %v", str, err)
395 }
396 ipNew := netip.PrefixFrom(ipAddr, ipAddr.BitLen())
397 h.trustedProxies = append(h.trustedProxies, ipNew)
398 }
399 }
400
401 // ensure any embedded headers handler module gets provisioned
402 // (see https://caddy.community/t/set-cookie-manipulation-in-reverse-proxy/7666?u=matt
403 // for what happens if we forget to provision it)
404 if h.Headers != nil {
405 err := h.Headers.Provision(ctx)
406 if err != nil {
407 return fmt.Errorf("provisioning embedded headers handler: %v", err)
408 }
409 }
410
411 if h.Rewrite != nil {
412 err := h.Rewrite.Provision(ctx)
413 if err != nil {
414 return fmt.Errorf("provisioning rewrite: %v", err)
415 }
416 }
417
418 // set up transport
419 if h.Transport == nil {
420 t := &HTTPTransport{}
421 err := t.Provision(ctx)
422 if err != nil {
423 return fmt.Errorf("provisioning default transport: %v", err)
424 }
425 h.Transport = t
426 }
427
428 h.tracedTransport = newTracedTransport(h.Transport)
429
430 // If the transport can provide header ops, cache them now so we don't
431 // have to compute them per-request. Provision the HeaderOps if present
432 // so any runtime artifacts (like precompiled regex) are prepared.
433 if tph, ok := h.Transport.(RequestHeaderOpsTransport); ok {
434 h.transportHeaderOps = tph.RequestHeaderOps()
435 if h.transportHeaderOps != nil {
436 if err := h.transportHeaderOps.Provision(ctx); err != nil {
437 return fmt.Errorf("provisioning transport header ops: %v", err)
438 }
439 }
440 }
441
442 // set up load balancing
443 if h.LoadBalancing == nil {
444 h.LoadBalancing = new(LoadBalancing)
445 }
446 if h.LoadBalancing.SelectionPolicy == nil {
447 h.LoadBalancing.SelectionPolicy = RandomSelection{}
448 }
449 if h.LoadBalancing.TryDuration > 0 && h.LoadBalancing.TryInterval == 0 {
450 // a non-zero try_duration with a zero try_interval
451 // will always spin the CPU for try_duration if the
452 // upstream is local or low-latency; avoid that by
453 // defaulting to a sane wait period between attempts
454 h.LoadBalancing.TryInterval = caddy.Duration(250 * time.Millisecond)
455 }
456 lbMatcherSets, err := ctx.LoadModule(h.LoadBalancing, "RetryMatchRaw")
457 if err != nil {
458 return err
459 }
460 err = h.LoadBalancing.RetryMatch.FromInterface(lbMatcherSets)
461 if err != nil {
462 return err
463 }
464
465 // set up upstreams
466 for _, u := range h.Upstreams {
467 h.provisionUpstream(u, false)
468 }
469
470 if h.HealthChecks != nil {
471 // set defaults on passive health checks, if necessary
472 if h.HealthChecks.Passive != nil {
473 h.HealthChecks.Passive.logger = h.logger.Named("health_checker.passive")
474 if h.HealthChecks.Passive.MaxFails == 0 {
475 h.HealthChecks.Passive.MaxFails = 1
476 }
477 }
478
479 // if active health checks are enabled, configure them and start a worker
480 if h.HealthChecks.Active != nil {
481 err := h.HealthChecks.Active.Provision(ctx, h)
482 if err != nil {
483 return err
484 }
485
486 if h.HealthChecks.Active.IsEnabled() {
487 go h.activeHealthChecker()
488 }
489 }
490 }
491
492 // set up any response routes
493 for i, rh := range h.HandleResponse {
494 err := rh.Provision(ctx)
495 if err != nil {
496 return fmt.Errorf("provisioning response handler %d: %v", i, err)
497 }
498 }
499
500 upstreamHealthyUpdater := newMetricsUpstreamsHealthyUpdater(h, ctx)
501 upstreamHealthyUpdater.init()
502
503 return nil
504 }
505
506 func (h Handler) streamLogsSkipHandshake() bool {
507 return h.StreamLogs != nil && h.StreamLogs.SkipHandshake
508 }
509
510 func (h Handler) streamLoggerForRequest(req *http.Request) *zap.Logger {
511 name := strings.TrimSpace(h.streamLogLoggerName)
512 if name == "" {
513 name = defaultStreamLoggerName
514 }
515
516 if name == streamLoggerNameUseAccess {
517 logger := caddy.Log().Named(defaultAccessLoggerBase)
518 names := caddyhttp.GetVar(req.Context(), caddyhttp.AccessLoggerNameVarKey)
519 namesSlice, ok := names.([]any)
520 if !ok {
521 return logger
522 }
523 for _, v := range namesSlice {
524 name, ok := v.(string)
525 if !ok {
526 continue
527 }
528 if name == "" {
529 return logger
530 }
531 return logger.Named(name)
532 }
533 return logger
534 }
535
536 return caddy.Log().Named(name)
537 }
538
539 var (
540 detachedTunnelTrackers = make(map[*tunnelTracker]struct{})
541 detachedTunnelTrackersMu sync.Mutex
542 )
543
544 func registerDetachedTunnelTrackers(ts *tunnelTracker) {
545 detachedTunnelTrackersMu.Lock()
546 defer detachedTunnelTrackersMu.Unlock()
547 detachedTunnelTrackers[ts] = struct{}{}
548 }
549
550 func notifyDetachedTunnelTrackersOfUpstreamRemoval(upstream string, self *tunnelTracker) error {
551 detachedTunnelTrackersMu.Lock()
552 trackers := make([]*tunnelTracker, 0, len(detachedTunnelTrackers))
553 for tunnel := range detachedTunnelTrackers {
554 trackers = append(trackers, tunnel)
555 }
556 detachedTunnelTrackersMu.Unlock()
557
558 // Connection deletion unregisters empty trackers. Do not hold the
559 // registry lock while acquiring tracker locks or closing connections.
560 // One deadline for every tracker; see closeConnectionsLocked.
561 deadline := time.Now().Add(closeControlWriteTimeout)
562 var err error
563 for _, tunnel := range trackers {
564 if closeErr := tunnel.closeConnectionsForUpstream(upstream, deadline); closeErr != nil && tunnel == self && err == nil {
565 err = closeErr
566 }
567 }
568 return err
569 }
570
571 func unregisterDetachedTunnelTrackers(ts *tunnelTracker) {
572 detachedTunnelTrackersMu.Lock()
573 defer detachedTunnelTrackersMu.Unlock()
574 delete(detachedTunnelTrackers, ts)
575 }
576
577 // Cleanup cleans up the resources made by h.
578 func (h *Handler) Cleanup() error {
579 // even if StreamDetached is true, extended connect websockets may still be running
580 err := h.tunnelTracker.cleanupAttachedConnections()
581 for _, upstream := range h.Upstreams {
582 // hosts.Delete returns deleted=true when the ref count reaches zero,
583 // meaning no other active config references this upstream. In that
584 // case close any tunnels proxying to it; otherwise let them survive
585 // to their natural end since the upstream is still in use.
586 deleted, _ := hosts.Delete(upstream.String())
587 if deleted {
588 if closeErr := notifyDetachedTunnelTrackersOfUpstreamRemoval(upstream.String(), h.tunnelTracker); closeErr != nil && err == nil {
589 err = closeErr
590 }
591 }
592 }
593 return err
594 }
595
596 // bodyNopCloserIfNotRead wraps a request body to prevent closing if not read, i.e., when
597 // dialing to upstream fails.
598 // It will close the body as normal if the body is read.
599 type bodyNopCloserIfNotRead struct {
600 io.ReadCloser
601 read int // tracks the number of bytes read, -1 when first Read returns 0, io.EOF
602 }
603
604 func (b *bodyNopCloserIfNotRead) Read(p []byte) (int, error) {
605 if b.read == -1 {
606 return 0, io.EOF
607 }
608 n, err := b.ReadCloser.Read(p)
609 // first Read returns 0, io.EOF
610 if b.read == 0 && n == 0 && err == io.EOF {
611 b.read = -1
612 } else {
613 b.read += n
614 }
615 return n, err
616 }
617
618 func (b *bodyNopCloserIfNotRead) Close() error {
619 // don't close the body
620 if b.read == 0 {
621 return nil
622 }
623 // close as usual, when -1, any read will return EOF as the original read will do
624 // in other cases, the read will fail as body is closed because we do not want partial bodies to be sent to the upstream
625 // users can buffer the entire request body to allow the request to be resent
626 return b.ReadCloser.Close()
627 }
628
629 func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
630 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
631
632 // prepare the request for proxying; this is needed only once
633 clonedReq, err := h.prepareRequest(r, repl)
634 if err != nil {
635 if errors.Is(err, errIncrementalRefused) {
636 return h.refuseIncremental(w, nil)
637 }
638 return caddyhttp.Error(http.StatusInternalServerError,
639 fmt.Errorf("preparing request for upstream round-trip: %v", err))
640 }
641
642 // 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
643 // Both use the same upgrade mechanism: server advertizes extended connect support, and client sends the pseudo header :protocol in a CONNECT request
644 // The quic-go http3 implementation also puts :protocol in r.Proto for CONNECT requests (quic-go/http3/headers.go@70-72,185,203)
645 // TODO: once we can reliably detect backend support this, it can be removed for those backends
646 if (r.ProtoMajor == 2 && r.Method == http.MethodConnect && r.Header.Get(":protocol") == "websocket") ||
647 (r.ProtoMajor == 3 && r.Method == http.MethodConnect && r.Proto == "websocket") {
648 clonedReq.Header.Del(":protocol")
649 // keep the body for later use. http1.1 upgrade uses http.NoBody
650 caddyhttp.SetVar(clonedReq.Context(), "extended_connect_websocket_body", clonedReq.Body)
651 clonedReq.Body = http.NoBody
652 clonedReq.Method = http.MethodGet
653 clonedReq.Header.Set("Upgrade", "websocket")
654 clonedReq.Header.Set("Connection", "Upgrade")
655 key := make([]byte, 16)
656 _, randErr := rand.Read(key)
657 if randErr != nil {
658 return randErr
659 }
660 clonedReq.Header.Set("Sec-WebSocket-Key", base64.StdEncoding.EncodeToString(key))
661 }
662
663 // we will need the original headers and Host value if
664 // header operations are configured; this is so that each
665 // retry can apply the modifications, because placeholders
666 // may be used which depend on the selected upstream for
667 // their values
668 reqHost := clonedReq.Host
669 reqHeader := clonedReq.Header
670 requestWasIncremental := caddyhttp.IsIncremental(reqHeader)
671
672 // If the request contained a body, wrap it in io.NopCloser
673 // to prevent Go's transport from closing it on dial errors.
674 // cloneRequest does a shallow copy, so clonedReq.Body and
675 // r.Body share the same io.ReadCloser — a dial-failure Close()
676 // would kill the original body for all subsequent retry
677 // attempts or subsequent handlers. The real body is closed by
678 // the HTTP server when the handler returns.
679 //
680 // If the body was already fully buffered (via request_buffers),
681 // we also extract the buffer so the retry loop can replay it
682 // from the beginning on each attempt. (see #6259, #7546, #7713)
683 var bufferedReqBody *bytes.Buffer
684 if clonedReq.Body != nil {
685 if reqBodyBuf, ok := clonedReq.Body.(bodyReadCloser); ok && reqBodyBuf.body == nil && reqBodyBuf.buf != nil {
686 bufferedReqBody = reqBodyBuf.buf
687 reqBodyBuf.buf = nil
688 clonedReq.Body = io.NopCloser(bytes.NewReader(bufferedReqBody.Bytes()))
689 defer func() {
690 bufferedReqBody.Reset()
691 bufPool.Put(bufferedReqBody)
692 }()
693 } else {
694 clonedReq.Body = &bodyNopCloserIfNotRead{ReadCloser: clonedReq.Body}
695 }
696 }
697
698 start := time.Now()
699 defer func() {
700 // total proxying duration, including time spent on LB and retries
701 repl.Set("http.reverse_proxy.duration", time.Since(start))
702 repl.Set("http.reverse_proxy.duration_ms", time.Since(start).Seconds()*1e3) // multiply seconds to preserve decimal (see #4666)
703 }()
704
705 // in the proxy loop, each iteration is an attempt to proxy the request,
706 // and because we may retry some number of times, carry over the error
707 // from previous tries because of the nuances of load balancing & retries
708 var proxyErr error
709 var retries int
710 for {
711 // if the request body was buffered (and only the entire body, hence no body
712 // set to read from after the buffer), make reading from the body idempotent
713 // and reusable, so if a backend partially or fully reads the body but then
714 // produces an error, the request can be repeated to the next backend with
715 // the full body (retries should only happen for idempotent requests) (see #6259)
716 if bufferedReqBody != nil {
717 clonedReq.Body = io.NopCloser(bytes.NewReader(bufferedReqBody.Bytes()))
718 }
719
720 var done bool
721 done, proxyErr = h.proxyLoopIteration(clonedReq, r, w, proxyErr, start, retries, repl, reqHeader, reqHost, requestWasIncremental, next)
722 if done {
723 break
724 }
725 if h.VerboseLogs {
726 var lbWait time.Duration
727 if h.LoadBalancing != nil {
728 lbWait = time.Duration(h.LoadBalancing.TryInterval)
729 }
730 if c := h.logger.Check(zapcore.DebugLevel, "retrying"); c != nil {
731 c.Write(zap.Error(proxyErr), zap.Duration("after", lbWait))
732 }
733 }
734 retries++
735 }
736
737 // number of retries actually performed
738 repl.Set("http.reverse_proxy.retries", retries)
739
740 if proxyErr != nil {
741 return statusError(proxyErr)
742 }
743
744 return nil
745 }
746
747 // proxyLoopIteration implements an iteration of the proxy loop. Despite the enormous amount of local state
748 // that has to be passed in, we brought this into its own method so that we could run defer more easily.
749 // It returns true when the loop is done and should break; false otherwise. The error value returned should
750 // be assigned to the proxyErr value for the next iteration of the loop (or the error handled after break).
751 func (h *Handler) proxyLoopIteration(r *http.Request, origReq *http.Request, w http.ResponseWriter, proxyErr error, start time.Time, retries int,
752 repl *caddy.Replacer, reqHeader http.Header, reqHost string, requestWasIncremental bool, next caddyhttp.Handler,
753 ) (bool, error) {
754 // get the updated list of upstreams
755 upstreams := h.Upstreams
756 if h.DynamicUpstreams != nil {
757 if retries > 0 {
758 // after a failure (and thus during a retry), give dynamic upstream modules an opportunity
759 // to purge their relevant cache entries so we don't keep retrying bad upstreams
760 if cachingDynamicUpstreams, ok := h.DynamicUpstreams.(CachingUpstreamSource); ok {
761 if err := cachingDynamicUpstreams.ResetCache(r); err != nil {
762 if c := h.logger.Check(zapcore.ErrorLevel, "failed clearing dynamic upstream source's cache"); c != nil {
763 c.Write(zap.Error(err))
764 }
765 }
766 }
767 }
768 dUpstreams, err := h.DynamicUpstreams.GetUpstreams(r)
769 if err != nil {
770 if c := h.logger.Check(zapcore.ErrorLevel, "failed getting dynamic upstreams; falling back to static upstreams"); c != nil {
771 c.Write(zap.Error(err))
772 }
773 } else {
774 upstreams = dUpstreams
775 for _, dUp := range dUpstreams {
776 h.provisionUpstream(dUp, true)
777 }
778 if c := h.logger.Check(zapcore.DebugLevel, "provisioned dynamic upstreams"); c != nil {
779 c.Write(zap.Int("count", len(dUpstreams)))
780 }
781 }
782 }
783
784 // choose an available upstream
785 upstream := h.LoadBalancing.SelectionPolicy.Select(upstreams, r, w)
786 if upstream == nil {
787 if proxyErr == nil {
788 proxyErr = caddyhttp.Error(http.StatusServiceUnavailable, errNoUpstream)
789 }
790 if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r, h.logger) {
791 return true, proxyErr
792 }
793 return false, proxyErr
794 }
795
796 // the dial address may vary per-request if placeholders are
797 // used, so perform those replacements here; the resulting
798 // DialInfo struct should have valid network address syntax
799 dialInfo, err := upstream.fillDialInfo(repl)
800 if err != nil {
801 return true, fmt.Errorf("making dial info: %v", err)
802 }
803
804 if c := h.logger.Check(zapcore.DebugLevel, "selected upstream"); c != nil {
805 c.Write(
806 zap.String("dial", dialInfo.Address),
807 zap.Int("total_upstreams", len(upstreams)),
808 )
809 }
810
811 // set placeholders with information about this upstream
812 repl.Set("http.reverse_proxy.upstream.address", dialInfo.String())
813 repl.Set("http.reverse_proxy.upstream.hostport", dialInfo.Address)
814 repl.Set("http.reverse_proxy.upstream.host", dialInfo.Host)
815 repl.Set("http.reverse_proxy.upstream.port", dialInfo.Port)
816 repl.Set("http.reverse_proxy.upstream.requests", upstream.Host.NumRequests())
817 repl.Set("http.reverse_proxy.upstream.max_requests", upstream.MaxRequests)
818 repl.Set("http.reverse_proxy.upstream.fails", upstream.Host.Fails())
819
820 // mutate request headers according to this upstream;
821 // because we're in a retry loop, we have to copy headers
822 // (and the r.Host value) from the original so that each
823 // retry is identical to the first. If either transport or
824 // user ops exist, apply them in order (transport first,
825 // then user, so user's config wins).
826 var userOps *headers.HeaderOps
827 if h.Headers != nil {
828 userOps = h.Headers.Request
829 }
830 transportOps := h.transportHeaderOps
831 if transportOps != nil || userOps != nil {
832 r.Header = make(http.Header)
833 copyHeader(r.Header, reqHeader)
834 r.Host = reqHost
835 if transportOps != nil {
836 transportOps.ApplyToRequest(r)
837 }
838 if userOps != nil {
839 userOps.ApplyToRequest(r)
840 }
841 }
842 if !requestWasIncremental && requestHasContent(r) && caddyhttp.IsIncremental(r.Header) &&
843 (h.RequestBuffers != 0 || r.ContentLength < 0 && h.transportRequiresContentLength()) {
844 return true, h.refuseIncremental(w, nil)
845 }
846 normalizeIncrementalRequest(r)
847
848 // normalize websocket headers for compatibility with older servers
849 if upgradeType(r.Header) != "" {
850 normalizeWebsocketHeaders(r.Header)
851 }
852
853 // proxy the request to that upstream
854 proxyErr = h.reverseProxy(w, r, origReq, repl, dialInfo, next)
855 if proxyErr == nil {
856 return true, nil
857 }
858 if errors.Is(proxyErr, context.Canceled) {
859 // context.Canceled happens when the downstream client cancels the
860 // request, which is not our failure; don't retry or ding the upstream.
861 // Record a 499 (client closed request) so the access log reflects the
862 // disconnect instead of a misleading 0 status (see #7396).
863 w.WriteHeader(499)
864 return true, nil
865 }
866
867 // if the handler has already committed a client-visible response
868 // (e.g. a successful roundtrip whose handle_response route errored,
869 // or a WebTransport upgrade that flushed 200 OK and hijacked the
870 // stream), don't retry against another upstream and don't ding the
871 // upstream's health status
872 if term, ok := proxyErr.(terminalError); ok {
873 return true, term.error
874 }
875
876 // remember this failure (if enabled); response-based retries
877 // are not counted as failures since the upstream did respond
878 // successfully - only the response content triggered a retry
879 if _, isRetryableResponse := proxyErr.(retryableResponseError); !isRetryableResponse {
880 h.countFailure(upstream)
881 }
882
883 // if we've tried long enough, break
884 if !h.LoadBalancing.tryAgain(h.ctx, start, retries, proxyErr, r, h.logger) {
885 return true, proxyErr
886 }
887
888 return false, proxyErr
889 }
890
891 // Mapping of the canonical form of the headers, to the RFC 6455 form,
892 // i.e. `WebSocket` with uppercase 'S'.
893 var websocketHeaderMapping = map[string]string{
894 "Sec-Websocket-Accept": "Sec-WebSocket-Accept",
895 "Sec-Websocket-Extensions": "Sec-WebSocket-Extensions",
896 "Sec-Websocket-Key": "Sec-WebSocket-Key",
897 "Sec-Websocket-Protocol": "Sec-WebSocket-Protocol",
898 "Sec-Websocket-Version": "Sec-WebSocket-Version",
899 }
900
901 // normalizeWebsocketHeaders ensures we use the standard casing as per
902 // RFC 6455, i.e. `WebSocket` with uppercase 'S'. Most servers don't
903 // care about this difference (read headers case insensitively), but
904 // some do, so this maximizes compatibility with upstreams.
905 // See https://github.com/caddyserver/caddy/pull/6621
906 func normalizeWebsocketHeaders(header http.Header) {
907 for k, rk := range websocketHeaderMapping {
908 if v, ok := header[k]; ok {
909 delete(header, k)
910 header[rk] = v
911 }
912 }
913 }
914
915 // prepareRequest clones req so that it can be safely modified without
916 // changing the original request or introducing data races. It then
917 // modifies it so that it is ready to be proxied, except for directing
918 // to a specific upstream. This method adjusts headers and other relevant
919 // properties of the cloned request and should be done just once (before
920 // proxying) regardless of proxy retries. This assumes that no mutations
921 // of the cloned request are performed by h during or after proxying.
922 func (h Handler) prepareRequest(req *http.Request, repl *caddy.Replacer) (*http.Request, error) {
923 origReq := req
924 req = cloneRequest(req)
925
926 // if enabled, perform rewrites on the cloned request; if
927 // the method is GET or HEAD, prevent the request body
928 // from being copied to the upstream
929 if h.Rewrite != nil {
930 changed := h.Rewrite.Rewrite(req, repl)
931 if changed && (h.Rewrite.Method == "GET" || h.Rewrite.Method == "HEAD") {
932 req.ContentLength = 0
933 req.Body = nil
934 }
935 }
936
937 if req.Body != nil {
938 // net/http fills in the incoming trailers only when Body.Read reaches
939 // EOF. Keep an independent map, but update it in that same Read before
940 // the transport writes the trailers. Install this before buffering,
941 // which may itself consume the body to EOF before the round trip.
942 if req.Trailer == nil {
943 req.Trailer = make(http.Header)
944 }
945 req.Body = &requestBodyWithTrailers{ReadCloser: req.Body, original: origReq, trailer: req.Trailer}
946 }
947
948 // Fully buffering the request is incompatible with incremental forwarding.
949 // A negative length is treated as potential content because determining
950 // whether it is empty would itself require waiting for the stream to end.
951 if h.incrementalRequestConflicts(req) {
952 return nil, errIncrementalRefused
953 }
954 normalizeIncrementalRequest(req)
955
956 // if enabled, buffer client request; this should only be
957 // enabled if the upstream requires it and does not work
958 // with "slow clients" (gunicorn, etc.) - this obviously
959 // has a perf overhead and makes the proxy at risk of
960 // exhausting memory and more susceptible to slowloris
961 // attacks, so it is strongly recommended to only use this
962 // feature if absolutely required, if read timeouts are
963 // set, and if body size is limited
964 if h.RequestBuffers != 0 && req.Body != nil && !caddyhttp.IsIncremental(req.Header) {
965 var readBytes int64
966 req.Body, readBytes = h.bufferedBody(req.Body, h.RequestBuffers)
967 // set Content-Length when body is fully buffered
968 if b, ok := req.Body.(bodyReadCloser); ok && b.body == nil {
969 req.ContentLength = readBytes
970 req.Header["Content-Length"] = []string{strconv.FormatInt(req.ContentLength, 10)}
971 }
972 }
973
974 // HTTP/1 upstreams require chunked framing to carry trailers, including
975 // when buffering has made the body length known (or the body is empty).
976 // Length-required transports such as FastCGI need the buffered length and
977 // do not carry HTTP trailers.
978 if len(req.Trailer) > 0 && req.Body != nil && !h.transportRequiresContentLength() {
979 req.ContentLength = -1
980 req.Header.Del("Content-Length")
981 }
982
983 if req.ContentLength == 0 {
984 req.Body = nil // Issue golang/go#16036: nil Body for http.Transport retries
985 }
986
987 req.Close = false
988
989 // if User-Agent is not set by client, then explicitly
990 // disable it so it's not set to default value by std lib
991 if _, ok := req.Header["User-Agent"]; !ok {
992 req.Header["User-Agent"] = []string{""}
993 }
994
995 // Indicate if request has been conveyed in early data.
996 // RFC 8470: "An intermediary that forwards a request prior to the
997 // completion of the TLS handshake with its client MUST send it with
998 // the Early-Data header field set to “1” (i.e., it adds it if not
999 // present in the request). An intermediary MUST use the Early-Data
1000 // header field if the request might have been subject to a replay and
1001 // might already have been forwarded by it or another instance
1002 // (see Section 6.2)."
1003 if req.TLS != nil && !req.TLS.HandshakeComplete {
1004 req.Header["Early-Data"] = []string{"1"}
1005 }
1006
1007 reqUpgradeType := upgradeType(req.Header)
1008 removeConnectionHeaders(req.Header)
1009
1010 // Remove hop-by-hop headers to the backend. Especially
1011 // important is "Connection" because we want a persistent
1012 // connection, regardless of what the client sent to us.
1013 // Issue golang/go#46313: don't skip if field is empty.
1014 for _, h := range hopHeaders {
1015 // Issue golang/go#21096: tell backend applications that care about trailer support
1016 // that we support trailers. (We do, but we don't go out of our way to
1017 // advertise that unless the incoming client request thought it was worth
1018 // mentioning.)
1019 if h == "Te" && httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") {
1020 req.Header["Te"] = []string{"trailers"}
1021 continue
1022 }
1023 // hopHeaders are already canonical, so skip the normalization Del does
1024 delete(req.Header, h)
1025 }
1026
1027 // After stripping all the hop-by-hop connection headers above, add back any
1028 // necessary for protocol upgrades, such as for websockets.
1029 if reqUpgradeType != "" {
1030 req.Header["Connection"] = []string{"Upgrade"}
1031 req.Header["Upgrade"] = []string{reqUpgradeType}
1032 }
1033
1034 // Set up the PROXY protocol info
1035 address := caddyhttp.GetVar(req.Context(), caddyhttp.ClientIPVarKey).(string)
1036 addrPort, err := netip.ParseAddrPort(address)
1037 if err != nil {
1038 // OK; probably didn't have a port
1039 addr, err := netip.ParseAddr(address)
1040 if err != nil {
1041 // Doesn't seem like a valid ip address at all
1042 } else {
1043 // Ok, only the port was missing
1044 addrPort = netip.AddrPortFrom(addr, 0)
1045 }
1046 }
1047 proxyProtocolInfo := ProxyProtocolInfo{AddrPort: addrPort}
1048 caddyhttp.SetVar(req.Context(), proxyProtocolInfoVarKey, proxyProtocolInfo)
1049
1050 // some of the outbound requests require h1 (e.g. websocket)
1051 // https://github.com/golang/go/blob/4837fbe4145cd47b43eed66fee9eed9c2b988316/src/net/http/request.go#L1579
1052 if isWebsocket(req) {
1053 caddyhttp.SetVar(req.Context(), tlsH1OnlyVarKey, true)
1054 }
1055
1056 // Add the supported X-Forwarded-* headers
1057 err = h.addForwardedHeaders(req)
1058 if err != nil {
1059 return nil, err
1060 }
1061
1062 // Via header(s)
1063 req.Header["Via"] = append(req.Header["Via"],
1064 strconv.Itoa(req.ProtoMajor)+"."+strconv.Itoa(req.ProtoMinor)+" Caddy")
1065
1066 return req, nil
1067 }
1068
1069 // addForwardedHeaders adds the de-facto standard X-Forwarded-*
1070 // headers to the request before it is sent upstream.
1071 //
1072 // These headers are security sensitive, so care is taken to only
1073 // use existing values for these headers from the incoming request
1074 // if the client IP is trusted (i.e. coming from a trusted proxy
1075 // sitting in front of this server). If the request didn't have
1076 // the headers at all, then they will be added with the values
1077 // that we can glean from the request.
1078 func (h Handler) addForwardedHeaders(req *http.Request) error {
1079 // Check if the client is a trusted proxy
1080 trusted := caddyhttp.GetVar(req.Context(), caddyhttp.TrustedProxyVarKey).(bool)
1081
1082 var clientIP string
1083
1084 if req.RemoteAddr == "@" {
1085 // For Unix socket connections, RemoteAddr is "@" which cannot
1086 // be parsed as host:port. If untrusted, strip forwarded headers
1087 // for security. If trusted, there is no peer IP to append to
1088 // X-Forwarded-For, so clientIP stays empty.
1089 if !trusted {
1090 delete(req.Header, "X-Forwarded-For")
1091 delete(req.Header, "X-Forwarded-Proto")
1092 delete(req.Header, "X-Forwarded-Host")
1093 return nil
1094 }
1095 } else {
1096 // Parse the remote IP, ignore the error as non-fatal,
1097 // but the remote IP is required to continue, so we
1098 // just return early. This should probably never happen
1099 // though, unless some other module manipulated the request's
1100 // remote address and used an invalid value.
1101 var err error
1102 clientIP, _, err = net.SplitHostPort(req.RemoteAddr)
1103 if err != nil {
1104 // Remove the `X-Forwarded-*` headers to avoid upstreams
1105 // potentially trusting a header that came from the client
1106 delete(req.Header, "X-Forwarded-For")
1107 delete(req.Header, "X-Forwarded-Proto")
1108 delete(req.Header, "X-Forwarded-Host")
1109 return nil
1110 }
1111
1112 // Client IP may contain a zone if IPv6, so we need
1113 // to pull that out before parsing the IP
1114 clientIP, _, _ = strings.Cut(clientIP, "%")
1115 ipAddr, err := netip.ParseAddr(clientIP)
1116
1117 // If ParseAddr fails (e.g. non-IP network like SCION), we cannot check
1118 // if it is a trusted proxy by IP range. In this case, we ignore the
1119 // error and treat the connection as untrusted (or retain existing status).
1120 if err == nil {
1121 for _, ipRange := range h.trustedProxies {
1122 if ipRange.Contains(ipAddr) {
1123 trusted = true
1124 break
1125 }
1126 }
1127 }
1128 }
1129
1130 // If we aren't the first proxy, and the proxy is trusted,
1131 // retain prior X-Forwarded-For information as a comma+space
1132 // separated list and fold multiple headers into one.
1133 prior, ok, omit := allHeaderValues(req.Header, "X-Forwarded-For")
1134 if !omit {
1135 if trusted && ok && prior != "" {
1136 if clientIP != "" {
1137 req.Header["X-Forwarded-For"] = []string{prior + ", " + clientIP}
1138 } else {
1139 req.Header["X-Forwarded-For"] = []string{prior}
1140 }
1141 } else if clientIP != "" {
1142 req.Header["X-Forwarded-For"] = []string{clientIP}
1143 }
1144 }
1145
1146 // Set X-Forwarded-Proto; many backend apps expect this,
1147 // so that they can properly craft URLs with the right
1148 // scheme to match the original request
1149 proto := "https"
1150 if req.TLS == nil {
1151 proto = "http"
1152 }
1153 prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Proto")
1154 if trusted && ok && prior != "" {
1155 proto = prior
1156 }
1157 if !omit {
1158 req.Header["X-Forwarded-Proto"] = []string{proto}
1159 }
1160
1161 // Set X-Forwarded-Host; often this is redundant because
1162 // we pass through the request Host as-is, but in situations
1163 // where we proxy over HTTPS, the user may need to override
1164 // Host themselves, so it's helpful to send the original too.
1165 host := req.Host
1166 prior, ok, omit = lastHeaderValue(req.Header, "X-Forwarded-Host")
1167 if trusted && ok && prior != "" {
1168 host = prior
1169 }
1170 if !omit {
1171 req.Header["X-Forwarded-Host"] = []string{host}
1172 }
1173
1174 return nil
1175 }
1176
1177 // reverseProxy performs a round-trip to the given backend and processes the response with the client.
1178 // (This method is mostly the beginning of what was borrowed from the net/http/httputil package in the
1179 // Go standard library which was used as the foundation.)
1180 func (h *Handler) reverseProxy(rw http.ResponseWriter, req *http.Request, origReq *http.Request, repl *caddy.Replacer, di DialInfo, next caddyhttp.Handler) error {
1181 _ = di.Upstream.Host.countRequest(1)
1182
1183 // Increment the in-flight request count
1184 incInFlightRequest(di.Address)
1185
1186 //nolint:errcheck
1187 defer func() {
1188 di.Upstream.Host.countRequest(-1)
1189 // Decrement the in-flight request count
1190 decInFlightRequest(di.Address)
1191 }()
1192
1193 // point the request to this upstream
1194 h.directRequest(req, di)
1195
1196 server := req.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server)
1197 shouldLogCredentials := server.Logs != nil && server.Logs.ShouldLogCredentials
1198
1199 // WebTransport: Extended CONNECT :protocol=webtransport can't flow
1200 // through the normal HTTP round-trip — the session hosts many QUIC
1201 // streams and datagrams that need bidirectional pumping. Swap
1202 // RoundTrip for a small hijack helper. Upstream dial failures
1203 // surface as DialError so the loop can retry across upstreams;
1204 // pre-upgrade misconfig and post-upgrade failures return
1205 // terminalError because the response is already committed to the
1206 // client or no upstream can fix the condition.
1207 if isWebTransportExtendedConnect(origReq) {
1208 return h.webTransportHijack(rw, req, origReq, repl, di, server)
1209 }
1210
1211 // Forward 1xx status codes, backported from https://github.com/golang/go/pull/53164
1212 var (
1213 roundTripMutex sync.Mutex
1214 roundTripDone bool
1215 )
1216 trace := &httptrace.ClientTrace{
1217 Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
1218 roundTripMutex.Lock()
1219 defer roundTripMutex.Unlock()
1220 if roundTripDone {
1221 // If RoundTrip has returned, don't try to further modify
1222 // the ResponseWriter's header map.
1223 return nil
1224 }
1225 h := rw.Header()
1226 ownHeaders := h.Clone()
1227 upstreamHeaders := http.Header(header).Clone()
1228 stripHopByHopHeaders(upstreamHeaders)
1229 copyHeader(h, upstreamHeaders)
1230 rw.WriteHeader(code)
1231
1232 // Clear headers coming from the backend, keeping our own
1233 // (it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses)
1234 clear(h)
1235 maps.Copy(h, ownHeaders)
1236
1237 return nil
1238 },
1239 }
1240 // attach to the request information about how to dial the upstream;
1241 // this is necessary because the information cannot be sufficiently
1242 // or satisfactorily represented in a URL
1243 // it's set before request is roundtripped to avoid a race condition when
1244 // http.Transport reads a newer value to dial a new connection when that new
1245 // value is updated by another reverse proxy handler, typically forward_auth.
1246 ctx := context.WithValue(req.Context(), dialInfoCtxKey, di)
1247 // Record the upstream socket for the websocket close message, since an
1248 // upgraded HTTP/1 body hides it; see upstreamWriteCloser.
1249 if isWebsocket(req) {
1250 upstreamConn := new(atomic.Pointer[net.Conn])
1251 trace.GotConn = func(info httptrace.GotConnInfo) {
1252 conn := info.Conn
1253 upstreamConn.Store(&conn)
1254 }
1255 ctx = context.WithValue(ctx, upstreamConnCtxKey, upstreamConn)
1256 }
1257 req = req.WithContext(httptrace.WithClientTrace(ctx, trace))
1258
1259 // do the round-trip
1260 start := time.Now()
1261 res, err := h.roundTrip(req)
1262 duration := time.Since(start)
1263
1264 // record that the round trip is done for the 1xx response handler
1265 roundTripMutex.Lock()
1266 roundTripDone = true
1267 roundTripMutex.Unlock()
1268
1269 // emit debug log with values we know are safe,
1270 // or if there is no error, emit fuller log entry
1271 logger := h.logger.With(
1272 zap.String("upstream", di.Upstream.String()),
1273 zap.Duration("duration", duration),
1274 zap.Object("request", caddyhttp.LoggableHTTPRequest{
1275 Request: req,
1276 ShouldLogCredentials: shouldLogCredentials,
1277 }),
1278 )
1279
1280 const logMessage = "upstream roundtrip"
1281
1282 if err != nil {
1283 if c := logger.Check(zapcore.DebugLevel, logMessage); c != nil {
1284 c.Write(zap.Error(err))
1285 }
1286 return err
1287 }
1288 if c := logger.Check(zapcore.DebugLevel, logMessage); c != nil {
1289 c.Write(
1290 zap.Object("headers", caddyhttp.LoggableHTTPHeader{
1291 Header: res.Header,
1292 ShouldLogCredentials: shouldLogCredentials,
1293 }),
1294 zap.Int("status", res.StatusCode),
1295 )
1296 }
1297
1298 h.recordUpstreamRoundTrip(di, repl, res.StatusCode, duration)
1299
1300 // if enabled, buffer the response body
1301 if h.ResponseBuffers != 0 && !caddyhttp.IsIncremental(res.Header) {
1302 res.Body, _ = h.bufferedBody(res.Body, h.ResponseBuffers)
1303 }
1304
1305 // set response placeholders so they can be used in retry match
1306 // expressions and handle_response routes; clear stale header
1307 // placeholders from a previous attempt first so they don't
1308 // leak into the next retry evaluation
1309 repl.DeleteByPrefix("http.reverse_proxy.header.")
1310 for field, value := range res.Header {
1311 repl.Set("http.reverse_proxy.header."+field, strings.Join(value, ","))
1312 }
1313 repl.Set("http.reverse_proxy.status_code", res.StatusCode)
1314 repl.Set("http.reverse_proxy.status_text", res.Status)
1315
1316 // check if the response matches a retry match entry; if so,
1317 // close the body and return a retryable error so the request
1318 // is retried with the next upstream. Only evaluate matcher sets
1319 // with an expression that references response data ({rp.status_code},
1320 // {rp.header.*}). Request-only matchers (method, path, or an
1321 // expression without response placeholders) are skipped to avoid
1322 // retrying every response that matches a request condition
1323 if h.LoadBalancing != nil && len(h.LoadBalancing.RetryMatch) > 0 {
1324 for _, matcherSet := range h.LoadBalancing.RetryMatch {
1325 if !matcherSetReferencesResponse(matcherSet) {
1326 continue
1327 }
1328 match, err := matcherSet.MatchWithError(req)
1329 if err != nil {
1330 h.logger.Error("error matching request for retry", zap.Error(err))
1331 break
1332 }
1333 if match {
1334 res.Body.Close()
1335 return retryableResponseError{
1336 error: fmt.Errorf("upstream response matched retry_match (status %d)", res.StatusCode),
1337 statusCode: res.StatusCode,
1338 }
1339 }
1340 }
1341 }
1342
1343 // see if any response handler is configured for this response from the backend
1344 for i, rh := range h.HandleResponse {
1345 if rh.Match != nil && !rh.Match.Match(res.StatusCode, res.Header) {
1346 continue
1347 }
1348
1349 // if configured to only change the status code,
1350 // do that then continue regular proxy response
1351 if statusCodeStr := rh.StatusCode.String(); statusCodeStr != "" {
1352 statusCode, err := strconv.Atoi(repl.ReplaceAll(statusCodeStr, ""))
1353 if err != nil {
1354 res.Body.Close()
1355 return caddyhttp.Error(http.StatusInternalServerError, err)
1356 }
1357 if statusCode != 0 {
1358 res.StatusCode = statusCode
1359 }
1360 break
1361 }
1362
1363 if c := logger.Check(zapcore.DebugLevel, "handling response"); c != nil {
1364 c.Write(zap.Int("handler", i))
1365 }
1366
1367 // we make some data available via request context to child routes
1368 // so that they may inherit some options and functions from the
1369 // handler, and be able to copy the response.
1370 // we use the original request here, so that any routes from 'next'
1371 // see the original request rather than the proxy cloned request.
1372 hrc := &handleResponseContext{
1373 handler: h,
1374 response: res,
1375 start: start,
1376 logger: logger,
1377 upstreamAddr: di.Upstream.String(),
1378 }
1379 ctx := origReq.Context()
1380 ctx = context.WithValue(ctx, proxyHandleResponseContextCtxKey, hrc)
1381
1382 // pass the request through the response handler routes
1383 routeErr := rh.Routes.Compile(next).ServeHTTP(rw, origReq.WithContext(ctx))
1384
1385 // close the response body afterwards, since we don't need it anymore;
1386 // either a route had 'copy_response' which already consumed the body,
1387 // or some other terminal handler ran which doesn't need the response
1388 // body after that point (e.g. 'file_server' for X-Accel-Redirect flow),
1389 // or we fell through to subsequent handlers past this proxy
1390 // (e.g. forward auth's 2xx response flow).
1391 if !hrc.isFinalized {
1392 res.Body.Close()
1393 }
1394
1395 // wrap any route error in terminalError so the outer loop knows
1396 // the response is committed and must not be retried
1397 if routeErr != nil {
1398 return terminalError{routeErr}
1399 }
1400
1401 // we're done handling the response, and we don't want to
1402 // fall through to the default finalize/copy behaviour
1403 return nil
1404 }
1405
1406 // copy the response body and headers back to the upstream client
1407 return h.finalizeResponse(rw, req, res, repl, start, logger, di.Upstream.String())
1408 }
1409
1410 // finalizeResponse prepares and copies the response.
1411 func (h *Handler) finalizeResponse(
1412 rw http.ResponseWriter,
1413 req *http.Request,
1414 res *http.Response,
1415 repl *caddy.Replacer,
1416 start time.Time,
1417 logger *zap.Logger,
1418 upstreamAddr string,
1419 ) error {
1420 responseWasIncremental := caddyhttp.IsIncremental(res.Header)
1421
1422 // Strip hop-by-hop headers from the upstream response.
1423 // For 101 Switching Protocols, save the Upgrade value
1424 // first (handleUpgradeResponse needs it for validation)
1425 // and restore it with a canonical Connection header.
1426 upgradeVal := res.Header.Get("Upgrade")
1427
1428 stripHopByHopHeaders(res.Header)
1429
1430 if res.StatusCode == http.StatusSwitchingProtocols && upgradeVal != "" {
1431 res.Header.Set("Upgrade", upgradeVal)
1432 res.Header.Set("Connection", "Upgrade")
1433 }
1434
1435 // deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
1436 if res.StatusCode == http.StatusSwitchingProtocols {
1437 h.handleUpgradeResponse(logger, rw, req, res, upstreamAddr)
1438 return nil
1439 }
1440
1441 // delete our Server header and use Via instead (see #6275)
1442 rwHeader := rw.Header()
1443 delete(rwHeader, "Server")
1444 var protoPrefix string
1445 if !strings.HasPrefix(strings.ToUpper(res.Proto), "HTTP/") {
1446 protoPrefix = res.Proto[:strings.Index(res.Proto, "/")+1]
1447 }
1448 rwHeader["Via"] = append(rwHeader["Via"], protoPrefix+strconv.Itoa(res.ProtoMajor)+"."+strconv.Itoa(res.ProtoMinor)+" Caddy")
1449
1450 // apply any response header operations
1451 if h.Headers != nil && h.Headers.Response != nil {
1452 if h.Headers.Response.Require == nil ||
1453 h.Headers.Response.Require.Match(res.StatusCode, res.Header) {
1454 h.Headers.Response.ApplyTo(res.Header, repl)
1455 }
1456 }
1457 if responseHasContent(req, res) && h.ResponseBuffers != 0 &&
1458 (responseWasIncremental || caddyhttp.IsIncremental(res.Header)) {
1459 res.Body.Close()
1460 return terminalError{h.refuseIncremental(rw, res.Header)}
1461 }
1462
1463 copyHeader(rw.Header(), res.Header)
1464
1465 // The "Trailer" header isn't included in the Transport's response,
1466 // at least for *http.Transport. Build it up from Trailer.
1467 announcedTrailers := len(res.Trailer)
1468 if announcedTrailers > 0 {
1469 trailerKeys := make([]string, 0, len(res.Trailer))
1470 for k := range res.Trailer {
1471 trailerKeys = append(trailerKeys, k)
1472 }
1473 rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
1474 }
1475
1476 rw.WriteHeader(res.StatusCode)
1477 if h.VerboseLogs {
1478 logger.Debug("wrote header")
1479 }
1480
1481 err := h.copyResponse(rw, res.Body, h.flushInterval(req, res, responseWasIncremental), logger)
1482 errClose := res.Body.Close() // close now, instead of defer, to populate res.Trailer
1483 if h.VerboseLogs || errClose != nil {
1484 if c := logger.Check(zapcore.DebugLevel, "closed response body from upstream"); c != nil {
1485 c.Write(zap.Error(errClose))
1486 }
1487 }
1488 if err != nil {
1489 // we're streaming the response and we've already written headers, so
1490 // there's nothing an error handler can do to recover at this point;
1491 // we'll just log the error and abort the stream here and panic just as
1492 // the standard lib's proxy to propagate the stream error.
1493 // see issue https://github.com/caddyserver/caddy/issues/5951
1494 lvl := zapcore.WarnLevel
1495 if isClientCanceledH3(err) {
1496 // the client canceled the request; expected and not actionable
1497 // see issue https://github.com/caddyserver/caddy/issues/5766
1498 lvl = zapcore.DebugLevel
1499 }
1500 if c := logger.Check(lvl, "aborting with incomplete response"); c != nil {
1501 c.Write(zap.Error(err))
1502 }
1503 // flush the buffer to ensure the client sees the partial response
1504 // see: https://github.com/caddyserver/caddy/issues/7845
1505 //nolint:bodyclose
1506 http.NewResponseController(rw).Flush()
1507 // no extra logging from stdlib
1508 panic(http.ErrAbortHandler)
1509 }
1510
1511 if len(res.Trailer) > 0 {
1512 // Force chunking if we saw a response trailer.
1513 // This prevents net/http from calculating the length for short
1514 // bodies and adding a Content-Length.
1515 //nolint:bodyclose
1516 http.NewResponseController(rw).Flush()
1517 }
1518
1519 // total duration spent proxying, including writing response body
1520 repl.Set("http.reverse_proxy.upstream.duration", time.Since(start))
1521 repl.Set("http.reverse_proxy.upstream.duration_ms", time.Since(start).Seconds()*1e3)
1522
1523 if len(res.Trailer) == announcedTrailers {
1524 copyHeader(rw.Header(), res.Trailer)
1525 return nil
1526 }
1527
1528 for k, vv := range res.Trailer {
1529 k = http.TrailerPrefix + k
1530 for _, v := range vv {
1531 rw.Header().Add(k, v)
1532 }
1533 }
1534
1535 if h.VerboseLogs {
1536 logger.Debug("response finalized")
1537 }
1538
1539 return nil
1540 }
1541
1542 // isClientCanceledH3 returns true if err is an HTTP/3 client canceling
1543 // its request (H3_REQUEST_CANCELLED) while the response was being written.
1544 // The same error read from an HTTP/3 backend is the backend's doing.
1545 func isClientCanceledH3(err error) bool {
1546 if !errors.Is(err, errWritingDownstream) {
1547 return false
1548 }
1549 h3Err, ok := errors.AsType[*http3.Error](err)
1550 return ok && h3Err.Remote && h3Err.ErrorCode == http3.ErrCodeRequestCanceled
1551 }
1552
1553 // tryAgain takes the time that the handler was initially invoked,
1554 // the amount of retries already performed, as well as any error
1555 // currently obtained, and the request being tried, and returns
1556 // true if another attempt should be made at proxying the request.
1557 // If true is returned, it has already blocked long enough before
1558 // the next retry (i.e. no more sleeping is needed). If false is
1559 // returned, the handler should stop trying to proxy the request.
1560 func (lb LoadBalancing) tryAgain(ctx caddy.Context, start time.Time, retries int, proxyErr error, req *http.Request, logger *zap.Logger) bool {
1561 // no retries are configured
1562 if lb.TryDuration == 0 && lb.Retries == 0 {
1563 return false
1564 }
1565
1566 // if we've tried long enough, break
1567 if lb.TryDuration > 0 && time.Since(start) >= time.Duration(lb.TryDuration) {
1568 return false
1569 }
1570
1571 // if we've reached the retry limit, break
1572 if lb.Retries > 0 && retries >= lb.Retries {
1573 return false
1574 }
1575
1576 // if the error occurred while dialing (i.e. a connection
1577 // could not even be established to the upstream), then it
1578 // should be safe to retry, since without a connection, no
1579 // HTTP request can be transmitted; but if the error is not
1580 // specifically a dialer error, we need to be careful; the
1581 // dial error may be wrapped, e.g. net/http wraps it in a
1582 // *net.OpError ("proxyconnect") when a forward proxy is used
1583 if proxyErr != nil {
1584 var dialErr DialError
1585 isDialError := errors.As(proxyErr, &dialErr)
1586 _, isRetryableResponse := proxyErr.(retryableResponseError)
1587 herr, isHandlerError := proxyErr.(caddyhttp.HandlerError)
1588
1589 // if the error occurred after a connection was established,
1590 // we have to assume the upstream received the request, and
1591 // retries need to be carefully decided, because some requests
1592 // are not idempotent; retryableResponseError is excluded here
1593 // because its retry decision was already made in reverseProxy()
1594 // when the response matchers were evaluated
1595 if !isDialError && !isRetryableResponse && (!isHandlerError || !errors.Is(herr, errNoUpstream)) {
1596 if lb.RetryMatch == nil && req.Method != "GET" {
1597 // by default, don't retry requests if they aren't GET
1598 return false
1599 }
1600
1601 // set transport error flag so CEL expressions can use
1602 // {rp.is_transport_error} to decide whether to retry
1603 repl, _ := req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
1604 if repl != nil {
1605 repl.Set("http.reverse_proxy.is_transport_error", true)
1606 defer repl.Delete("http.reverse_proxy.is_transport_error")
1607 }
1608
1609 match, err := lb.RetryMatch.AnyMatchWithError(req)
1610 if err != nil {
1611 logger.Error("error matching request for retry", zap.Error(err))
1612 return false
1613 }
1614 if !match {
1615 return false
1616 }
1617 }
1618 }
1619
1620 // fast path; if the interval is zero, we don't need to wait
1621 if lb.TryInterval == 0 {
1622 return true
1623 }
1624
1625 // otherwise, wait and try the next available host
1626 timer := time.NewTimer(time.Duration(lb.TryInterval))
1627 select {
1628 case <-timer.C:
1629 return true
1630 case <-ctx.Done():
1631 if !timer.Stop() {
1632 // if the timer has been stopped then read from the channel
1633 <-timer.C
1634 }
1635 return false
1636 }
1637 }
1638
1639 // newTracedTransport wraps rt so that round trips are recorded as
1640 // OpenTelemetry client spans. The tracer provider is taken from the span
1641 // in the request context (set by the tracing handler), so the wrapper does
1642 // not depend on any global tracer provider.
1643 func newTracedTransport(rt http.RoundTripper) http.RoundTripper {
1644 return otelhttp.NewTransport(rt,
1645 otelhttp.WithPropagators(autoprop.NewTextMapPropagator()),
1646 )
1647 }
1648
1649 // roundTrip sends req to the upstream. If req carries a valid span context,
1650 // the round trip is recorded as an OpenTelemetry client span and that span's
1651 // context is propagated to the upstream.
1652 func (h *Handler) roundTrip(req *http.Request) (*http.Response, error) {
1653 if h.tracedTransport == nil || !oteltrace.SpanContextFromContext(req.Context()).IsValid() {
1654 return h.Transport.RoundTrip(req)
1655 }
1656 // the traced transport clones req, so set the scheme beforehand
1657 // to keep it visible to the span attributes and to req itself
1658 if ss, ok := h.Transport.(interface{ SetScheme(*http.Request) }); ok {
1659 ss.SetScheme(req)
1660 }
1661 return h.tracedTransport.RoundTrip(req)
1662 }
1663
1664 // directRequest modifies only req.URL so that it points to the upstream
1665 // in the given DialInfo. It must modify ONLY the request URL.
1666 func (h *Handler) directRequest(req *http.Request, di DialInfo) {
1667 // we need a host, so set the upstream's host address
1668 reqHost := di.Address
1669
1670 // if the port equates to the scheme, strip the port because
1671 // it's weird to make a request like http://example.com:80/.
1672 if (req.URL.Scheme == "http" && di.Port == "80") ||
1673 (req.URL.Scheme == "https" && di.Port == "443") {
1674 reqHost = di.Host
1675 }
1676
1677 // add client address to the host to let transport differentiate requests from different clients
1678 if ppt, ok := h.Transport.(ProxyProtocolTransport); ok && ppt.ProxyProtocolEnabled() {
1679 if proxyProtocolInfo, ok := caddyhttp.GetVar(req.Context(), proxyProtocolInfoVarKey).(ProxyProtocolInfo); ok {
1680 // encode the request so it plays well with h2 transport, it's unnecessary for h1 but anyway
1681 // The issue is that h2 transport will use the address to determine if new connections are needed
1682 // to roundtrip requests but the without escaping, new connections are constantly created and closed until
1683 // file descriptors are exhausted.
1684 // see: https://github.com/caddyserver/caddy/issues/7529
1685 reqHost = url.QueryEscape(proxyProtocolInfo.AddrPort.String() + "->" + reqHost)
1686 }
1687 }
1688
1689 req.URL.Host = reqHost
1690 }
1691
1692 func (h Handler) provisionUpstream(upstream *Upstream, dynamic bool) {
1693 // create or get the host representation for this upstream;
1694 // dynamic upstreams are tracked in a separate map with last-seen
1695 // timestamps so their health state persists across requests without
1696 // being reference-counted (and thus discarded between requests).
1697 if dynamic {
1698 upstream.fillDynamicHost()
1699 } else {
1700 upstream.fillHost()
1701 }
1702
1703 // give it the circuit breaker, if any
1704 upstream.cb = h.CB
1705
1706 // if the passive health checker has a non-zero UnhealthyRequestCount
1707 // but the upstream has no MaxRequests set (they are the same thing,
1708 // but the passive health checker is a default value for upstreams
1709 // without MaxRequests), copy the value into this upstream, since the
1710 // value in the upstream (MaxRequests) is what is used during
1711 // availability checks
1712 if h.HealthChecks != nil &&
1713 h.HealthChecks.Passive != nil &&
1714 h.HealthChecks.Passive.UnhealthyRequestCount > 0 &&
1715 upstream.MaxRequests == 0 {
1716 upstream.MaxRequests = h.HealthChecks.Passive.UnhealthyRequestCount
1717 }
1718
1719 // upstreams need independent access to the passive
1720 // health check policy because passive health checks
1721 // run without access to h.
1722 if h.HealthChecks != nil {
1723 upstream.healthCheckPolicy = h.HealthChecks.Passive
1724 }
1725 }
1726
1727 // bufferedBody reads originalBody into a buffer with maximum size of limit (-1 for unlimited),
1728 // then returns a reader for the buffer along with how many bytes were buffered. Always close
1729 // the return value when done with it, just like if it was the original body! If limit is 0
1730 // (which it shouldn't be), this function returns its input; i.e. is a no-op, for safety.
1731 // Otherwise, it returns bodyReadCloser, the original body will be closed and body will be nil
1732 // if it's explicitly configured to buffer all or EOF is reached when reading.
1733 // If reading fails, the body is returned as partially buffered, so the read error
1734 // is not hidden from the caller.
1735 func (h Handler) bufferedBody(originalBody io.ReadCloser, limit int64) (io.ReadCloser, int64) {
1736 if limit == 0 {
1737 return originalBody, 0
1738 }
1739 var written int64
1740 var err error
1741 buf := bufPool.Get().(*bytes.Buffer)
1742 buf.Reset()
1743 if limit > 0 {
1744 written, err = io.CopyN(buf, originalBody, limit)
1745 } else {
1746 written, err = io.Copy(buf, originalBody)
1747 }
1748 if (err != nil && err != io.EOF) || written == limit {
1749 return bodyReadCloser{
1750 Reader: io.MultiReader(buf, originalBody),
1751 buf: buf,
1752 body: originalBody,
1753 }, written
1754 }
1755 originalBody.Close() // no point in keeping it open
1756 return bodyReadCloser{
1757 Reader: buf,
1758 buf: buf,
1759 }, written
1760 }
1761
1762 // requestBodyWithTrailers publishes a snapshot of the incoming trailers at EOF.
1763 // Close only closes the underlying body; it must not read or publish trailers.
1764 type requestBodyWithTrailers struct {
1765 io.ReadCloser
1766 original *http.Request
1767 trailer http.Header
1768 }
1769
1770 func (b *requestBodyWithTrailers) Read(p []byte) (int, error) {
1771 n, err := b.ReadCloser.Read(p)
1772 if err == io.EOF && b.original != nil {
1773 clear(b.trailer)
1774 for k, vv := range b.original.Trailer {
1775 b.trailer[k] = slices.Clone(vv)
1776 }
1777 b.original = nil // repeated EOF reads must not recopy or append values
1778 }
1779 return n, err
1780 }
1781
1782 // cloneRequest makes a semi-deep clone of origReq.
1783 //
1784 // Most of this code is borrowed from the Go stdlib reverse proxy,
1785 // but we make a shallow-ish clone the request (deep clone only
1786 // the headers and URL) so we can avoid manipulating the original
1787 // request when using it to proxy upstream. This prevents request
1788 // corruption and data races.
1789 func cloneRequest(origReq *http.Request) *http.Request {
1790 req := new(http.Request)
1791 *req = *origReq
1792 if origReq.URL != nil {
1793 newURL := new(url.URL)
1794 *newURL = *origReq.URL
1795 if origReq.URL.User != nil {
1796 newURL.User = new(url.Userinfo)
1797 *newURL.User = *origReq.URL.User
1798 }
1799 // sanitize the request URL; we expect it to not contain the
1800 // scheme and host since those should be determined by r.TLS
1801 // and r.Host respectively, but some clients may include it
1802 // in the request-line, which is technically valid in HTTP,
1803 // but breaks reverseproxy behaviour, overriding how the
1804 // dialer will behave. See #4237 for context.
1805 newURL.Scheme = ""
1806 newURL.Host = ""
1807 req.URL = newURL
1808 }
1809 if origReq.Header != nil {
1810 req.Header = origReq.Header.Clone()
1811 }
1812 if origReq.Trailer != nil {
1813 req.Trailer = origReq.Trailer.Clone()
1814 }
1815 return req
1816 }
1817
1818 func copyHeader(dst, src http.Header) {
1819 for k, vv := range src {
1820 for _, v := range vv {
1821 dst.Add(k, v)
1822 }
1823 }
1824 }
1825
1826 // recordUpstreamRoundTrip publishes latency placeholders, records circuit
1827 // breaker metrics, and applies passive health-check strikes for one
1828 // completed upstream attempt. Used by both the HTTP round-trip path and
1829 // the WebTransport hijack path.
1830 func (h *Handler) recordUpstreamRoundTrip(di DialInfo, repl *caddy.Replacer, status int, duration time.Duration) {
1831 repl.Set("http.reverse_proxy.upstream.latency", duration)
1832 repl.Set("http.reverse_proxy.upstream.latency_ms", duration.Seconds()*1e3) // multiply seconds to preserve decimal (see #4666)
1833
1834 if di.Upstream != nil && di.Upstream.cb != nil {
1835 di.Upstream.cb.RecordMetric(status, duration)
1836 }
1837
1838 if h.HealthChecks != nil && h.HealthChecks.Passive != nil {
1839 for _, badStatus := range h.HealthChecks.Passive.UnhealthyStatus {
1840 if caddyhttp.StatusCodeMatches(status, badStatus) {
1841 h.countFailure(di.Upstream)
1842 }
1843 }
1844 if h.HealthChecks.Passive.UnhealthyLatency > 0 &&
1845 duration >= time.Duration(h.HealthChecks.Passive.UnhealthyLatency) {
1846 h.countFailure(di.Upstream)
1847 }
1848 }
1849 }
1850
1851 // allHeaderValues gets all values for a given header field,
1852 // joined by a comma and space if more than one is set. If the
1853 // header field is nil, then the omit is true, meaning some
1854 // earlier logic in the server wanted to prevent this header from
1855 // getting written at all. If the header is empty, then ok is
1856 // false. Callers should still check that the value is not empty
1857 // (the header field may be set but have an empty value).
1858 func allHeaderValues(h http.Header, field string) (value string, ok bool, omit bool) {
1859 values, ok := h[http.CanonicalHeaderKey(field)]
1860 if ok && values == nil {
1861 return "", true, true
1862 }
1863 if len(values) == 0 {
1864 return "", false, false
1865 }
1866 return strings.Join(values, ", "), true, false
1867 }
1868
1869 // lastHeaderValue gets the last value for a given header field
1870 // if more than one is set. If the header field is nil, then
1871 // the omit is true, meaning some earlier logic in the server
1872 // wanted to prevent this header from getting written at all.
1873 // If the header is empty, then ok is false. Callers should
1874 // still check that the value is not empty (the header field
1875 // may be set but have an empty value).
1876 func lastHeaderValue(h http.Header, field string) (value string, ok bool, omit bool) {
1877 values, ok := h[http.CanonicalHeaderKey(field)]
1878 if ok && values == nil {
1879 return "", true, true
1880 }
1881 if len(values) == 0 {
1882 return "", false, false
1883 }
1884 return values[len(values)-1], true, false
1885 }
1886
1887 func upgradeType(h http.Header) string {
1888 if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
1889 return ""
1890 }
1891 if v := h["Upgrade"]; len(v) > 0 {
1892 return strings.ToLower(v[0])
1893 }
1894 return ""
1895 }
1896
1897 // removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h.
1898 // See RFC 7230, section 6.1
1899 func removeConnectionHeaders(h http.Header) {
1900 for _, f := range h["Connection"] {
1901 for sf := range strings.SplitSeq(f, ",") {
1902 if sf = textproto.TrimString(sf); sf != "" {
1903 h.Del(sf)
1904 }
1905 }
1906 }
1907 }
1908
1909 // stripHopByHopHeaders removes hop-by-hop headers from h, including any
1910 // headers nominated by the Connection header.
1911 // See RFC 7230, section 6.1.
1912 func stripHopByHopHeaders(h http.Header) {
1913 removeConnectionHeaders(h)
1914 for _, hop := range hopHeaders {
1915 h.Del(hop)
1916 }
1917 }
1918
1919 // statusError returns an error value that has a status code.
1920 func statusError(err error) error {
1921 // if a response-based retry was exhausted, use the actual upstream
1922 // status code instead of a generic 502
1923 if rre, ok := err.(retryableResponseError); ok {
1924 return caddyhttp.Error(rre.statusCode, err)
1925 }
1926
1927 // errors proxying usually mean there is a problem with the upstream(s)
1928 statusCode := http.StatusBadGateway
1929
1930 // timeout errors have a standard status code (see issue #4823)
1931 if err, ok := err.(net.Error); ok && err.Timeout() {
1932 statusCode = http.StatusGatewayTimeout
1933 }
1934
1935 // if the client canceled the request (usually this means they closed
1936 // the connection, so they won't see any response), we can report it
1937 // as a client error (4xx) and not a server error (5xx); unfortunately
1938 // the Go standard library, at least at time of writing in late 2020,
1939 // obnoxiously wraps the exported, standard context.Canceled error with
1940 // an unexported garbage value that we have to do a substring check for:
1941 // https://github.com/golang/go/blob/6965b01ea248cabb70c3749fd218b36089a21efb/src/net/net.go#L416-L430
1942 if errors.Is(err, context.Canceled) || strings.Contains(err.Error(), "operation was canceled") {
1943 // regrettably, there is no standard error code for "client closed connection", but
1944 // for historical reasons we can use a code that a lot of people are already using;
1945 // using 5xx is problematic for users; see #3748
1946 statusCode = 499
1947 }
1948 return caddyhttp.Error(statusCode, err)
1949 }
1950
1951 // LoadBalancing has parameters related to load balancing.
1952 type LoadBalancing struct {
1953 // A selection policy is how to choose an available backend.
1954 // The default policy is random selection.
1955 SelectionPolicyRaw json.RawMessage `json:"selection_policy,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"`
1956
1957 // How many times to retry selecting available backends for each
1958 // request if the next available host is down. If try_duration is
1959 // also configured, then retries may stop early if the duration
1960 // is reached. By default, retries are disabled (zero).
1961 Retries int `json:"retries,omitempty"`
1962
1963 // How long to try selecting available backends for each request
1964 // if the next available host is down. Clients will wait for up
1965 // to this long while the load balancer tries to find an available
1966 // upstream host. If retries is also configured, tries may stop
1967 // early if the maximum retries is reached. By default, retries
1968 // are disabled (zero duration).
1969 TryDuration caddy.Duration `json:"try_duration,omitempty"`
1970
1971 // How long to wait between selecting the next host from the pool.
1972 // Default is 250ms if try_duration is enabled, otherwise zero. Only
1973 // relevant when a request to an upstream host fails. Be aware that
1974 // setting this to 0 with a non-zero try_duration can cause the CPU
1975 // to spin if all backends are down and latency is very low.
1976 TryInterval caddy.Duration `json:"try_interval,omitempty"`
1977
1978 // A list of matcher sets that controls retry behavior. Matcher sets
1979 // without expression matchers (e.g. method, path) restrict which
1980 // requests are retried on transport errors - if unspecified, only
1981 // GET requests will be retried. Matcher sets with CEL expression
1982 // matchers are evaluated against upstream responses and can
1983 // reference {rp.status_code}, {rp.header.*}, and
1984 // {rp.is_transport_error}. Dial errors are always retried
1985 // regardless of this setting. Retries use the next available
1986 // upstream per the load balancing policy
1987 RetryMatchRaw caddyhttp.RawMatcherSets `json:"retry_match,omitempty" caddy:"namespace=http.matchers"`
1988
1989 SelectionPolicy Selector `json:"-"`
1990 RetryMatch caddyhttp.MatcherSets `json:"-"`
1991 }
1992
1993 // Selector selects an available upstream from the pool.
1994 type Selector interface {
1995 Select(UpstreamPool, *http.Request, http.ResponseWriter) *Upstream
1996 }
1997
1998 // UpstreamSource gets the list of upstreams that can be used when
1999 // proxying a request. Returned upstreams will be load balanced and
2000 // health-checked. This should be a very fast function -- instant
2001 // if possible -- and the return value must be as stable as possible.
2002 // In other words, the list of upstreams should ideally not change much
2003 // across successive calls. If the list of upstreams changes or the
2004 // ordering is not stable, load balancing will suffer. This function
2005 // may be called during each retry, multiple times per request, and as
2006 // such, needs to be instantaneous. The returned slice will not be
2007 // modified.
2008 //
2009 // For upstream sources that cache results, implement the
2010 // [CachingUpstreamSource] interface for optimal performance.
2011 type UpstreamSource interface {
2012 GetUpstreams(*http.Request) ([]*Upstream, error)
2013 }
2014
2015 // CachingUpstreamSource is an upstream source that caches its upstreams.
2016 // The relevant cache entry can be cleared/reset for a given request during
2017 // retries if a request fails. This can help ensure that failing backends
2018 // are not retried.
2019 //
2020 // EXPERIMENTAL: Subject to change.
2021 type CachingUpstreamSource interface {
2022 UpstreamSource
2023
2024 // ResetCache clears any cache entry related to the given request.
2025 // The next time GetUpstreams is called, it should have new upstream
2026 // information for the given request.
2027 ResetCache(*http.Request) error
2028 }
2029
2030 // Hop-by-hop headers. These are removed when sent to the backend.
2031 // As of RFC 7230, hop-by-hop headers are required to appear in the
2032 // Connection header field. These are the headers defined by the
2033 // obsoleted RFC 2616 (section 13.5.1) and are used for backward
2034 // compatibility.
2035 var hopHeaders = []string{
2036 "Alt-Svc",
2037 "Connection",
2038 "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
2039 "Keep-Alive",
2040 "Proxy-Authenticate",
2041 "Proxy-Authorization",
2042 "Te", // canonicalized version of "TE"
2043 "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
2044 "Transfer-Encoding",
2045 "Upgrade",
2046 }
2047
2048 // DialError is an error that specifically occurs
2049 // in a call to Dial or DialContext.
2050 type DialError struct{ error }
2051
2052 // NewDialError wraps err as a DialError for transports outside this package.
2053 func NewDialError(err error) DialError {
2054 return DialError{err}
2055 }
2056
2057 // TLSTransport is implemented by transports
2058 // that are capable of using TLS.
2059 type TLSTransport interface {
2060 // TLSEnabled returns true if the transport
2061 // has TLS enabled, false otherwise.
2062 TLSEnabled() bool
2063
2064 // EnableTLS enables TLS within the transport
2065 // if it is not already, using the provided
2066 // value as a basis for the TLS config.
2067 EnableTLS(base *TLSConfig) error
2068 }
2069
2070 // H2CTransport is implemented by transports
2071 // that are capable of using h2c.
2072 type H2CTransport interface {
2073 EnableH2C() error
2074 }
2075
2076 // ProxyProtocolTransport is implemented by transports
2077 // that are capable of using proxy protocol.
2078 type ProxyProtocolTransport interface {
2079 ProxyProtocolEnabled() bool
2080 }
2081
2082 // HealthCheckSchemeOverriderTransport is implemented by transports
2083 // that can override the scheme used for health checks.
2084 type HealthCheckSchemeOverriderTransport interface {
2085 OverrideHealthCheckScheme(base *url.URL, port string)
2086 }
2087
2088 // proxyErrorIncrementalRefused is the Proxy-Status error type (RFC 9209) for
2089 // a message we refuse to forward incrementally, as registered by RFC 10036
2090 // section 5.
2091 const proxyErrorIncrementalRefused = "incremental_refused"
2092
2093 // errIncrementalRefused is the cause reported when a message asking for
2094 // incremental forwarding cannot be forwarded that way.
2095 var errIncrementalRefused = errors.New("refusing to forward the message incrementally")
2096
2097 // refuseIncremental reports that a message asking for incremental forwarding
2098 // cannot be forwarded that way without overriding configured buffering or the
2099 // transport's framing requirements. RFC 10036 section 3 requires an error
2100 // response when incremental forwarding is refused. Section 4.1 recommends this
2101 // status and Proxy-Status error type. Upstream carries the headers of the
2102 // response being refused when present. This preserves its valid existing
2103 // members.
2104 func (h *Handler) refuseIncremental(rw http.ResponseWriter, upstream http.Header) error {
2105 if value, ok := h.proxyStatus(upstream, proxyErrorIncrementalRefused); ok {
2106 rw.Header().Set("Proxy-Status", value)
2107 }
2108
2109 return caddyhttp.Error(http.StatusNotImplemented, errIncrementalRefused)
2110 }
2111
2112 // proxyStatus builds a Proxy-Status field value (RFC 9209) reporting proxyErr,
2113 // appending this proxy to the members upstream already reported so the whole
2114 // chain stays visible. It reports false if no name identifies this deployment,
2115 // since a software name identifies no intermediary and generating the field at
2116 // all is optional.
2117 func (h *Handler) proxyStatus(upstream http.Header, proxyErr string) (string, bool) {
2118 if h.ProxyStatusName == "" {
2119 return "", false
2120 }
2121
2122 // a malformed field from upstream is dropped rather than propagated
2123 list, err := httpsfv.UnmarshalList(upstream.Values("Proxy-Status"))
2124 if err != nil {
2125 list = httpsfv.List{}
2126 }
2127 for _, member := range list {
2128 item, ok := member.(httpsfv.Item)
2129 if !ok {
2130 list = httpsfv.List{}
2131 break
2132 }
2133 valid := false
2134 switch item.Value.(type) {
2135 case string, httpsfv.Token:
2136 valid = true
2137 }
2138 if !valid {
2139 list = httpsfv.List{}
2140 break
2141 }
2142 }
2143
2144 // the name is a token where it can be, as the examples in RFC 9209 are,
2145 // and a string where a token cannot hold it (a space, say)
2146 item := httpsfv.NewItem(httpsfv.Token(h.ProxyStatusName))
2147 item.Params.Add("error", httpsfv.Token(proxyErr))
2148 if _, err := httpsfv.Marshal(item); err != nil {
2149 item.Value = h.ProxyStatusName
2150 }
2151
2152 value, err := httpsfv.Marshal(append(list, item))
2153 if err != nil {
2154 return "", false
2155 }
2156
2157 return value, true
2158 }
2159
2160 // responseHasContent reports whether res can carry content for req. This uses
2161 // the response semantics as well as Body because custom transports are not
2162 // required to represent an empty body with http.NoBody.
2163 func responseHasContent(req *http.Request, res *http.Response) bool {
2164 if req.Method == http.MethodHead || res.Body == nil || res.Body == http.NoBody || res.ContentLength == 0 {
2165 return false
2166 }
2167 if req.Method == http.MethodConnect && res.StatusCode >= 200 && res.StatusCode < 300 {
2168 return false
2169 }
2170 if res.StatusCode >= 100 && res.StatusCode < 200 ||
2171 res.StatusCode == http.StatusNoContent || res.StatusCode == http.StatusResetContent ||
2172 res.StatusCode == http.StatusNotModified {
2173 return false
2174 }
2175 return true
2176 }
2177
2178 // requestHasContent reports whether r may carry content that matters for
2179 // incremental forwarding. HTTP/3 uses an unknown length for bodyless GET and
2180 // HEAD requests (see issue #6678), so their usual no-body semantics are used
2181 // rather than waiting for the request stream to end.
2182 func requestHasContent(r *http.Request) bool {
2183 if r.ContentLength > 0 {
2184 return true
2185 }
2186 if r.ContentLength == 0 {
2187 return false
2188 }
2189
2190 switch r.Method {
2191 case http.MethodGet, http.MethodHead, http.MethodOptions,
2192 http.MethodDelete, http.MethodTrace, http.MethodConnect:
2193 return false
2194 }
2195
2196 return true
2197 }
2198
2199 func normalizeIncrementalRequest(req *http.Request) {
2200 if caddyhttp.IsIncremental(req.Header) && !requestHasContent(req) {
2201 // HTTP/3 can represent a bodyless GET or HEAD with an unknown length.
2202 // Do not pass that sentinel to transports that require framing.
2203 req.ContentLength = 0
2204 req.Body = nil
2205 }
2206 }
2207
2208 // incrementalRequestConflicts reports whether honouring an incremental request
2209 // would override an explicit buffer or violate the transport's framing needs.
2210 func (h *Handler) incrementalRequestConflicts(req *http.Request) bool {
2211 if !requestHasContent(req) || !caddyhttp.IsIncremental(req.Header) {
2212 return false
2213 }
2214 needsLength := h.transportRequiresContentLength()
2215 if h.RequestBuffers != 0 {
2216 if !h.requestBuffersFromTransport || !needsLength {
2217 return true
2218 }
2219 }
2220 return req.ContentLength < 0 && needsLength
2221 }
2222
2223 // ContentLengthRequiredTransport is implemented by transports that cannot
2224 // forward a request body whose length they do not know, and so need it
2225 // buffered in full when the request does not carry a Content-Length.
2226 type ContentLengthRequiredTransport interface {
2227 // RequiresContentLength returns true if the transport needs the length of
2228 // a request body before it can forward it.
2229 RequiresContentLength() bool
2230 }
2231
2232 // transportRequiresContentLength reports whether the transport in use cannot
2233 // forward a request body of unknown length.
2234 func (h *Handler) transportRequiresContentLength() bool {
2235 clt, ok := h.Transport.(ContentLengthRequiredTransport)
2236
2237 return ok && clt.RequiresContentLength()
2238 }
2239
2240 // BufferedTransport is implemented by transports
2241 // that needs to buffer requests and/or responses.
2242 type BufferedTransport interface {
2243 // DefaultBufferSizes returns the default buffer sizes
2244 // for requests and responses, respectively if buffering isn't enabled.
2245 DefaultBufferSizes() (int64, int64)
2246 }
2247
2248 // RequestHeaderOpsTransport may be implemented by a transport to provide
2249 // header operations to apply to requests immediately before the RoundTrip.
2250 // For example, overriding the default Host when TLS is enabled.
2251 type RequestHeaderOpsTransport interface {
2252 // RequestHeaderOps allows a transport to provide header operations
2253 // to apply to the request. The transport is asked at provision time
2254 // to return a HeaderOps (or nil) that will be applied before
2255 // user-configured header ops.
2256 RequestHeaderOps() *headers.HeaderOps
2257 }
2258
2259 // responsePlaceholders are the placeholders that are only set once the
2260 // upstream round trip completes ({rp.status_code} is adapted to
2261 // {http.reverse_proxy.status_code}, and so on)
2262 var responsePlaceholders = []string{
2263 "http.reverse_proxy.status_code",
2264 "http.reverse_proxy.status_text",
2265 "http.reverse_proxy.upstream.latency",
2266 "http.reverse_proxy.upstream.latency_ms",
2267 }
2268
2269 // responseHeaderPlaceholderPrefix is the prefix of the response
2270 // header placeholders, {http.reverse_proxy.header.*}
2271 const responseHeaderPlaceholderPrefix = "http.reverse_proxy.header."
2272
2273 // matcherSetReferencesResponse reports whether a matcher set contains an
2274 // expression matcher that reads response data, or a placeholder whose name
2275 // is only known at evaluation time. Other matcher sets only test request or
2276 // upstream selection properties and should not be evaluated for
2277 // response-based retry decisions
2278 func matcherSetReferencesResponse(matcherSet caddyhttp.MatcherSet) bool {
2279 for _, m := range matcherSet {
2280 expr, ok := m.(*caddyhttp.MatchExpression)
2281 if !ok {
2282 continue
2283 }
2284 for _, name := range expr.Placeholders() {
2285 if name == "" ||
2286 slices.Contains(responsePlaceholders, name) ||
2287 strings.HasPrefix(name, responseHeaderPlaceholderPrefix) {
2288 return true
2289 }
2290 }
2291 }
2292 return false
2293 }
2294
2295 // terminalError signals that the proxy loop must stop and the wrapped
2296 // error must be propagated unchanged. It is emitted in any situation
2297 // where the handler has committed enough client-visible state that
2298 // retrying against another upstream would be unsafe — for example, a
2299 // handle_response route that ran after a successful round-trip, or a
2300 // WebTransport upgrade that already flushed 200 OK and hijacked the
2301 // stream. The inner error may be nil to signal terminal success.
2302 type terminalError struct{ error }
2303
2304 func (e terminalError) Unwrap() error { return e.error }
2305
2306 // retryableResponseError is returned when the upstream response matched
2307 // a retry_match entry, indicating the request should be retried with the
2308 // next upstream. It preserves the original status code so that if retries
2309 // are exhausted, the actual upstream status is reported instead of a
2310 // generic 502
2311 type retryableResponseError struct {
2312 error
2313 statusCode int
2314 }
2315
2316 // bodyReadCloser is a reader that, upon closing, will return
2317 // its buffer to the pool and close the underlying body reader.
2318 type bodyReadCloser struct {
2319 io.Reader
2320 buf *bytes.Buffer
2321 body io.ReadCloser
2322 }
2323
2324 func (brc bodyReadCloser) Close() error {
2325 // Inside this package this will be set to nil for fully-buffered
2326 // requests due to the possibility of retrial.
2327 if brc.buf != nil {
2328 bufPool.Put(brc.buf)
2329 }
2330 // For fully-buffered bodies, body is nil, so Close is a no-op.
2331 if brc.body != nil {
2332 return brc.body.Close()
2333 }
2334 return nil
2335 }
2336
2337 // StreamLogs controls logging for upgraded stream lifecycle events.
2338 type StreamLogs struct {
2339 // The minimum level at which stream lifecycle events are logged.
2340 // Supported values are debug, info, warn, and error. Default: debug.
2341 Level string `json:"level,omitempty"`
2342
2343 // Logger name for stream lifecycle logs. Default: "http.handlers.reverse_proxy.stream".
2344 // Special value "access" uses the access logger namespace and, if set,
2345 // respects the first value in access_logger_names/log_name for the request.
2346 LoggerName string `json:"logger_name,omitempty"`
2347
2348 // If true, suppresses the access log entry normally emitted when an
2349 // upgraded stream handshake completes and the request unwinds.
2350 SkipHandshake bool `json:"skip_handshake,omitempty"`
2351 }
2352
2353 // bufPool is used for buffering requests and responses.
2354 var bufPool = sync.Pool{
2355 New: func() any {
2356 return new(bytes.Buffer)
2357 },
2358 }
2359
2360 // handleResponseContext carries some contextual information about the
2361 // current proxy handling.
2362 type handleResponseContext struct {
2363 // handler is the active proxy handler instance, so that
2364 // routes like copy_response may inherit some config
2365 // options and have access to handler methods.
2366 handler *Handler
2367
2368 // response is the actual response received from the proxy
2369 // roundtrip, to potentially be copied if a copy_response
2370 // handler is in the handle_response routes.
2371 response *http.Response
2372
2373 // start is the time just before the proxy roundtrip was
2374 // performed, used for logging.
2375 start time.Time
2376
2377 // logger is the prepared logger which is used to write logs
2378 // with the request, duration, and selected upstream attached.
2379 logger *zap.Logger
2380
2381 // isFinalized is whether the response has been finalized,
2382 // i.e. copied and closed, to make sure that it doesn't
2383 // happen twice.
2384 isFinalized bool
2385
2386 // upstreamAddr is the selected upstream address for this request.
2387 upstreamAddr string
2388 }
2389
2390 // proxyHandleResponseContextCtxKey is the context key for the active proxy handler
2391 // so that handle_response routes can inherit some config options
2392 // from the proxy handler.
2393 const proxyHandleResponseContextCtxKey caddy.CtxKey = "reverse_proxy_handle_response_context"
2394
2395 // errNoUpstream occurs when there are no upstream available.
2396 var errNoUpstream = fmt.Errorf("no upstreams available")
2397
2398 const (
2399 defaultStreamLogLevel = zapcore.DebugLevel
2400 defaultStreamLoggerName = "http.handlers.reverse_proxy.stream"
2401 streamLoggerNameUseAccess = "access"
2402 defaultAccessLoggerBase = "http.log.access"
2403 )
2404
2405 // Interface guards
2406 var (
2407 _ caddy.Provisioner = (*Handler)(nil)
2408 _ caddy.CleanerUpper = (*Handler)(nil)
2409 _ caddyhttp.MiddlewareHandler = (*Handler)(nil)
2410 )