-
Notifications
You must be signed in to change notification settings - Fork 7
/
base.go
77 lines (70 loc) · 1.53 KB
/
base.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
package main
import (
"net"
"sync"
"github.com/ccsexyz/shadowsocks-go/internal/utils"
ss "github.com/ccsexyz/shadowsocks-go/shadowsocks"
)
func RunTCPServer(address string, c *ss.Config,
listen func(string, *ss.Config) (net.Listener, error),
handler func(ss.Conn, *ss.Config)) {
var addresses []string
func() {
addrsMap := make(map[string]bool)
c.Localaddrs = append(c.Localaddrs, c.Localaddr)
for _, addr := range c.Localaddrs {
if len(addr) > 0 {
addrsMap[addr] = true
}
}
for addr, _ := range addrsMap {
addresses = append(addresses, addr)
}
}()
var wg sync.WaitGroup
for _, address := range addresses {
wg.Add(1)
go func(address string) {
defer wg.Done()
lis, err := listen(address, c)
if err != nil {
c.Logger.Fatal(err)
}
defer lis.Close()
go func() {
if c.Die != nil {
<-c.Die
lis.Close()
}
}()
for {
conn, err := lis.Accept()
if err != nil {
return
}
go handler(conn.(ss.Conn), c)
}
}(address)
}
wg.Wait()
}
func GetDstOfConn(conn ss.Conn) string {
dst := conn.GetDst()
if dst == nil {
return ""
}
return dst.String()
}
func getDefaultUDPServerCtx() *utils.UDPServerCtx {
return &utils.UDPServerCtx{Mtu: 2048, Expires: 60}
}
func RunUDPServer(listener net.PacketConn, config *ss.Config, creator func(*ss.Config) func(*utils.SubConn) (net.Conn, net.Conn, error)) {
go func() {
if config.Die == nil {
return
}
defer listener.Close()
<-config.Die
}()
getDefaultUDPServerCtx().RunUDPServer(listener, creator(config))
}