-
-
Notifications
You must be signed in to change notification settings - Fork 643
Expand file tree
/
Copy pathengine.go
More file actions
267 lines (228 loc) · 5.78 KB
/
Copy pathengine.go
File metadata and controls
267 lines (228 loc) · 5.78 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package engine
import (
"errors"
"fmt"
"net"
"os/exec"
"sync"
"time"
"github.com/docker/go-units"
"github.com/google/shlex"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"github.com/xjasonlyu/tun2socks/v2/core"
"github.com/xjasonlyu/tun2socks/v2/core/adapter"
"github.com/xjasonlyu/tun2socks/v2/core/device"
"github.com/xjasonlyu/tun2socks/v2/core/option"
"github.com/xjasonlyu/tun2socks/v2/dialer"
"github.com/xjasonlyu/tun2socks/v2/log"
"github.com/xjasonlyu/tun2socks/v2/proxy"
"github.com/xjasonlyu/tun2socks/v2/restapi"
"github.com/xjasonlyu/tun2socks/v2/tunnel"
)
var (
_engineMu sync.Mutex
// _defaultKey holds the default key for the engine.
_defaultKey *Key
// _defaultProxy holds the default proxy for the engine.
_defaultProxy proxy.Proxy
// _defaultDevice holds the default device for the engine.
_defaultDevice device.Device
// _defaultStack holds the default stack for the engine.
_defaultStack *stack.Stack
// _icmpHandler holds the custom ICMP handler for the engine.
_icmpHandler adapter.NetworkHandler
)
// Start starts the default engine up.
func Start() {
if err := start(); err != nil {
log.Fatalf("[ENGINE] failed to start: %v", err)
}
}
// Stop shuts the default engine down.
func Stop() {
if err := stop(); err != nil {
log.Fatalf("[ENGINE] failed to stop: %v", err)
}
}
// Insert loads *Key to the default engine.
func Insert(k *Key) {
_engineMu.Lock()
_defaultKey = k
_engineMu.Unlock()
}
// SetICMPHandler sets the custom ICMP handler for the default engine.
func SetICMPHandler(h adapter.NetworkHandler) {
_engineMu.Lock()
_icmpHandler = h
_engineMu.Unlock()
}
func start() error {
_engineMu.Lock()
defer _engineMu.Unlock()
if _defaultKey == nil {
return errors.New("empty key")
}
for _, f := range []func(*Key) error{
general,
restAPI,
netstack,
} {
if err := f(_defaultKey); err != nil {
return err
}
}
return nil
}
func stop() (err error) {
_engineMu.Lock()
if _defaultDevice != nil {
_defaultDevice.Close()
}
if _defaultStack != nil {
_defaultStack.Close()
_defaultStack.Wait()
}
_engineMu.Unlock()
return nil
}
func execCommand(cmd string) error {
parts, err := shlex.Split(cmd)
if err != nil {
return err
}
if len(parts) == 0 {
return errors.New("empty command")
}
_, err = exec.Command(parts[0], parts[1:]...).Output()
return err
}
func general(k *Key) error {
level, err := log.ParseLevel(k.LogLevel)
if err != nil {
return err
}
log.SetLogger(log.Must(log.NewLeveled(level)))
// Reset default dialer before registering options.
dialer.Reset()
if k.Interface != "" {
iface, err := net.InterfaceByName(k.Interface)
if err != nil {
return err
}
dialer.RegisterSockOpt(dialer.WithBindToInterface(iface))
log.Infof("[DIALER] bind to interface: %s", k.Interface)
}
if k.Mark != 0 {
dialer.RegisterSockOpt(dialer.WithRoutingMark(k.Mark))
log.Infof("[DIALER] set fwmark: %#x", k.Mark)
}
if k.UDPTimeout > 0 {
if k.UDPTimeout < time.Second {
return errors.New("invalid udp timeout value")
}
tunnel.T().SetUDPTimeout(k.UDPTimeout)
}
return nil
}
func restAPI(k *Key) error {
if k.RestAPI != "" {
u, err := parseRestAPI(k.RestAPI)
if err != nil {
return err
}
host, token := u.Host, u.User.String()
restapi.SetStatsFunc(func() tcpip.Stats {
_engineMu.Lock()
defer _engineMu.Unlock()
// default stack is not initialized.
if _defaultStack == nil {
return tcpip.Stats{}
}
return _defaultStack.Stats()
})
go func() {
if err := restapi.Start(host, token); err != nil {
log.Errorf("[RESTAPI] failed to start: %v", err)
}
}()
log.Infof("[RESTAPI] serve at: %s", u)
}
return nil
}
func netstack(k *Key) (err error) {
if k.Device == "" {
return errors.New("empty device")
}
if k.TUNPreUp != "" {
log.Infof("[TUN] pre-execute command: `%s`", k.TUNPreUp)
if preUpErr := execCommand(k.TUNPreUp); preUpErr != nil {
log.Errorf("[TUN] failed to pre-execute: %s: %v", k.TUNPreUp, preUpErr)
}
}
defer func() {
if k.TUNPostUp == "" || err != nil {
return
}
log.Infof("[TUN] post-execute command: `%s`", k.TUNPostUp)
if postUpErr := execCommand(k.TUNPostUp); postUpErr != nil {
log.Errorf("[TUN] failed to post-execute: %s: %v", k.TUNPostUp, postUpErr)
}
}()
multicastGroups, err := parseMulticastGroups(k.MulticastGroups)
if err != nil {
return err
}
if _defaultProxy, err = buildProxy(k); err != nil {
return err
}
tunnel.T().SetProxy(_defaultProxy)
if _defaultDevice, err = parseDevice(k.Device, uint32(k.MTU)); err != nil {
return err
}
var opts []option.Option
if k.TCPModerateReceiveBuffer {
opts = append(opts, option.WithTCPModerateReceiveBuffer(true))
}
if k.TCPSendBufferSize != "" {
size, err := units.RAMInBytes(k.TCPSendBufferSize)
if err != nil {
return err
}
opts = append(opts, option.WithTCPSendBufferSize(int(size)))
}
if k.TCPReceiveBufferSize != "" {
size, err := units.RAMInBytes(k.TCPReceiveBufferSize)
if err != nil {
return err
}
opts = append(opts, option.WithTCPReceiveBufferSize(int(size)))
}
if _defaultStack, err = core.CreateStack(&core.Config{
LinkEndpoint: _defaultDevice,
TransportHandler: tunnel.T(),
ICMPHandler: _icmpHandler,
MulticastGroups: multicastGroups,
Options: opts,
}); err != nil {
return err
}
log.Infof("[STACK] %s <-> %s", k.Device, proxyDescription(k))
return nil
}
// proxyDescription renders a short, log-friendly description of the
// proxy configuration, accounting for the split case where tcp-proxy
// and/or udp-proxy override --proxy.
func proxyDescription(k *Key) string {
if k.TCPProxy == "" && k.UDPProxy == "" {
return k.Proxy
}
tcp, udp := k.TCPProxy, k.UDPProxy
if tcp == "" {
tcp = k.Proxy
}
if udp == "" {
udp = k.Proxy
}
return fmt.Sprintf("tcp=%s udp=%s", tcp, udp)
}