Debian Codegraph @

listen.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 //go:build !unix || solaris
16
17 package caddy
18
19 import (
20 "context"
21 "fmt"
22 "net"
23 "os"
24 "slices"
25 "strconv"
26 "sync"
27 "sync/atomic"
28 "time"
29
30 "go.uber.org/zap"
31 )
32
33 func listenReusable(ctx context.Context, lnKey string, network, address string, config net.ListenConfig) (any, error) {
34 var socketFile *os.File
35
36 fd := slices.Contains([]string{"fd", "fdgram"}, network)
37 if fd {
38 socketFd, err := strconv.ParseUint(address, 0, strconv.IntSize)
39 if err != nil {
40 return nil, fmt.Errorf("invalid file descriptor: %v", err)
41 }
42
43 func() {
44 socketFilesMu.Lock()
45 defer socketFilesMu.Unlock()
46
47 socketFdWide := uintptr(socketFd)
48 var ok bool
49
50 socketFile, ok = socketFiles[socketFdWide]
51
52 if !ok {
53 socketFile = os.NewFile(socketFdWide, lnKey)
54 if socketFile != nil {
55 socketFiles[socketFdWide] = socketFile
56 }
57 }
58 }()
59
60 if socketFile == nil {
61 return nil, fmt.Errorf("invalid socket file descriptor: %d", socketFd)
62 }
63 }
64
65 datagram := slices.Contains([]string{"udp", "udp4", "udp6", "unixgram", "fdgram"}, network)
66 if datagram {
67 sharedPc, _, err := listenerPool.LoadOrNew(lnKey, func() (Destructor, error) {
68 var (
69 pc net.PacketConn
70 err error
71 )
72 if fd {
73 pc, err = net.FilePacketConn(socketFile)
74 } else {
75 pc, err = config.ListenPacket(ctx, network, address)
76 }
77 if err != nil {
78 return nil, err
79 }
80 return &sharedPacketConn{PacketConn: pc, key: lnKey}, nil
81 })
82 if err != nil {
83 return nil, err
84 }
85 return &fakeClosePacketConn{sharedPacketConn: sharedPc.(*sharedPacketConn)}, nil
86 }
87
88 sharedLn, _, err := listenerPool.LoadOrNew(lnKey, func() (Destructor, error) {
89 var (
90 ln net.Listener
91 err error
92 )
93 if fd {
94 ln, err = net.FileListener(socketFile)
95 } else {
96 ln, err = config.Listen(ctx, network, address)
97 }
98 if err != nil {
99 return nil, err
100 }
101 return &sharedListener{Listener: ln, key: lnKey}, nil
102 })
103 if err != nil {
104 return nil, err
105 }
106
107 return &fakeCloseListener{sharedListener: sharedLn.(*sharedListener), keepAliveConfig: config.KeepAliveConfig}, nil
108 }
109
110 // fakeCloseListener is a private wrapper over a listener that
111 // is shared. The state of fakeCloseListener is not shared.
112 // This allows one user of a socket to "close" the listener
113 // while in reality the socket stays open for other users of
114 // the listener. In this way, servers become hot-swappable
115 // while the listener remains running. Listeners should be
116 // re-wrapped in a new fakeCloseListener each time the listener
117 // is reused. This type is atomic and values must not be copied.
118 type fakeCloseListener struct {
119 closed atomic.Bool
120 *sharedListener // embedded, so we also become a net.Listener
121 keepAliveConfig net.KeepAliveConfig
122 }
123
124 type canSetKeepAliveConfig interface {
125 SetKeepAliveConfig(config net.KeepAliveConfig) error
126 }
127
128 func (fcl *fakeCloseListener) Accept() (net.Conn, error) {
129 // if the listener is already "closed", return error
130 if fcl.closed.Load() {
131 return nil, fakeClosedErr(fcl)
132 }
133
134 // call underlying accept
135 conn, err := fcl.sharedListener.Accept()
136 if err == nil {
137 // if 0, do nothing, Go's default is already set
138 // and if the connection allows setting KeepAlive, set it
139 if tconn, ok := conn.(canSetKeepAliveConfig); ok && fcl.keepAliveConfig.Enable {
140 err = tconn.SetKeepAliveConfig(fcl.keepAliveConfig)
141 if err != nil {
142 Log().With(zap.String("server", fcl.sharedListener.key)).Warn("unable to set keepalive for new connection:", zap.Error(err))
143 }
144 }
145 return conn, nil
146 }
147
148 // since Accept() returned an error, it may be because our reference to
149 // the listener (this fakeCloseListener) may have been closed, i.e. the
150 // server is shutting down; in that case, we need to clear the deadline
151 // that we set when Close() was called, and return a non-temporary and
152 // non-timeout error value to the caller, masking the "true" error, so
153 // that server loops / goroutines won't retry, linger, and leak
154 if fcl.closed.Load() {
155 // we dereference the sharedListener explicitly even though it's embedded
156 // so that it's clear in the code that side-effects are shared with other
157 // users of this listener, not just our own reference to it; we also don't
158 // do anything with the error because all we could do is log it, but we
159 // explicitly assign it to nothing so we don't forget it's there if needed
160 _ = fcl.sharedListener.clearDeadline()
161
162 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
163 return nil, fakeClosedErr(fcl)
164 }
165 }
166
167 return nil, err
168 }
169
170 // Close stops accepting new connections without closing the
171 // underlying listener. The underlying listener is only closed
172 // if the caller is the last known user of the socket.
173 func (fcl *fakeCloseListener) Close() error {
174 if fcl.closed.CompareAndSwap(false, true) {
175 // There are two ways I know of to get an Accept()
176 // function to return to the server loop that called
177 // it: close the listener, or set a deadline in the
178 // past. Obviously, we can't close the socket yet
179 // since others may be using it (hence this whole
180 // file). But we can set the deadline in the past,
181 // and this is kind of cheating, but it works, and
182 // it apparently even works on Windows.
183 _ = fcl.sharedListener.setDeadline()
184 _, _ = listenerPool.Delete(fcl.sharedListener.key)
185 }
186 return nil
187 }
188
189 // sharedListener is a wrapper over an underlying listener. The listener
190 // and the other fields on the struct are shared state that is synchronized,
191 // so sharedListener structs must never be copied (always use a pointer).
192 type sharedListener struct {
193 net.Listener
194 key string // uniquely identifies this listener
195 deadline bool // whether a deadline is currently set
196 deadlineMu sync.Mutex
197 }
198
199 func (sl *sharedListener) clearDeadline() error {
200 var err error
201 sl.deadlineMu.Lock()
202 if sl.deadline {
203 switch ln := sl.Listener.(type) {
204 case *net.TCPListener:
205 err = ln.SetDeadline(time.Time{})
206 }
207 sl.deadline = false
208 }
209 sl.deadlineMu.Unlock()
210 return err
211 }
212
213 func (sl *sharedListener) setDeadline() error {
214 timeInPast := time.Now().Add(-1 * time.Minute)
215 var err error
216 sl.deadlineMu.Lock()
217 if !sl.deadline {
218 switch ln := sl.Listener.(type) {
219 case *net.TCPListener:
220 err = ln.SetDeadline(timeInPast)
221 }
222 sl.deadline = true
223 }
224 sl.deadlineMu.Unlock()
225 return err
226 }
227
228 // Destruct is called by the UsagePool when the listener is
229 // finally not being used anymore. It closes the socket.
230 func (sl *sharedListener) Destruct() error {
231 return sl.Listener.Close()
232 }
233
234 // fakeClosePacketConn is like fakeCloseListener, but for PacketConns,
235 // or more specifically, *net.UDPConn
236 type fakeClosePacketConn struct {
237 closed atomic.Bool
238 *sharedPacketConn // embedded, so we also become a net.PacketConn; its key is used in Close
239 }
240
241 func (fcpc *fakeClosePacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
242 // if the listener is already "closed", return error
243 if fcpc.closed.Load() {
244 return 0, nil, &net.OpError{
245 Op: "readfrom",
246 Net: fcpc.LocalAddr().Network(),
247 Addr: fcpc.LocalAddr(),
248 Err: errFakeClosed,
249 }
250 }
251
252 // call underlying readfrom
253 n, addr, err = fcpc.sharedPacketConn.ReadFrom(p)
254 if err != nil {
255 // this server was stopped, so clear the deadline and let
256 // any new server continue reading; but we will exit
257 if fcpc.closed.Load() {
258 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
259 if err = fcpc.SetReadDeadline(time.Time{}); err != nil {
260 return n, addr, err
261 }
262 }
263 }
264 return n, addr, err
265 }
266
267 return n, addr, err
268 }
269
270 // Close won't close the underlying socket unless there is no more reference, then listenerPool will close it.
271 func (fcpc *fakeClosePacketConn) Close() error {
272 if fcpc.closed.CompareAndSwap(false, true) {
273 _ = fcpc.SetReadDeadline(time.Now()) // unblock ReadFrom() calls to kick old servers out of their loops
274 _, _ = listenerPool.Delete(fcpc.sharedPacketConn.key)
275 }
276 return nil
277 }
278
279 func (fcpc *fakeClosePacketConn) Unwrap() net.PacketConn {
280 return fcpc.sharedPacketConn.PacketConn
281 }
282
283 // sharedPacketConn is like sharedListener, but for net.PacketConns.
284 type sharedPacketConn struct {
285 net.PacketConn
286 key string
287 }
288
289 // Destruct closes the underlying socket.
290 func (spc *sharedPacketConn) Destruct() error {
291 return spc.PacketConn.Close()
292 }
293
294 // Unwrap returns the underlying socket
295 func (spc *sharedPacketConn) Unwrap() net.PacketConn {
296 return spc.PacketConn
297 }
298
299 // Interface guards (see https://github.com/caddyserver/caddy/issues/3998)
300 var (
301 _ (interface {
302 Unwrap() net.PacketConn
303 }) = (*fakeClosePacketConn)(nil)
304 )
305
306 // socketFiles is a fd -> *os.File map used to make a FileListener/FilePacketConn from a socket file descriptor.
307 var socketFiles = map[uintptr]*os.File{}
308
309 // socketFilesMu synchronizes socketFiles insertions
310 var socketFilesMu sync.Mutex