-
Notifications
You must be signed in to change notification settings - Fork 1
/
hub.go
95 lines (75 loc) · 1.4 KB
/
hub.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
package main;
import (
"fmt";
"os";
"net";
"time";
"encoding/json";
"io/ioutil";
);
type Address struct {
Host string
Port int16
};
type Config struct {
Maps []ProxyMap
}
type ProxyMap struct {
SrcPort int16
DstAddr []Address
};
func sendBuf(dst Address, buf []byte, ret chan int) {
conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", dst.Host, dst.Port));
check(err);
n, err := conn.Write(buf)
check(err);
ret <- 1
}
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
var cfg Config;
count := 0;
file, err := ioutil.ReadFile("./config.json");
check(err);
err = json.Unmarshal(file, &cfg);
check(err);
trigger := time.Tick(10 * time.Second);
counter := make(chan int);
for i := range(cfg.Maps) {
proxymap := cfg.Maps[i];
go proxy(proxymap.SrcPort, proxymap.DstAddr, counter);
}
for {
select {
case <- counter:
count++;
case <- trigger:
fmt.Printf("count=%d\n", count);
}
}
}
func proxy(port int16, destinations []Address, count chan int) {
sock, err := net.ListenPacket("udp", fmt.Sprintf(":%d", port));
check(err);
// select on socket
for {
var buf [65535]byte;
rlen, _, err := sock.ReadFrom(buf[0:]);
if err != nil {
fmt.Println(err);
os.Exit(1);
}
if rlen == 0 {
continue;
}
// send to destinations
for k := range(destinations) {
dst := destinations[k];
go sendBuf(dst, buf[:rlen], count);
}
}
}