-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnel.go
98 lines (86 loc) · 2.15 KB
/
tunnel.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
package inbound
import (
"fmt"
C "github.com/qauzy/aiat/constant"
"github.com/qauzy/aiat/listener/tunnel"
"github.com/qauzy/aiat/log"
)
type TunnelOption struct {
BaseOption
Network []string `inbound:"network"`
Target string `inbound:"target"`
}
func (o TunnelOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
type Tunnel struct {
*Base
config *TunnelOption
ttl *tunnel.Listener
tul *tunnel.PacketConn
}
func NewTunnel(options *TunnelOption) (*Tunnel, error) {
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
return &Tunnel{
Base: base,
config: options,
}, nil
}
// Config implements constant.InboundListener
func (t *Tunnel) Config() C.InboundConfig {
return t.config
}
// Close implements constant.InboundListener
func (t *Tunnel) Close() error {
var err error
if t.ttl != nil {
if tcpErr := t.ttl.Close(); tcpErr != nil {
err = tcpErr
}
}
if t.tul != nil {
if udpErr := t.tul.Close(); udpErr != nil {
if err == nil {
err = udpErr
} else {
return fmt.Errorf("close tcp err: %s, close udp err: %s", err.Error(), udpErr.Error())
}
}
}
return err
}
// Address implements constant.InboundListener
func (t *Tunnel) Address() string {
if t.ttl != nil {
return t.ttl.Address()
}
if t.tul != nil {
return t.tul.Address()
}
return ""
}
// Listen implements constant.InboundListener
func (t *Tunnel) Listen(tcpIn chan<- C.ConnContext, udpIn chan<- C.PacketAdapter, natTable C.NatTable) error {
var err error
for _, network := range t.config.Network {
switch network {
case "tcp":
if t.ttl, err = tunnel.New(t.RawAddress(), t.config.Target, t.config.SpecialProxy, tcpIn, t.Additions()...); err != nil {
return err
}
case "udp":
if t.tul, err = tunnel.NewUDP(t.RawAddress(), t.config.Target, t.config.SpecialProxy, udpIn, t.Additions()...); err != nil {
return err
}
default:
log.Warnln("unknown network type: %s, passed", network)
continue
}
log.Infoln("Tunnel[%s](%s/%s)proxy listening at: %s", t.Name(), network, t.config.Target, t.Address())
}
return nil
}
var _ C.InboundListener = (*Tunnel)(nil)