-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconn.go
63 lines (58 loc) · 1.2 KB
/
conn.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
package proxy
import (
"crypto/tls"
"io"
"net"
)
type SOCKSConf struct {
Auth func(username, password string) bool
Dial func(network, address string) (net.Conn, error)
HandleError func(error)
TLSConfig *tls.Config
}
func Serve(listener net.Listener, conf *SOCKSConf) {
if conf.HandleError == nil {
conf.HandleError = func(_ error) {}
}
for {
conn, err := listener.Accept()
if err != nil {
conf.HandleError(err)
continue
}
go handleConn(conn, conf)
}
}
func IsSOCKS(r io.Reader) bool {
header := make([]byte, 1)
if _, err := r.Read(header); err != nil {
return false
}
return header[0] == 4 || header[0] == 5
}
func handleConn(conn net.Conn, conf *SOCKSConf) {
var err error
buffer := make([]byte, 1)
if _, err = conn.Read(buffer); err != nil {
conf.HandleError(err)
return
}
switch buffer[0] {
case socks4version:
if conf.Auth != nil || conf.TLSConfig != nil {
return
}
socksConn := &socks4Conn{conn, conf}
err = socksConn.Serve()
case socks5version:
if conf.TLSConfig != nil {
conn = tls.Server(conn, conf.TLSConfig)
}
socksConn := &socks5Conn{conn, conf}
err = socksConn.Serve()
}
if err != nil {
conf.HandleError(err)
return
}
}