-
Notifications
You must be signed in to change notification settings - Fork 51
/
tcp.go
87 lines (71 loc) · 1.66 KB
/
tcp.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
package autoredir
import (
"net"
"net/netip"
"github.com/phuslu/log"
"github.com/yaling888/clash/adapter/inbound"
C "github.com/yaling888/clash/constant"
"github.com/yaling888/clash/transport/socks5"
)
type Listener struct {
listener net.Listener
addr string
closed bool
lookupFunc func(netip.AddrPort) (socks5.Addr, error)
}
// RawAddress implements C.Listener
func (l *Listener) RawAddress() string {
return l.addr
}
// Address implements C.Listener
func (l *Listener) Address() string {
return l.listener.Addr().String()
}
// Close implements C.Listener
func (l *Listener) Close() error {
l.closed = true
return l.listener.Close()
}
func (l *Listener) TCPAddr() netip.AddrPort {
return l.listener.Addr().(*net.TCPAddr).AddrPort()
}
func (l *Listener) SetLookupFunc(lookupFunc func(netip.AddrPort) (socks5.Addr, error)) {
l.lookupFunc = lookupFunc
}
func (l *Listener) handleRedir(conn net.Conn, in chan<- C.ConnContext) {
if l.lookupFunc == nil {
log.Error().Msg("[Auto Redirect] lookup function is nil")
return
}
target, err := l.lookupFunc(conn.RemoteAddr().(*net.TCPAddr).AddrPort())
if err != nil {
log.Warn().Err(err).Msg("[Auto Redirect]")
_ = conn.Close()
return
}
_ = conn.(*net.TCPConn).SetKeepAlive(true)
in <- inbound.NewSocket(target, conn, C.REDIR)
}
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
al := &Listener{
listener: l,
addr: addr,
}
go func() {
for {
c, err := l.Accept()
if err != nil {
if al.closed {
break
}
continue
}
go al.handleRedir(c, in)
}
}()
return al, nil
}