Debian Codegraph @

listen_unix.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 // Even though the filename ends in _unix.go, we still have to specify the
16 // build constraint here, because the filename convention only works for
17 // literal GOOS values, and "unix" is a shortcut unique to build tags.
18 //go:build unix && !solaris
19
20 package caddy
21
22 import (
23 "context"
24 "errors"
25 "fmt"
26 "io"
27 "io/fs"
28 "net"
29 "os"
30 "slices"
31 "strconv"
32 "sync"
33 "sync/atomic"
34 "syscall"
35
36 "go.uber.org/zap"
37 "golang.org/x/sys/unix"
38 )
39
40 // reuseUnixSocket copies and reuses the unix domain socket (UDS) if we already
41 // have it open; if not, unlink it so we can have it.
42 // No-op if not a unix network.
43 func reuseUnixSocket(network, addr string) (any, error) {
44 socketKey := listenerKey(network, addr)
45
46 socket, exists := unixSockets[socketKey]
47 if exists {
48 // make copy of file descriptor
49 socketFile, err := socket.File() // does dup() deep down
50 if err != nil {
51 return nil, err
52 }
53
54 // use copied fd to make new Listener or PacketConn, then replace
55 // it in the map so that future copies always come from the most
56 // recent fd (as the previous ones will be closed, and we'd get
57 // "use of closed network connection" errors) -- note that we
58 // preserve the *pointer* to the counter (not just the value) so
59 // that all socket wrappers will refer to the same value
60 switch unixSocket := socket.(type) {
61 case *unixListener:
62 ln, err := net.FileListener(socketFile)
63 if err != nil {
64 return nil, err
65 }
66 unixSocket.count.Add(1)
67 unixSockets[socketKey] = &unixListener{ln.(*net.UnixListener), socketKey, unixSocket.count}
68
69 case *unixConn:
70 pc, err := net.FilePacketConn(socketFile)
71 if err != nil {
72 return nil, err
73 }
74 unixSocket.count.Add(1)
75 unixSockets[socketKey] = &unixConn{pc.(*net.UnixConn), socketKey, unixSocket.count}
76 }
77
78 return unixSockets[socketKey], nil
79 }
80
81 // from what I can tell after some quick research, it's quite common for programs to
82 // leave their socket file behind after they close, so the typical pattern is to
83 // unlink it before you bind to it -- this is often crucial if the last program using
84 // it was killed forcefully without a chance to clean up the socket, but there is a
85 // race, as the comment in net.UnixListener.close() explains... oh well, I guess?
86 if err := syscall.Unlink(addr); err != nil && !errors.Is(err, fs.ErrNotExist) {
87 return nil, err
88 }
89
90 return nil, nil
91 }
92
93 // listenReusable creates a new listener for the given network and address, and adds it to listenerPool.
94 func listenReusable(ctx context.Context, lnKey string, network, address string, config net.ListenConfig) (any, error) {
95 // even though SO_REUSEPORT lets us bind the socket multiple times,
96 // we still put it in the listenerPool so we can count how many
97 // configs are using this socket; necessary to ensure we can know
98 // whether to enforce shutdown delays, for example (see #5393).
99 var (
100 ln io.Closer
101 err error
102 socketFile *os.File
103 )
104
105 fd := slices.Contains([]string{"fd", "fdgram"}, network)
106 if fd {
107 socketFd, err := strconv.ParseUint(address, 0, strconv.IntSize)
108 if err != nil {
109 return nil, fmt.Errorf("invalid file descriptor: %v", err)
110 }
111
112 func() {
113 socketFilesMu.Lock()
114 defer socketFilesMu.Unlock()
115
116 socketFdWide := uintptr(socketFd)
117 var ok bool
118
119 socketFile, ok = socketFiles[socketFdWide]
120
121 if !ok {
122 socketFile = os.NewFile(socketFdWide, lnKey)
123 if socketFile != nil {
124 socketFiles[socketFdWide] = socketFile
125 }
126 }
127 }()
128
129 if socketFile == nil {
130 return nil, fmt.Errorf("invalid socket file descriptor: %d", socketFd)
131 }
132 } else {
133 // wrap any Control function set by the user so we can also add our reusePort control without clobbering theirs
134 oldControl := config.Control
135 config.Control = func(network, address string, c syscall.RawConn) error {
136 if oldControl != nil {
137 if err := oldControl(network, address, c); err != nil {
138 return err
139 }
140 }
141 return reusePort(network, address, c)
142 }
143 }
144
145 datagram := slices.Contains([]string{"udp", "udp4", "udp6", "unixgram", "fdgram"}, network)
146 if datagram {
147 if fd {
148 ln, err = net.FilePacketConn(socketFile)
149 } else {
150 ln, err = config.ListenPacket(ctx, network, address)
151 }
152 } else {
153 if fd {
154 ln, err = net.FileListener(socketFile)
155 } else {
156 ln, err = config.Listen(ctx, network, address)
157 }
158 }
159
160 if err == nil {
161 listenerPool.LoadOrStore(lnKey, nil)
162 }
163
164 if datagram {
165 if !fd {
166 // TODO: Not 100% sure this is necessary, but we do this for net.UnixListener, so...
167 if unix, ok := ln.(*net.UnixConn); ok {
168 cnt := new(atomic.Int32)
169 cnt.Store(1)
170 ln = &unixConn{unix, lnKey, cnt}
171 unixSockets[lnKey] = ln.(*unixConn)
172 }
173 }
174 // lightly wrap the connection so that when it is closed,
175 // we can decrement the usage pool counter
176 if specificLn, ok := ln.(net.PacketConn); ok {
177 ln = deletePacketConn{specificLn, lnKey}
178 }
179 } else {
180 if !fd {
181 // if new listener is a unix socket, make sure we can reuse it later
182 // (we do our own "unlink on close" -- not required, but more tidy)
183 if unix, ok := ln.(*net.UnixListener); ok {
184 unix.SetUnlinkOnClose(false)
185 cnt := new(atomic.Int32)
186 cnt.Store(1)
187 ln = &unixListener{unix, lnKey, cnt}
188 unixSockets[lnKey] = ln.(*unixListener)
189 }
190 }
191 // lightly wrap the listener so that when it is closed,
192 // we can decrement the usage pool counter
193 if specificLn, ok := ln.(net.Listener); ok {
194 ln = deleteListener{specificLn, lnKey}
195 }
196 }
197
198 // other types, I guess we just return them directly
199 return ln, err
200 }
201
202 // reusePort sets SO_REUSEPORT. Ineffective for unix sockets.
203 func reusePort(network, address string, conn syscall.RawConn) error {
204 if IsUnixNetwork(network) {
205 return nil
206 }
207 return conn.Control(func(descriptor uintptr) {
208 if err := unix.SetsockoptInt(int(descriptor), unix.SOL_SOCKET, unixSOREUSEPORT, 1); err != nil {
209 Log().Error("setting SO_REUSEPORT",
210 zap.String("network", network),
211 zap.String("address", address),
212 zap.Uintptr("descriptor", descriptor),
213 zap.Error(err))
214 }
215 })
216 }
217
218 type unixListener struct {
219 *net.UnixListener
220 mapKey string
221 count *atomic.Int32
222 }
223
224 func (uln *unixListener) Close() error {
225 newCount := uln.count.Add(-1)
226 if newCount == 0 {
227 file, err := uln.File()
228 var name string
229 if err == nil {
230 name = file.Name()
231 }
232 defer func() {
233 unixSocketsMu.Lock()
234 delete(unixSockets, uln.mapKey)
235 unixSocketsMu.Unlock()
236 if err == nil {
237 _ = syscall.Unlink(name)
238 }
239 }()
240 }
241 return uln.UnixListener.Close()
242 }
243
244 type unixConn struct {
245 *net.UnixConn
246 mapKey string
247 count *atomic.Int32
248 }
249
250 func (uc *unixConn) Close() error {
251 newCount := uc.count.Add(-1)
252 if newCount == 0 {
253 file, err := uc.File()
254 var name string
255 if err == nil {
256 name = file.Name()
257 }
258 defer func() {
259 unixSocketsMu.Lock()
260 delete(unixSockets, uc.mapKey)
261 unixSocketsMu.Unlock()
262 if err == nil {
263 _ = syscall.Unlink(name)
264 }
265 }()
266 }
267 return uc.UnixConn.Close()
268 }
269
270 func (uc *unixConn) Unwrap() net.PacketConn {
271 return uc.UnixConn
272 }
273
274 // unixSockets keeps track of the currently-active unix sockets
275 // so we can transfer their FDs gracefully during reloads.
276 var unixSockets = make(map[string]interface {
277 File() (*os.File, error)
278 })
279
280 // socketFiles is a fd -> *os.File map used to make a FileListener/FilePacketConn from a socket file descriptor.
281 var socketFiles = map[uintptr]*os.File{}
282
283 // socketFilesMu synchronizes socketFiles insertions
284 var socketFilesMu sync.Mutex
285
286 // deleteListener is a type that simply deletes itself
287 // from the listenerPool when it closes. It is used
288 // solely for the purpose of reference counting (i.e.
289 // counting how many configs are using a given socket).
290 type deleteListener struct {
291 net.Listener
292 lnKey string
293 }
294
295 func (dl deleteListener) Close() error {
296 _, _ = listenerPool.Delete(dl.lnKey)
297 return dl.Listener.Close()
298 }
299
300 // deletePacketConn is like deleteListener, but
301 // for net.PacketConns.
302 type deletePacketConn struct {
303 net.PacketConn
304 lnKey string
305 }
306
307 func (dl deletePacketConn) Close() error {
308 _, _ = listenerPool.Delete(dl.lnKey)
309 return dl.PacketConn.Close()
310 }
311
312 func (dl deletePacketConn) Unwrap() net.PacketConn {
313 return dl.PacketConn
314 }