-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bootstrap.go
109 lines (80 loc) · 2 KB
/
Bootstrap.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
package main
import (
"encoding/json"
"fmt"
"net"
"os"
"packet-mirror/utils"
"packet-mirror/worker"
"strconv"
"time"
)
var _logger = utils.NewLogger("Bootstrap")
func main() {
// Read Config
configFile := "./config.json"
_, err := os.Stat(configFile)
if os.IsNotExist(err) {
panic("config file not found")
}
buffer, err := os.ReadFile(configFile)
if err == nil && len(buffer) > 0 {
config := make(map[string]interface{})
err = json.Unmarshal(buffer, &config)
if err != nil {
panic(err)
}
if configurations, found := config["configurations"]; found {
printInterval := int(config["print.interval.sec"].(float64))
for _, c := range configurations.([]interface{}) {
mirror(c.(map[string]interface{}), printInterval)
}
}
select {}
} else {
panic("Config file is empty")
}
}
func mirror(config map[string]interface{}, interval int) {
srcPort := strconv.Itoa(int(config["src.port"].(float64)))
// Open a socket to receive incoming packets
connection, err := net.ListenPacket(config["protocol"].(string), ":"+srcPort)
if err != nil {
_logger.Error(err.Error())
return
}
// stats
totalPacket := 0
var workers []*worker.Worker
for _, _mirror := range config["mirrors"].([]interface{}) {
w := worker.New(_mirror.(map[string]interface{}), connection)
_logger.Info(fmt.Sprintf("%s --> %s", connection.LocalAddr().String(), w.ToString()))
workers = append(workers, w)
}
// Receive packets from the socket and send them to the destination addresses
go func() {
for {
buf := make([]byte, 5*1024*1024)
n, _, err := connection.ReadFrom(buf)
if err != nil {
_logger.Error(err.Error())
continue
}
totalPacket++
for _, _worker := range workers {
_worker.Packets <- buf[:n]
}
}
}()
// stats
go func() {
ticker := time.NewTicker(time.Second * time.Duration(interval))
for {
select {
case <-ticker.C:
_logger.Debug(connection.LocalAddr().String() + ": " + strconv.Itoa(totalPacket))
totalPacket = 0
}
}
}()
}