-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
84 lines (72 loc) · 2.34 KB
/
socket.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
package socket
import (
"net"
"os"
"strconv"
"strings"
"syscall"
)
// Parse produces a struct suitable for net.Dial
// given a string representing a socket address to bind or connect to
func Parse(value string) (string, string) {
value = strings.TrimSpace(value)
// If value begins with "unix:" then we are a Unix domain socket
if strings.Index(value, "unix:") == 0 {
return "unix", strings.TrimSpace(value[5:])
}
// If value is a port number, prepend a colon
if _, err := strconv.Atoi(value); err == nil {
return "tcp", ":" + value
}
// If the value is a host with a port, return exact.
if host, port, err := net.SplitHostPort(value); err == nil {
if host == "*" {
host = ""
}
return "tcp", net.JoinHostPort(host, port)
}
// Otherwise, assume that the input is just a hostname or IP
// However, if it is an IPv6 address, we need to remove brackets for JoinHostPort to work.
value = strings.Trim(value, "[]")
// Use default port of 80
return "tcp", net.JoinHostPort(value, "80")
}
// Listen takes the same arguments as the net.Listen function but includes
// the mode with which to set the file permissions if creating a Unix socket.
//
// The socket path is appended with ".tmp" before it is created and later renamed.
//
// This function calls syscall.Umask before the socket is created in order to
// completely restrict the socket before it is restored again with os.Chmod.
// Therefore, this function is not thread-safe as Umask is non-reentrant.
//
// Additionally, this function will make sure to remove the temporary socket path
// before creating it.
func Listen(network, address string, mode os.FileMode) (net.Listener, error) {
switch network {
case "unix", "unixgram", "unixpacket":
// Create temporary socket with no permissions
addressTmp := address + ".tmp"
listener, err := func() (net.Listener, error) {
os.Remove(addressTmp)
oldmask := syscall.Umask(0777)
defer syscall.Umask(oldmask)
return net.Listen(network, addressTmp)
}()
if err != nil {
return nil, err
}
// Set desired socket permissions
if err := os.Chmod(addressTmp, mode); err != nil {
listener.Close()
return nil, err
}
// Move socket to its final resting place
if err := os.Rename(addressTmp, address); err != nil {
listener.Close()
return nil, err
}
return listener, err
}
return net.Listen(network, address)
}