-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetventory.go
916 lines (811 loc) · 24 KB
/
netventory.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
package main
import (
_ "embed"
"flag"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/jackpal/gateway"
"github.com/ramborogers/netventory/scanner"
"github.com/ramborogers/netventory/telemetry"
"github.com/ramborogers/netventory/views"
"github.com/ramborogers/netventory/web"
)
const (
version = "0.3.0n"
debug = false // Default debug setting, can be overridden by --debug flag
authTokenLength = 50
)
//go:embed private.txt
var privateConfig string
var (
workerCount = 50 // Default worker count, can be overridden by --workers flag
webPort = 7331 // Default web interface port
webServer *web.Server
telemetryClient *telemetry.Client
)
// parsePrivateConfig parses the embedded configuration
func parsePrivateConfig() (server, token string, err error) {
lines := strings.Split(privateConfig, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
switch key {
case "TELEMETRY_SERVER":
server = value
case "TELEMETRY_TOKEN":
token = value
}
}
if server == "" {
return "", "", fmt.Errorf("TELEMETRY_SERVER not found in embedded config")
}
if token == "" {
return "", "", fmt.Errorf("TELEMETRY_TOKEN not found in embedded config")
}
return server, token, nil
}
func init() {
// Initialize telemetry client in background
go func() {
server, token, err := parsePrivateConfig()
if err != nil {
log.Printf("Warning: Failed to parse embedded config: %v", err)
return
}
var clientErr error
telemetryClient, clientErr = telemetry.NewClient(server, token, version)
if clientErr != nil {
// Log error but continue - telemetry is non-critical
log.Printf("Failed to initialize telemetry: %v", clientErr)
return
}
if err := telemetryClient.Start(); err != nil {
// Log error but continue - telemetry is non-critical
log.Printf("Failed to start telemetry: %v", err)
telemetryClient = nil // Disable telemetry on error
}
}()
// Parse command line flags
debugFlag := flag.Bool("debug", debug, "Enable debug mode (generates debug.log and report.log)")
flag.BoolVar(debugFlag, "d", debug, "") // Shorthand
workers := flag.Int("workers", workerCount, "Number of concurrent scanning workers")
webFlag := flag.Bool("web", false, "Enable web interface mode")
flag.BoolVar(webFlag, "w", false, "") // Shorthand
portFlag := flag.Int("port", webPort, "Web interface port")
flag.IntVar(portFlag, "p", webPort, "") // Shorthand
versionFlag := flag.Bool("version", false, "Display version information")
flag.BoolVar(versionFlag, "v", false, "") // Shorthand
// Add help text
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "netventory %s - Network Discovery Tool\n", version)
fmt.Fprintf(os.Stderr, "https://github.com/RamboRogers/netventory\n\n")
fmt.Fprintf(os.Stderr, "Usage: %s [options]\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Options:\n")
fmt.Fprintf(os.Stderr, " -d, --debug Enable debug mode (generates debug.log and report.log)\n")
fmt.Fprintf(os.Stderr, " -w, --web Enable web interface mode\n")
fmt.Fprintf(os.Stderr, " -p, --port Web interface port (default: 7331)\n")
fmt.Fprintf(os.Stderr, " -v, --version Display version information\n")
fmt.Fprintf(os.Stderr, " --workers Number of concurrent scanning workers (default: 50)\n")
os.Exit(1)
}
flag.Parse()
// Handle version flag first
if *versionFlag {
fmt.Printf("netventory %s\n", version)
fmt.Printf("https://github.com/RamboRogers/netventory\n")
os.Exit(0)
}
// Show help if any non-flag arguments are provided
if flag.NArg() > 0 {
fmt.Fprintf(os.Stderr, "Error: unexpected argument '%s'\n\n", flag.Arg(0))
flag.Usage()
}
// Update global settings from flags
if *debugFlag {
// Set up logging to file if debug is enabled
f, err := os.OpenFile("debug.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening debug.log: %v", err)
}
log.SetOutput(f)
} else {
// Disable logging when debug is false
log.SetOutput(io.Discard)
}
if *workers > 0 {
workerCount = *workers
}
if *webFlag {
webPort = *portFlag
startWebInterface()
// Wait indefinitely while web server runs
select {}
}
}
// startWebInterface initializes and starts the web interface
func startWebInterface() {
// Restore console logging for web interface
log.SetOutput(os.Stderr)
fmt.Printf("\033[92mnetventory %s - Network Discovery Tool\033[0m\n", version)
fmt.Printf("\033[94mhttps://github.com/RamboRogers/netventory\033[0m\n\n")
// Generate auth token
authToken := generateAuthToken(authTokenLength)
// Get all network interfaces
interfaces, err := getNetworkInterfaces()
if err != nil {
log.Printf("Warning: Could not get network interfaces: %v", err)
}
server, err := web.NewServer(webPort, authToken, fmt.Sprintf("v%s", version))
if err != nil {
log.Fatalf("Failed to create web server: %v", err)
}
// Start web server in a goroutine
go func() {
fmt.Printf("\033[92mWeb interface available at:\033[0m\n")
fmt.Printf(" \033[94mhttp://localhost:%d?auth=%s\033[0m \n", webPort, authToken)
// Print URLs for all network interfaces
for _, iface := range interfaces {
if iface.IPAddress != "" && !strings.HasPrefix(iface.IPAddress, "127.") {
fmt.Printf(" \033[94mhttp://%s:%d?auth=%s\033[0m\n", iface.IPAddress, webPort, authToken)
}
}
fmt.Println("\nAuthentication token required in URL: ?auth=<token>")
fmt.Println("Token will be valid until program restart")
fmt.Println()
if err := server.Start(); err != nil {
log.Fatalf("Web server error: %v", err)
}
}()
// Store server reference for updates
webServer = server
}
// Model represents the application state
type Model struct {
currentScreen string
interfaces []views.Interface
selectedIndex int
err error
width int
height int
frame int
proposedRange string
editingRange bool
cursorPos int
devices map[string]scanner.Device
scanningActive bool
currentIP string
scanSelectedIndex int
showingDetails bool
activeScans map[string]bool
deviceMutex sync.RWMutex
tableOffset int
totalIPs int32
scannedCount int32
discoveredCount int32
scanStartTime time.Time
workerStats map[int]*scanner.WorkerStatus
statsLock sync.RWMutex
scanner *scanner.Scanner
styles *views.Styles
welcomeView *views.WelcomeView
interfacesView *views.InterfacesView
confirmView *views.ConfirmView
scanningView *views.ScanningView
deviceDetailsView *views.DeviceDetailsView
}
// Add constants for screen states
const (
screenWelcome = "welcome"
screenInterfaces = "interfaces"
screenConfirm = "confirm"
screenScanning = "scanning"
screenResults = "results"
)
// Add message types
type interfacesMsg []views.Interface
type errMsg struct{ error }
type deviceMsg struct {
done bool
}
// Add DeviceUpdate type definition near other types at the top
type DeviceUpdate struct {
Device scanner.Device
}
// Add new message type for scan updates
type scanUpdateMsg struct {
device scanner.Device
totalHosts int
scannedHosts int
}
// Add new message type for stats updates
type statsUpdateMsg struct{}
// Add stats ticker command
func statsTick() tea.Cmd {
return tea.Tick(time.Millisecond*200, func(t time.Time) tea.Msg {
return statsUpdateMsg{}
})
}
// Add new message type for welcome timer
type welcomeTimerMsg struct{}
// Add welcome timer command
func welcomeTimer() tea.Cmd {
return tea.Tick(900*time.Millisecond, func(t time.Time) tea.Msg {
return welcomeTimerMsg{}
})
}
// generateAuthToken creates a cryptographically secure random token
func generateAuthToken(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
log.Fatalf("Failed to generate secure token: %v", err)
}
for i := range b {
b[i] = charset[int(b[i])%len(charset)]
}
return string(b)
}
// Update initialModel to start the welcome timer
func initialModel() *Model {
styles := views.NewStyles()
m := &Model{
currentScreen: screenWelcome,
devices: make(map[string]scanner.Device),
activeScans: make(map[string]bool),
workerStats: make(map[int]*scanner.WorkerStatus),
selectedIndex: 0,
scanSelectedIndex: 0,
tableOffset: 0,
showingDetails: false,
editingRange: false,
cursorPos: 0,
frame: 0,
scanningActive: false,
currentIP: "",
styles: styles,
welcomeView: views.NewWelcomeView(styles, version),
interfacesView: views.NewInterfacesView(styles),
confirmView: views.NewConfirmView(styles),
scanningView: views.NewScanningView(styles),
deviceDetailsView: views.NewDeviceDetailsView(styles),
}
return m
}
// Define a command that reads exactly one result from resultsChan or doneChan.
// We'll call this each time we handle scanUpdateMsg so it keeps pulling messages until the channel is closed.
func (m *Model) readScanResultCmd() tea.Cmd {
return func() tea.Msg {
if m.scanner == nil {
return deviceMsg{done: true}
}
resultsChan, doneChan := m.scanner.GetResults()
select {
case device, ok := <-resultsChan:
if !ok {
// resultsChan was closed
log.Printf("Results channel closed")
return deviceMsg{done: true}
}
log.Printf("Received device: %s", device.IPAddress)
// Get latest stats from scanner
stats := m.scanner.GetWorkerStats()
var totalScanned int32
for _, stat := range stats {
totalScanned += atomic.LoadInt32(&stat.IPsScanned)
}
// Return a scanUpdateMsg with latest stats
return scanUpdateMsg{
device: device,
totalHosts: int(atomic.LoadInt32(&m.totalIPs)),
scannedHosts: int(totalScanned),
}
case <-doneChan:
// The scanning goroutines have signaled completion
log.Printf("Scan complete - closing scanner")
m.scanner.Close() // Close the scanner and its report file
m.scanningActive = false
return deviceMsg{done: true}
default:
// No update available, check again soon
time.Sleep(100 * time.Millisecond)
return scanUpdateMsg{} // Empty update to keep the UI refreshing
}
}
}
// Improved scanning pipeline
func (m *Model) scanNetwork(cidr string) tea.Cmd {
return func() tea.Msg {
log.Printf("=== Starting new scan ===")
log.Printf("CIDR Range: %s", cidr)
// Create new scanner instance
m.scanner = scanner.NewScanner(debug)
if m.scanner == nil {
return errMsg{fmt.Errorf("failed to create scanner")}
}
// Reset scan state
m.deviceMutex.Lock()
m.devices = make(map[string]scanner.Device)
m.deviceMutex.Unlock()
// Reset worker stats
m.statsLock.Lock()
m.workerStats = make(map[int]*scanner.WorkerStatus)
m.statsLock.Unlock()
// Parse CIDR to get total IPs for progress tracking
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
return errMsg{err}
}
ips := scanner.GetAllIPs(ipNet)
atomic.StoreInt32(&m.totalIPs, int32(len(ips)))
atomic.StoreInt32(&m.scannedCount, 0)
atomic.StoreInt32(&m.discoveredCount, 0)
m.scanStartTime = time.Now()
m.scanningActive = true
// Set scan start time in the scanning view
m.scanningView.SetScanStartTime(m.scanStartTime)
// Start the scan
if err := m.scanner.ScanNetwork(cidr, workerCount); err != nil {
return errMsg{err}
}
// Return both commands
return tea.Batch(
m.readScanResultCmd(),
statsTick(),
)()
}
}
// Update animation speed
func tick() tea.Cmd {
return tea.Tick(time.Millisecond*80, func(t time.Time) tea.Msg {
return tickMsg(t)
})
}
// Add tick message type
type tickMsg time.Time
// Init implements tea.Model
func (m *Model) Init() tea.Cmd {
return tea.Batch(
welcomeTimer(),
func() tea.Msg {
interfaces, err := getNetworkInterfaces()
if err != nil {
return errMsg{err}
}
return interfacesMsg(interfaces)
},
)
}
// Update implements tea.Model
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case welcomeTimerMsg:
if m.currentScreen == screenWelcome {
m.currentScreen = screenInterfaces
}
return m, nil
case tickMsg:
m.frame++ // Increment frame counter for animation
return m, tick()
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
return m, nil
case interfacesMsg:
m.interfaces = msg
return m, nil
case errMsg:
m.err = msg
return m, nil
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
case "q":
if !m.showingDetails && (m.currentScreen == screenScanning || m.currentScreen == screenResults) {
return m, tea.Quit
}
case "e":
if m.currentScreen == screenConfirm {
m.editingRange = true
}
case "up", "k":
if m.currentScreen == screenScanning || m.currentScreen == screenResults {
if m.scanSelectedIndex > 0 {
m.scanSelectedIndex--
if m.scanSelectedIndex < m.tableOffset {
m.tableOffset = m.scanSelectedIndex
}
}
} else if m.selectedIndex > 0 {
m.selectedIndex--
}
case "down", "j":
if m.currentScreen == screenScanning || m.currentScreen == screenResults {
deviceCount := len(m.devices)
if m.scanSelectedIndex < deviceCount-1 {
m.scanSelectedIndex++
if m.scanSelectedIndex >= m.tableOffset+10 {
m.tableOffset = m.scanSelectedIndex - 9
}
}
} else if m.selectedIndex < len(m.interfaces)-1 {
m.selectedIndex++
}
case "pgup":
if m.currentScreen == screenScanning || m.currentScreen == screenResults {
m.tableOffset = max(0, m.tableOffset-10)
m.scanSelectedIndex = max(m.scanSelectedIndex-10, m.tableOffset)
}
case "pgdown":
if m.currentScreen == screenScanning || m.currentScreen == screenResults {
deviceCount := len(m.devices)
maxOffset := max(0, deviceCount-10)
m.tableOffset = min(maxOffset, m.tableOffset+10)
m.scanSelectedIndex = min(m.scanSelectedIndex+10, deviceCount-1)
}
case "s":
if m.currentScreen == screenScanning && m.scanningActive {
m.scanner.Stop() // Actually stop the scanner
m.scanningActive = false
m.currentScreen = screenResults
}
case "r":
if m.currentScreen == screenResults {
m.currentScreen = screenScanning
m.scanningActive = true
return m, tea.Batch(
m.scanNetwork(m.proposedRange),
tick(),
)
}
case "enter":
switch m.currentScreen {
case screenWelcome:
m.currentScreen = screenInterfaces
case screenInterfaces:
if len(m.interfaces) > 0 {
selected := m.interfaces[m.selectedIndex]
m.proposedRange = calculateNetworkRange(selected.IPAddress, selected.CIDR)
m.currentScreen = screenConfirm
m.editingRange = false
m.cursorPos = len(m.proposedRange)
}
case screenConfirm:
if m.editingRange {
m.editingRange = false
} else {
m.currentScreen = screenScanning
m.scanningActive = true
return m, tea.Batch(
m.scanNetwork(m.proposedRange),
tick(),
)
}
case screenScanning, screenResults:
if device, ok := m.scanningView.GetSelectedDevice(); ok {
m.showingDetails = !m.showingDetails
if m.showingDetails {
m.deviceDetailsView.SetDevice(device)
m.deviceDetailsView.SetDimensions(m.width, m.height)
}
}
}
case "esc":
if m.currentScreen == screenConfirm {
if m.editingRange {
m.editingRange = false
} else {
m.currentScreen = screenInterfaces
}
} else if m.showingDetails {
m.showingDetails = false
}
// Add editing controls when editing range
case "left":
if m.editingRange && m.cursorPos > 0 {
m.cursorPos--
}
case "right":
if m.editingRange && m.cursorPos < len(m.proposedRange) {
m.cursorPos++
}
case "backspace":
if m.editingRange && m.cursorPos > 0 {
m.proposedRange = m.proposedRange[:m.cursorPos-1] + m.proposedRange[m.cursorPos:]
m.cursorPos--
}
default:
if m.editingRange {
// Only allow numbers, dots, and forward slash
if matched, _ := regexp.MatchString(`^[0-9./]$`, msg.String()); matched {
m.proposedRange = m.proposedRange[:m.cursorPos] + msg.String() + m.proposedRange[m.cursorPos:]
m.cursorPos++
}
}
}
case scanUpdateMsg:
if msg.device.IPAddress != "" {
m.deviceMutex.Lock()
m.devices[msg.device.IPAddress] = msg.device
m.deviceMutex.Unlock()
atomic.AddInt32(&m.discoveredCount, 1)
// Update web interface if enabled
if webServer != nil {
webServer.UpdateDevices(m.devices)
}
}
// Update scan progress from scanner
if m.scanner != nil {
stats := m.scanner.GetWorkerStats()
var totalScanned int32
for _, stat := range stats {
totalScanned += atomic.LoadInt32(&stat.IPsScanned)
}
atomic.StoreInt32(&m.scannedCount, totalScanned)
// Update worker stats
m.statsLock.Lock()
m.workerStats = make(map[int]*scanner.WorkerStatus, len(stats))
for id, stat := range stats {
statCopy := stat // Create a copy of the stat
m.workerStats[id] = &statCopy
}
m.statsLock.Unlock()
// Update scanning view with latest stats
m.scanningView.SetProgress(m.scannedCount, m.totalIPs, m.discoveredCount)
m.scanningView.SetWorkerStats(m.workerStats)
// Update web interface if enabled
if webServer != nil {
webServer.UpdateProgress(m.scannedCount, m.totalIPs, m.discoveredCount)
}
// Force a refresh of the view
m.frame++ // Increment frame to trigger redraw
}
// Update current IP display
m.currentIP = fmt.Sprintf("Scanning: %s (%d/%d)",
msg.device.IPAddress,
atomic.LoadInt32(&m.scannedCount),
atomic.LoadInt32(&m.totalIPs),
)
// Return ourselves plus readScanResultCmd() again
// so Bubble Tea keeps reading from resultsChan
return m, tea.Batch(
tick(),
m.readScanResultCmd(),
)
case deviceMsg:
if msg.done {
m.scanningActive = false
m.currentScreen = screenResults
// Notify web interface if enabled
if webServer != nil {
webServer.BroadcastUpdate(map[string]interface{}{
"type": "scan_complete",
})
}
return m, nil
}
return m, nil
case statsUpdateMsg:
if m.scanningActive && m.scanner != nil {
// Update scan progress from scanner
stats := m.scanner.GetWorkerStats()
var totalScanned int32
for _, stat := range stats {
totalScanned += atomic.LoadInt32(&stat.IPsScanned)
}
atomic.StoreInt32(&m.scannedCount, totalScanned)
// Update worker stats
m.statsLock.Lock()
m.workerStats = make(map[int]*scanner.WorkerStatus, len(stats))
for id, stat := range stats {
statCopy := stat
m.workerStats[id] = &statCopy
}
m.statsLock.Unlock()
// Force a refresh of the view
m.frame++
// Continue stats updates while scanning
return m, statsTick()
}
return m, nil
}
return m, tea.Batch(cmds...)
}
// Add helper functions
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Add calculateNetworkRange function
func calculateNetworkRange(ip string, cidr string) string {
_, network, err := net.ParseCIDR(ip + cidr)
if err != nil {
return ip + cidr
}
return network.String()
}
// Add getNetworkInterfaces function
func getNetworkInterfaces() ([]views.Interface, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
// Get default gateway information
gatewayIP, err := gateway.DiscoverGateway()
if err != nil {
log.Printf("Error discovering gateway: %v", err)
gatewayIP = nil
}
var networkInterfaces []views.Interface
for _, iface := range ifaces {
// Handle interface flags based on OS
isUp := iface.Flags&net.FlagUp != 0
if runtime.GOOS == "windows" {
// Windows might need additional checks
isUp = isUp && iface.Flags&net.FlagBroadcast != 0
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok {
continue
}
// Skip loopback and non-IPv4
if ipNet.IP.IsLoopback() || ipNet.IP.To4() == nil {
continue
}
// Get display name
displayName := iface.Name
if runtime.GOOS == "windows" {
if friendly := getWindowsFriendlyName(iface.Name); friendly != "" {
displayName = friendly
}
}
// Determine gateway for this interface
gateway := "Not detected"
if gatewayIP != nil && ipNet.Contains(gatewayIP) {
gateway = gatewayIP.String()
}
// Get subnet mask in CIDR notation
ones, _ := ipNet.Mask.Size()
cidr := fmt.Sprintf("/%d", ones)
networkInterfaces = append(networkInterfaces, views.Interface{
Name: iface.Name,
FriendlyName: displayName,
IPAddress: ipNet.IP.String(),
SubnetMask: ipNet.Mask.String(),
CIDR: cidr,
MACAddress: iface.HardwareAddr.String(),
Gateway: gateway,
IsUp: isUp,
Priority: getPriority(displayName), // Use display name for priority
})
}
}
// Sort interfaces by priority
sort.Slice(networkInterfaces, func(i, j int) bool {
return networkInterfaces[i].Priority < networkInterfaces[j].Priority
})
return networkInterfaces, nil
}
func getWindowsFriendlyName(interfaceName string) string {
if runtime.GOOS != "windows" {
return interfaceName
}
return interfaceName // Simplified for now
}
func getPriority(name string) int {
switch {
case strings.HasPrefix(name, "en"):
return 1 // Ethernet/WiFi on macOS/BSD
case strings.HasPrefix(name, "eth"):
return 2 // Ethernet on Linux
case strings.HasPrefix(name, "wlan"):
return 3 // WiFi on Linux
case strings.Contains(name, "Ethernet") || strings.Contains(name, "Local Area Connection"):
return 2 // Ethernet on Windows
case strings.Contains(name, "Wi-Fi") || strings.Contains(name, "Wireless"):
return 3 // WiFi on Windows
default:
return 100 // Other interfaces
}
}
// View implements tea.Model
func (m *Model) View() string {
switch m.currentScreen {
case screenWelcome:
return m.renderWelcomeView()
case screenInterfaces:
return m.renderInterfacesView()
case screenConfirm:
return m.renderConfirmView()
case screenScanning, screenResults:
if m.showingDetails {
m.deviceDetailsView.SetDimensions(m.width, m.height)
return m.deviceDetailsView.Render()
}
return m.renderScanningView()
default:
return "Unknown screen"
}
}
func (m *Model) renderWelcomeView() string {
m.welcomeView.SetDimensions(m.width, m.height)
m.welcomeView.SetFrame(m.frame)
return m.welcomeView.Render()
}
func (m *Model) renderInterfacesView() string {
m.interfacesView.SetDimensions(m.width, m.height)
m.interfacesView.SetInterfaces(m.interfaces)
m.interfacesView.SetSelectedIndex(m.selectedIndex)
return m.interfacesView.Render()
}
func (m *Model) renderConfirmView() string {
m.confirmView.SetDimensions(m.width, m.height)
m.confirmView.SetInterface(m.interfaces[m.selectedIndex])
m.confirmView.SetRange(m.proposedRange)
m.confirmView.SetEditing(m.editingRange)
m.confirmView.SetCursor(m.cursorPos)
return m.confirmView.Render()
}
func (m *Model) renderScanningView() string {
m.scanningView.SetDimensions(m.width, m.height)
m.scanningView.SetDevices(m.devices)
m.scanningView.SetSelectedIndex(m.scanSelectedIndex)
m.scanningView.SetTableOffset(m.tableOffset)
m.scanningView.SetShowingDetails(m.showingDetails)
m.scanningView.SetScanningActive(m.scanningActive)
m.scanningView.SetCurrentIP(m.currentIP)
m.scanningView.SetProgress(m.scannedCount, m.totalIPs, m.discoveredCount)
m.scanningView.SetScanStartTime(m.scanStartTime)
m.scanningView.SetWorkerStats(m.workerStats)
return m.scanningView.Render()
}
func main() {
defer func() {
// Clean up telemetry client on exit
if telemetryClient != nil {
telemetryClient.Stop()
}
}()
p := tea.NewProgram(
initialModel(),
tea.WithAltScreen(), // Use alternate screen buffer
)
if _, err := p.Run(); err != nil {
fmt.Printf("Error running program: %v", err)
os.Exit(1)
}
}