Debian Codegraph @

modules/caddyhttp/server.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyhttp
16
17 import (
18 "context"
19 "crypto/tls"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io"
24 "net"
25 "net/http"
26 "net/netip"
27 "net/url"
28 "runtime"
29 "slices"
30 "strings"
31 "sync/atomic"
32 "time"
33
34 "github.com/caddyserver/certmagic"
35 "github.com/quic-go/quic-go"
36 "github.com/quic-go/quic-go/http3"
37 h3qlog "github.com/quic-go/quic-go/http3/qlog"
38 "go.uber.org/zap"
39 "go.uber.org/zap/zapcore"
40
41 "github.com/caddyserver/caddy/v2"
42 "github.com/caddyserver/caddy/v2/modules/caddyevents"
43 "github.com/caddyserver/caddy/v2/modules/caddytls"
44 )
45
46 // Server describes an HTTP server.
47 type Server struct {
48 // Socket addresses to which to bind listeners. Accepts
49 // [network addresses](/docs/conventions#network-addresses)
50 // that may include port ranges. Listener addresses must
51 // be unique; they cannot be repeated across all defined
52 // servers.
53 Listen []string `json:"listen,omitempty"`
54
55 // A list of listener wrapper modules, which can modify the behavior
56 // of the base listener. They are applied in the given order.
57 ListenerWrappersRaw []json.RawMessage `json:"listener_wrappers,omitempty" caddy:"namespace=caddy.listeners inline_key=wrapper"`
58
59 // A list of packet conn wrapper modules, which can modify the behavior
60 // of the base packet conn. They are applied in the given order.
61 PacketConnWrappersRaw []json.RawMessage `json:"packet_conn_wrappers,omitempty" caddy:"namespace=caddy.packetconns inline_key=wrapper"`
62
63 // How long to allow a read from a client's upload. Setting this
64 // to a short, non-zero value can mitigate slowloris attacks, but
65 // may also affect legitimately slow clients.
66 ReadTimeout caddy.Duration `json:"read_timeout,omitempty"`
67
68 // ReadHeaderTimeout is like ReadTimeout but for request headers.
69 // Default is 1 minute.
70 ReadHeaderTimeout caddy.Duration `json:"read_header_timeout,omitempty"`
71
72 // WriteTimeout is how long to allow a write to a client. Note
73 // that setting this to a small value when serving large files
74 // may negatively affect legitimately slow clients.
75 WriteTimeout caddy.Duration `json:"write_timeout,omitempty"`
76
77 // IdleTimeout is the maximum time to wait for the next request
78 // when keep-alives are enabled. If zero, a default timeout of
79 // 5m is applied to help avoid resource exhaustion.
80 IdleTimeout caddy.Duration `json:"idle_timeout,omitempty"`
81
82 // KeepAliveInterval is the interval at which TCP keepalive packets
83 // are sent to keep the connection alive at the TCP layer when no other
84 // data is being transmitted.
85 // If zero, the default is 15s.
86 // If negative, keepalive packets are not sent and other keepalive parameters
87 // are ignored.
88 KeepAliveInterval caddy.Duration `json:"keepalive_interval,omitempty"`
89
90 // KeepAliveIdle is the time that the connection must be idle before
91 // the first TCP keep-alive probe is sent when no other data is being
92 // transmitted.
93 // If zero, the default is 15s.
94 // If negative, underlying socket value is unchanged.
95 KeepAliveIdle caddy.Duration `json:"keepalive_idle,omitempty"`
96
97 // KeepAliveCount is the maximum number of TCP keep-alive probes that
98 // should be sent before dropping a connection.
99 // If zero, the default is 9.
100 // If negative, underlying socket value is unchanged.
101 KeepAliveCount int `json:"keepalive_count,omitempty"`
102
103 // MaxHeaderBytes is the maximum size to parse from a client's
104 // HTTP request headers.
105 MaxHeaderBytes int `json:"max_header_bytes,omitempty"`
106
107 // Enable full-duplex communication for HTTP/1 requests.
108 // Only has an effect if Caddy was built with Go 1.21 or later.
109 //
110 // For HTTP/1 requests, the Go HTTP server by default consumes any
111 // unread portion of the request body before beginning to write the
112 // response, preventing handlers from concurrently reading from the
113 // request and writing the response. Enabling this option disables
114 // this behavior and permits handlers to continue to read from the
115 // request while concurrently writing the response.
116 //
117 // For HTTP/2 requests, the Go HTTP server always permits concurrent
118 // reads and responses, so this option has no effect.
119 //
120 // Test thoroughly with your HTTP clients, as some older clients may
121 // not support full-duplex HTTP/1 which can cause them to deadlock.
122 // See https://github.com/golang/go/issues/57786 for more info.
123 //
124 // TODO: This is an EXPERIMENTAL feature. Subject to change or removal.
125 EnableFullDuplex bool `json:"enable_full_duplex,omitempty"`
126
127 // Routes describes how this server will handle requests.
128 // Routes are executed sequentially. First a route's matchers
129 // are evaluated, then its grouping. If it matches and has
130 // not been mutually-excluded by its grouping, then its
131 // handlers are executed sequentially. The sequence of invoked
132 // handlers comprises a compiled middleware chain that flows
133 // from each matching route and its handlers to the next.
134 //
135 // By default, all unrouted requests receive a 200 OK response
136 // to indicate the server is working.
137 Routes RouteList `json:"routes,omitempty"`
138
139 // Errors is how this server will handle errors returned from any
140 // of the handlers in the primary routes. If the primary handler
141 // chain returns an error, the error along with its recommended
142 // status code are bubbled back up to the HTTP server which
143 // executes a separate error route, specified using this property.
144 // The error routes work exactly like the normal routes.
145 Errors *HTTPErrorConfig `json:"errors,omitempty"`
146
147 // NamedRoutes describes a mapping of reusable routes that can be
148 // invoked by their name. This can be used to optimize memory usage
149 // when the same route is needed for many subroutes, by having
150 // the handlers and matchers be only provisioned once, but used from
151 // many places. These routes are not executed unless they are invoked
152 // from another route.
153 //
154 // EXPERIMENTAL: Subject to change or removal.
155 NamedRoutes map[string]*Route `json:"named_routes,omitempty"`
156
157 // How to handle TLS connections. At least one policy is
158 // required to enable HTTPS on this server if automatic
159 // HTTPS is disabled or does not apply.
160 TLSConnPolicies caddytls.ConnectionPolicies `json:"tls_connection_policies,omitempty"`
161
162 // AutoHTTPS configures or disables automatic HTTPS within this server.
163 // HTTPS is enabled automatically and by default when qualifying names
164 // are present in a Host matcher and/or when the server is listening
165 // only on the HTTPS port.
166 AutoHTTPS *AutoHTTPSConfig `json:"automatic_https,omitempty"`
167
168 // If true, will require that a request's Host header match
169 // the value of the ServerName sent by the client's TLS
170 // ClientHello; often a necessary safeguard when using TLS
171 // client authentication.
172 StrictSNIHost *bool `json:"strict_sni_host,omitempty"`
173
174 // A module which provides a source of IP ranges, from which
175 // requests should be trusted. By default, no proxies are
176 // trusted.
177 //
178 // On its own, this configuration will not do anything,
179 // but it can be used as a default set of ranges for
180 // handlers or matchers in routes to pick up, instead
181 // of needing to configure each of them. See the
182 // `reverse_proxy` handler for example, which uses this
183 // to trust sensitive incoming `X-Forwarded-*` headers.
184 TrustedProxiesRaw json.RawMessage `json:"trusted_proxies,omitempty" caddy:"namespace=http.ip_sources inline_key=source"`
185
186 // The headers from which the client IP address could be
187 // read from. These will be considered in order, with the
188 // first good value being used as the client IP.
189 // By default, only `X-Forwarded-For` is considered.
190 //
191 // This depends on `trusted_proxies` being configured and
192 // the request being validated as coming from a trusted
193 // proxy, otherwise the client IP will be set to the direct
194 // remote IP address.
195 ClientIPHeaders []string `json:"client_ip_headers,omitempty"`
196
197 // If greater than zero, enables strict ClientIPHeaders
198 // (default X-Forwarded-For) parsing. If enabled, the
199 // ClientIPHeaders will be parsed from right to left, and
200 // the first value that is both valid and doesn't match the
201 // trusted proxy list will be used as client IP. If zero,
202 // the ClientIPHeaders will be parsed from left to right,
203 // and the first value that is a valid IP address will be
204 // used as client IP.
205 //
206 // This depends on `trusted_proxies` being configured.
207 // This option is disabled by default.
208 TrustedProxiesStrict int `json:"trusted_proxies_strict,omitempty"`
209
210 // If greater than zero, enables trusting socket connections
211 // (e.g. Unix domain sockets) as coming from a trusted
212 // proxy.
213 //
214 // This option is disabled by default.
215 TrustedProxiesUnix bool `json:"trusted_proxies_unix,omitempty"`
216
217 // Enables access logging and configures how access logs are handled
218 // in this server. To minimally enable access logs, simply set this
219 // to a non-null, empty struct.
220 Logs *ServerLogConfig `json:"logs,omitempty"`
221
222 // Protocols specifies which HTTP protocols to enable.
223 // Supported values are:
224 //
225 // - `h1` (HTTP/1.1)
226 // - `h2` (HTTP/2)
227 // - `h2c` (cleartext HTTP/2)
228 // - `h3` (HTTP/3)
229 //
230 // If enabling `h2` or `h2c`, `h1` must also be enabled;
231 // this is due to current limitations in the Go standard
232 // library.
233 //
234 // HTTP/2 operates only over TLS (HTTPS). HTTP/3 opens
235 // a UDP socket to serve QUIC connections.
236 //
237 // H2C operates over plain TCP if the client supports it;
238 // however, because this is not implemented by the Go
239 // standard library, other server options are not compatible
240 // and will not be applied to H2C requests. Do not enable this
241 // only to achieve maximum client compatibility. In practice,
242 // very few clients implement H2C, and even fewer require it.
243 // Enabling H2C can be useful for serving/proxying gRPC
244 // if encryption is not possible or desired.
245 //
246 // We recommend for most users to simply let Caddy use the
247 // default settings.
248 //
249 // Default: `[h1 h2 h3]`
250 Protocols []string `json:"protocols,omitempty"`
251
252 // ListenProtocols overrides Protocols for each parallel address in Listen.
253 // A nil value or element indicates that Protocols will be used instead.
254 ListenProtocols [][]string `json:"listen_protocols,omitempty"`
255
256 // If set, overrides whether QUIC listeners allow 0-RTT (early data).
257 // If nil, the default behavior is used (currently allowed).
258 //
259 // One reason to disable 0-RTT is if a remote IP matcher is used,
260 // which introduces a dependency on the remote address being verified
261 // if routing happens before the TLS handshake completes. An HTTP 425
262 // response is written in that case, but some clients misbehave and
263 // don't perform a retry, so disabling 0-RTT can smooth it out.
264 Allow0RTT *bool `json:"allow_0rtt,omitempty"`
265
266 // If set, metrics observations will be enabled.
267 // This setting is EXPERIMENTAL and subject to change.
268 // DEPRECATED: Use the app-level `metrics` field.
269 Metrics *Metrics `json:"metrics,omitempty"`
270
271 name string
272
273 primaryHandlerChain Handler
274 errorHandlerChain Handler
275 listenerWrappers []caddy.ListenerWrapper
276 packetConnWrappers []caddy.PacketConnWrapper
277 listeners []net.Listener
278 quicListeners []http3.QUICListener // http3 now leave the quic.Listener management to us
279
280 tlsApp *caddytls.TLS
281 events *caddyevents.App
282 logger *zap.Logger
283 accessLogger *zap.Logger
284 errorLogger *zap.Logger
285 traceLogger *zap.Logger
286 ctx caddy.Context
287
288 server *http.Server
289 h3server *http3.Server
290 addresses []caddy.NetworkAddress
291
292 trustedProxies IPRangeSource
293
294 shutdownAt atomic.Pointer[time.Time]
295
296 // registered callback functions
297 connStateFuncs []func(net.Conn, http.ConnState)
298 connContextFuncs []func(ctx context.Context, c net.Conn) context.Context
299 onShutdownFuncs []func()
300 onStopFuncs []func(context.Context) error // TODO: Experimental (Nov. 2023)
301 }
302
303 var defaultProtocols = []string{"h1", "h2", "h3"}
304
305 var (
306 ServerHeader = "Caddy"
307 serverHeader = []string{ServerHeader}
308 )
309
310 // ServeHTTP is the entry point for all HTTP requests.
311 func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
312 start := time.Now()
313
314 // If there are listener wrappers that process tls connections but don't return a *tls.Conn, this field will be nil.
315 if r.TLS == nil {
316 if tlsConnStateFunc, ok := r.Context().Value(tlsConnectionStateFuncCtxKey).(func() *tls.ConnectionState); ok {
317 r.TLS = tlsConnStateFunc()
318 }
319 }
320
321 // enable full-duplex for HTTP/1, ensuring the entire
322 // request body gets consumed before writing the response
323 if s.EnableFullDuplex && r.ProtoMajor == 1 {
324 if err := http.NewResponseController(w).EnableFullDuplex(); err != nil { //nolint:bodyclose
325 if c := s.logger.Check(zapcore.WarnLevel, "failed to enable full duplex"); c != nil {
326 c.Write(zap.Error(err))
327 }
328 }
329 }
330
331 // set the Server header
332 h := w.Header()
333 h["Server"] = serverHeader
334
335 // advertise HTTP/3, if enabled
336 if s.h3server != nil && r.ProtoMajor < 3 {
337 if err := s.h3server.SetQUICHeaders(h); err != nil {
338 if c := s.logger.Check(zapcore.ErrorLevel, "setting HTTP/3 Alt-Svc header"); c != nil {
339 c.Write(zap.Error(err))
340 }
341 }
342 }
343
344 // prepare internals of the request for the handler pipeline
345 repl := caddy.NewReplacer()
346 r = PrepareRequest(r, repl, w, s)
347
348 // clone the request for logging purposes before it enters any handler chain;
349 // this is necessary to capture the original request in case it gets modified
350 // during handling (cloning the request and using .WithLazy is considerably
351 // faster than using .With, which will JSON-encode the request immediately)
352 shouldLogCredentials := s.Logs != nil && s.Logs.ShouldLogCredentials
353 loggableReq := zap.Object("request", LoggableHTTPRequest{
354 Request: r.Clone(r.Context()),
355 ShouldLogCredentials: shouldLogCredentials,
356 })
357 errLog := s.errorLogger.WithLazy(loggableReq)
358
359 var duration time.Duration
360
361 if s.shouldLogRequest(r) {
362 wrec := NewResponseRecorder(w, nil, nil)
363 w = wrec
364
365 // wrap the request body in a LengthReader
366 // so we can track the number of bytes read from it
367 var bodyReader *lengthReader
368 if r.Body != nil {
369 bodyReader = &lengthReader{Source: r.Body}
370 r.Body = bodyReader
371
372 // should always be true, private interface can only be referenced in the same package
373 if setReadSizer, ok := wrec.(interface{ setReadSize(*int) }); ok {
374 setReadSizer.setReadSize(&bodyReader.Length)
375 }
376 }
377
378 // capture the original version of the request
379 accLog := s.accessLogger.WithLazy(loggableReq)
380
381 defer s.logRequest(accLog, r, wrec, &duration, repl, bodyReader, shouldLogCredentials)
382 }
383
384 // guarantee ACME HTTP challenges; handle them separately from any user-defined handlers
385 if s.tlsApp.HandleHTTPChallenge(w, r) {
386 duration = time.Since(start)
387 return
388 }
389
390 err := s.serveHTTP(w, r)
391 duration = time.Since(start)
392
393 if err == nil {
394 return
395 }
396
397 // restore original request before invoking error handler chain (issue #3717)
398 // NOTE: this does not restore original headers if modified (for efficiency)
399 origReq, ok := r.Context().Value(OriginalRequestCtxKey).(http.Request)
400 if ok {
401 r.Method = origReq.Method
402 r.RemoteAddr = origReq.RemoteAddr
403 r.RequestURI = origReq.RequestURI
404 cloneURL(origReq.URL, r.URL)
405 }
406
407 // prepare the error log
408 errLog = errLog.With(zap.Duration("duration", duration))
409 errLoggers := []*zap.Logger{errLog}
410 if s.Logs != nil {
411 errLoggers = s.Logs.wrapLogger(errLog, r)
412 }
413
414 // get the values that will be used to log the error
415 errStatus, errMsg, errFields := errLogValues(err)
416
417 // add HTTP error information to request context
418 r = s.Errors.WithError(r, err)
419
420 var fields []zapcore.Field
421 if s.Errors != nil && len(s.Errors.Routes) > 0 {
422 // execute user-defined error handling route
423 if err2 := s.errorHandlerChain.ServeHTTP(w, r); err2 == nil {
424 // user's error route handled the error response successfully, so now just log the error
425 for _, logger := range errLoggers {
426 if c := logger.Check(zapcore.DebugLevel, errMsg); c != nil {
427 if fields == nil {
428 fields = errFields()
429 }
430 c.Write(fields...)
431 }
432 }
433 } else {
434 // well... this is awkward
435 for _, logger := range errLoggers {
436 if c := logger.Check(zapcore.ErrorLevel, "error handling handler error"); c != nil {
437 if fields == nil {
438 fields = errFields()
439 fields = append([]zapcore.Field{
440 zap.String("error", err2.Error()),
441 zap.Namespace("first_error"),
442 zap.String("msg", errMsg),
443 }, fields...)
444 }
445 c.Write(fields...)
446 }
447 }
448 if handlerErr, ok := err.(HandlerError); ok {
449 w.WriteHeader(handlerErr.StatusCode)
450 } else {
451 w.WriteHeader(http.StatusInternalServerError)
452 }
453 }
454 } else {
455 logLevel := zapcore.DebugLevel
456 if errStatus >= 500 {
457 logLevel = zapcore.ErrorLevel
458 }
459
460 for _, logger := range errLoggers {
461 if c := logger.Check(logLevel, errMsg); c != nil {
462 if fields == nil {
463 fields = errFields()
464 }
465 c.Write(fields...)
466 }
467 }
468 w.WriteHeader(errStatus)
469 }
470 }
471
472 func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) error {
473 // reject very long methods; probably a mistake or an attack
474 if len(r.Method) > 32 {
475 if s.shouldLogRequest(r) {
476 if c := s.accessLogger.Check(zapcore.DebugLevel, "rejecting request with long method"); c != nil {
477 c.Write(
478 zap.String("method_trunc", r.Method[:32]),
479 zap.String("remote_addr", r.RemoteAddr),
480 )
481 }
482 }
483 return HandlerError{StatusCode: http.StatusMethodNotAllowed}
484 }
485
486 // RFC 9112 section 3.2: "A server MUST respond with a 400 (Bad Request) status
487 // code to any HTTP/1.1 request message that lacks a Host header field and to any
488 // request message that contains more than one Host header field line or a Host
489 // header field with an invalid field value."
490 if r.ProtoMajor == 1 && r.ProtoMinor == 1 && r.Host == "" {
491 return HandlerError{
492 Err: errors.New("rfc9112 forbids empty Host"),
493 StatusCode: http.StatusBadRequest,
494 }
495 }
496
497 // Drop headers whose names contain `_`: once FastCGI/CGI/FrankenPHP etc. rewrites `-` to
498 // `_`, an underscore alias collides with the legitimate hyphenated header
499 // and can bypass `forward_auth copy_headers` (GHSA-f59h-q822-g45g).
500 for k := range r.Header {
501 if strings.ContainsRune(k, '_') {
502 delete(r.Header, k)
503
504 if c := s.logger.Check(zapcore.DebugLevel, "dropping header containing underscore"); c != nil {
505 c.Write(zap.String("header", k))
506 }
507 }
508 }
509
510 // execute the primary handler chain
511 return s.primaryHandlerChain.ServeHTTP(w, r)
512 }
513
514 // wrapPrimaryRoute wraps stack (a compiled middleware handler chain)
515 // in s.enforcementHandler which performs crucial security checks, etc.
516 func (s *Server) wrapPrimaryRoute(stack Handler) Handler {
517 return HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
518 return s.enforcementHandler(w, r, stack)
519 })
520 }
521
522 // enforcementHandler is an implicit middleware which performs
523 // standard checks before executing the HTTP middleware chain.
524 func (s *Server) enforcementHandler(w http.ResponseWriter, r *http.Request, next Handler) error {
525 // enforce strict host matching, which ensures that the SNI
526 // value (if any), matches the Host header; essential for
527 // servers that rely on TLS ClientAuth sharing a listener
528 // with servers that do not; if not enforced, client could
529 // bypass by sending benign SNI then restricted Host header
530 if s.StrictSNIHost != nil && *s.StrictSNIHost && r.TLS != nil {
531 hostname, _, err := net.SplitHostPort(r.Host)
532 if err != nil {
533 hostname = r.Host // OK; probably lacked port
534 }
535 if !strings.EqualFold(r.TLS.ServerName, hostname) {
536 err := fmt.Errorf("strict host matching: TLS ServerName (%s) and HTTP Host (%s) values differ",
537 r.TLS.ServerName, hostname)
538 r.Close = true
539 return Error(http.StatusMisdirectedRequest, err)
540 }
541 }
542 return next.ServeHTTP(w, r)
543 }
544
545 // listenersUseAnyPortOtherThan returns true if there are any
546 // listeners in s that use a port which is not otherPort.
547 func (s *Server) listenersUseAnyPortOtherThan(otherPort int) bool {
548 for _, lnAddr := range s.Listen {
549 laddrs, err := caddy.ParseNetworkAddress(lnAddr)
550 if err != nil {
551 continue
552 }
553 if uint(otherPort) > laddrs.EndPort || uint(otherPort) < laddrs.StartPort {
554 return true
555 }
556 }
557 return false
558 }
559
560 // hasListenerAddress returns true if s has a listener
561 // at the given address fullAddr. Currently, fullAddr
562 // must represent exactly one socket address (port
563 // ranges are not supported)
564 func (s *Server) hasListenerAddress(fullAddr string) bool {
565 laddrs, err := caddy.ParseNetworkAddress(fullAddr)
566 if err != nil {
567 return false
568 }
569 if laddrs.PortRangeSize() != 1 {
570 return false // TODO: support port ranges
571 }
572
573 for _, lnAddr := range s.Listen {
574 thisAddrs, err := caddy.ParseNetworkAddress(lnAddr)
575 if err != nil {
576 continue
577 }
578 if thisAddrs.Network != laddrs.Network {
579 continue
580 }
581
582 // Apparently, Linux requires all bound ports to be distinct
583 // *regardless of host interface* even if the addresses are
584 // in fact different; binding "192.168.0.1:9000" and then
585 // ":9000" will fail for ":9000" because "address is already
586 // in use" even though it's not, and the same bindings work
587 // fine on macOS. I also found on Linux that listening on
588 // "[::]:9000" would fail with a similar error, except with
589 // the address "0.0.0.0:9000", as if deliberately ignoring
590 // that I specified the IPv6 interface explicitly. This seems
591 // to be a major bug in the Linux network stack and I don't
592 // know why it hasn't been fixed yet, so for now we have to
593 // special-case ourselves around Linux like a doting parent.
594 // The second issue seems very similar to a discussion here:
595 // https://github.com/nodejs/node/issues/9390
596 //
597 // However, binding to *different specific* interfaces
598 // (e.g. 127.0.0.2:80 and 127.0.0.3:80) IS allowed on Linux.
599 // The conflict only happens when mixing specific IPs with
600 // wildcards (0.0.0.0 or ::).
601
602 // Hosts match exactly (e.g. 127.0.0.2 == 127.0.0.2) -> Conflict.
603 hostMatch := thisAddrs.Host == laddrs.Host
604
605 // On Linux, specific IP vs Wildcard fails to bind.
606 // So if we are on Linux AND either host is empty (wildcard), we treat
607 // it as a match (conflict). But if both are specific and different
608 // (127.0.0.2 vs 127.0.0.3), this remains false (no conflict).
609 linuxWildcardConflict := runtime.GOOS == "linux" && (thisAddrs.Host == "" || laddrs.Host == "")
610
611 if (hostMatch || linuxWildcardConflict) &&
612 (laddrs.StartPort <= thisAddrs.EndPort) &&
613 (laddrs.StartPort >= thisAddrs.StartPort) {
614 return true
615 }
616 }
617 return false
618 }
619
620 func (s *Server) hasTLSClientAuth() bool {
621 return slices.ContainsFunc(s.TLSConnPolicies, func(cp *caddytls.ConnectionPolicy) bool {
622 return cp.ClientAuthentication != nil && cp.ClientAuthentication.Active()
623 })
624 }
625
626 // findLastRouteWithHostMatcher returns the index of the last route
627 // in the server which has a host matcher. Used during Automatic HTTPS
628 // to determine where to insert the HTTP->HTTPS redirect route, such
629 // that it is after any other host matcher but before any "catch-all"
630 // route without a host matcher.
631 func (s *Server) findLastRouteWithHostMatcher() int {
632 foundHostMatcher := false
633 lastIndex := len(s.Routes)
634
635 for i, route := range s.Routes {
636 // since we want to break out of an inner loop, use a closure
637 // to allow us to use 'return' when we found a host matcher
638 found := (func() bool {
639 for _, sets := range route.MatcherSets {
640 for _, matcher := range sets {
641 switch matcher.(type) {
642 case *MatchHost:
643 foundHostMatcher = true
644 return true
645 }
646 }
647 }
648 return false
649 })()
650
651 // if we found the host matcher, change the lastIndex to
652 // just after the current route
653 if found {
654 lastIndex = i + 1
655 }
656 }
657
658 // If we didn't actually find a host matcher, return 0
659 // because that means every defined route was a "catch-all".
660 // See https://caddy.community/t/how-to-set-priority-in-caddyfile/13002/8
661 if !foundHostMatcher {
662 return 0
663 }
664
665 return lastIndex
666 }
667
668 // serveHTTP3 creates a QUIC listener, configures an HTTP/3 server if
669 // not already done, and then uses that server to serve HTTP/3 over
670 // the listener, with Server s as the handler.
671 func (s *Server) serveHTTP3(addr caddy.NetworkAddress, tlsCfg *tls.Config) error {
672 h3net, err := getHTTP3Network(addr.Network)
673 if err != nil {
674 return fmt.Errorf("starting HTTP/3 QUIC listener: %v", err)
675 }
676 addr.Network = h3net
677 h3ln, err := addr.ListenQUIC(s.ctx, 0, net.ListenConfig{}, tlsCfg, s.packetConnWrappers, s.Allow0RTT)
678 if err != nil {
679 return fmt.Errorf("starting HTTP/3 QUIC listener: %v", err)
680 }
681
682 // create HTTP/3 server if not done already
683 if s.h3server == nil {
684 s.h3server = &http3.Server{
685 Handler: s,
686 TLSConfig: tlsCfg,
687 MaxHeaderBytes: s.MaxHeaderBytes,
688 QUICConfig: &quic.Config{
689 Versions: []quic.Version{quic.Version1, quic.Version2},
690 Tracer: h3qlog.DefaultConnectionTracer,
691 },
692 IdleTimeout: time.Duration(s.IdleTimeout),
693 }
694 }
695
696 s.quicListeners = append(s.quicListeners, h3ln)
697
698 //nolint:errcheck
699 go s.h3server.ServeListener(h3ln)
700
701 return nil
702 }
703
704 // configureServer applies/binds the registered callback functions to the server.
705 func (s *Server) configureServer(server *http.Server) {
706 for _, f := range s.connStateFuncs {
707 if server.ConnState != nil {
708 baseConnStateFunc := server.ConnState
709 server.ConnState = func(conn net.Conn, state http.ConnState) {
710 baseConnStateFunc(conn, state)
711 f(conn, state)
712 }
713 } else {
714 server.ConnState = f
715 }
716 }
717
718 for _, f := range s.connContextFuncs {
719 if server.ConnContext != nil {
720 baseConnContextFunc := server.ConnContext
721 server.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
722 return f(baseConnContextFunc(ctx, c), c)
723 }
724 } else {
725 server.ConnContext = f
726 }
727 }
728
729 for _, f := range s.onShutdownFuncs {
730 server.RegisterOnShutdown(f)
731 }
732 }
733
734 // RegisterConnState registers f to be invoked on s.ConnState.
735 func (s *Server) RegisterConnState(f func(net.Conn, http.ConnState)) {
736 s.connStateFuncs = append(s.connStateFuncs, f)
737 }
738
739 // RegisterConnContext registers f to be invoked as part of s.ConnContext.
740 func (s *Server) RegisterConnContext(f func(ctx context.Context, c net.Conn) context.Context) {
741 s.connContextFuncs = append(s.connContextFuncs, f)
742 }
743
744 // RegisterOnShutdown registers f to be invoked when the server begins to shut down.
745 func (s *Server) RegisterOnShutdown(f func()) {
746 s.onShutdownFuncs = append(s.onShutdownFuncs, f)
747 }
748
749 // RegisterOnStop registers f to be invoked after the server has shut down completely.
750 //
751 // EXPERIMENTAL: Subject to change or removal.
752 func (s *Server) RegisterOnStop(f func(context.Context) error) {
753 s.onStopFuncs = append(s.onStopFuncs, f)
754 }
755
756 // HTTPErrorConfig determines how to handle errors
757 // from the HTTP handlers.
758 type HTTPErrorConfig struct {
759 // The routes to evaluate after the primary handler
760 // chain returns an error. In an error route, extra
761 // placeholders are available:
762 //
763 // Placeholder | Description
764 // ------------|---------------
765 // `{http.error.status_code}` | The recommended HTTP status code
766 // `{http.error.status_text}` | The status text associated with the recommended status code
767 // `{http.error.message}` | The error message
768 // `{http.error.trace}` | The origin of the error
769 // `{http.error.id}` | An identifier for this occurrence of the error
770 Routes RouteList `json:"routes,omitempty"`
771 }
772
773 // WithError makes a shallow copy of r to add the error to its
774 // context, and sets placeholders on the request's replacer
775 // related to err. It returns the modified request which has
776 // the error information in its context and replacer. It
777 // overwrites any existing error values that are stored.
778 func (*HTTPErrorConfig) WithError(r *http.Request, err error) *http.Request {
779 // add the raw error value to the request context
780 // so it can be accessed by error handlers
781 c := context.WithValue(r.Context(), ErrorCtxKey, err)
782 r = r.WithContext(c)
783
784 // add error values to the replacer
785 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
786 repl.Set("http.error", err)
787 if handlerErr, ok := err.(HandlerError); ok {
788 repl.Set("http.error.status_code", handlerErr.StatusCode)
789 repl.Set("http.error.status_text", http.StatusText(handlerErr.StatusCode))
790 repl.Set("http.error.id", handlerErr.ID)
791 repl.Set("http.error.trace", handlerErr.Trace)
792 if handlerErr.Err != nil {
793 repl.Set("http.error.message", handlerErr.Err.Error())
794 } else {
795 repl.Set("http.error.message", http.StatusText(handlerErr.StatusCode))
796 }
797 }
798
799 return r
800 }
801
802 // shouldLogRequest returns true if this request should be logged.
803 func (s *Server) shouldLogRequest(r *http.Request) bool {
804 if s.accessLogger == nil || s.Logs == nil {
805 // logging is disabled
806 return false
807 }
808
809 // strip off the port if any, logger names are host only
810 hostWithoutPort, _, err := net.SplitHostPort(r.Host)
811 if err != nil {
812 hostWithoutPort = r.Host
813 }
814
815 for loggerName := range s.Logs.LoggerNames {
816 if certmagic.MatchWildcard(hostWithoutPort, loggerName) {
817 // this host is mapped to a particular logger name
818 return true
819 }
820 }
821 for _, dh := range s.Logs.SkipHosts {
822 // logging for this particular host is disabled
823 if certmagic.MatchWildcard(hostWithoutPort, dh) {
824 return false
825 }
826 }
827 // if configured, this host is not mapped and thus must not be logged
828 return !s.Logs.SkipUnmappedHosts
829 }
830
831 // logTrace will log that this middleware handler is being invoked.
832 // It emits at DEBUG level.
833 func (s *Server) logTrace(mh MiddlewareHandler) {
834 if s.Logs == nil || !s.Logs.Trace {
835 return
836 }
837 if c := s.traceLogger.Check(zapcore.DebugLevel, caddy.GetModuleName(mh)); c != nil {
838 c.Write(zap.Any("module", mh))
839 }
840 }
841
842 // logRequest logs the request to access logs, unless skipped.
843 func (s *Server) logRequest(
844 accLog *zap.Logger, r *http.Request, wrec ResponseRecorder, duration *time.Duration,
845 repl *caddy.Replacer, bodyReader *lengthReader, shouldLogCredentials bool,
846 ) {
847 ctx := r.Context()
848
849 // this request may be flagged as omitted from the logs
850 if skip, ok := GetVar(ctx, LogSkipVar).(bool); ok && skip {
851 return
852 }
853
854 status := wrec.Status()
855 size := wrec.Size()
856
857 repl.Set("http.response.status", status) // will be 0 if no response is written by us (Go will write 200 to client)
858 repl.Set("http.response.size", size)
859 repl.Set("http.response.duration", duration)
860 repl.Set("http.response.duration_ms", duration.Seconds()*1e3) // multiply seconds to preserve decimal (see #4666)
861
862 loggers := []*zap.Logger{accLog}
863 if s.Logs != nil {
864 loggers = s.Logs.wrapLogger(accLog, r)
865 }
866
867 message := "handled request"
868 if nop, ok := GetVar(ctx, "unhandled").(bool); ok && nop {
869 message = "NOP"
870 }
871
872 logLevel := zapcore.InfoLevel
873 if status >= 500 {
874 logLevel = zapcore.ErrorLevel
875 }
876
877 var fields []zapcore.Field
878 for _, logger := range loggers {
879 c := logger.Check(logLevel, message)
880 if c == nil {
881 continue
882 }
883
884 if fields == nil {
885 userID, _ := repl.GetString("http.auth.user.id")
886
887 reqBodyLength := 0
888 if bodyReader != nil {
889 reqBodyLength = bodyReader.Length
890 }
891
892 extra := ctx.Value(ExtraLogFieldsCtxKey).(*ExtraLogFields)
893
894 fieldCount := 6
895 fields = make([]zapcore.Field, 0, fieldCount+len(extra.fields))
896 fields = append(fields,
897 zap.Int("bytes_read", reqBodyLength),
898 zap.String("user_id", userID),
899 zap.Duration("duration", *duration),
900 zap.Int("size", size),
901 zap.Int("status", status),
902 zap.Object("resp_headers", LoggableHTTPHeader{
903 Header: wrec.Header(),
904 ShouldLogCredentials: shouldLogCredentials,
905 }),
906 )
907 fields = append(fields, extra.fields...)
908 }
909
910 c.Write(fields...)
911 }
912 }
913
914 // protocol returns true if the protocol proto is configured/enabled.
915 func (s *Server) protocol(proto string) bool {
916 if s.ListenProtocols == nil {
917 return slices.Contains(s.protocolsWithDefaults(), proto)
918 }
919
920 for _, lnProtocols := range s.ListenProtocols {
921 if slices.Contains(s.listenerProtocolsWithDefaults(lnProtocols), proto) {
922 return true
923 }
924 }
925
926 return false
927 }
928
929 func (s *Server) protocolsWithDefaults() []string {
930 if len(s.Protocols) == 0 {
931 return defaultProtocols
932 }
933 return s.Protocols
934 }
935
936 func (s *Server) listenerProtocolsWithDefaults(lnProtocols []string) []string {
937 serverProtocols := s.protocolsWithDefaults()
938 if len(lnProtocols) == 0 {
939 return serverProtocols
940 }
941
942 lnProtocolsDefault := false
943 lnProtocolsInclude := make([]string, 0, len(lnProtocols)+len(serverProtocols))
944 srvProtocolsInclude := make(map[string]struct{}, len(serverProtocols))
945 for _, srvProtocol := range serverProtocols {
946 srvProtocolsInclude[srvProtocol] = struct{}{}
947 }
948
949 for _, lnProtocol := range lnProtocols {
950 if lnProtocol == "" {
951 lnProtocolsDefault = true
952 continue
953 }
954 lnProtocolsInclude = append(lnProtocolsInclude, lnProtocol)
955 delete(srvProtocolsInclude, lnProtocol)
956 }
957
958 if lnProtocolsDefault {
959 for _, srvProtocol := range serverProtocols {
960 if _, ok := srvProtocolsInclude[srvProtocol]; ok {
961 lnProtocolsInclude = append(lnProtocolsInclude, srvProtocol)
962 }
963 }
964 }
965
966 return lnProtocolsInclude
967 }
968
969 // Listeners returns the server's listeners. These are active listeners,
970 // so calling Accept() or Close() on them will probably break things.
971 // They are made available here for read-only purposes (e.g. Addr())
972 // and for type-asserting for purposes where you know what you're doing.
973 //
974 // EXPERIMENTAL: Subject to change or removal.
975 func (s *Server) Listeners() []net.Listener { return s.listeners }
976
977 // Name returns the server's name.
978 func (s *Server) Name() string { return s.name }
979
980 // PrepareRequest fills the request r for use in a Caddy HTTP handler chain. w and s can
981 // be nil, but the handlers will lose response placeholders and access to the server.
982 func PrepareRequest(r *http.Request, repl *caddy.Replacer, w http.ResponseWriter, s *Server) *http.Request {
983 // set up the context for the request
984 ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl)
985 ctx = context.WithValue(ctx, ServerCtxKey, s)
986
987 trusted, clientIP := determineTrustedProxy(r, s)
988 ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{
989 TrustedProxyVarKey: trusted,
990 ClientIPVarKey: clientIP,
991 })
992
993 ctx = context.WithValue(ctx, routeGroupCtxKey, make(map[string]struct{}))
994
995 var url2 url.URL // avoid letting this escape to the heap
996 ctx = context.WithValue(ctx, OriginalRequestCtxKey, originalRequest(r, &url2))
997
998 ctx = context.WithValue(ctx, ExtraLogFieldsCtxKey, new(ExtraLogFields))
999 r = r.WithContext(ctx)
1000
1001 // once the pointer to the request won't change
1002 // anymore, finish setting up the replacer
1003 addHTTPVarsToReplacer(repl, r, w)
1004
1005 return r
1006 }
1007
1008 // originalRequest returns a partial, shallow copy of
1009 // req, including: req.Method, deep copy of req.URL
1010 // (into the urlCopy parameter, which should be on the
1011 // stack), req.RequestURI, and req.RemoteAddr. Notably,
1012 // headers are not copied. This function is designed to
1013 // be very fast and efficient, and useful primarily for
1014 // read-only/logging purposes.
1015 func originalRequest(req *http.Request, urlCopy *url.URL) http.Request {
1016 cloneURL(req.URL, urlCopy)
1017 return http.Request{
1018 Method: req.Method,
1019 RemoteAddr: req.RemoteAddr,
1020 RequestURI: req.RequestURI,
1021 URL: urlCopy,
1022 }
1023 }
1024
1025 // determineTrustedProxy parses the remote IP address of
1026 // the request, and determines (if the server configured it)
1027 // if the client is a trusted proxy. If trusted, also returns
1028 // the real client IP if possible.
1029 func determineTrustedProxy(r *http.Request, s *Server) (bool, string) {
1030 // If there's no server, then we can't check anything
1031 if s == nil {
1032 return false, ""
1033 }
1034
1035 if s.TrustedProxiesUnix && r.RemoteAddr == "@" {
1036 if s.TrustedProxiesStrict > 0 {
1037 ipRanges := []netip.Prefix{}
1038 if s.trustedProxies != nil {
1039 ipRanges = s.trustedProxies.GetIPRanges(r)
1040 }
1041 return true, strictUntrustedClientIp(r, s.ClientIPHeaders, ipRanges, "@")
1042 } else {
1043 return true, trustedRealClientIP(r, s.ClientIPHeaders, "@")
1044 }
1045 }
1046 // Parse the remote IP, ignore the error as non-fatal,
1047 // but the remote IP is required to continue, so we
1048 // just return early. This should probably never happen
1049 // though, unless some other module manipulated the request's
1050 // remote address and used an invalid value.
1051 clientIP, _, err := net.SplitHostPort(r.RemoteAddr)
1052 if err != nil {
1053 return false, ""
1054 }
1055
1056 // Client IP may contain a zone if IPv6, so we need
1057 // to pull that out before parsing the IP
1058 clientIP, _, _ = strings.Cut(clientIP, "%")
1059 ipAddr, err := netip.ParseAddr(clientIP)
1060 if err != nil {
1061 return false, ""
1062 }
1063
1064 // Check if the client is a trusted proxy
1065 if s.trustedProxies == nil {
1066 return false, ipAddr.String()
1067 }
1068
1069 if isTrustedClientIP(ipAddr, s.trustedProxies.GetIPRanges(r)) {
1070 if s.TrustedProxiesStrict > 0 {
1071 return true, strictUntrustedClientIp(r, s.ClientIPHeaders, s.trustedProxies.GetIPRanges(r), ipAddr.String())
1072 }
1073 return true, trustedRealClientIP(r, s.ClientIPHeaders, ipAddr.String())
1074 }
1075
1076 return false, ipAddr.String()
1077 }
1078
1079 // isTrustedClientIP returns true if the given IP address is
1080 // in the list of trusted IP ranges.
1081 func isTrustedClientIP(ipAddr netip.Addr, trusted []netip.Prefix) bool {
1082 return slices.ContainsFunc(trusted, func(prefix netip.Prefix) bool {
1083 return prefix.Contains(ipAddr)
1084 })
1085 }
1086
1087 // trustedRealClientIP finds the client IP from the request assuming it is
1088 // from a trusted client. If there is no client IP headers, then the
1089 // direct remote address is returned. If there are client IP headers,
1090 // then the first value from those headers is used.
1091 func trustedRealClientIP(r *http.Request, headers []string, clientIP string) string {
1092 // Read all the values of the configured client IP headers, in order
1093 // nolint:prealloc
1094 var values []string
1095 for _, field := range headers {
1096 values = append(values, r.Header.Values(field)...)
1097 }
1098
1099 // If we don't have any values, then give up
1100 if len(values) == 0 {
1101 return clientIP
1102 }
1103
1104 // Since there can be many header values, we need to
1105 // join them together before splitting to get the full list
1106 allValues := strings.SplitSeq(strings.Join(values, ","), ",")
1107
1108 // Get first valid left-most IP address
1109 for part := range allValues {
1110 // Some proxies may retain the port number, so split if possible
1111 host, _, err := net.SplitHostPort(part)
1112 if err != nil {
1113 host = part
1114 }
1115
1116 // Remove any zone identifier from the IP address
1117 host, _, _ = strings.Cut(strings.TrimSpace(host), "%")
1118
1119 // Parse the IP address
1120 ipAddr, err := netip.ParseAddr(host)
1121 if err != nil {
1122 continue
1123 }
1124 return ipAddr.String()
1125 }
1126
1127 // We didn't find a valid IP
1128 return clientIP
1129 }
1130
1131 // strictUntrustedClientIp iterates through the list of client IP headers,
1132 // parses them from right-to-left, and returns the first valid IP address
1133 // that is untrusted. If no valid IP address is found, then the direct
1134 // remote address is returned.
1135 func strictUntrustedClientIp(r *http.Request, headers []string, trusted []netip.Prefix, clientIP string) string {
1136 for _, headerName := range headers {
1137 parts := strings.Split(strings.Join(r.Header.Values(headerName), ","), ",")
1138
1139 for _, part := range slices.Backward(parts) {
1140 // Some proxies may retain the port number, so split if possible
1141 host, _, err := net.SplitHostPort(part)
1142 if err != nil {
1143 host = part
1144 }
1145
1146 // Remove any zone identifier from the IP address
1147 host, _, _ = strings.Cut(strings.TrimSpace(host), "%")
1148
1149 // Parse the IP address
1150 ipAddr, err := netip.ParseAddr(host)
1151 if err != nil {
1152 continue
1153 }
1154 if !isTrustedClientIP(ipAddr, trusted) {
1155 return ipAddr.String()
1156 }
1157 }
1158 }
1159
1160 return clientIP
1161 }
1162
1163 // cloneURL makes a copy of r.URL and returns a
1164 // new value that doesn't reference the original.
1165 func cloneURL(from, to *url.URL) {
1166 *to = *from
1167 if from.User != nil {
1168 userInfo := new(url.Userinfo)
1169 *userInfo = *from.User
1170 to.User = userInfo
1171 }
1172 }
1173
1174 // lengthReader is an io.ReadCloser that keeps track of the
1175 // number of bytes read from the request body.
1176 type lengthReader struct {
1177 Source io.ReadCloser
1178 Length int
1179 }
1180
1181 func (r *lengthReader) Read(b []byte) (int, error) {
1182 n, err := r.Source.Read(b)
1183 r.Length += n
1184 return n, err
1185 }
1186
1187 func (r *lengthReader) Close() error {
1188 return r.Source.Close()
1189 }
1190
1191 // Context keys for HTTP request context values.
1192 const (
1193 // For referencing the server instance
1194 ServerCtxKey caddy.CtxKey = "server"
1195
1196 // For the request's variable table
1197 VarsCtxKey caddy.CtxKey = "vars"
1198
1199 // For a partial copy of the unmodified request that
1200 // originally came into the server's entry handler
1201 OriginalRequestCtxKey caddy.CtxKey = "original_request"
1202
1203 // DEPRECATED: not used anymore.
1204 // To refer to the underlying connection, implement a middleware plugin
1205 // that RegisterConnContext during provisioning.
1206 ConnCtxKey caddy.CtxKey = "conn"
1207
1208 // used to get the tls connection state in the context, if available
1209 tlsConnectionStateFuncCtxKey caddy.CtxKey = "tls_connection_state_func"
1210
1211 // For tracking whether the client is a trusted proxy
1212 TrustedProxyVarKey string = "trusted_proxy"
1213
1214 // For tracking the real client IP (affected by trusted_proxy)
1215 ClientIPVarKey string = "client_ip"
1216 )
1217
1218 var networkTypesHTTP3 = map[string]string{
1219 "unixgram": "unixgram",
1220 "udp": "udp",
1221 "udp4": "udp4",
1222 "udp6": "udp6",
1223 "tcp": "udp",
1224 "tcp4": "udp4",
1225 "tcp6": "udp6",
1226 "fdgram": "fdgram",
1227 }
1228
1229 // RegisterNetworkHTTP3 registers a mapping from non-HTTP/3 network to HTTP/3
1230 // network. This should be called during init() and will panic if the network
1231 // type is standard, reserved, or already registered.
1232 //
1233 // EXPERIMENTAL: Subject to change.
1234 func RegisterNetworkHTTP3(originalNetwork, h3Network string) {
1235 if _, ok := networkTypesHTTP3[strings.ToLower(originalNetwork)]; ok {
1236 panic("network type " + originalNetwork + " is already registered")
1237 }
1238 networkTypesHTTP3[originalNetwork] = h3Network
1239 }
1240
1241 func getHTTP3Network(originalNetwork string) (string, error) {
1242 h3Network, ok := networkTypesHTTP3[strings.ToLower(originalNetwork)]
1243 if !ok {
1244 return "", fmt.Errorf("network '%s' cannot handle HTTP/3 connections", originalNetwork)
1245 }
1246 return h3Network, nil
1247 }