This repository was archived by the owner on Apr 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathserver.go
630 lines (575 loc) · 15.8 KB
/
server.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
ss "github.com/bonafideyan/shadowsocks-go/shadowsocks"
)
const (
idType = 0 // address type index
idIP0 = 1 // ip address start index
idDmLen = 1 // domain address length index
idDm0 = 2 // domain address start index
typeIPv4 = 1 // type is ipv4 address
typeDm = 3 // type is domain address
typeIPv6 = 4 // type is ipv6 address
lenIPv4 = net.IPv4len + 2 // ipv4 + 2port
lenIPv6 = net.IPv6len + 2 // ipv6 + 2port
lenDmBase = 2 // 1addrLen + 2port, plus addrLen
// lenHmacSha1 = 10
)
var debug ss.DebugLog
var sanitizeIps bool
var udp bool
var managerAddr string
func getRequest(conn *ss.Conn) (host string, err error) {
ss.SetReadTimeout(conn)
// buf size should at least have the same size with the largest possible
// request size (when addrType is 3, domain name has at most 256 bytes)
// 1(addrType) + 1(lenByte) + 255(max length address) + 2(port) + 10(hmac-sha1)
buf := make([]byte, 269)
// read till we get possible domain length field
if _, err = io.ReadFull(conn, buf[:idType+1]); err != nil {
return
}
var reqStart, reqEnd int
addrType := buf[idType]
switch addrType & ss.AddrMask {
case typeIPv4:
reqStart, reqEnd = idIP0, idIP0+lenIPv4
case typeIPv6:
reqStart, reqEnd = idIP0, idIP0+lenIPv6
case typeDm:
if _, err = io.ReadFull(conn, buf[idType+1:idDmLen+1]); err != nil {
return
}
reqStart, reqEnd = idDm0, idDm0+int(buf[idDmLen])+lenDmBase
default:
err = fmt.Errorf("addr type %d not supported", addrType&ss.AddrMask)
return
}
if _, err = io.ReadFull(conn, buf[reqStart:reqEnd]); err != nil {
return
}
// Return string for typeIP is not most efficient, but browsers (Chrome,
// Safari, Firefox) all seems using typeDm exclusively. So this is not a
// big problem.
switch addrType & ss.AddrMask {
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+int(buf[idDmLen])])
}
// parse port
port := binary.BigEndian.Uint16(buf[reqEnd-2 : reqEnd])
host = net.JoinHostPort(host, strconv.Itoa(int(port)))
return
}
const logCntDelta = 100
var connCnt int
var nextLogConnCnt = logCntDelta
func sanitizeAddr(addr net.Addr) string {
if sanitizeIps {
return "x.x.x.x:zzzz"
} else {
return addr.String()
}
}
func handleConnection(conn *ss.Conn, port string) {
var host string
connCnt++ // this maybe not accurate, but should be enough
if connCnt-nextLogConnCnt >= 0 {
// XXX There's no xadd in the atomic package, so it's difficult to log
// the message only once with low cost. Also note nextLogConnCnt maybe
// added twice for current peak connection number level.
log.Printf("Number of client connections reaches %d\n", nextLogConnCnt)
nextLogConnCnt += logCntDelta
}
// function arguments are always evaluated, so surround debug statement
// with if statement
if debug {
debug.Printf("new client %s->%s\n", sanitizeAddr(conn.RemoteAddr()), conn.LocalAddr())
}
closed := false
defer func() {
if debug {
debug.Printf("closed pipe %s<->%s\n", sanitizeAddr(conn.RemoteAddr()), host)
}
connCnt--
if !closed {
conn.Close()
}
}()
host, err := getRequest(conn)
if err != nil {
log.Println("error getting request", sanitizeAddr(conn.RemoteAddr()), conn.LocalAddr(), err)
closed = true
return
}
// ensure the host does not contain some illegal characters, NUL may panic on Win32
if strings.ContainsRune(host, 0x00) {
log.Println("invalid domain name.")
closed = true
return
}
debug.Println("connecting", host)
remote, err := net.Dial("tcp", host)
if err != nil {
if ne, ok := err.(*net.OpError); ok && (ne.Err == syscall.EMFILE || ne.Err == syscall.ENFILE) {
// log too many open file error
// EMFILE is process reaches open file limits, ENFILE is system limit
log.Println("dial error:", err)
} else {
log.Println("error connecting to:", host, err)
}
return
}
defer func() {
if !closed {
remote.Close()
}
}()
if debug {
debug.Printf("piping %s<->%s", sanitizeAddr(conn.RemoteAddr()), host)
}
go func() {
ss.PipeThenClose(conn, remote, func(Traffic int) {
passwdManager.addTraffic(port, Traffic)
}, nil, 0)
}()
ss.PipeThenClose(remote, conn, func(Traffic int) {
passwdManager.addTraffic(port, Traffic)
}, nil, 0)
closed = true
return
}
type PortListener struct {
password string
listener net.Listener
}
type UDPListener struct {
password string
listener *net.UDPConn
}
type PasswdManager struct {
sync.Mutex
portListener map[string]*PortListener
udpListener map[string]*UDPListener
trafficStats map[string]int64
}
func (pm *PasswdManager) add(port, password string, listener net.Listener) {
pm.Lock()
pm.portListener[port] = &PortListener{password, listener}
pm.trafficStats[port] = 0
pm.Unlock()
}
func (pm *PasswdManager) addUDP(port, password string, listener *net.UDPConn) {
pm.Lock()
pm.udpListener[port] = &UDPListener{password, listener}
pm.Unlock()
}
func (pm *PasswdManager) get(port string) (pl *PortListener, ok bool) {
pm.Lock()
pl, ok = pm.portListener[port]
pm.Unlock()
return
}
func (pm *PasswdManager) getUDP(port string) (pl *UDPListener, ok bool) {
pm.Lock()
pl, ok = pm.udpListener[port]
pm.Unlock()
return
}
func (pm *PasswdManager) del(port string) {
pl, ok := pm.get(port)
if !ok {
return
}
if udp {
upl, ok := pm.getUDP(port)
if !ok {
return
}
upl.listener.Close()
}
pl.listener.Close()
pm.Lock()
delete(pm.portListener, port)
delete(pm.trafficStats, port)
if udp {
delete(pm.udpListener, port)
}
pm.Unlock()
}
func (pm *PasswdManager) addTraffic(port string, n int) {
pm.Lock()
pm.trafficStats[port] = pm.trafficStats[port] + int64(n)
pm.Unlock()
return
}
func (pm *PasswdManager) getTrafficStats() map[string]int64 {
pm.Lock()
copy := make(map[string]int64)
for k, v := range pm.trafficStats {
copy[k] = v
}
pm.Unlock()
return copy
}
// Update port password would first close a port and restart listening on that
// port. A different approach would be directly change the password used by
// that port, but that requires **sharing** password between the port listener
// and password manager.
func (pm *PasswdManager) updatePortPasswd(port, password string) {
pl, ok := pm.get(port)
if !ok {
log.Printf("new port %s added\n", port)
} else {
if pl.password == password {
return
}
log.Printf("closing port %s to update password\n", port)
pl.listener.Close()
}
// run will add the new port listener to passwdManager.
// So there maybe concurrent access to passwdManager and we need lock to protect it.
go run(port, password)
if udp {
pl, ok := pm.getUDP(port)
if !ok {
log.Printf("new udp port %s added\n", port)
} else {
if pl.password == password {
return
}
log.Printf("closing udp port %s to update password\n", port)
pl.listener.Close()
}
go runUDP(port, password)
}
}
var passwdManager = PasswdManager{
portListener: map[string]*PortListener{},
udpListener: map[string]*UDPListener{},
trafficStats: map[string]int64{},
}
func updatePasswd() {
log.Println("updating password")
newconfig, err := ss.ParseConfig(configFile)
if err != nil {
log.Printf("error parsing config file %s to update password: %v\n", configFile, err)
return
}
oldconfig := config
config = newconfig
if err = unifyPortPassword(config); err != nil {
return
}
for port, passwd := range config.PortPassword {
passwdManager.updatePortPasswd(port, passwd)
if oldconfig.PortPassword != nil {
delete(oldconfig.PortPassword, port)
}
}
// port password still left in the old config should be closed
for port := range oldconfig.PortPassword {
log.Printf("closing port %s as it's deleted\n", port)
passwdManager.del(port)
}
log.Println("password updated")
}
func waitSignal() {
var sigChan = make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGHUP)
for sig := range sigChan {
if sig == syscall.SIGHUP {
updatePasswd()
} else {
// is this going to happen?
log.Printf("caught signal %v, exit", sig)
os.Exit(0)
}
}
}
func run(port, password string) {
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Printf("error listening port %v: %v\n", port, err)
os.Exit(1)
}
passwdManager.add(port, password, ln)
var cipher *ss.Cipher
log.Printf("server listening port %v ...\n", port)
for {
conn, err := ln.Accept()
if err != nil {
// listener maybe closed to update password
debug.Printf("accept error: %v\n", err)
return
}
// Creating cipher upon first connection.
if cipher == nil {
log.Println("creating cipher for port:", port)
cipher, err = ss.NewCipher(config.Method, password)
if err != nil {
log.Printf("Error generating cipher for port: %s %v\n", port, err)
conn.Close()
continue
}
}
go handleConnection(ss.NewConn(conn, cipher.Copy()), port)
}
}
func runUDP(port, password string) {
var cipher *ss.Cipher
port_i, _ := strconv.Atoi(port)
log.Printf("listening udp port %v\n", port)
conn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IPv6zero,
Port: port_i,
})
passwdManager.addUDP(port, password, conn)
if err != nil {
log.Printf("error listening udp port %v: %v\n", port, err)
return
}
defer conn.Close()
cipher, err = ss.NewCipher(config.Method, password)
if err != nil {
log.Printf("Error generating cipher for udp port: %s %v\n", port, err)
conn.Close()
}
SecurePacketConn := ss.NewSecurePacketConn(conn, cipher.Copy())
for {
if err := ss.ReadAndHandleUDPReq(SecurePacketConn, func(traffic int) {
passwdManager.addTraffic(port, traffic)
}); err != nil {
debug.Printf("udp read error: %v\n", err)
return
}
}
}
func enoughOptions(config *ss.Config) bool {
return config.ServerPort != 0 && config.Password != ""
}
func unifyPortPassword(config *ss.Config) (err error) {
if len(config.PortPassword) == 0 { // this handles both nil PortPassword and empty one
if !enoughOptions(config) {
fmt.Fprintln(os.Stderr, "must specify both port and password")
return errors.New("not enough options")
}
port := strconv.Itoa(config.ServerPort)
config.PortPassword = map[string]string{port: config.Password}
} else {
if config.Password != "" || config.ServerPort != 0 {
fmt.Fprintln(os.Stderr, "given port_password, ignore server_port and password option")
}
}
return
}
var configFile string
var config *ss.Config
func main() {
log.SetOutput(os.Stdout)
var cmdConfig ss.Config
var printVer bool
var core int
flag.BoolVar(&printVer, "version", false, "print version")
flag.StringVar(&configFile, "c", "config.json", "specify config file")
flag.StringVar(&cmdConfig.Password, "k", "", "password")
flag.IntVar(&cmdConfig.ServerPort, "p", 0, "server port")
flag.IntVar(&cmdConfig.Timeout, "t", 300, "timeout in seconds")
flag.StringVar(&cmdConfig.Method, "m", "", "encryption method, default: aes-256-cfb")
flag.IntVar(&core, "core", 0, "maximum number of CPU cores to use, default is determinied by Go runtime")
flag.BoolVar((*bool)(&debug), "d", false, "print debug message")
flag.BoolVar((*bool)(&sanitizeIps), "A", false, "anonymize client ip addresses in all output")
flag.BoolVar(&udp, "u", false, "UDP Relay")
flag.StringVar(&managerAddr, "manager-address", "", "shadowsocks manager listening address")
flag.Parse()
if printVer {
ss.PrintVersion()
os.Exit(0)
}
ss.SetDebug(debug)
var err error
config, err = ss.ParseConfig(configFile)
if err != nil {
if !os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "error reading %s: %v\n", configFile, err)
os.Exit(1)
}
config = &cmdConfig
ss.UpdateConfig(config, config)
} else {
ss.UpdateConfig(config, &cmdConfig)
}
if config.Method == "" {
config.Method = "aes-256-cfb"
}
if err = ss.CheckCipherMethod(config.Method); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err = unifyPortPassword(config); err != nil {
os.Exit(1)
}
if core > 0 {
runtime.GOMAXPROCS(core)
}
for port, password := range config.PortPassword {
go run(port, password)
if udp {
go runUDP(port, password)
}
}
if managerAddr != "" {
addr, err := net.ResolveUDPAddr("udp", managerAddr)
if err != nil {
fmt.Fprintln(os.Stderr, "Can't resolve address: ", err)
os.Exit(1)
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Fprintln(os.Stderr, "Error listening:", err)
os.Exit(1)
}
log.Printf("manager listening udp addr %v ...\n", managerAddr)
defer conn.Close()
go managerDaemon(conn)
}
waitSignal()
}
func managerDaemon(conn *net.UDPConn) {
// add a report address set for ping response
// according to https://github.com/shadowsocks/shadowsocks/wiki/Manage-Multiple-Users#example-code
ctx := make(chan bool, 1)
defer close(ctx)
reportconnSet := make(map[string]*net.UDPAddr, 1024)
go func() {
timer := time.Tick(10 * time.Second)
for {
select {
case <-ctx:
return
case <-timer:
for _, addr := range reportconnSet {
res := reportStat()
if len(res) == 0 {
continue
}
conn.WriteToUDP(res, addr)
}
}
}
}()
for {
data := make([]byte, 300)
_, remote, err := conn.ReadFromUDP(data)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to read UDP manage msg, error: ", err.Error())
continue
}
command := string(data)
var res []byte
switch {
case strings.HasPrefix(command, "add:"):
res = handleAddPort(bytes.Trim(data[4:], "\x00\r\n "))
case strings.HasPrefix(command, "remove:"):
res = handleRemovePort(bytes.Trim(data[7:], "\x00\r\n "))
case strings.HasPrefix(command, "ping-stop"): // add the stop ping command
conn.WriteToUDP(handlePing(), remote)
delete(reportconnSet, remote.String())
case strings.HasPrefix(command, "ping"):
conn.WriteToUDP(handlePing(), remote)
reportconnSet[remote.String()] = remote // append the host into the report list
}
if len(res) == 0 {
continue
}
_, err = conn.WriteToUDP(res, remote)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to write UDP manage msg, error: ", err.Error())
continue
}
}
}
func handleAddPort(payload []byte) []byte {
var params struct {
ServerPort interface{} `json:"server_port"` // may be string or int
Password string `json:"password"`
}
json.Unmarshal(payload, ¶ms)
if params.ServerPort == nil || params.Password == "" {
fmt.Fprintln(os.Stderr, "Failed to parse add req: ", string(payload))
return []byte("err")
}
port := parsePortNum(params.ServerPort)
if port == "" {
return []byte("err")
}
passwdManager.updatePortPasswd(port, params.Password)
return []byte("ok")
}
func handleRemovePort(payload []byte) []byte {
var params struct {
ServerPort interface{} `json:"server_port"` // may be string or int
}
json.Unmarshal(payload, ¶ms)
if params.ServerPort == nil {
fmt.Fprintln(os.Stderr, "Failed to parse remove req: ", string(payload))
return []byte("err")
}
port := parsePortNum(params.ServerPort)
if port == "" {
return []byte("err")
}
log.Printf("closing port %s\n", port)
passwdManager.del(port)
return []byte("ok")
}
func handlePing() []byte {
return []byte("pong")
}
// reportStat get the stat:trafficStat and return avery 10 sec as for the protocol
// https://github.com/shadowsocks/shadowsocks/wiki/Manage-Multiple-Users
func reportStat() []byte {
stats := passwdManager.getTrafficStats()
var buf bytes.Buffer
buf.WriteString("stat: ")
ret, _ := json.Marshal(stats)
buf.Write(ret)
return buf.Bytes()
}
func parsePortNum(in interface{}) string {
var port string
switch in.(type) {
case string:
// try to convert to number then convert back, to ensure valid value
portNum, err := strconv.Atoi(in.(string))
if portNum == 0 || err != nil {
return ""
}
port = strconv.Itoa(portNum)
case float64:
port = strconv.Itoa(int(in.(float64)))
default:
return ""
}
return port
}