Debian Codegraph @

listeners.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 caddy
16
17 import (
18 "context"
19 "crypto/tls"
20 "errors"
21 "fmt"
22 "io"
23 "io/fs"
24 "net"
25 "net/netip"
26 "os"
27 "strconv"
28 "strings"
29 "sync"
30 "sync/atomic"
31
32 "github.com/quic-go/quic-go"
33 "github.com/quic-go/quic-go/http3"
34 h3qlog "github.com/quic-go/quic-go/http3/qlog"
35 "go.uber.org/zap"
36 "golang.org/x/time/rate"
37
38 "github.com/caddyserver/caddy/v2/internal"
39 )
40
41 // NetworkAddress represents one or more network addresses.
42 // It contains the individual components for a parsed network
43 // address of the form accepted by ParseNetworkAddress().
44 type NetworkAddress struct {
45 // Should be a network value accepted by Go's net package or
46 // by a plugin providing a listener for that network type.
47 Network string
48
49 // The "main" part of the network address is the host, which
50 // often takes the form of a hostname, DNS name, IP address,
51 // or socket path.
52 Host string
53
54 // For addresses that contain a port, ranges are given by
55 // [StartPort, EndPort]; i.e. for a single port, StartPort
56 // and EndPort are the same. For no port, they are 0.
57 StartPort uint
58 EndPort uint
59 }
60
61 // ListenAll calls Listen for all addresses represented by this struct, i.e. all ports in the range.
62 // (If the address doesn't use ports or has 1 port only, then only 1 listener will be created.)
63 // It returns an error if any listener failed to bind, and closes any listeners opened up to that point.
64 func (na NetworkAddress) ListenAll(ctx context.Context, config net.ListenConfig) ([]any, error) {
65 var listeners []any
66 var err error
67
68 // if one of the addresses has a failure, we need to close
69 // any that did open a socket to avoid leaking resources
70 defer func() {
71 if err == nil {
72 return
73 }
74 for _, ln := range listeners {
75 if cl, ok := ln.(io.Closer); ok {
76 cl.Close()
77 }
78 }
79 }()
80
81 // an address can contain a port range, which represents multiple addresses;
82 // some addresses don't use ports at all and have a port range size of 1;
83 // whatever the case, iterate each address represented and bind a socket
84 for portOffset := uint(0); portOffset < na.PortRangeSize(); portOffset++ {
85 select {
86 case <-ctx.Done():
87 return nil, ctx.Err()
88 default:
89 }
90
91 // create (or reuse) the listener ourselves
92 var ln any
93 ln, err = na.Listen(ctx, portOffset, config)
94 if err != nil {
95 return nil, err
96 }
97 listeners = append(listeners, ln)
98 }
99
100 return listeners, nil
101 }
102
103 // Listen is similar to net.Listen, with a few differences:
104 //
105 // Listen announces on the network address using the port calculated by adding
106 // portOffset to the start port. (For network types that do not use ports, the
107 // portOffset is ignored.)
108 //
109 // First Listen checks if a plugin can provide a listener from this address. Otherwise,
110 // the provided ListenConfig is used to create the listener. Its Control function,
111 // if set, may be wrapped by an internally-used Control function. The provided
112 // context may be used to cancel long operations early. The context is not used
113 // to close the listener after it has been created.
114 //
115 // Caddy's listeners can overlap each other: multiple listeners may be created on
116 // the same socket at the same time. This is useful because during config changes,
117 // the new config is started while the old config is still running. How this is
118 // accomplished varies by platform and network type. For example, on Unix, SO_REUSEPORT
119 // is set except on Unix sockets, for which the file descriptor is duplicated and
120 // reused; on Windows, the close logic is virtualized using timeouts. Like normal
121 // listeners, be sure to Close() them when you are done.
122 //
123 // This method returns any type, as the implementations of listeners for various
124 // network types are not interchangeable. The type of listener returned is switched
125 // on the network type. Stream-based networks ("tcp", "unix", "unixpacket", etc.)
126 // return a net.Listener; datagram-based networks ("udp", "unixgram", etc.) return
127 // a net.PacketConn; and so forth. The actual concrete types are not guaranteed to
128 // be standard, exported types (wrapping is necessary to provide graceful reloads).
129 //
130 // Unix sockets will be unlinked before being created, to ensure we can bind to
131 // it even if the previous program using it exited uncleanly; it will also be
132 // unlinked upon a graceful exit (or when a new config does not use that socket).
133 // Listen synchronizes binds to unix domain sockets to avoid race conditions
134 // while an existing socket is unlinked.
135 func (na NetworkAddress) Listen(ctx context.Context, portOffset uint, config net.ListenConfig) (any, error) {
136 if na.IsUnixNetwork() {
137 unixSocketsMu.Lock()
138 defer unixSocketsMu.Unlock()
139 }
140
141 // check to see if plugin provides listener
142 if ln, err := getListenerFromPlugin(ctx, na.Network, na.Host, na.port(), portOffset, config); ln != nil || err != nil {
143 return ln, err
144 }
145
146 // create (or reuse) the listener ourselves
147 return na.listen(ctx, portOffset, config)
148 }
149
150 func (na NetworkAddress) listen(ctx context.Context, portOffset uint, config net.ListenConfig) (any, error) {
151 var (
152 ln any
153 err error
154 address string
155 unixFileMode fs.FileMode
156 )
157
158 // split unix socket addr early so lnKey
159 // is independent of permissions bits
160 if na.IsUnixNetwork() {
161 address, unixFileMode, err = internal.SplitUnixSocketPermissionsBits(na.Host)
162 if err != nil {
163 return nil, err
164 }
165 } else if na.IsFdNetwork() {
166 address = na.Host
167 } else {
168 address = na.JoinHostPort(portOffset)
169 }
170
171 if strings.HasPrefix(na.Network, "ip") {
172 ln, err = config.ListenPacket(ctx, na.Network, address)
173 } else {
174 if na.IsUnixNetwork() {
175 // if this is a unix socket, see if we already have it open
176 ln, err = reuseUnixSocket(na.Network, address)
177 }
178
179 if ln == nil && err == nil {
180 // otherwise, create a new listener
181 lnKey := listenerKey(na.Network, address)
182 ln, err = listenReusable(ctx, lnKey, na.Network, address, config)
183 }
184 }
185
186 if err != nil {
187 return nil, err
188 }
189
190 if ln == nil {
191 return nil, fmt.Errorf("unsupported network type: %s", na.Network)
192 }
193
194 if IsUnixNetwork(na.Network) {
195 isAbstractUnixSocket := strings.HasPrefix(address, "@")
196 if !isAbstractUnixSocket {
197 err = os.Chmod(address, unixFileMode)
198 if err != nil {
199 return nil, fmt.Errorf("unable to set permissions (%s) on %s: %v", unixFileMode, address, err)
200 }
201 }
202 }
203
204 return ln, nil
205 }
206
207 // IsUnixNetwork returns true if na.Network is
208 // unix, unixgram, or unixpacket.
209 func (na NetworkAddress) IsUnixNetwork() bool {
210 return IsUnixNetwork(na.Network)
211 }
212
213 // IsFdNetwork returns true if na.Network is
214 // fd or fdgram.
215 func (na NetworkAddress) IsFdNetwork() bool {
216 return IsFdNetwork(na.Network)
217 }
218
219 // JoinHostPort is like net.JoinHostPort, but where the port
220 // is StartPort + offset.
221 func (na NetworkAddress) JoinHostPort(offset uint) string {
222 if na.IsUnixNetwork() || na.IsFdNetwork() {
223 return na.Host
224 }
225 return net.JoinHostPort(na.Host, strconv.FormatUint(uint64(na.StartPort+offset), 10))
226 }
227
228 // Expand returns one NetworkAddress for each port in the port range.
229 func (na NetworkAddress) Expand() []NetworkAddress {
230 size := na.PortRangeSize()
231 addrs := make([]NetworkAddress, size)
232 for portOffset := range size {
233 addrs[portOffset] = na.At(portOffset)
234 }
235 return addrs
236 }
237
238 // At returns a NetworkAddress with a port range of just 1
239 // at the given port offset; i.e. a NetworkAddress that
240 // represents precisely 1 address only.
241 func (na NetworkAddress) At(portOffset uint) NetworkAddress {
242 na2 := na
243 na2.StartPort, na2.EndPort = na.StartPort+portOffset, na.StartPort+portOffset
244 return na2
245 }
246
247 // PortRangeSize returns how many ports are in
248 // pa's port range. Port ranges are inclusive,
249 // so the size is the difference of start and
250 // end ports plus one.
251 func (na NetworkAddress) PortRangeSize() uint {
252 if na.EndPort < na.StartPort {
253 return 0
254 }
255 return (na.EndPort - na.StartPort) + 1
256 }
257
258 func (na NetworkAddress) isLoopback() bool {
259 if na.IsUnixNetwork() || na.IsFdNetwork() {
260 return true
261 }
262 if na.Host == "localhost" {
263 return true
264 }
265 if ip, err := netip.ParseAddr(na.Host); err == nil {
266 return ip.IsLoopback()
267 }
268 return false
269 }
270
271 func (na NetworkAddress) isWildcardInterface() bool {
272 if na.Host == "" {
273 return true
274 }
275 if ip, err := netip.ParseAddr(na.Host); err == nil {
276 return ip.IsUnspecified()
277 }
278 return false
279 }
280
281 func (na NetworkAddress) port() string {
282 if na.StartPort == na.EndPort {
283 return strconv.FormatUint(uint64(na.StartPort), 10)
284 }
285 return fmt.Sprintf("%d-%d", na.StartPort, na.EndPort)
286 }
287
288 // String reconstructs the address string for human display.
289 // The output can be parsed by ParseNetworkAddress(). If the
290 // address is a unix socket, any non-zero port will be dropped.
291 func (na NetworkAddress) String() string {
292 if na.Network == "tcp" && (na.Host != "" || na.port() != "") {
293 na.Network = "" // omit default network value for brevity
294 }
295 return JoinNetworkAddress(na.Network, na.Host, na.port())
296 }
297
298 // IsUnixNetwork returns true if the netw is a unix network.
299 func IsUnixNetwork(netw string) bool {
300 return strings.HasPrefix(netw, "unix")
301 }
302
303 // IsFdNetwork returns true if the netw is a fd network.
304 func IsFdNetwork(netw string) bool {
305 return strings.HasPrefix(netw, "fd")
306 }
307
308 // ParseNetworkAddress parses addr into its individual
309 // components. The input string is expected to be of
310 // the form "network/host:port-range" where any part is
311 // optional. The default network, if unspecified, is tcp.
312 // Port ranges are inclusive.
313 //
314 // Network addresses are distinct from URLs and do not
315 // use URL syntax.
316 func ParseNetworkAddress(addr string) (NetworkAddress, error) {
317 return ParseNetworkAddressWithDefaults(addr, "tcp", 0)
318 }
319
320 // ParseNetworkAddressWithDefaults is like ParseNetworkAddress but allows
321 // the default network and port to be specified.
322 func ParseNetworkAddressWithDefaults(addr, defaultNetwork string, defaultPort uint) (NetworkAddress, error) {
323 var host, port string
324 network, host, port, err := SplitNetworkAddress(addr)
325 if err != nil {
326 return NetworkAddress{}, err
327 }
328 if network == "" {
329 network = defaultNetwork
330 }
331 if IsUnixNetwork(network) {
332 _, _, err := internal.SplitUnixSocketPermissionsBits(host)
333 return NetworkAddress{
334 Network: network,
335 Host: host,
336 }, err
337 }
338 if IsFdNetwork(network) {
339 return NetworkAddress{
340 Network: network,
341 Host: host,
342 }, nil
343 }
344 var start, end uint64
345 if port == "" {
346 start = uint64(defaultPort)
347 end = uint64(defaultPort)
348 } else {
349 before, after, found := strings.Cut(port, "-")
350 if !found {
351 after = before
352 }
353 start, err = strconv.ParseUint(before, 10, 16)
354 if err != nil {
355 return NetworkAddress{}, fmt.Errorf("invalid start port: %v", err)
356 }
357 end, err = strconv.ParseUint(after, 10, 16)
358 if err != nil {
359 return NetworkAddress{}, fmt.Errorf("invalid end port: %v", err)
360 }
361 if end < start {
362 return NetworkAddress{}, fmt.Errorf("end port must not be less than start port")
363 }
364 if (end - start) > maxPortSpan {
365 return NetworkAddress{}, fmt.Errorf("port range exceeds %d ports", maxPortSpan)
366 }
367 }
368 return NetworkAddress{
369 Network: network,
370 Host: host,
371 StartPort: uint(start),
372 EndPort: uint(end),
373 }, nil
374 }
375
376 // SplitNetworkAddress splits a into its network, host, and port components.
377 // Note that port may be a port range (:X-Y), or omitted for unix sockets.
378 func SplitNetworkAddress(a string) (network, host, port string, err error) {
379 beforeSlash, afterSlash, slashFound := strings.Cut(a, "/")
380 if slashFound {
381 network = strings.ToLower(strings.TrimSpace(beforeSlash))
382 a = afterSlash
383 if IsUnixNetwork(network) || IsFdNetwork(network) {
384 host = a
385 return network, host, port, err
386 }
387 }
388
389 host, port, err = net.SplitHostPort(a)
390 firstErr := err
391
392 if err != nil {
393 // in general, if there was an error, it was likely "missing port",
394 // so try removing square brackets around an IPv6 host, adding a bogus
395 // port to take advantage of standard library's robust parser, then
396 // strip the artificial port.
397 host, _, err = net.SplitHostPort(net.JoinHostPort(strings.Trim(a, "[]"), "0"))
398 port = ""
399 }
400
401 if err != nil {
402 err = errors.Join(firstErr, err)
403 }
404
405 return network, host, port, err
406 }
407
408 // JoinNetworkAddress combines network, host, and port into a single
409 // address string of the form accepted by ParseNetworkAddress(). For
410 // unix sockets, the network should be "unix" (or "unixgram" or
411 // "unixpacket") and the path to the socket should be given as the
412 // host parameter.
413 func JoinNetworkAddress(network, host, port string) string {
414 var a string
415 if network != "" {
416 a = network + "/"
417 }
418 if (host != "" && port == "") || IsUnixNetwork(network) || IsFdNetwork(network) {
419 a += host
420 } else if port != "" {
421 a += net.JoinHostPort(host, port)
422 }
423 return a
424 }
425
426 // ListenQUIC returns a http3.QUICEarlyListener suitable for use in a Caddy module.
427 //
428 // The network will be transformed into a QUIC-compatible type if the same address can be used with
429 // different networks. Currently this just means that for tcp, udp will be used with the same
430 // address instead.
431 //
432 // NOTE: This API is EXPERIMENTAL and may be changed or removed.
433 // NOTE: user should close the returned listener twice, once to stop accepting new connections, the second time to free up the packet conn.
434 func (na NetworkAddress) ListenQUIC(ctx context.Context, portOffset uint, config net.ListenConfig, tlsConf *tls.Config, pcWrappers []PacketConnWrapper, allow0rttconf *bool) (http3.QUICListener, error) {
435 lnKey := listenerKey("quic"+na.Network, na.JoinHostPort(portOffset))
436
437 sharedEarlyListener, _, err := listenerPool.LoadOrNew(lnKey, func() (Destructor, error) {
438 lnAny, err := na.Listen(ctx, portOffset, config)
439 if err != nil {
440 return nil, err
441 }
442
443 ln := lnAny.(net.PacketConn)
444
445 h3ln := ln
446 if len(pcWrappers) == 0 {
447 for {
448 // retrieve the underlying socket, so quic-go can optimize.
449 if unwrapper, ok := h3ln.(interface{ Unwrap() net.PacketConn }); ok {
450 h3ln = unwrapper.Unwrap()
451 } else {
452 break
453 }
454 }
455 } else {
456 // wrap packet conn before QUIC
457 for _, pcWrapper := range pcWrappers {
458 h3ln = pcWrapper.WrapPacketConn(h3ln)
459 }
460 }
461
462 sqs := newSharedQUICState(tlsConf)
463 // http3.ConfigureTLSConfig only uses this field and tls App sets this field as well
464 //nolint:gosec
465 quicTlsConfig := &tls.Config{
466 GetConfigForClient: sqs.getConfigForClient,
467 GetEncryptedClientHelloKeys: sqs.getEncryptedClientHelloKeys,
468 }
469 // Require clients to verify their source address when we're handling more than 1000 handshakes per second.
470 // TODO: make tunable?
471 limiter := rate.NewLimiter(1000, 1000)
472 tr := &quic.Transport{
473 Conn: h3ln,
474 VerifySourceAddress: func(addr net.Addr) bool { return !limiter.Allow() },
475 }
476 allow0rtt := true
477 if allow0rttconf != nil {
478 allow0rtt = *allow0rttconf
479 }
480 earlyLn, err := tr.ListenEarly(
481 http3.ConfigureTLSConfig(quicTlsConfig),
482 &quic.Config{
483 Allow0RTT: allow0rtt,
484 Tracer: h3qlog.DefaultConnectionTracer,
485 },
486 )
487 if err != nil {
488 return nil, err
489 }
490 // TODO: figure out when to close the listener and the transport
491 // using the original net.PacketConn to close them properly
492 return &sharedQuicListener{EarlyListener: earlyLn, packetConn: ln, sqs: sqs, key: lnKey}, nil
493 })
494 if err != nil {
495 return nil, err
496 }
497
498 sql := sharedEarlyListener.(*sharedQuicListener)
499 // add current tls.Config to sqs, so GetConfigForClient will always return the latest tls.Config in case of context cancellation
500 ctx, cancel := sql.sqs.addState(tlsConf)
501
502 return &fakeCloseQuicListener{
503 sharedQuicListener: sql,
504 context: ctx,
505 contextCancel: cancel,
506 }, nil
507 }
508
509 // ListenerUsage returns the current usage count of the given listener address.
510 func ListenerUsage(network, addr string) int {
511 count, _ := listenerPool.References(listenerKey(network, addr))
512 return count
513 }
514
515 // contextAndCancelFunc groups context and its cancelFunc
516 type contextAndCancelFunc struct {
517 context.Context
518 context.CancelCauseFunc
519 }
520
521 // sharedQUICState manages GetConfigForClient
522 // see issue: https://github.com/caddyserver/caddy/pull/4849
523 type sharedQUICState struct {
524 rmu sync.RWMutex
525 tlsConfs map[*tls.Config]contextAndCancelFunc
526 activeTlsConf *tls.Config
527 }
528
529 // newSharedQUICState creates a new sharedQUICState
530 func newSharedQUICState(tlsConfig *tls.Config) *sharedQUICState {
531 sqtc := &sharedQUICState{
532 tlsConfs: make(map[*tls.Config]contextAndCancelFunc),
533 activeTlsConf: tlsConfig,
534 }
535 sqtc.addState(tlsConfig)
536 return sqtc
537 }
538
539 // getConfigForClient is used as tls.Config's GetConfigForClient field
540 func (sqs *sharedQUICState) getConfigForClient(ch *tls.ClientHelloInfo) (*tls.Config, error) {
541 sqs.rmu.RLock()
542 defer sqs.rmu.RUnlock()
543 return sqs.activeTlsConf.GetConfigForClient(ch)
544 }
545
546 // getEncryptedClientHelloKeys is used as tls.Config's GetEncryptedClientHelloKeys field.
547 func (sqs *sharedQUICState) getEncryptedClientHelloKeys(ch *tls.ClientHelloInfo) ([]tls.EncryptedClientHelloKey, error) {
548 sqs.rmu.RLock()
549 defer sqs.rmu.RUnlock()
550 if sqs.activeTlsConf.GetEncryptedClientHelloKeys == nil {
551 return nil, nil
552 }
553 return sqs.activeTlsConf.GetEncryptedClientHelloKeys(ch)
554 }
555
556 // addState adds tls.Config and activeRequests to the map if not present and returns the corresponding context and its cancelFunc
557 // so that when cancelled, the active tls.Config will change
558 func (sqs *sharedQUICState) addState(tlsConfig *tls.Config) (context.Context, context.CancelCauseFunc) {
559 sqs.rmu.Lock()
560 defer sqs.rmu.Unlock()
561
562 if cacc, ok := sqs.tlsConfs[tlsConfig]; ok {
563 return cacc.Context, cacc.CancelCauseFunc
564 }
565
566 ctx, cancel := context.WithCancelCause(context.Background())
567 wrappedCancel := func(cause error) {
568 cancel(cause)
569
570 sqs.rmu.Lock()
571 defer sqs.rmu.Unlock()
572
573 delete(sqs.tlsConfs, tlsConfig)
574 if sqs.activeTlsConf == tlsConfig {
575 // select another tls.Config, if there is none,
576 // related sharedQuicListener will be destroyed anyway
577 for tc := range sqs.tlsConfs {
578 sqs.activeTlsConf = tc
579 break
580 }
581 }
582 }
583 sqs.tlsConfs[tlsConfig] = contextAndCancelFunc{ctx, wrappedCancel}
584 // there should be at most 2 tls.Configs
585 if len(sqs.tlsConfs) > 2 {
586 Log().Warn("quic listener tls configs are more than 2", zap.Int("number of configs", len(sqs.tlsConfs)))
587 }
588 return ctx, wrappedCancel
589 }
590
591 // sharedQuicListener is like sharedListener, but for quic.EarlyListeners.
592 type sharedQuicListener struct {
593 *quic.EarlyListener
594 packetConn net.PacketConn // we have to hold these because quic-go won't close listeners it didn't create
595 sqs *sharedQUICState
596 key string
597 }
598
599 // Destruct closes the underlying QUIC listener and its associated net.PacketConn.
600 func (sql *sharedQuicListener) Destruct() error {
601 // close EarlyListener first to stop any operations being done to the net.PacketConn
602 _ = sql.EarlyListener.Close()
603 // then close the net.PacketConn
604 return sql.packetConn.Close()
605 }
606
607 // fakeClosedErr returns an error value that is not temporary
608 // nor a timeout, suitable for making the caller think the
609 // listener is actually closed
610 func fakeClosedErr(l interface{ Addr() net.Addr }) error {
611 return &net.OpError{
612 Op: "accept",
613 Net: l.Addr().Network(),
614 Addr: l.Addr(),
615 Err: errFakeClosed,
616 }
617 }
618
619 // errFakeClosed is the underlying error value returned by
620 // fakeCloseListener.Accept() after Close() has been called,
621 // indicating that it is pretending to be closed so that the
622 // server using it can terminate, while the underlying
623 // socket is actually left open.
624 var errFakeClosed = fmt.Errorf("QUIC listener 'closed' 😉")
625
626 type fakeCloseQuicListener struct {
627 closed atomic.Int32
628 *sharedQuicListener // embedded, so we also become a quic.EarlyListener
629 context context.Context
630 contextCancel context.CancelCauseFunc
631 }
632
633 // Currently Accept ignores the passed context, however a situation where
634 // someone would need a hotswappable QUIC-only (not http3, since it uses context.Background here)
635 // server on which Accept would be called with non-empty contexts
636 // (mind that the default net listeners' Accept doesn't take a context argument)
637 // sounds way too rare for us to sacrifice efficiency here.
638 func (fcql *fakeCloseQuicListener) Accept(_ context.Context) (*quic.Conn, error) {
639 conn, err := fcql.sharedQuicListener.Accept(fcql.context)
640 if err == nil {
641 return conn, nil
642 }
643
644 // if the listener is "closed", return a fake closed error instead
645 if fcql.closed.Load() == 1 && errors.Is(err, context.Canceled) {
646 return nil, fakeClosedErr(fcql)
647 }
648 return nil, err
649 }
650
651 func (fcql *fakeCloseQuicListener) Close() error {
652 if fcql.closed.CompareAndSwap(0, 1) {
653 fcql.contextCancel(errFakeClosed)
654 } else if fcql.closed.CompareAndSwap(1, 2) {
655 _, _ = listenerPool.Delete(fcql.sharedQuicListener.key)
656 }
657 return nil
658 }
659
660 // RegisterNetwork registers a network type with Caddy so that if a listener is
661 // created for that network type, getListener will be invoked to get the listener.
662 // This should be called during init() and will panic if the network type is standard
663 // or reserved, or if it is already registered. EXPERIMENTAL and subject to change.
664 func RegisterNetwork(network string, getListener ListenerFunc) {
665 network = strings.TrimSpace(strings.ToLower(network))
666
667 if network == "tcp" || network == "tcp4" || network == "tcp6" ||
668 network == "udp" || network == "udp4" || network == "udp6" ||
669 network == "unix" || network == "unixpacket" || network == "unixgram" ||
670 strings.HasPrefix(network, "ip:") || strings.HasPrefix(network, "ip4:") || strings.HasPrefix(network, "ip6:") ||
671 network == "fd" || network == "fdgram" {
672 panic("network type " + network + " is reserved")
673 }
674
675 if _, ok := networkTypes[strings.ToLower(network)]; ok {
676 panic("network type " + network + " is already registered")
677 }
678
679 networkTypes[network] = getListener
680 }
681
682 var unixSocketsMu sync.Mutex
683
684 // getListenerFromPlugin returns a listener on the given network and address
685 // if a plugin has registered the network name. It may return (nil, nil) if
686 // no plugin can provide a listener.
687 func getListenerFromPlugin(ctx context.Context, network, host, port string, portOffset uint, config net.ListenConfig) (any, error) {
688 // get listener from plugin if network type is registered
689 if getListener, ok := networkTypes[network]; ok {
690 Log().Debug("getting listener from plugin", zap.String("network", network))
691 return getListener(ctx, network, host, port, portOffset, config)
692 }
693
694 return nil, nil
695 }
696
697 func listenerKey(network, addr string) string {
698 return network + "/" + addr
699 }
700
701 // ListenerFunc is a function that can return a listener given a network and address.
702 // The listeners must be capable of overlapping: with Caddy, new configs are loaded
703 // before old ones are unloaded, so listeners may overlap briefly if the configs
704 // both need the same listener. EXPERIMENTAL and subject to change.
705 type ListenerFunc func(ctx context.Context, network, host, portRange string, portOffset uint, cfg net.ListenConfig) (any, error)
706
707 var networkTypes = map[string]ListenerFunc{}
708
709 // ListenerWrapper is a type that wraps a listener
710 // so it can modify the input listener's methods.
711 // Modules that implement this interface are found
712 // in the caddy.listeners namespace. Usually, to
713 // wrap a listener, you will define your own struct
714 // type that embeds the input listener, then
715 // implement your own methods that you want to wrap,
716 // calling the underlying listener's methods where
717 // appropriate.
718 type ListenerWrapper interface {
719 WrapListener(net.Listener) net.Listener
720 }
721
722 // PacketConnWrapper is a type that wraps a packet conn
723 // so it can modify the input packet conn methods.
724 // Modules that implement this interface are found
725 // in the caddy.packetconns namespace. Usually, to
726 // wrap a packet conn, you will define your own struct
727 // type that embeds the input packet conn, then
728 // implement your own methods that you want to wrap,
729 // calling the underlying packet conn methods where
730 // appropriate.
731 type PacketConnWrapper interface {
732 WrapPacketConn(net.PacketConn) net.PacketConn
733 }
734
735 // listenerPool stores and allows reuse of active listeners.
736 var listenerPool = NewUsagePool()
737
738 const maxPortSpan = 65535