Repository navigation
Expand file tree
/
Copy pathstack_go_socket_unix.go
More file actions
111 lines (94 loc) · 2.47 KB
/
Copy pathstack_go_socket_unix.go
File metadata and controls
111 lines (94 loc) · 2.47 KB
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
//go:build darwin || linux
package tun
import (
"net/netip"
"os"
"syscall"
"unsafe"
"github.com/sagernet/sing/common/control"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
"golang.org/x/sys/unix"
)
const (
goSocketSendFlags = unix.MSG_DONTWAIT | unix.MSG_NOSIGNAL
goSpliceDuplicatesSocket = true
)
type goIOVector = unix.Iovec
type goSocket struct {
fd int
token uint32
registered bool
packetGRO bool
packetGSODisabled bool
}
func goSpliceSocket(conn syscall.Conn) (goSocket, error) {
fd, err := control.Conn0[int](conn, func(fd uintptr) (int, error) {
return unix.FcntlInt(fd, unix.F_DUPFD_CLOEXEC, 0)
})
if err != nil {
return goSocket{}, err
}
return goSocket{fd: fd}, nil
}
func (s *goSocket) close() {
if s.fd < 0 {
return
}
descriptor := s.fd
s.fd = -1
unix.Close(descriptor)
}
func newUnpolledFile(fd int, name string) *os.File {
unix.SetNonblock(fd, false)
file := os.NewFile(uintptr(fd), name)
unix.SetNonblock(fd, true)
return file
}
func (s *goSocket) shutdownWrite() {
unix.Shutdown(s.fd, unix.SHUT_WR)
}
func (s *goSocket) family() (uint8, error) {
name, err := unix.Getsockname(s.fd)
if err != nil {
return 0, err
}
switch name.(type) {
case *unix.SockaddrInet4:
return unix.AF_INET, nil
case *unix.SockaddrInet6:
return unix.AF_INET6, nil
default:
return 0, E.New("unsupported socket family")
}
}
func (s *goSocket) peerAddress() (netip.AddrPort, bool) {
name, err := unix.Getpeername(s.fd)
if err != nil {
return netip.AddrPort{}, false
}
return M.SocksaddrFromNetIP(M.AddrPortFromSockaddr(name)).Unwrap().AddrPort(), true
}
func goIovecsFromSegments(iovecs []goIOVector, segments [][]byte) []goIOVector {
iovecs = iovecs[:0]
for _, segment := range segments {
if len(segment) == 0 {
continue
}
vector := unix.Iovec{Base: &segment[0]}
vector.SetLen(len(segment))
iovecs = append(iovecs, vector)
}
return iovecs
}
func goSocketWouldBlock(errno syscall.Errno) bool {
return errno == unix.EAGAIN || errno == unix.EWOULDBLOCK || errno == unix.EINTR
}
func goSocketDropped(errno syscall.Errno) bool {
return errno == unix.EMSGSIZE || errno == unix.EAFNOSUPPORT || errno == unix.ENOBUFS
}
func (s *goSocket) readVector(iovecs []unix.Iovec) (int, syscall.Errno) {
//nolint:staticcheck
n, _, errno := unix.RawSyscall(unix.SYS_READV, uintptr(s.fd), uintptr(unsafe.Pointer(&iovecs[0])), uintptr(len(iovecs)))
return int(n), errno
}