-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproxy_shadowsocks.go
91 lines (84 loc) · 2.06 KB
/
proxy_shadowsocks.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
package proxyclient
import (
"context"
"errors"
"net"
"net/url"
"strconv"
ss "github.com/shadowsocks/go-shadowsocks2/core"
)
// buildSSAddr 构造 Shadowsocks 请求头
// 格式: ATYP + DST.ADDR + DST.PORT
// ATYP: 1字节, 0x01 = IPv4, 0x03 = 域名, 0x04 = IPv6
// DST.ADDR: 变长,根据 ATYP 决定
// DST.PORT: 2字节,网络字节序
func buildSSAddr(host string, port int) ([]byte, error) {
if len(host) == 0 {
return nil, errors.New("empty host")
}
var buf []byte
if ip := net.ParseIP(host); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
buf = make([]byte, 1+net.IPv4len+2)
buf[0] = 0x01 // IPv4
copy(buf[1:], ip4)
} else {
buf = make([]byte, 1+net.IPv6len+2)
buf[0] = 0x04 // IPv6
copy(buf[1:], ip)
}
} else {
if len(host) > 255 {
return nil, errors.New("target host name too long")
}
buf = make([]byte, 1+1+len(host)+2)
buf[0] = 0x03 // Domain name
buf[1] = byte(len(host))
copy(buf[2:], []byte(host))
}
// 写入端口(网络字节序)
buf[len(buf)-2], buf[len(buf)-1] = byte(port>>8), byte(port)
return buf, nil
}
func newShadowsocksProxyClient(proxy *url.URL, upstreamDial Dial) (dial Dial, err error) {
if proxy, err = decodedBase64EncodedURL(proxy); err != nil {
return
}
if proxy.User == nil {
err = errors.New("method and password is not available")
return
}
var cipher ss.Cipher
if password, ok := proxy.User.Password(); ok {
method := proxy.User.Username()
cipher, err = ss.PickCipher(method, nil, password)
if err != nil {
return
}
}
conn, err := upstreamDial(context.Background(), "tcp", proxy.Host)
if err != nil {
return nil, err
}
conn = cipher.StreamConn(conn)
dial = func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
portI, err := strconv.Atoi(port)
if err != nil {
return nil, err
}
addr, err := buildSSAddr(host, portI)
if err != nil {
return nil, err
}
_, err = conn.Write(addr)
if err != nil {
return nil, err
}
return conn, nil
}
return
}