-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
345 lines (293 loc) · 7.1 KB
/
handler.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package tap
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"time"
"github.com/go-gost/core/chain"
"github.com/go-gost/core/common/bufpool"
"github.com/go-gost/core/handler"
"github.com/go-gost/core/logger"
md "github.com/go-gost/core/metadata"
"github.com/go-gost/x/registry"
"github.com/gost-dev/x/extra/util/ss"
tap_util "github.com/gost-dev/x/extra/util/tap"
"github.com/shadowsocks/go-shadowsocks2/core"
"github.com/shadowsocks/go-shadowsocks2/shadowaead"
"github.com/songgao/water/waterutil"
)
func init() {
registry.HandlerRegistry().Register("tap", NewHandler)
}
type tapHandler struct {
hop chain.Hop
routes sync.Map
exit chan struct{}
cipher core.Cipher
router *chain.Router
md metadata
options handler.Options
}
func NewHandler(opts ...handler.Option) handler.Handler {
options := handler.Options{}
for _, opt := range opts {
opt(&options)
}
return &tapHandler{
exit: make(chan struct{}, 1),
options: options,
}
}
func (h *tapHandler) Init(md md.Metadata) (err error) {
if err = h.parseMetadata(md); err != nil {
return
}
if h.options.Auth != nil {
method := h.options.Auth.Username()
password, _ := h.options.Auth.Password()
h.cipher, err = ss.ShadowCipher(method, password, h.md.key)
if err != nil {
return
}
}
h.router = h.options.Router
if h.router == nil {
h.router = chain.NewRouter(chain.LoggerRouterOption(h.options.Logger))
}
return
}
// Forward implements handler.Forwarder.
func (h *tapHandler) Forward(hop chain.Hop) {
h.hop = hop
}
func (h *tapHandler) Handle(ctx context.Context, conn net.Conn, opts ...handler.HandleOption) error {
defer os.Exit(0)
defer conn.Close()
log := h.options.Logger
v, _ := conn.(md.Metadatable)
if v == nil {
err := errors.New("tap: wrong connection type")
log.Error(err)
return err
}
start := time.Now()
log = log.WithFields(map[string]any{
"remote": conn.RemoteAddr().String(),
"local": conn.LocalAddr().String(),
})
log.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
defer func() {
log.WithFields(map[string]any{
"duration": time.Since(start),
}).Infof("%s >< %s", conn.RemoteAddr(), conn.LocalAddr())
}()
network := "udp"
var raddr net.Addr
var err error
var target *chain.Node
if h.hop != nil {
target = h.hop.Select(ctx)
}
if target != nil {
raddr, err = net.ResolveUDPAddr(network, target.Addr)
if err != nil {
log.Error(err)
return err
}
log = log.WithFields(map[string]any{
"dst": fmt.Sprintf("%s/%s", raddr.String(), raddr.Network()),
})
log.Debugf("%s >> %s", conn.RemoteAddr(), target.Addr)
}
config := v.Metadata().Get("config").(*tap_util.Config)
h.handleLoop(ctx, conn, raddr, config, log)
return nil
}
func (h *tapHandler) handleLoop(ctx context.Context, conn net.Conn, addr net.Addr, config *tap_util.Config, log logger.Logger) {
var tempDelay time.Duration
for {
err := func() error {
var err error
var pc net.PacketConn
if addr != nil {
cc, err := h.router.Dial(ctx, addr.Network(), "")
if err != nil {
return err
}
var ok bool
pc, ok = cc.(net.PacketConn)
if !ok {
return errors.New("wrong connection type")
}
} else {
laddr, _ := net.ResolveUDPAddr("udp", conn.LocalAddr().String())
pc, err = net.ListenUDP("udp", laddr)
}
if err != nil {
return err
}
if h.cipher != nil {
pc = h.cipher.PacketConn(pc)
}
defer pc.Close()
return h.transport(conn, pc, addr, config, log)
}()
if err != nil {
log.Error(err)
}
select {
case <-h.exit:
return
default:
}
if err != nil {
if tempDelay == 0 {
tempDelay = 1000 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 6 * time.Second; tempDelay > max {
tempDelay = max
}
time.Sleep(tempDelay)
continue
}
tempDelay = 0
}
}
func (h *tapHandler) transport(tap net.Conn, conn net.PacketConn, raddr net.Addr, config *tap_util.Config, log logger.Logger) error {
errc := make(chan error, 1)
go func() {
for {
err := func() error {
b := bufpool.Get(h.md.bufferSize)
defer bufpool.Put(b)
n, err := tap.Read(*b)
if err != nil {
select {
case h.exit <- struct{}{}:
default:
}
return err
}
src := waterutil.MACSource((*b)[:n])
dst := waterutil.MACDestination((*b)[:n])
eType := etherType(waterutil.MACEthertype((*b)[:n]))
log.Debugf("%s >> %s %s %d", src, dst, eType, n)
// client side, deliver frame directly.
if raddr != nil {
_, err := conn.WriteTo((*b)[:n], raddr)
return err
}
// server side, broadcast.
if waterutil.IsBroadcast(dst) {
go h.routes.Range(func(k, v any) bool {
conn.WriteTo((*b)[:n], v.(net.Addr))
return true
})
return nil
}
var addr net.Addr
if v, ok := h.routes.Load(hwAddrToTapRouteKey(dst)); ok {
addr = v.(net.Addr)
}
if addr == nil {
log.Debugf("no route for %s -> %s %s %d", src, dst, eType, n)
return nil
}
if _, err := conn.WriteTo((*b)[:n], addr); err != nil {
return err
}
return nil
}()
if err != nil {
errc <- err
return
}
}
}()
go func() {
for {
err := func() error {
b := bufpool.Get(h.md.bufferSize)
defer bufpool.Put(b)
n, addr, err := conn.ReadFrom(*b)
if err != nil &&
err != shadowaead.ErrShortPacket {
return err
}
src := waterutil.MACSource((*b)[:n])
dst := waterutil.MACDestination((*b)[:n])
eType := etherType(waterutil.MACEthertype((*b)[:n]))
log.Debugf("%s >> %s %s %d", src, dst, eType, n)
// client side, deliver frame to tap device.
if raddr != nil {
_, err := tap.Write((*b)[:n])
return err
}
// server side, record route.
rkey := hwAddrToTapRouteKey(src)
if actual, loaded := h.routes.LoadOrStore(rkey, addr); loaded {
if actual.(net.Addr).String() != addr.String() {
log.Debugf("update route: %s -> %s (old %s)",
src, addr, actual.(net.Addr))
h.routes.Store(rkey, addr)
}
} else {
log.Debugf("new route: %s -> %s", src, addr)
}
if waterutil.IsBroadcast(dst) {
go h.routes.Range(func(k, v any) bool {
if k.(tapRouteKey) != rkey {
conn.WriteTo((*b)[:n], v.(net.Addr))
}
return true
})
}
if v, ok := h.routes.Load(hwAddrToTapRouteKey(dst)); ok {
log.Debugf("find route: %s -> %s", dst, v)
_, err := conn.WriteTo((*b)[:n], v.(net.Addr))
return err
}
if _, err := tap.Write((*b)[:n]); err != nil {
select {
case h.exit <- struct{}{}:
default:
}
return err
}
return nil
}()
if err != nil {
errc <- err
return
}
}
}()
err := <-errc
if err != nil && err == io.EOF {
err = nil
}
return err
}
var mEtherTypes = map[waterutil.Ethertype]string{
waterutil.IPv4: "ip",
waterutil.ARP: "arp",
waterutil.RARP: "rarp",
waterutil.IPv6: "ip6",
}
func etherType(et waterutil.Ethertype) string {
if s, ok := mEtherTypes[et]; ok {
return s
}
return fmt.Sprintf("unknown(%v)", et)
}
type tapRouteKey [6]byte
func hwAddrToTapRouteKey(addr net.HardwareAddr) (key tapRouteKey) {
copy(key[:], addr)
return
}