-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcp.go
108 lines (95 loc) · 2.08 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package socks
import (
"io"
"net"
"github.com/chwjbn/xclash/adapter/inbound"
N "github.com/chwjbn/xclash/common/net"
C "github.com/chwjbn/xclash/constant"
authStore "github.com/chwjbn/xclash/listener/auth"
"github.com/chwjbn/xclash/transport/socks4"
"github.com/chwjbn/xclash/transport/socks5"
)
type Listener struct {
listener net.Listener
addr string
closed bool
}
// 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 New(addr string, in chan<- C.ConnContext) (*Listener, error) {
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
sl := &Listener{
listener: l,
addr: addr,
}
go func() {
for {
c, err := l.Accept()
if err != nil {
if sl.closed {
break
}
continue
}
go handleSocks(c, in)
}
}()
return sl, nil
}
func handleSocks(conn net.Conn, in chan<- C.ConnContext) {
bufConn := N.NewBufferedConn(conn)
head, err := bufConn.Peek(1)
if err != nil {
conn.Close()
return
}
switch head[0] {
case socks4.Version:
HandleSocks4(bufConn, in)
case socks5.Version:
HandleSocks5(bufConn, in)
default:
conn.Close()
}
}
func HandleSocks4(conn net.Conn, in chan<- C.ConnContext) {
addr, _, err := socks4.ServerHandshake(conn, authStore.Authenticator())
if err != nil {
conn.Close()
return
}
if c, ok := conn.(*net.TCPConn); ok {
c.SetKeepAlive(true)
}
in <- inbound.NewSocket(socks5.ParseAddr(addr), conn, C.SOCKS4)
}
func HandleSocks5(conn net.Conn, in chan<- C.ConnContext) {
authUser, target, command, err := socks5.ServerHandshake(conn, authStore.Authenticator())
if err != nil {
conn.Close()
return
}
if c, ok := conn.(*net.TCPConn); ok {
c.SetKeepAlive(true)
}
if command == socks5.CmdUDPAssociate {
defer conn.Close()
io.Copy(io.Discard, conn)
return
}
in <- inbound.NewSocketWithAuth(target, conn, C.SOCKS5, authUser)
}