-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
434 lines (393 loc) · 11.2 KB
/
main.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package main
import (
"encoding/binary"
"errors"
"flag"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"path"
"strconv"
"time"
ss "shadowsocks-go/shadowsocks"
)
var debug ss.DebugLog
var (
errAddrType = errors.New("socks addr type not supported")
errVer = errors.New("socks version not supported")
errMethod = errors.New("socks only support 1 method now")
errAuthExtraData = errors.New("socks authentication get extra data")
errReqExtraData = errors.New("socks request get extra data")
errCmd = errors.New("socks command not supported")
)
const (
socksVer5 = 5
socksCmdConnect = 1
)
func init() {
rand.Seed(time.Now().Unix())
}
func handShake(conn net.Conn) (err error) {
const (
idVer = 0
idNmethod = 1
)
// version identification and method selection message in theory can have
// at most 256 methods, plus version and nmethod field in total 258 bytes
// the current rfc defines only 3 authentication methods (plus 2 reserved),
// so it won't be such long in practice
buf := make([]byte, 258)
var n int
ss.SetReadTimeout(conn)
// make sure we get the nmethod field
if n, err = io.ReadAtLeast(conn, buf, idNmethod+1); err != nil {
return
}
if buf[idVer] != socksVer5 {
return errVer
}
nmethod := int(buf[idNmethod])
msgLen := nmethod + 2
if n == msgLen { // handshake done, common case
// do nothing, jump directly to send confirmation
} else if n < msgLen { // has more methods to read, rare case
if _, err = io.ReadFull(conn, buf[n:msgLen]); err != nil {
return
}
} else { // error, should not get extra data
return errAuthExtraData
}
// send confirmation: version 5, no authentication required
_, err = conn.Write([]byte{socksVer5, 0})
return
}
func getRequest(conn net.Conn) (rawaddr []byte, host string, err error) {
const (
idVer = 0
idCmd = 1
idType = 3 // address type index
idIP0 = 4 // ip addres start index
idDmLen = 4 // domain address length index
idDm0 = 5 // domain address start index
typeIPv4 = 1 // type is ipv4 address
typeDm = 3 // type is domain address
typeIPv6 = 4 // type is ipv6 address
lenIPv4 = 3 + 1 + net.IPv4len + 2 // 3(ver+cmd+rsv) + 1addrType + ipv4 + 2port
lenIPv6 = 3 + 1 + net.IPv6len + 2 // 3(ver+cmd+rsv) + 1addrType + ipv6 + 2port
lenDmBase = 3 + 1 + 1 + 2 // 3 + 1addrType + 1addrLen + 2port, plus addrLen
)
// refer to getRequest in server.go for why set buffer size to 263
buf := make([]byte, 263)
var n int
ss.SetReadTimeout(conn)
// read till we get possible domain length field
if n, err = io.ReadAtLeast(conn, buf, idDmLen+1); err != nil {
return
}
// check version and cmd
if buf[idVer] != socksVer5 {
err = errVer
return
}
if buf[idCmd] != socksCmdConnect {
err = errCmd
return
}
reqLen := -1
switch buf[idType] {
case typeIPv4:
reqLen = lenIPv4
case typeIPv6:
reqLen = lenIPv6
case typeDm:
reqLen = int(buf[idDmLen]) + lenDmBase
default:
err = errAddrType
return
}
if n == reqLen {
// common case, do nothing
} else if n < reqLen { // rare case
if _, err = io.ReadFull(conn, buf[n:reqLen]); err != nil {
return
}
} else {
err = errReqExtraData
return
}
rawaddr = buf[idType:reqLen]
if debug {
switch buf[idType] {
case typeIPv4:
host = net.IP(buf[idIP0 : idIP0+net.IPv4len]).String()
case typeIPv6:
host = net.IP(buf[idIP0 : idIP0+net.IPv6len]).String()
case typeDm:
host = string(buf[idDm0 : idDm0+buf[idDmLen]])
}
port := binary.BigEndian.Uint16(buf[reqLen-2 : reqLen])
host = net.JoinHostPort(host, strconv.Itoa(int(port)))
}
return
}
type ServerCipher struct {
server string
cipher *ss.Cipher
}
var servers struct {
srvCipher []*ServerCipher
failCnt []int // failed connection count
}
func parseServerConfig(config *ss.Config) {
hasPort := func(s string) bool {
_, port, err := net.SplitHostPort(s)
if err != nil {
return false
}
return port != ""
}
if len(config.ServerPassword) == 0 {
method := config.Method
// only one encryption table
cipher, err := ss.NewCipher(method, config.Password)
if err != nil {
log.Fatal("Failed generating ciphers:", err)
}
srvPort := strconv.Itoa(config.ServerPort)
srvArr := config.GetServerArray()
n := len(srvArr)
servers.srvCipher = make([]*ServerCipher, n)
for i, s := range srvArr {
if hasPort(s) {
log.Println("ignore server_port option for server", s)
servers.srvCipher[i] = &ServerCipher{s, cipher}
} else {
servers.srvCipher[i] = &ServerCipher{net.JoinHostPort(s, srvPort), cipher}
}
}
} else {
// multiple servers
n := len(config.ServerPassword)
servers.srvCipher = make([]*ServerCipher, n)
cipherCache := make(map[string]*ss.Cipher)
i := 0
for _, serverInfo := range config.ServerPassword {
if len(serverInfo) < 2 || len(serverInfo) > 3 {
log.Fatalf("server %v syntax error\n", serverInfo)
}
server := serverInfo[0]
passwd := serverInfo[1]
encmethod := ""
if len(serverInfo) == 3 {
encmethod = serverInfo[2]
}
if !hasPort(server) {
log.Fatalf("no port for server %s\n", server)
}
// Using "|" as delimiter is safe here, since no encryption
// method contains it in the name.
cacheKey := encmethod + "|" + passwd
cipher, ok := cipherCache[cacheKey]
if !ok {
var err error
cipher, err = ss.NewCipher(encmethod, passwd)
if err != nil {
log.Fatal("Failed generating ciphers:", err)
}
cipherCache[cacheKey] = cipher
}
servers.srvCipher[i] = &ServerCipher{server, cipher}
i++
}
}
servers.failCnt = make([]int, len(servers.srvCipher))
for _, se := range servers.srvCipher {
log.Println("available remote server", se.server)
}
if config.Gfw != "" {
readGfwlist(config.Gfw)
}
if config.Fgfw != "" {
fgfw = true
}
return
}
func connectToServer(serverId int, rawaddr []byte, addr string) (remote *ss.Conn, err error) {
se := servers.srvCipher[serverId]
remote, err = ss.DialWithRawAddr(rawaddr, se.server, se.cipher.Copy())
if err != nil {
log.Println("error connecting to shadowsocks server:", err)
const maxFailCnt = 30
if servers.failCnt[serverId] < maxFailCnt {
servers.failCnt[serverId]++
}
return nil, err
}
debug.Printf("connected to %s via %s\n", addr, se.server)
servers.failCnt[serverId] = 0
return
}
// Connection to the server in the order specified in the config. On
// connection failure, try the next server. A failed server will be tried with
// some probability according to its fail count, so we can discover recovered
// servers.
func createServerConn(rawaddr []byte, addr string) (remote *ss.Conn, err error) {
const baseFailCnt = 20
n := len(servers.srvCipher)
skipped := make([]int, 0)
for i := 0; i < n; i++ {
// skip failed server, but try it with some probability
if servers.failCnt[i] > 0 && rand.Intn(servers.failCnt[i]+baseFailCnt) != 0 {
skipped = append(skipped, i)
continue
}
remote, err = connectToServer(i, rawaddr, addr)
if err == nil {
return
}
}
// last resort, try skipped servers, not likely to succeed
for _, i := range skipped {
remote, err = connectToServer(i, rawaddr, addr)
if err == nil {
return
}
}
return nil, err
}
func handleConnection(conn net.Conn) {
if debug {
debug.Printf("socks connect from %s\n", conn.RemoteAddr().String())
}
closed := false
defer func() {
if !closed {
conn.Close()
}
}()
var err error = nil
if err = handShake(conn); err != nil {
log.Println("socks handshake:", err)
return
}
rawaddr, addr, err := getRequest(conn)
if err != nil {
log.Println("error getting request:", err)
return
}
// Sending connection established message immediately to client.
// This some round trip time for creating socks connection with the client.
// But if connection failed, the client will get connection reset error.
_, err = conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x08, 0x43})
if err != nil {
debug.Println("send connection confirmation:", err)
return
}
remote, err := createServerConn(rawaddr, addr)
if err != nil {
if len(servers.srvCipher) > 1 {
log.Println("Failed connect to all avaiable shadowsocks server")
}
return
}
defer func() {
if !closed {
remote.Close()
}
}()
go ss.PipeThenClose(conn, remote)
ss.PipeThenClose(remote, conn)
closed = true
debug.Println("closed connection to", addr)
}
func run(listenAddr string) {
ln, err := net.Listen("tcp", listenAddr)
if err != nil {
log.Fatal(err)
}
log.Printf("starting local socks5 server at %v ...\n", listenAddr)
for {
conn, err := ln.Accept()
if err != nil {
log.Println("accept:", err)
continue
}
go handleConnection(conn)
}
}
func enoughOptions(config *ss.Config) bool {
return config.Server != nil && config.ServerPort != 0 &&
config.Password != ""
}
func main() {
log.SetOutput(os.Stdout)
var configFile, cmdServer, cmdLocal string
var cmdConfig ss.Config
var printVer bool
flag.BoolVar(&printVer, "version", false, "print version")
flag.StringVar(&configFile, "c", "config.json", "specify config file")
flag.StringVar(&cmdServer, "s", "", "server address")
flag.StringVar(&cmdLocal, "b", "", "local address, listen only to this address if specified")
flag.StringVar(&cmdConfig.HttpProxy, "P", "", "local http proxy address")
flag.StringVar(&cmdConfig.Password, "k", "", "password")
flag.IntVar(&cmdConfig.ServerPort, "p", 0, "server port")
flag.IntVar(&cmdConfig.Timeout, "t", 300, "timeout in seconds")
flag.IntVar(&cmdConfig.LocalPort, "l", 0, "local socks5 proxy port")
flag.StringVar(&cmdConfig.Method, "m", "", "encryption method, default: aes-256-cfb")
flag.StringVar(&cmdConfig.Gfw, "gfw", "", "gfwlist config file")
flag.BoolVar((*bool)(&fgfw), "fgfw", false, "all traffic takes the agent")
flag.BoolVar((*bool)(&debug), "d", false, "print debug message")
flag.Parse()
if printVer {
ss.PrintVersion()
os.Exit(0)
}
cmdConfig.Server = cmdServer
ss.SetDebug(debug)
exists, err := ss.IsFileExists(configFile)
// If no config file in current directory, try search it in the binary directory
// Note there's no portable way to detect the binary directory.
binDir := path.Dir(os.Args[0])
if (!exists || err != nil) && binDir != "" && binDir != "." {
oldConfig := configFile
configFile = path.Join(binDir, "config.json")
log.Printf("%s not found, try config file %s\n", oldConfig, configFile)
}
config, err := ss.ParseConfig(configFile)
if err != nil {
config = &cmdConfig
if !os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "error reading %s: %v\n", configFile, err)
os.Exit(1)
}
} else {
ss.UpdateConfig(config, &cmdConfig)
}
if config.Method == "" {
config.Method = "aes-256-cfb"
}
if len(config.ServerPassword) == 0 {
if !enoughOptions(config) {
fmt.Fprintln(os.Stderr, "must specify server address, password and both server/local port")
os.Exit(1)
}
} else {
if config.Password != "" || config.ServerPort != 0 || config.GetServerArray() != nil {
fmt.Fprintln(os.Stderr, "given server_password, ignore server, server_port and password option:", config)
}
if config.LocalPort == 0 {
//fmt.Fprintln(os.Stderr, "must specify local port")
//os.Exit(1)
}
}
parseServerConfig(config)
if config.LocalPort != 0 {
go run(cmdLocal + ":" + strconv.Itoa(config.LocalPort))
}
if config.HttpProxy != "" {
httpProxy(config.HttpProxy)
}
}