-
Notifications
You must be signed in to change notification settings - Fork 3
/
net_unix.go
111 lines (88 loc) · 2.06 KB
/
net_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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
package gotfo
import (
"context"
"net"
"syscall"
)
import (
"os"
)
const (
TCP_FASTOPEN = 23
LISTEN_BACKLOG = 23
)
type TFOListener struct {
*net.TCPListener
fd *netFD
}
func socket(family int) (int, error) {
fd, err := syscall.Socket(family, syscall.SOCK_STREAM, 0)
if err != nil {
return 0, err
}
if err := syscall.SetsockoptInt(fd, syscall.SOL_TCP, TCP_FASTOPEN, 1); err != nil {
return 0, err
}
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
return 0, err
}
return fd, nil
}
func Listen(address string) (net.Listener, error) {
laddr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, err
}
fd, err := socket(syscall.AF_INET)
if err != nil {
syscall.Close(fd)
return nil, err
}
sa := tcpAddrToSockaddr(laddr)
if err := syscall.Bind(fd, sa); err != nil {
syscall.Close(fd)
return nil, err
}
if err := syscall.Listen(fd, LISTEN_BACKLOG); err != nil {
syscall.Close(fd)
return nil, err
}
nfd := newFD(fd)
if err := nfd.init(); err != nil {
syscall.Close(fd)
return nil, err
}
return newTCPListener(nfd, false), nil
}
func Dial(address string, data []byte) (*net.TCPConn, error) {
return DialContext(context.Background(), address, data)
}
func DialContext(ctx context.Context, address string, data []byte) (*net.TCPConn, error) {
raddr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, err
}
fd, err := socket(syscall.AF_INET)
if err != nil {
syscall.Close(fd)
return nil, err
}
sa := tcpAddrToSockaddr(raddr)
nfd := newFD(fd)
if err := nfd.init(); err != nil {
syscall.Close(fd)
return nil, err
}
for {
err = syscall.Sendto(nfd.sysfd, data, syscall.MSG_FASTOPEN, sa)
if err == syscall.EAGAIN {
continue
}
break
}
if _, ok := err.(syscall.Errno); ok {
err = os.NewSyscallError("sendto", err)
}
return newTCPConn(nfd), err
}