Debian Codegraph @

modules/caddyhttp/app.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 "cmp"
19 "context"
20 "crypto/tls"
21 "errors"
22 "fmt"
23 "net"
24 "net/http"
25 "strconv"
26 "sync"
27 "time"
28
29 "go.uber.org/zap"
30 "golang.org/x/net/http2"
31
32 "github.com/caddyserver/caddy/v2"
33 "github.com/caddyserver/caddy/v2/modules/caddyevents"
34 "github.com/caddyserver/caddy/v2/modules/caddytls"
35 )
36
37 func init() {
38 caddy.RegisterModule(App{})
39 }
40
41 // App is a robust, production-ready HTTP server.
42 //
43 // HTTPS is enabled by default if host matchers with qualifying names are used
44 // in any of routes; certificates are automatically provisioned and renewed.
45 // Additionally, automatic HTTPS will also enable HTTPS for servers that listen
46 // only on the HTTPS port but which do not have any TLS connection policies
47 // defined by adding a good, default TLS connection policy.
48 //
49 // In HTTP routes, additional placeholders are available (replace any `*`):
50 //
51 // Placeholder | Description
52 // ------------|---------------
53 // `{http.request.body}` | The request body (⚠️ inefficient; use only for debugging)
54 // `{http.request.body_base64}` | The request body, base64-encoded (⚠️ for debugging)
55 // `{http.request.cookie.*}` | HTTP request cookie
56 // `{http.request.duration}` | Time up to now spent handling the request (after decoding headers from client)
57 // `{http.request.duration_ms}` | Same as 'duration', but in milliseconds.
58 // `{http.request.uuid}` | The request unique identifier
59 // `{http.request.header.*}` | Specific request header field
60 // `{http.request.host}` | The host part of the request's Host header
61 // `{http.request.host.labels.*}` | Request host labels (0-based from right); e.g. for foo.example.com: 0=com, 1=example, 2=foo
62 // `{http.request.hostport}` | The host and port from the request's Host header
63 // `{http.request.method}` | The request method
64 // `{http.request.orig_method}` | The request's original method
65 // `{http.request.orig_uri}` | The request's original URI
66 // `{http.request.orig_uri.path}` | The request's original path
67 // `{http.request.orig_uri.path.*}` | Parts of the original path, split by `/` (0-based from left)
68 // `{http.request.orig_uri.path.dir}` | The request's original directory
69 // `{http.request.orig_uri.path.file}` | The request's original filename
70 // `{http.request.orig_uri.query}` | The request's original query string (without `?`)
71 // `{http.request.orig_uri.prefixed_query}` | The request's original query string with a `?` prefix, if non-empty
72 // `{http.request.port}` | The port part of the request's Host header
73 // `{http.request.proto}` | The protocol of the request
74 // `{http.request.local.host}` | The host (IP) part of the local address the connection arrived on
75 // `{http.request.local.port}` | The port part of the local address the connection arrived on
76 // `{http.request.local}` | The local address the connection arrived on
77 // `{http.request.remote.host}` | The host (IP) part of the remote client's address, if available (not known with HTTP/3 early data)
78 // `{http.request.remote.port}` | The port part of the remote client's address
79 // `{http.request.remote}` | The address of the remote client
80 // `{http.request.scheme}` | The request scheme, typically `http` or `https`
81 // `{http.request.tls.version}` | The TLS version name
82 // `{http.request.tls.cipher_suite}` | The TLS cipher suite
83 // `{http.request.tls.resumed}` | The TLS connection resumed a previous connection
84 // `{http.request.tls.proto}` | The negotiated next protocol
85 // `{http.request.tls.proto_mutual}` | The negotiated next protocol was advertised by the server
86 // `{http.request.tls.server_name}` | The server name requested by the client, if any
87 // `{http.request.tls.ech}` | Whether ECH was offered by the client and accepted by the server
88 // `{http.request.tls.client.fingerprint}` | The SHA256 checksum of the client certificate
89 // `{http.request.tls.client.public_key}` | The public key of the client certificate.
90 // `{http.request.tls.client.public_key_sha256}` | The SHA256 checksum of the client's public key.
91 // `{http.request.tls.client.certificate_pem}` | The PEM-encoded value of the certificate.
92 // `{http.request.tls.client.certificate_der_base64}` | The base64-encoded value of the certificate.
93 // `{http.request.tls.client.issuer}` | The issuer DN of the client certificate
94 // `{http.request.tls.client.serial}` | The serial number of the client certificate
95 // `{http.request.tls.client.subject}` | The subject DN of the client certificate
96 // `{http.request.tls.client.san.dns_names.*}` | SAN DNS names(index optional)
97 // `{http.request.tls.client.san.emails.*}` | SAN email addresses (index optional)
98 // `{http.request.tls.client.san.ips.*}` | SAN IP addresses (index optional)
99 // `{http.request.tls.client.san.uris.*}` | SAN URIs (index optional)
100 // `{http.request.uri}` | The full request URI
101 // `{http.request.uri_escaped}` | The full request URI with query-style URL encoding applied (using url.QueryEscape)
102 // `{http.request.uri.path}` | The path component of the request URI
103 // `{http.request.uri.path_escaped}` | The path component of the request URI with query-style URL encoding applied (using url.QueryEscape)
104 // `{http.request.uri.path.*}` | Parts of the path, split by `/` (0-based from left)
105 // `{http.request.uri.path.dir}` | The directory, excluding leaf filename
106 // `{http.request.uri.path.file}` | The filename of the path, excluding directory
107 // `{http.request.uri.query}` | The query string (without `?`)
108 // `{http.request.uri.query_escaped}` | The query string with query-style URL encoding applied (using url.QueryEscape)
109 // `{http.request.uri.prefixed_query}` | The query string with a `?` prefix, if non-empty
110 // `{http.request.uri.query.*}` | Individual query string value
111 // `{http.response.header.*}` | Specific response header field
112 // `{http.vars.*}` | Custom variables in the HTTP handler chain
113 // `{http.shutting_down}` | True if the HTTP app is shutting down
114 // `{http.time_until_shutdown}` | Time until HTTP server shutdown, if scheduled
115 type App struct {
116 // HTTPPort specifies the port to use for HTTP (as opposed to HTTPS),
117 // which is used when setting up HTTP->HTTPS redirects or ACME HTTP
118 // challenge solvers. Default: 80.
119 HTTPPort int `json:"http_port,omitempty"`
120
121 // HTTPSPort specifies the port to use for HTTPS, which is used when
122 // solving the ACME TLS-ALPN challenges, or whenever HTTPS is needed
123 // but no specific port number is given. Default: 443.
124 HTTPSPort int `json:"https_port,omitempty"`
125
126 // GracePeriod is how long to wait for active connections when shutting
127 // down the servers. During the grace period, no new connections are
128 // accepted, idle connections are closed, and active connections will
129 // be given the full length of time to become idle and close.
130 // Once the grace period is over, connections will be forcefully closed.
131 // If zero, the grace period is eternal. Default: 0.
132 GracePeriod caddy.Duration `json:"grace_period,omitempty"`
133
134 // ShutdownDelay is how long to wait before initiating the grace
135 // period. When this app is stopping (e.g. during a config reload or
136 // process exit), all servers will be shut down. Normally this immediately
137 // initiates the grace period. However, if this delay is configured, servers
138 // will not be shut down until the delay is over. During this time, servers
139 // continue to function normally and allow new connections. At the end, the
140 // grace period will begin. This can be useful to allow downstream load
141 // balancers time to move this instance out of the rotation without hiccups.
142 //
143 // When shutdown has been scheduled, placeholders {http.shutting_down} (bool)
144 // and {http.time_until_shutdown} (duration) may be useful for health checks.
145 ShutdownDelay caddy.Duration `json:"shutdown_delay,omitempty"`
146
147 // Servers is the list of servers, keyed by arbitrary names chosen
148 // at your discretion for your own convenience; the keys do not
149 // affect functionality.
150 Servers map[string]*Server `json:"servers,omitempty"`
151
152 // If set, metrics observations will be enabled.
153 // This setting is EXPERIMENTAL and subject to change.
154 Metrics *Metrics `json:"metrics,omitempty"`
155
156 ctx caddy.Context
157 logger *zap.Logger
158 tlsApp *caddytls.TLS
159
160 // stopped indicates whether the app has stopped
161 // It can only happen if it has started successfully in the first place.
162 // Otherwise, Cleanup will call Stop to clean up resources.
163 stopped bool
164
165 // used temporarily between phases 1 and 2 of auto HTTPS
166 allCertDomains map[string]struct{}
167 }
168
169 // CaddyModule returns the Caddy module information.
170 func (App) CaddyModule() caddy.ModuleInfo {
171 return caddy.ModuleInfo{
172 ID: "http",
173 New: func() caddy.Module { return new(App) },
174 }
175 }
176
177 // Provision sets up the app.
178 func (app *App) Provision(ctx caddy.Context) error {
179 // store some references
180 app.logger = ctx.Logger()
181 app.ctx = ctx
182
183 // provision TLS and events apps
184 tlsAppIface, err := ctx.App("tls")
185 if err != nil {
186 return fmt.Errorf("getting tls app: %v", err)
187 }
188 app.tlsApp = tlsAppIface.(*caddytls.TLS)
189
190 eventsAppIface, err := ctx.App("events")
191 if err != nil {
192 return fmt.Errorf("getting events app: %v", err)
193 }
194
195 repl := caddy.NewReplacer()
196
197 // this provisions the matchers for each route,
198 // and prepares auto HTTP->HTTPS redirects, and
199 // is required before we provision each server
200 err = app.automaticHTTPSPhase1(ctx, repl)
201 if err != nil {
202 return err
203 }
204
205 if app.Metrics != nil {
206 app.Metrics.init = sync.Once{}
207 app.Metrics.httpMetrics = &httpMetrics{}
208 // Scan config for allowed hosts to prevent cardinality explosion
209 app.Metrics.scanConfigForHosts(app)
210 if err := app.Metrics.provisionOTLP(ctx); err != nil {
211 return err
212 }
213 }
214 // prepare each server
215 oldContext := ctx.Context
216 for srvName, srv := range app.Servers {
217 ctx.Context = context.WithValue(oldContext, ServerCtxKey, srv)
218 srv.name = srvName
219 srv.tlsApp = app.tlsApp
220 srv.events = eventsAppIface.(*caddyevents.App)
221 srv.ctx = ctx
222 srv.logger = app.logger.Named("log")
223 srv.errorLogger = app.logger.Named("log.error")
224 if srv.Metrics != nil {
225 srv.logger.Warn("per-server 'metrics' is deprecated; use 'metrics' in the root 'http' app instead")
226 app.Metrics = cmp.Or(app.Metrics, &Metrics{
227 init: sync.Once{},
228 httpMetrics: &httpMetrics{},
229 })
230 app.Metrics.PerHost = app.Metrics.PerHost || srv.Metrics.PerHost
231 }
232
233 // only enable access logs if configured
234 if srv.Logs != nil {
235 srv.accessLogger = app.logger.Named("log.access")
236 if srv.Logs.Trace {
237 srv.traceLogger = app.logger.Named("log.trace")
238 }
239 }
240
241 // if no protocols configured explicitly, enable all except h2c
242 if len(srv.Protocols) == 0 {
243 srv.Protocols = srv.protocolsWithDefaults()
244 }
245
246 if srv.ListenProtocols != nil {
247 if len(srv.ListenProtocols) != len(srv.Listen) {
248 return fmt.Errorf("server %s: listener protocols count does not match address count: %d != %d",
249 srvName, len(srv.ListenProtocols), len(srv.Listen))
250 }
251
252 for i, lnProtocols := range srv.ListenProtocols {
253 if lnProtocols != nil {
254 srv.ListenProtocols[i] = srv.listenerProtocolsWithDefaults(lnProtocols)
255 }
256 }
257 }
258
259 // if not explicitly configured by the user, disallow TLS
260 // client auth bypass (domain fronting) which could
261 // otherwise be exploited by sending an unprotected SNI
262 // value during a TLS handshake, then putting a protected
263 // domain in the Host header after establishing connection;
264 // this is a safe default, but we allow users to override
265 // it for example in the case of running a proxy where
266 // domain fronting is desired and access is not restricted
267 // based on hostname
268 if srv.StrictSNIHost == nil && srv.hasTLSClientAuth() {
269 app.logger.Warn("enabling strict SNI-Host enforcement because TLS client auth is configured",
270 zap.String("server_id", srvName))
271 trueBool := true
272 srv.StrictSNIHost = &trueBool
273 }
274
275 // set up the trusted proxies source
276 for srv.TrustedProxiesRaw != nil {
277 val, err := ctx.LoadModule(srv, "TrustedProxiesRaw")
278 if err != nil {
279 return fmt.Errorf("loading trusted proxies modules: %v", err)
280 }
281 srv.trustedProxies = val.(IPRangeSource)
282 }
283
284 // set the default client IP header to read from
285 if srv.ClientIPHeaders == nil {
286 srv.ClientIPHeaders = []string{"X-Forwarded-For"}
287 }
288
289 // process each listener address
290 for i := range srv.Listen {
291 lnOut, err := repl.ReplaceOrErr(srv.Listen[i], true, true)
292 if err != nil {
293 return fmt.Errorf("server %s, listener %d: %v", srvName, i, err)
294 }
295 srv.Listen[i] = lnOut
296 }
297
298 // set up each listener modifier
299 if srv.ListenerWrappersRaw != nil {
300 vals, err := ctx.LoadModule(srv, "ListenerWrappersRaw")
301 if err != nil {
302 return fmt.Errorf("loading listener wrapper modules: %v", err)
303 }
304 var hasTLSPlaceholder bool
305 for i, val := range vals.([]any) {
306 if _, ok := val.(*tlsPlaceholderWrapper); ok {
307 if i == 0 {
308 // putting the tls placeholder wrapper first is nonsensical because
309 // that is the default, implicit setting: without it, all wrappers
310 // will go after the TLS listener anyway
311 return fmt.Errorf("it is unnecessary to specify the TLS listener wrapper in the first position because that is the default")
312 }
313 if hasTLSPlaceholder {
314 return fmt.Errorf("TLS listener wrapper can only be specified once")
315 }
316 hasTLSPlaceholder = true
317 }
318 srv.listenerWrappers = append(srv.listenerWrappers, val.(caddy.ListenerWrapper))
319 }
320 // if any wrappers were configured but the TLS placeholder wrapper is
321 // absent, prepend it so all defined wrappers come after the TLS
322 // handshake; this simplifies logic when starting the server, since we
323 // can simply assume the TLS placeholder will always be there
324 if !hasTLSPlaceholder && len(srv.listenerWrappers) > 0 {
325 srv.listenerWrappers = append([]caddy.ListenerWrapper{new(tlsPlaceholderWrapper)}, srv.listenerWrappers...)
326 }
327 }
328
329 // set up each packet conn modifier
330 if srv.PacketConnWrappersRaw != nil {
331 vals, err := ctx.LoadModule(srv, "PacketConnWrappersRaw")
332 if err != nil {
333 return fmt.Errorf("loading packet conn wrapper modules: %v", err)
334 }
335 // if any wrappers were configured, they come before the QUIC handshake;
336 // unlike TLS above, there is no QUIC placeholder
337 for _, val := range vals.([]any) {
338 srv.packetConnWrappers = append(srv.packetConnWrappers, val.(caddy.PacketConnWrapper))
339 }
340 }
341
342 // pre-compile the primary handler chain, and be sure to wrap it in our
343 // route handler so that important security checks are done, etc.
344 primaryRoute := emptyHandler
345 if srv.Routes != nil {
346 err := srv.Routes.ProvisionHandlers(ctx, app.Metrics)
347 if err != nil {
348 return fmt.Errorf("server %s: setting up route handlers: %v", srvName, err)
349 }
350 primaryRoute = srv.Routes.Compile(emptyHandler)
351 }
352 srv.primaryHandlerChain = srv.wrapPrimaryRoute(primaryRoute)
353
354 // pre-compile the error handler chain
355 if srv.Errors != nil {
356 err := srv.Errors.Routes.Provision(ctx)
357 if err != nil {
358 return fmt.Errorf("server %s: setting up error handling routes: %v", srvName, err)
359 }
360 srv.errorHandlerChain = srv.Errors.Routes.Compile(errorEmptyHandler)
361 }
362
363 // provision the named routes (they get compiled at runtime)
364 for name, route := range srv.NamedRoutes {
365 err := route.Provision(ctx, app.Metrics)
366 if err != nil {
367 return fmt.Errorf("server %s: setting up named route '%s' handlers: %v", name, srvName, err)
368 }
369 }
370
371 // prepare the TLS connection policies
372 err = srv.TLSConnPolicies.Provision(ctx)
373 if err != nil {
374 return fmt.Errorf("server %s: setting up TLS connection policies: %v", srvName, err)
375 }
376
377 // if there is no idle timeout, set a sane default; users have complained
378 // before that aggressive CDNs leave connections open until the server
379 // closes them, so if we don't close them it leads to resource exhaustion
380 if srv.IdleTimeout == 0 {
381 srv.IdleTimeout = defaultIdleTimeout
382 }
383 if srv.ReadHeaderTimeout == 0 {
384 srv.ReadHeaderTimeout = defaultReadHeaderTimeout // see #6663
385 }
386 }
387 ctx.Context = oldContext
388 return nil
389 }
390
391 // Validate ensures the app's configuration is valid.
392 func (app *App) Validate() error {
393 lnAddrs := make(map[string]string)
394
395 for srvName, srv := range app.Servers {
396 // each server must use distinct listener addresses
397 for _, addr := range srv.Listen {
398 listenAddr, err := caddy.ParseNetworkAddress(addr)
399 if err != nil {
400 return fmt.Errorf("invalid listener address '%s': %v", addr, err)
401 }
402 // check that every address in the port range is unique to this server;
403 // we do not use <= here because PortRangeSize() adds 1 to EndPort for us
404 for i := uint(0); i < listenAddr.PortRangeSize(); i++ {
405 addr := caddy.JoinNetworkAddress(listenAddr.Network, listenAddr.Host, strconv.FormatUint(uint64(listenAddr.StartPort+i), 10))
406 if sn, ok := lnAddrs[addr]; ok {
407 return fmt.Errorf("server %s: listener address repeated: %s (already claimed by server '%s')", srvName, addr, sn)
408 }
409 lnAddrs[addr] = srvName
410 }
411 }
412
413 // logger names must not have ports
414 if srv.Logs != nil {
415 for host := range srv.Logs.LoggerNames {
416 if _, _, err := net.SplitHostPort(host); err == nil {
417 return fmt.Errorf("server %s: logger name must not have a port: %s", srvName, host)
418 }
419 }
420 }
421 }
422 return nil
423 }
424
425 func removeTLSALPN(srv *Server, target string) {
426 for _, cp := range srv.TLSConnPolicies {
427 // the TLSConfig was already provisioned, so... manually remove it
428 for i, np := range cp.TLSConfig.NextProtos {
429 if np == target {
430 cp.TLSConfig.NextProtos = append(cp.TLSConfig.NextProtos[:i], cp.TLSConfig.NextProtos[i+1:]...)
431 break
432 }
433 }
434 // remove it from the parent connection policy too, just to keep things tidy
435 for i, alpn := range cp.ALPN {
436 if alpn == target {
437 cp.ALPN = append(cp.ALPN[:i], cp.ALPN[i+1:]...)
438 break
439 }
440 }
441 }
442 }
443
444 // Start runs the app. It finishes automatic HTTPS if enabled,
445 // including management of certificates.
446 func (app *App) Start() error {
447 // get a logger compatible with http.Server
448 serverLogger, err := zap.NewStdLogAt(app.logger.Named("stdlib"), zap.DebugLevel)
449 if err != nil {
450 return fmt.Errorf("failed to set up server logger: %v", err)
451 }
452
453 for srvName, srv := range app.Servers {
454 srv.server = &http.Server{
455 ReadTimeout: time.Duration(srv.ReadTimeout),
456 ReadHeaderTimeout: time.Duration(srv.ReadHeaderTimeout),
457 WriteTimeout: time.Duration(srv.WriteTimeout),
458 IdleTimeout: time.Duration(srv.IdleTimeout),
459 MaxHeaderBytes: srv.MaxHeaderBytes,
460 Handler: srv,
461 ErrorLog: serverLogger,
462 Protocols: new(http.Protocols),
463 ConnContext: func(ctx context.Context, c net.Conn) context.Context {
464 if nc, ok := c.(interface{ tlsNetConn() net.Conn }); ok {
465 getTlsConStateFunc := sync.OnceValue(func() *tls.ConnectionState {
466 tlsConnState := nc.tlsNetConn().(connectionStater).ConnectionState()
467 return &tlsConnState
468 })
469 ctx = context.WithValue(ctx, tlsConnectionStateFuncCtxKey, getTlsConStateFunc)
470 }
471 return ctx
472 },
473 }
474
475 // disable HTTP/2, which we enabled by default during provisioning
476 if !srv.protocol("h2") {
477 srv.server.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
478 removeTLSALPN(srv, "h2")
479 }
480 if !srv.protocol("h1") {
481 removeTLSALPN(srv, "http/1.1")
482 }
483
484 // configure the http versions the server will serve
485 if srv.protocol("h1") {
486 srv.server.Protocols.SetHTTP1(true)
487 }
488
489 if srv.protocol("h2") || srv.protocol("h2c") {
490 // skip setting h2 because if NextProtos is present, it's list of alpn versions will take precedence.
491 // it will always be present because http2.ConfigureServer will populate that field
492 // enabling h2c because some listener wrapper will wrap the connection that is no longer *tls.Conn
493 // However, we need to handle the case that if the connection is h2c but h2c is not enabled. We identify
494 // this type of connection by checking if it's behind a TLS listener wrapper or if it implements tls.ConnectionState.
495 srv.server.Protocols.SetUnencryptedHTTP2(true)
496 // when h2c is enabled but h2 disabled, we already removed h2 from NextProtos
497 // the handshake will never succeed with h2
498 // http2.ConfigureServer will enable the server to handle both h2 and h2c
499 h2server := new(http2.Server)
500 //nolint:errcheck
501 http2.ConfigureServer(srv.server, h2server)
502 }
503
504 // this TLS config is used by the std lib to choose the actual TLS config for connections
505 // by looking through the connection policies to find the first one that matches
506 tlsCfg := srv.TLSConnPolicies.TLSConfig(app.ctx)
507 srv.configureServer(srv.server)
508
509 for lnIndex, lnAddr := range srv.Listen {
510 listenAddr, err := caddy.ParseNetworkAddress(lnAddr)
511 if err != nil {
512 return fmt.Errorf("%s: parsing listen address '%s': %v", srvName, lnAddr, err)
513 }
514
515 srv.addresses = append(srv.addresses, listenAddr)
516
517 protocols := srv.Protocols
518 if srv.ListenProtocols != nil && srv.ListenProtocols[lnIndex] != nil {
519 protocols = srv.ListenProtocols[lnIndex]
520 }
521
522 protocolsUnique := map[string]struct{}{}
523 for _, protocol := range protocols {
524 protocolsUnique[protocol] = struct{}{}
525 }
526 _, h1ok := protocolsUnique["h1"]
527 _, h2ok := protocolsUnique["h2"]
528 _, h2cok := protocolsUnique["h2c"]
529 _, h3ok := protocolsUnique["h3"]
530
531 for portOffset := uint(0); portOffset < listenAddr.PortRangeSize(); portOffset++ {
532 hostport := listenAddr.JoinHostPort(portOffset)
533
534 // enable TLS if there is a policy and if this is not the HTTP port
535 useTLS := len(srv.TLSConnPolicies) > 0 && int(listenAddr.StartPort+portOffset) != app.httpPort()
536
537 if h1ok || h2ok && useTLS || h2cok {
538 // create the listener for this socket
539 lnAny, err := listenAddr.Listen(app.ctx, portOffset, net.ListenConfig{
540 KeepAliveConfig: net.KeepAliveConfig{
541 Enable: srv.KeepAliveInterval >= 0,
542 Interval: time.Duration(srv.KeepAliveInterval),
543 Idle: time.Duration(srv.KeepAliveIdle),
544 Count: srv.KeepAliveCount,
545 },
546 })
547 if err != nil {
548 return fmt.Errorf("listening on %s: %v", listenAddr.At(portOffset), err)
549 }
550 ln, ok := lnAny.(net.Listener)
551 if !ok {
552 return fmt.Errorf("network '%s' cannot handle HTTP/1 or HTTP/2 connections", listenAddr.Network)
553 }
554
555 // wrap listener before TLS (up to the TLS placeholder wrapper)
556 var lnWrapperIdx int
557 for i, lnWrapper := range srv.listenerWrappers {
558 if _, ok := lnWrapper.(*tlsPlaceholderWrapper); ok {
559 lnWrapperIdx = i + 1 // mark the next wrapper's spot
560 break
561 }
562 ln = lnWrapper.WrapListener(ln)
563 }
564
565 if useTLS {
566 // create TLS listener - this enables and terminates TLS
567 ln = tls.NewListener(ln, tlsCfg)
568 }
569
570 // finish wrapping listener where we left off before TLS
571 for i := lnWrapperIdx; i < len(srv.listenerWrappers); i++ {
572 ln = srv.listenerWrappers[i].WrapListener(ln)
573 }
574
575 // check if the connection is h2c
576 ln = &http2Listener{
577 useTLS: useTLS,
578 useH1: h1ok,
579 useH2: h2ok || h2cok,
580 Listener: ln,
581 logger: app.logger,
582 }
583
584 // if binding to port 0, the OS chooses a port for us;
585 // but the user won't know the port unless we print it
586 if !listenAddr.IsUnixNetwork() && !listenAddr.IsFdNetwork() && listenAddr.StartPort == 0 && listenAddr.EndPort == 0 {
587 app.logger.Info("port 0 listener",
588 zap.String("input_address", lnAddr),
589 zap.String("actual_address", ln.Addr().String()))
590 }
591
592 app.logger.Debug("starting server loop",
593 zap.String("address", ln.Addr().String()),
594 zap.Bool("tls", useTLS),
595 zap.Bool("http3", srv.h3server != nil))
596
597 srv.listeners = append(srv.listeners, ln)
598
599 //nolint:errcheck
600 go srv.server.Serve(ln)
601 }
602
603 if h2ok && !useTLS {
604 // Can only serve h2 with TLS enabled
605 app.logger.Warn("HTTP/2 skipped because it requires TLS",
606 zap.String("network", listenAddr.Network),
607 zap.String("addr", hostport))
608 }
609
610 if h3ok {
611 // Can't serve HTTP/3 on the same socket as HTTP/1 and 2 because it uses
612 // a different transport mechanism... which is fine, but the OS doesn't
613 // differentiate between a SOCK_STREAM file and a SOCK_DGRAM file; they
614 // are still one file on the system. So even though "unixpacket" and
615 // "unixgram" are different network types just as "tcp" and "udp" are,
616 // the OS will not let us use the same file as both STREAM and DGRAM.
617 if listenAddr.IsUnixNetwork() {
618 app.logger.Warn("HTTP/3 disabled because Unix can't multiplex STREAM and DGRAM on same socket",
619 zap.String("file", hostport))
620 continue
621 }
622
623 if useTLS {
624 // enable HTTP/3 if configured
625 app.logger.Info("enabling HTTP/3 listener", zap.String("addr", hostport))
626 if err := srv.serveHTTP3(listenAddr.At(portOffset), tlsCfg); err != nil {
627 return err
628 }
629 } else {
630 // Can only serve h3 with TLS enabled
631 app.logger.Warn("HTTP/3 skipped because it requires TLS",
632 zap.String("network", listenAddr.Network),
633 zap.String("addr", hostport))
634 }
635 }
636 }
637 }
638
639 srv.logger.Info("server running",
640 zap.String("name", srvName),
641 zap.Strings("protocols", srv.Protocols))
642 }
643
644 // finish automatic HTTPS by finally beginning
645 // certificate management
646 err = app.automaticHTTPSPhase2()
647 if err != nil {
648 return fmt.Errorf("finalizing automatic HTTPS: %v", err)
649 }
650
651 return nil
652 }
653
654 // Stop gracefully shuts down the HTTP server.
655 func (app *App) Stop() error {
656 ctx := context.Background()
657
658 // see if any listeners in our config will be closing or if they are continuing
659 // through a reload; because if any are closing, we will enforce shutdown delay
660 var delay bool
661 scheduledTime := time.Now().Add(time.Duration(app.ShutdownDelay))
662 if app.ShutdownDelay > 0 {
663 for _, server := range app.Servers {
664 for _, na := range server.addresses {
665 for _, addr := range na.Expand() {
666 if caddy.ListenerUsage(addr.Network, addr.JoinHostPort(0)) < 2 {
667 app.logger.Debug("listener closing and shutdown delay is configured", zap.String("address", addr.String()))
668 server.shutdownAt.Store(&scheduledTime)
669 delay = true
670 } else {
671 app.logger.Debug("shutdown delay configured but listener will remain open", zap.String("address", addr.String()))
672 }
673 }
674 }
675 }
676 }
677
678 // honor scheduled/delayed shutdown time
679 if delay {
680 app.logger.Info("shutdown scheduled",
681 zap.Duration("delay_duration", time.Duration(app.ShutdownDelay)),
682 zap.Time("time", scheduledTime))
683 time.Sleep(time.Duration(app.ShutdownDelay))
684 }
685
686 // enforce grace period if configured
687 if app.GracePeriod > 0 {
688 var cancel context.CancelFunc
689 timeout := time.Duration(app.GracePeriod)
690 ctx, cancel = context.WithTimeoutCause(ctx, timeout, fmt.Errorf("server graceful shutdown %ds timeout", int(timeout.Seconds())))
691 defer cancel()
692 app.logger.Info("servers shutting down; grace period initiated", zap.Duration("duration", timeout))
693 } else {
694 app.logger.Info("servers shutting down with eternal grace period")
695 }
696
697 // goroutines aren't guaranteed to be scheduled right away,
698 // so we'll use one WaitGroup to wait for all the goroutines
699 // to start their server shutdowns, and another to wait for
700 // them to finish; we'll always block for them to start so
701 // that when we return the caller can be confident* that the
702 // old servers are no longer accepting new connections
703 // (* the scheduler might still pause them right before
704 // calling Shutdown(), but it's unlikely)
705 var startedShutdown, finishedShutdown sync.WaitGroup
706
707 // these will run in goroutines
708 stopServer := func(server *Server) {
709 defer finishedShutdown.Done()
710 startedShutdown.Done()
711
712 // possible if server failed to Start
713 if server.server == nil {
714 return
715 }
716
717 if err := server.server.Shutdown(ctx); err != nil {
718 if cause := context.Cause(ctx); cause != nil && errors.Is(err, context.DeadlineExceeded) {
719 err = cause
720 }
721 app.logger.Error("server shutdown",
722 zap.Error(err),
723 zap.Strings("addresses", server.Listen))
724 }
725 }
726 stopH3Server := func(server *Server) {
727 defer finishedShutdown.Done()
728 startedShutdown.Done()
729
730 if server.h3server == nil {
731 return
732 }
733
734 // closing quic listeners won't affect accepted connections now
735 // so like stdlib, close listeners first, but keep the net.PacketConns open
736 for _, h3ln := range server.quicListeners {
737 if err := h3ln.Close(); err != nil {
738 app.logger.Error("http3 listener close",
739 zap.Error(err))
740 }
741 }
742
743 if err := server.h3server.Shutdown(ctx); err != nil {
744 if cause := context.Cause(ctx); cause != nil && errors.Is(err, context.DeadlineExceeded) {
745 err = cause
746 }
747 app.logger.Error("HTTP/3 server shutdown",
748 zap.Error(err),
749 zap.Strings("addresses", server.Listen))
750 }
751
752 // close the underlying net.PacketConns now
753 // see the comment for ListenQUIC
754 for _, h3ln := range server.quicListeners {
755 if err := h3ln.Close(); err != nil {
756 app.logger.Error("http3 listener close socket",
757 zap.Error(err))
758 }
759 }
760 }
761
762 for _, server := range app.Servers {
763 startedShutdown.Add(2)
764 finishedShutdown.Add(2)
765 go stopServer(server)
766 go stopH3Server(server)
767 }
768
769 // block until all the goroutines have been run by the scheduler;
770 // this means that they have likely called Shutdown() by now
771 startedShutdown.Wait()
772
773 // if the process is exiting, we need to block here and wait
774 // for the grace periods to complete, otherwise the process will
775 // terminate before the servers are finished shutting down; but
776 // we don't really need to wait for the grace period to finish
777 // if the process isn't exiting (but note that frequent config
778 // reloads with long grace periods for a sustained length of time
779 // may deplete resources)
780 if caddy.Exiting() {
781 finishedShutdown.Wait()
782 }
783
784 // run stop callbacks now that the server shutdowns are complete
785 for name, s := range app.Servers {
786 for _, stopHook := range s.onStopFuncs {
787 if err := stopHook(ctx); err != nil {
788 app.logger.Error("server stop hook", zap.String("server", name), zap.Error(err))
789 }
790 }
791 }
792
793 // flush and shut down the OTLP metrics exporter (if configured) so any
794 // last data point reaches the collector before the process exits
795 if err := app.Metrics.shutdown(ctx); err != nil {
796 app.logger.Error("shutting down OTLP metrics", zap.Error(err))
797 }
798
799 app.stopped = true
800 return nil
801 }
802
803 // Cleanup will close remaining listeners if they still remain
804 // because some of the servers fail to start.
805 // It simply calls Stop because Stop won't be called when Start fails.
806 func (app *App) Cleanup() error {
807 if app.stopped {
808 return nil
809 }
810 return app.Stop()
811 }
812
813 func (app *App) httpPort() int {
814 if app.HTTPPort == 0 {
815 return DefaultHTTPPort
816 }
817 return app.HTTPPort
818 }
819
820 func (app *App) httpsPort() int {
821 if app.HTTPSPort == 0 {
822 return DefaultHTTPSPort
823 }
824 return app.HTTPSPort
825 }
826
827 const (
828 // defaultIdleTimeout is the default HTTP server timeout
829 // for closing idle connections; useful to avoid resource
830 // exhaustion behind hungry CDNs, for example (we've had
831 // several complaints without this).
832 defaultIdleTimeout = caddy.Duration(5 * time.Minute)
833
834 // defaultReadHeaderTimeout is the default timeout for
835 // reading HTTP headers from clients. Headers are generally
836 // small, often less than 1 KB, so it shouldn't take a
837 // long time even on legitimately slow connections or
838 // busy servers to read it.
839 defaultReadHeaderTimeout = caddy.Duration(time.Minute)
840 )
841
842 // Interface guards
843 var (
844 _ caddy.App = (*App)(nil)
845 _ caddy.Provisioner = (*App)(nil)
846 _ caddy.Validator = (*App)(nil)
847 )