forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
308 lines (271 loc) · 6.27 KB
/
worker.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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package inbound
import (
"context"
"io"
"net"
"sync"
"sync/atomic"
"time"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
"v2ray.com/core/app/proxyman"
"v2ray.com/core/common/buf"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/proxy"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/tcp"
"v2ray.com/core/transport/internet/udp"
)
type worker interface {
Start() error
Close()
Port() v2net.Port
Proxy() proxy.Inbound
}
type tcpWorker struct {
address v2net.Address
port v2net.Port
proxy proxy.Inbound
stream *internet.StreamConfig
recvOrigDest bool
tag string
dispatcher dispatcher.Interface
sniffers []proxyman.KnownProtocols
ctx context.Context
cancel context.CancelFunc
hub internet.Listener
}
func (w *tcpWorker) callback(conn internet.Connection) {
ctx, cancel := context.WithCancel(w.ctx)
if w.recvOrigDest {
dest, err := tcp.GetOriginalDestination(conn)
if err != nil {
log.Trace(newError("failed to get original destination").Base(err))
}
if dest.IsValid() {
ctx = proxy.ContextWithOriginalTarget(ctx, dest)
}
}
if len(w.tag) > 0 {
ctx = proxy.ContextWithInboundTag(ctx, w.tag)
}
ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.TCPDestination(w.address, w.port))
ctx = proxy.ContextWithSource(ctx, v2net.DestinationFromAddr(conn.RemoteAddr()))
if len(w.sniffers) > 0 {
ctx = proxyman.ContextWithProtocolSniffers(ctx, w.sniffers)
}
if err := w.proxy.Process(ctx, v2net.Network_TCP, conn, w.dispatcher); err != nil {
log.Trace(newError("connection ends").Base(err))
}
cancel()
conn.Close()
}
func (w *tcpWorker) Proxy() proxy.Inbound {
return w.proxy
}
func (w *tcpWorker) Start() error {
ctx, cancel := context.WithCancel(context.Background())
w.ctx = ctx
w.cancel = cancel
ctx = internet.ContextWithStreamSettings(ctx, w.stream)
conns := make(chan internet.Connection, 16)
hub, err := internet.ListenTCP(ctx, w.address, w.port, conns)
if err != nil {
return newError("failed to listen TCP on ", w.port).Base(err)
}
go w.handleConnections(conns)
w.hub = hub
return nil
}
func (w *tcpWorker) handleConnections(conns <-chan internet.Connection) {
for {
select {
case <-w.ctx.Done():
w.hub.Close()
L:
for {
select {
case conn := <-conns:
conn.Close()
default:
break L
}
}
return
case conn := <-conns:
go w.callback(conn)
}
}
}
func (w *tcpWorker) Close() {
if w.hub != nil {
w.cancel()
}
}
func (w *tcpWorker) Port() v2net.Port {
return w.port
}
type udpConn struct {
lastActivityTime int64 // in seconds
input chan *buf.Buffer
output func([]byte) (int, error)
remote net.Addr
local net.Addr
cancel context.CancelFunc
}
func (c *udpConn) updateActivity() {
atomic.StoreInt64(&c.lastActivityTime, time.Now().Unix())
}
func (c *udpConn) Read(buf []byte) (int, error) {
in, open := <-c.input
if !open {
return 0, io.EOF
}
defer in.Release()
c.updateActivity()
return copy(buf, in.Bytes()), nil
}
// Write implements io.Writer.
func (c *udpConn) Write(buf []byte) (int, error) {
n, err := c.output(buf)
if err == nil {
c.updateActivity()
}
return n, err
}
func (c *udpConn) Close() error {
return nil
}
func (c *udpConn) RemoteAddr() net.Addr {
return c.remote
}
func (c *udpConn) LocalAddr() net.Addr {
return c.remote
}
func (*udpConn) SetDeadline(time.Time) error {
return nil
}
func (*udpConn) SetReadDeadline(time.Time) error {
return nil
}
func (*udpConn) SetWriteDeadline(time.Time) error {
return nil
}
type udpWorker struct {
sync.RWMutex
proxy proxy.Inbound
hub *udp.Hub
address v2net.Address
port v2net.Port
recvOrigDest bool
tag string
dispatcher dispatcher.Interface
ctx context.Context
cancel context.CancelFunc
activeConn map[v2net.Destination]*udpConn
}
func (w *udpWorker) getConnection(src v2net.Destination) (*udpConn, bool) {
w.Lock()
defer w.Unlock()
if conn, found := w.activeConn[src]; found {
return conn, true
}
conn := &udpConn{
input: make(chan *buf.Buffer, 32),
output: func(b []byte) (int, error) {
return w.hub.WriteTo(b, src)
},
remote: &net.UDPAddr{
IP: src.Address.IP(),
Port: int(src.Port),
},
local: &net.UDPAddr{
IP: w.address.IP(),
Port: int(w.port),
},
}
w.activeConn[src] = conn
conn.updateActivity()
return conn, false
}
func (w *udpWorker) callback(b *buf.Buffer, source v2net.Destination, originalDest v2net.Destination) {
conn, existing := w.getConnection(source)
select {
case conn.input <- b:
default:
b.Release()
}
if !existing {
go func() {
ctx := w.ctx
ctx, cancel := context.WithCancel(ctx)
conn.cancel = cancel
if originalDest.IsValid() {
ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
}
if len(w.tag) > 0 {
ctx = proxy.ContextWithInboundTag(ctx, w.tag)
}
ctx = proxy.ContextWithSource(ctx, source)
ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.UDPDestination(w.address, w.port))
if err := w.proxy.Process(ctx, v2net.Network_UDP, conn, w.dispatcher); err != nil {
log.Trace(newError("connection ends").Base(err))
}
w.removeConn(source)
cancel()
}()
}
}
func (w *udpWorker) removeConn(src v2net.Destination) {
w.Lock()
delete(w.activeConn, src)
w.Unlock()
}
func (w *udpWorker) Start() error {
w.activeConn = make(map[v2net.Destination]*udpConn)
ctx, cancel := context.WithCancel(context.Background())
w.ctx = ctx
w.cancel = cancel
h, err := udp.ListenUDP(w.address, w.port, udp.ListenOption{
Callback: w.callback,
ReceiveOriginalDest: w.recvOrigDest,
})
if err != nil {
return err
}
go w.monitor()
w.hub = h
return nil
}
func (w *udpWorker) Close() {
if w.hub != nil {
w.hub.Close()
w.cancel()
}
}
func (w *udpWorker) monitor() {
timer := time.NewTicker(time.Second * 16)
defer timer.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-timer.C:
nowSec := time.Now().Unix()
w.Lock()
for addr, conn := range w.activeConn {
if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 {
delete(w.activeConn, addr)
conn.cancel()
}
}
w.Unlock()
}
}
}
func (w *udpWorker) Port() v2net.Port {
return w.port
}
func (w *udpWorker) Proxy() proxy.Inbound {
return w.proxy
}