-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
315 lines (262 loc) · 7.15 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
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
package main
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"github.com/netwatcherio/netwatcher-agent/probes"
"github.com/netwatcherio/netwatcher-agent/workers"
"github.com/netwatcherio/netwatcher-agent/ws"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson/primitive"
"io"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"time"
)
func main() {
fmt.Printf("Starting NetWatcher Agent...\n")
var configPath string
flag.StringVar(&configPath, "config", "./config.conf", "Path to the config file")
flag.Parse()
loadConfig(configPath)
// Download dependency
err := downloadTrippyDependency()
if err != nil {
log.Fatalf("Failed to download dependency: %v", err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for _ = range c {
shutdown()
return
}
}()
var probeGetCh = make(chan []probes.Probe)
var probeDataCh = make(chan probes.ProbeData)
wsH := &ws.WebSocketHandler{
Host: os.Getenv("HOST"),
HostWS: os.Getenv("HOST_WS"),
Pin: os.Getenv("PIN"),
ID: os.Getenv("ID"),
AgentVersion: VERSION,
ProbeGetCh: probeGetCh,
}
wsH.InitWS()
// init the config getter before starting the probe workers?
workers.InitProbeDataWorker(wsH, probeDataCh)
go func(ws *ws.WebSocketHandler) {
for {
time.Sleep(time.Minute * 1)
log.Info("Getting probes again...")
ws.GetConnection().Emit("probe_get", []byte("please"))
}
}(wsH)
thisAgent, err := primitive.ObjectIDFromHex(wsH.ID)
if err != nil {
return
}
workers.InitProbeWorker(probeGetCh, probeDataCh, thisAgent)
// todo handle if on start it isn't able to pull information from backend??
// eg. power goes out but network fails to come up?
// todo input channel into wsH for inbound/outbound data to be handled
// if a list of probes is received, send it to the channel for inbound probes and such
// once receiving probes, have it cycle through, set the unique id for it, if a different one exists as the same ID,
//update/remove it, n use the new settings
select {}
}
func shutdown() {
log.Fatalf("Currently %d threads", runtime.NumGoroutine())
log.Fatal("Shutting down NetWatcher Agent...")
}
func downloadTrippyDependency() error {
var version = "0.10.0"
baseURL := "https://github.com/fujiapple852/trippy/releases/download/" + version + "/"
var fileName, extractedName string
switch runtime.GOOS {
case "windows":
if runtime.GOARCH == "amd64" {
fileName = "trippy-VER-x86_64-pc-windows-msvc.zip"
} else {
fileName = "trippy-VER-aarch64-pc-windows-msvc.zip"
}
extractedName = "trip.exe"
case "darwin":
fileName = "trippy-VER-x86_64-apple-darwin.tar.gz"
extractedName = "trip"
case "linux":
if runtime.GOARCH == "amd64" {
fileName = "trippy-VER-x86_64-unknown-linux-musl.tar.gz"
} else if runtime.GOARCH == "arm64" {
fileName = "trippy-VER-aarch64-unknown-linux-musl.tar.gz"
} else {
return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
}
extractedName = "trip"
default:
return fmt.Errorf("unsupported OS: %s", runtime.GOOS)
}
var format = strings.Replace(fileName, "VER", version, -1)
url := baseURL + format
libPath := filepath.Join(".", "lib")
os.MkdirAll(libPath, os.ModePerm)
filePath := filepath.Join(libPath, extractedName)
// Check if file already exists
if _, err := os.Stat(filePath); err == nil {
log.Printf("Trippy binary already exists: %s\n", filePath)
return nil
}
log.Printf("Downloading %s to %s\n", url, filePath)
// Download file
tempFilePath := filePath + ".temp"
err := downloadFile(url, tempFilePath)
if err != nil {
return fmt.Errorf("failed to download file: %v", err)
}
var newHash string
if runtime.GOOS == "windows" {
newHash, err = extractZipAndHash(tempFilePath, libPath)
if err != nil {
os.Remove(tempFilePath)
return fmt.Errorf("failed to extract archive: %v", err)
}
// Remove the temporary zip file
os.Remove(tempFilePath)
} else {
// Extract the tar.gz for Linux and macOS
newHash, err = extractTarGzAndHash(tempFilePath, libPath)
if err != nil {
os.Remove(tempFilePath)
return fmt.Errorf("failed to extract archive: %v", err)
}
// Remove the temporary tar.gz file
os.Remove(tempFilePath)
}
log.Printf("Downloaded trippy binary: %s\n", filePath)
// Make the file executable
err = os.Chmod(filePath, 0755)
if err != nil {
return fmt.Errorf("failed to make file executable: %v", err)
}
// Store the hash for future comparisons
err = os.WriteFile(filePath+".hash", []byte(newHash), 0644)
if err != nil {
log.Printf("Failed to write hash file: %v", err)
}
return nil
}
func extractTarGzAndHash(archivePath, destPath string) (string, error) {
file, err := os.Open(archivePath)
if err != nil {
return "", err
}
defer file.Close()
gzr, err := gzip.NewReader(file)
if err != nil {
return "", err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return "", err
}
if header.Typeflag == tar.TypeReg && filepath.Base(header.Name) == "trip" {
outPath := filepath.Join(destPath, "trip")
outFile, err := os.Create(outPath)
if err != nil {
return "", err
}
defer outFile.Close()
hasher := sha256.New()
writer := io.MultiWriter(outFile, hasher)
if _, err := io.Copy(writer, tr); err != nil {
return "", err
}
log.Printf("Extracted file: %s\n", header.Name)
return hex.EncodeToString(hasher.Sum(nil)), nil
}
}
return "", fmt.Errorf("'trip' binary not found in archive")
}
func extractZipAndHash(archivePath, destPath string) (string, error) {
reader, err := zip.OpenReader(archivePath)
if err != nil {
return "", err
}
defer reader.Close()
for _, file := range reader.File {
if filepath.Base(file.Name) == "trip.exe" {
outPath := filepath.Join(destPath, "trip.exe")
src, err := file.Open()
if err != nil {
return "", err
}
defer src.Close()
dst, err := os.Create(outPath)
if err != nil {
return "", err
}
defer dst.Close()
hasher := sha256.New()
writer := io.MultiWriter(dst, hasher)
if _, err := io.Copy(writer, src); err != nil {
return "", err
}
fmt.Printf("Extracted file: %s\n", file.Name)
return hex.EncodeToString(hasher.Sum(nil)), nil
}
}
return "", fmt.Errorf("'netwatcher-agent.exe' not found in archive")
}
func getFileHash(filePath string) (string, error) {
f, err := os.Open(filePath)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func isUpdateNeeded(filePath string) bool {
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
return true
}
hashFile := filePath + ".hash"
_, err = os.Stat(hashFile)
if os.IsNotExist(err) {
return true
}
// If both files exist, assume it's up to date
return false
}
func downloadFile(url string, filePath string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
out, err := os.Create(filePath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}