-
Notifications
You must be signed in to change notification settings - Fork 646
/
socket_unix.go
78 lines (65 loc) · 1.88 KB
/
socket_unix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// +build !windows,!plan9,!js
// (c) 2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package socket
import (
"net"
"os"
"syscall"
"time"
)
var (
staleSocketTimeout = 100 * time.Millisecond
)
func listen(addr string) (net.Listener, error) {
uAddr, err := net.ResolveUnixAddr("unix", addr)
if err != nil {
return nil, err
}
// Try to listen on the socket. If that fails we check to see if it's a stale
// socket and remove it if it is. Then we try to listen one more time.
l, err := net.ListenUnix("unix", uAddr)
if err != nil {
if err = removeIfStaleUnixSocket(addr); err != nil {
return nil, err
}
if l, err = net.ListenUnix("unix", uAddr); err != nil {
return nil, err
}
}
return l, err
}
// Dial creates a new *Client connected to the given address over a Unix socket
func Dial(addr string) (*Client, error) {
unixAddr, err := net.ResolveUnixAddr("unix", addr)
if err != nil {
return nil, err
}
c, err := net.DialUnix("unix", nil, unixAddr)
if err != nil {
if isTimeoutError(err) {
return nil, errReadTimeout{c.RemoteAddr()}
}
return nil, err
}
return &Client{Conn: c, maxMessageSize: DefaultMaxMessageSize}, nil
}
// removeIfStaleUnixSocket takes in a path and removes it iff it is a socket
// that is refusing connections
func removeIfStaleUnixSocket(socketPath string) error {
// Ensure it's a socket; if not return without an error
if st, err := os.Stat(socketPath); err != nil || st.Mode()&os.ModeType != os.ModeSocket {
return nil
}
// Try to connect
conn, err := net.DialTimeout("unix", socketPath, staleSocketTimeout)
switch {
// The connection was refused so this socket is stale; remove it
case isSyscallError(err, syscall.ECONNREFUSED):
return os.Remove(socketPath)
// The socket is alive so close this connection and leave the socket alone
case err == nil:
return conn.Close()
}
return nil
}