-
Notifications
You must be signed in to change notification settings - Fork 663
/
socket_unix.go
85 lines (69 loc) · 1.98 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
79
80
81
82
83
84
85
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
//go:build !windows && !plan9 && !js
// +build !windows,!plan9,!js
package socket
import (
"net"
"os"
"syscall"
"time"
"github.com/ava-labs/avalanchego/utils/constants"
)
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.
l, err := net.ListenUnix("unix", uAddr)
if err == nil {
return l, nil
}
// Check to see if the socket is stale and remove it if it is.
if err := removeIfStaleUnixSocket(addr); err != nil {
return nil, err
}
// Try listening again now that it shouldn't be stale.
return net.ListenUnix("unix", uAddr)
}
// 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: int64(constants.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
st, err := os.Stat(socketPath)
if err != nil {
return nil
}
if 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()
default:
return nil
}
}