-
Notifications
You must be signed in to change notification settings - Fork 33
/
main.go
84 lines (71 loc) · 1.72 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
package main
import (
"log"
"net/http"
"sync"
"time"
"github.com/Qv2ray/mmp-go/config"
"github.com/Qv2ray/mmp-go/dispatcher"
_ "github.com/Qv2ray/mmp-go/dispatcher/tcp"
_ "github.com/Qv2ray/mmp-go/dispatcher/udp"
)
const HttpClientTimeout = 10 * time.Second
type MapPortDispatcher map[int]*[len(protocols)]dispatcher.Dispatcher
type SyncMapPortDispatcher struct {
sync.Mutex
Map MapPortDispatcher
}
func NewSyncMapPortDispatcher() *SyncMapPortDispatcher {
return &SyncMapPortDispatcher{Map: make(MapPortDispatcher)}
}
var (
protocols = [...]string{"tcp", "udp"}
groupWG sync.WaitGroup
mPortDispatcher = NewSyncMapPortDispatcher()
)
func listenGroup(group *config.Group) {
err := listenProtocols(group, protocols[:])
if err != nil {
mPortDispatcher.Lock()
// error but listening
if _, ok := mPortDispatcher.Map[group.Port]; ok {
log.Fatalln(err)
}
mPortDispatcher.Unlock()
}
}
func listenProtocols(group *config.Group, protocols []string) error {
mPortDispatcher.Lock()
if _, ok := mPortDispatcher.Map[group.Port]; !ok {
mPortDispatcher.Map[group.Port] = new([2]dispatcher.Dispatcher)
}
t := mPortDispatcher.Map[group.Port]
mPortDispatcher.Unlock()
ch := make(chan error, len(protocols))
for i, protocol := range protocols {
d, _ := dispatcher.New(protocol, group)
(*t)[i] = d
go func() {
err := d.Listen()
ch <- err
}()
}
return <-ch
}
func main() {
conf := config.NewConfig(&http.Client{
Timeout: HttpClientTimeout,
})
// handle reload
go signalHandler(conf)
mPortDispatcher.Lock()
for i := range conf.Groups {
groupWG.Add(1)
go func(group *config.Group) {
listenGroup(group)
groupWG.Done()
}(&conf.Groups[i])
}
mPortDispatcher.Unlock()
groupWG.Wait()
}