-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockopt_linux.go
99 lines (85 loc) · 2.62 KB
/
sockopt_linux.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
package internet
import (
"net"
"syscall"
)
const (
// For incoming connections.
TCP_FASTOPEN = 23
// For out-going connections.
TCP_FASTOPEN_CONNECT = 30
)
func bindAddr(fd uintptr, ip []byte, port uint32) error {
err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
if err != nil {
return newError("failed to set resuse_addr").Base(err).AtWarning()
}
var sockaddr syscall.Sockaddr
switch len(ip) {
case net.IPv4len:
a4 := &syscall.SockaddrInet4{
Port: int(port),
}
copy(a4.Addr[:], ip)
sockaddr = a4
case net.IPv6len:
a6 := &syscall.SockaddrInet6{
Port: int(port),
}
copy(a6.Addr[:], ip)
sockaddr = a6
default:
return newError("unexpected length of ip")
}
return syscall.Bind(int(fd), sockaddr)
}
func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error {
if config.Mark != 0 {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil {
return newError("failed to set SO_MARK").Base(err)
}
}
if isTCPSocket(network) {
switch config.Tfo {
case SocketConfig_Enable:
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN_CONNECT, 1); err != nil {
return newError("failed to set TCP_FASTOPEN_CONNECT=1").Base(err)
}
case SocketConfig_Disable:
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN_CONNECT, 0); err != nil {
return newError("failed to set TCP_FASTOPEN_CONNECT=0").Base(err)
}
}
}
if config.Tproxy.IsEnabled() {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
return newError("failed to set IP_TRANSPARENT").Base(err)
}
}
return nil
}
func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error {
if isTCPSocket(network) {
switch config.Tfo {
case SocketConfig_Enable:
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN, 1); err != nil {
return newError("failed to set TCP_FASTOPEN=1").Base(err)
}
case SocketConfig_Disable:
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN, 0); err != nil {
return newError("failed to set TCP_FASTOPEN=0").Base(err)
}
}
}
if config.Tproxy.IsEnabled() {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
return newError("failed to set IP_TRANSPARENT").Base(err)
}
}
if config.ReceiveOriginalDestAddress && isUDPSocket(network) {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR, 1); err != nil {
return err
}
}
return nil
}