Debian Codegraph @

internal/utils/unix_socket.go

raw
1 package utils
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "net"
8 "os"
9 "syscall"
10 "time"
11 )
12
13 const unixSocketProbeTimeout = time.Second
14
15 // PrepareUnixSocket removes path when it is a stale Unix socket. It refuses to
16 // remove active sockets and other filesystem objects.
17 func PrepareUnixSocket(ctx context.Context, path string) error {
18 info, err := os.Lstat(path)
19 if errors.Is(err, os.ErrNotExist) {
20 return nil
21 }
22
23 if err != nil {
24 return fmt.Errorf("inspect unix socket %q: %w", path, err)
25 }
26
27 if info.Mode()&os.ModeSocket == 0 {
28 return fmt.Errorf("unix socket path %q exists and is not a socket", path)
29 }
30
31 dialer := net.Dialer{Timeout: unixSocketProbeTimeout}
32
33 conn, err := dialer.DialContext(ctx, "unix", path)
34 if err == nil {
35 _ = conn.Close()
36
37 return fmt.Errorf("unix socket path %q is already in use", path)
38 }
39
40 if !errors.Is(err, syscall.ECONNREFUSED) {
41 return fmt.Errorf("probe unix socket %q: %w", path, err)
42 }
43
44 return removeStaleUnixSocket(path, info)
45 }
46
47 func removeStaleUnixSocket(path string, previousInfo os.FileInfo) error {
48 currentInfo, err := os.Lstat(path)
49 if errors.Is(err, os.ErrNotExist) {
50 return nil
51 }
52
53 if err != nil {
54 return fmt.Errorf("inspect stale unix socket %q: %w", path, err)
55 }
56
57 if currentInfo.Mode()&os.ModeSocket == 0 || !os.SameFile(previousInfo, currentInfo) {
58 return fmt.Errorf("unix socket path %q changed while checking it", path)
59 }
60
61 if err := os.Remove(path); err != nil {
62 return fmt.Errorf("remove stale unix socket %q: %w", path, err)
63 }
64
65 return nil
66 }