-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstack.go
217 lines (191 loc) · 4.66 KB
/
stack.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main
import (
"errors"
"fmt"
"io"
"net"
"os"
"strconv"
"sync"
"time"
"proxy-ns/fakedns"
"proxy-ns/proxy"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/link/fdbased"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
"gvisor.dev/gvisor/pkg/waiter"
)
const (
// defaultWndSize if set to zero, the default
// receive window buffer size is used instead.
defaultWndSize = 0
// maxConnAttempts specifies the maximum number
// of in-flight tcp connection attempts.
maxConnAttempts = 2 << 10
udpSessionTimeout = time.Minute
maxPacketSize = (1 << 16) - 1
)
func manageTun(mtu uint32, fd int, dialer proxy.Dialer, fakeDNSServer *fakedns.Server) (err error) {
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol},
})
linkEP, err := fdbased.New(&fdbased.Options{
FDs: []int{fd},
MTU: mtu,
})
if err != nil {
return
}
nicID := s.NextNICID()
if err := s.CreateNIC(nicID, linkEP); err != nil {
return errors.New(err.String())
}
e := s.SetPromiscuousMode(nicID, true)
if e != nil {
return errors.New(e.String())
}
e = s.SetSpoofing(nicID, true)
if e != nil {
return errors.New(e.String())
}
s.SetRouteTable([]tcpip.Route{
{
Destination: header.IPv4EmptySubnet,
NIC: nicID,
},
})
var addrFromID func(stack.TransportEndpointID) string
if fakeDNSServer != nil {
addrFromID = func(id stack.TransportEndpointID) (result string) {
remoteAddr := id.LocalAddress
remotePort := id.LocalPort
if fakeDNSServer.Contains(remoteAddr.AsSlice()) {
name := fakeDNSServer.NameFromIP(remoteAddr.AsSlice())
if name == "" {
return ""
}
result = net.JoinHostPort(name, strconv.Itoa(int(remotePort)))
} else {
result = net.JoinHostPort(remoteAddr.String(), strconv.Itoa(int(remotePort)))
}
return result
}
} else {
addrFromID = func(id stack.TransportEndpointID) (result string) {
remoteAddr := id.LocalAddress
remotePort := id.LocalPort
return net.JoinHostPort(remoteAddr.String(), strconv.Itoa(int(remotePort)))
}
}
tcpForwarder := tcp.NewForwarder(s, defaultWndSize, maxConnAttempts, func(r *tcp.ForwarderRequest) {
var wq waiter.Queue
ep, e := r.CreateEndpoint(&wq)
if e != nil {
r.Complete(true)
return
}
originConn := gonet.NewTCPConn(&wq, ep)
remoteAddrStr := addrFromID(r.ID())
if remoteAddrStr == "" {
r.Complete(true)
return
}
r.Complete(false)
go func() {
remoteConn, err := dialer.Dial("tcp", remoteAddrStr)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
forwardConn(originConn, remoteConn, io.Copy)
}()
})
udpForwarder := udp.NewForwarder(s, func(r *udp.ForwarderRequest) {
var wq waiter.Queue
ep, e := r.CreateEndpoint(&wq)
if e != nil {
return
}
originConn := gonet.NewUDPConn(&wq, ep)
remoteAddrStr := addrFromID(r.ID())
if remoteAddrStr == "" {
return
}
go func() {
remoteConn, err := dialer.Dial("udp", remoteAddrStr)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
forwardConn(originConn, remoteConn, copyPacketData)
}()
})
s.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpForwarder.HandlePacket)
s.SetTransportProtocolHandler(udp.ProtocolNumber, udpForwarder.HandlePacket)
return nil
}
// TODO: handle tcp closeWrite/closeRead
func forwardConn(c1, c2 net.Conn, copyFn func(io.Writer, io.Reader) (int64, error)) error {
var (
wg sync.WaitGroup
e1, e2 error
)
wg.Add(2)
go func() {
_, e1 = copyFn(c1, c2)
c1.Close()
c2.Close()
wg.Done()
}()
go func() {
_, e2 = copyFn(c2, c1)
c1.Close()
c2.Close()
wg.Done()
}()
wg.Wait()
if e1 != nil || e2 != nil {
return fmt.Errorf("%w, %w", e1, e2)
}
return nil
}
var errInvalidWrite = errors.New("invalid write result")
func copyPacketData(dst io.Writer, src io.Reader) (written int64, err error) {
buf := make([]byte, maxPacketSize)
for {
src.(net.Conn).SetReadDeadline(time.Now().Add(udpSessionTimeout))
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw < 0 || nr < nw {
nw = 0
if ew == nil {
ew = errInvalidWrite
}
}
written += int64(nw)
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
dst.(net.Conn).SetReadDeadline(time.Now().Add(udpSessionTimeout))
}
return written, err
}