-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2461 lines (2223 loc) · 74.7 KB
/
main.go
File metadata and controls
2461 lines (2223 loc) · 74.7 KB
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"dhcplane/arp"
"dhcplane/config"
"dhcplane/dhcpserver"
"dhcplane/statistics"
"encoding/json"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"text/tabwriter"
"time"
"github.com/fsnotify/fsnotify"
"github.com/insomniacslk/dhcp/dhcpv4"
"github.com/logrusorgru/aurora"
planeconsole "github.com/network-plane/planeconsole"
"github.com/spf13/cobra"
"gopkg.in/natefinch/lumberjack.v2"
)
var appVersion = "0.1.67"
func buildConsoleConfig(maxLines int) planeconsole.Config {
if maxLines <= 0 {
maxLines = planeconsole.DefaultMaxLines
}
return planeconsole.Config{
MaxLines: maxLines,
Counters: []planeconsole.CounterSpec{
{Match: "REQUEST", CaseSensitive: false, Label: "RPM", WindowSeconds: 60},
{Match: "ACK", CaseSensitive: false, Label: "APM", WindowSeconds: 60},
},
Highlights: []planeconsole.HighlightSpec{
{Match: "BANNED-MAC", CaseSensitive: true, Style: &planeconsole.Style{FG: "red", Attrs: "b"}},
{Match: "NAK", CaseSensitive: true, Style: &planeconsole.Style{FG: "red", Attrs: "b"}},
{Match: "ACK", CaseSensitive: true, Style: &planeconsole.Style{FG: "green", Attrs: "b"}},
{Match: "OFFER", CaseSensitive: true, Style: &planeconsole.Style{FG: "green", Attrs: "b"}},
{Match: "REQUEST", CaseSensitive: true, Style: &planeconsole.Style{FG: "yellow", Attrs: "b"}},
{Match: "DISCOVER", CaseSensitive: true, Style: &planeconsole.Style{FG: "yellow", Attrs: "b"}},
{Match: "RELEASE", CaseSensitive: true, Style: &planeconsole.Style{FG: "yellow", Attrs: "b"}},
{Match: "DECLINE", CaseSensitive: true, Style: &planeconsole.Style{FG: "yellow", Attrs: "b"}},
{Match: "DETECT DHCPSERVERS", CaseSensitive: true, Style: &planeconsole.Style{FG: "green", Attrs: "b"}},
{Match: "FOREIGN-DHCP-SERVER", CaseSensitive: true, Style: &planeconsole.Style{FG: "red", Attrs: "b"}},
{Match: "ARP-ANOMALY", CaseSensitive: true, Style: &planeconsole.Style{FG: "red", Attrs: "b"}},
},
}
}
func consoleSocketCandidates() []string {
candidates := []string{
"/run/dhcplane/consoleui.sock",
"/tmp/consoleui.sock",
}
if xdg := os.Getenv("XDG_RUNTIME_DIR"); xdg != "" {
candidates = append(candidates, filepath.Join(xdg, "dhcplane.sock"))
}
return candidates
}
// multiListener wraps multiple net.Listeners and multiplexes Accept() across them.
type multiListener struct {
listeners []net.Listener
connCh chan net.Conn
errCh chan error
closeCh chan struct{}
closeOnce sync.Once
}
func newMultiListener(listeners ...net.Listener) *multiListener {
ml := &multiListener{
listeners: listeners,
connCh: make(chan net.Conn),
errCh: make(chan error, 1),
closeCh: make(chan struct{}),
}
for _, ln := range listeners {
go ml.acceptLoop(ln)
}
return ml
}
func (ml *multiListener) acceptLoop(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
select {
case <-ml.closeCh:
return
case ml.errCh <- err:
default:
}
return
}
select {
case ml.connCh <- conn:
case <-ml.closeCh:
conn.Close()
return
}
}
}
func (ml *multiListener) Accept() (net.Conn, error) {
select {
case conn := <-ml.connCh:
return conn, nil
case err := <-ml.errCh:
return nil, err
case <-ml.closeCh:
return nil, net.ErrClosed
}
}
func (ml *multiListener) Close() error {
ml.closeOnce.Do(func() {
close(ml.closeCh)
})
var lastErr error
for _, ln := range ml.listeners {
if err := ln.Close(); err != nil {
lastErr = err
}
}
return lastErr
}
func (ml *multiListener) Addr() net.Addr {
if len(ml.listeners) > 0 {
return ml.listeners[0].Addr()
}
return nil
}
// buildConsoleBroker wires the generic console broker with our DHCP-specific counters and highlights.
// If tcpAddr is non-empty (e.g., "0.0.0.0:9090"), it listens on both UNIX socket AND TCP.
// If tcpAddr is empty, it only listens on UNIX socket.
func buildConsoleBroker(maxLines int, tcpAddr string) (*planeconsole.Broker, string) {
opts := planeconsole.BrokerOptions{
Config: buildConsoleConfig(maxLines),
}
if tcpAddr != "" {
// Listen on BOTH UNIX socket and TCP using multiListener
opts.ListenerFactory = func() (string, net.Listener, error) {
var listeners []net.Listener
var addrs []string
// Try to create UNIX socket listener
for _, sockPath := range consoleSocketCandidates() {
// Remove stale socket file if it exists
_ = os.Remove(sockPath)
// Ensure directory exists
if err := os.MkdirAll(filepath.Dir(sockPath), 0o755); err != nil {
continue
}
unixLn, err := net.Listen("unix", sockPath)
if err == nil {
listeners = append(listeners, unixLn)
addrs = append(addrs, "unix:"+sockPath)
break
}
}
// Create TCP listener
tcpLn, err := net.Listen("tcp", tcpAddr)
if err != nil {
// Close any UNIX listener we created
for _, ln := range listeners {
ln.Close()
}
return "", nil, fmt.Errorf("tcp listen %s: %w", tcpAddr, err)
}
listeners = append(listeners, tcpLn)
addrs = append(addrs, "tcp:"+tcpLn.Addr().String())
if len(listeners) == 0 {
return "", nil, fmt.Errorf("failed to create any listeners")
}
ml := newMultiListener(listeners...)
return strings.Join(addrs, ", "), ml, nil
}
return planeconsole.NewBroker(opts), tcpAddr
}
// Default: UNIX socket only
opts.SocketCandidates = consoleSocketCandidates()
return planeconsole.NewBroker(opts), ""
}
/* ----------------- Logging ----------------- */
func setupLogger(cfg config.Config) (*log.Logger, io.Closer, error) {
var full string
if cfg.Logging.LogFile != "" {
// New style: single log_file path (already resolved by ValidateAndNormalizeConfig)
full = cfg.Logging.LogFile
} else {
// Legacy style: separate path and filename
filename := cfg.Logging.Filename
if filename == "" {
filename = "dhcplane.log"
}
full = filename
if cfg.Logging.Path != "" {
full = filepath.Join(cfg.Logging.Path, filename)
}
}
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil && !os.IsExist(err) {
return nil, nil, err
}
rot := &lumberjack.Logger{
Filename: full,
MaxSize: cfg.Logging.MaxSize,
MaxBackups: cfg.Logging.MaxBackups,
MaxAge: cfg.Logging.MaxAge,
Compress: cfg.Logging.Compress,
}
lg := log.New(rot, "", log.LstdFlags|log.Lmicroseconds)
return lg, rot, nil
}
func writePID(pidPath string) error {
if pidPath == "" {
return nil
}
if err := os.MkdirAll(filepath.Dir(pidPath), 0o755); err != nil && !os.IsExist(err) {
return err
}
return os.WriteFile(pidPath, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0o644)
}
func readPID(pidPath string) (int, error) {
b, err := os.ReadFile(pidPath)
if err != nil {
return 0, err
}
var pid int
_, err = fmt.Sscanf(string(b), "%d", &pid)
if err != nil {
return 0, err
}
return pid, nil
}
/* ----------------- Server bootstrap ----------------- */
// logDetect prints the detection mode line to logs and console via logSink.
func logDetect(cfg *config.Config, iface string, logSink func(string, ...any)) {
if cfg.DetectDHCPServers.Enabled {
logSink("DETECT DHCPSERVERS start mode=%s interval=%ds rate_limit=%d/min iface=%s whitelist=%d",
strings.ToLower(strings.TrimSpace(cfg.DetectDHCPServers.ActiveProbe)),
cfg.DetectDHCPServers.ProbeInterval,
cfg.DetectDHCPServers.RateLimit,
iface,
len(cfg.DetectDHCPServers.WhitelistServers),
)
} else {
logSink("DETECT DHCPSERVERS disabled (config) iface=%s", iface)
}
}
// PathOverrides holds command-line overrides for file paths.
type PathOverrides struct {
LeasesPath string
ReservationsPath string
LogFilePath string
PIDFilePath string
}
// applyPathOverrides applies command-line path overrides to the config.
func applyPathOverrides(cfg *config.Config, overrides PathOverrides) {
if overrides.LeasesPath != "" {
cfg.LeaseDBPath = config.ResolveFilePath(overrides.LeasesPath, "dhcplane.leases", "")
}
if overrides.ReservationsPath != "" {
cfg.ReservationsPath = config.ResolveFilePath(overrides.ReservationsPath, "dhcplane.reservations", "")
}
if overrides.LogFilePath != "" {
cfg.Logging.LogFile = config.ResolveFilePath(overrides.LogFilePath, "dhcplane.log", "")
// Clear legacy fields to avoid confusion
cfg.Logging.Path = ""
cfg.Logging.Filename = ""
}
if overrides.PIDFilePath != "" {
cfg.PIDFile = config.ResolveFilePath(overrides.PIDFilePath, "dhcplane.pid", "")
}
}
// FileCheckResult holds the result of a file path validation check.
type FileCheckResult struct {
Path string
Description string
Exists bool
DirExists bool
Writable bool
Error error
}
// validateFilePaths checks if all required file paths are accessible and writable.
// Returns a slice of check results and an overall error if any critical path fails.
func validateFilePaths(cfg config.Config) ([]FileCheckResult, error) {
var results []FileCheckResult
var errors []string
// Define paths to check with their descriptions
pathsToCheck := []struct {
path string
description string
critical bool // if true, failure stops startup
}{
{cfg.LeaseDBPath, "Leases database", true},
{cfg.ReservationsPath, "Reservations file", true},
{cfg.PIDFile, "PID file", true},
}
// Add log file path
logPath := cfg.Logging.LogFile
if logPath == "" && cfg.Logging.Path != "" {
filename := cfg.Logging.Filename
if filename == "" {
filename = "dhcplane.log"
}
logPath = filepath.Join(cfg.Logging.Path, filename)
} else if logPath == "" {
logPath = cfg.Logging.Filename
if logPath == "" {
logPath = "dhcplane.log"
}
}
pathsToCheck = append(pathsToCheck, struct {
path string
description string
critical bool
}{logPath, "Log file", true})
for _, p := range pathsToCheck {
result := checkFilePath(p.path, p.description)
results = append(results, result)
if result.Error != nil && p.critical {
errors = append(errors, fmt.Sprintf("%s (%s): %v", p.description, p.path, result.Error))
}
}
if len(errors) > 0 {
return results, fmt.Errorf("startup file path validation failed:\n - %s", strings.Join(errors, "\n - "))
}
return results, nil
}
// checkFilePath validates a single file path.
func checkFilePath(path, description string) FileCheckResult {
result := FileCheckResult{
Path: path,
Description: description,
}
if path == "" {
result.Error = fmt.Errorf("path is empty")
return result
}
// Get absolute path for clearer error messages
absPath, err := filepath.Abs(path)
if err != nil {
result.Error = fmt.Errorf("cannot resolve absolute path: %w", err)
return result
}
result.Path = absPath
// Check if file exists
fileInfo, err := os.Stat(absPath)
if err == nil {
result.Exists = true
result.DirExists = true
// File exists, check if writable
if err := checkWritable(absPath, fileInfo.IsDir()); err != nil {
result.Error = fmt.Errorf("file exists but is not writable: %w", err)
return result
}
result.Writable = true
return result
}
if !os.IsNotExist(err) {
result.Error = fmt.Errorf("cannot stat file: %w", err)
return result
}
// File doesn't exist, check if directory exists
dir := filepath.Dir(absPath)
dirInfo, err := os.Stat(dir)
if err == nil {
if !dirInfo.IsDir() {
result.Error = fmt.Errorf("parent path %s exists but is not a directory", dir)
return result
}
result.DirExists = true
// Directory exists, check if we can create file
if err := checkCanCreateFile(absPath); err != nil {
result.Error = fmt.Errorf("directory exists but cannot create file: %w", err)
return result
}
result.Writable = true
return result
}
if !os.IsNotExist(err) {
result.Error = fmt.Errorf("cannot stat parent directory %s: %w", dir, err)
return result
}
// Directory doesn't exist, try to create it
if err := os.MkdirAll(dir, 0o755); err != nil {
result.Error = fmt.Errorf("cannot create directory %s: %w (check permissions or run as root)", dir, err)
return result
}
result.DirExists = true
// Now check if we can create the file
if err := checkCanCreateFile(absPath); err != nil {
result.Error = fmt.Errorf("created directory but cannot create file: %w", err)
return result
}
result.Writable = true
return result
}
// checkWritable checks if a file or directory is writable.
func checkWritable(path string, isDir bool) error {
if isDir {
// For directories, try to create a temp file
testFile := filepath.Join(path, ".dhcplane_write_test")
f, err := os.Create(testFile)
if err != nil {
return fmt.Errorf("cannot write to directory: %w", err)
}
f.Close()
os.Remove(testFile)
return nil
}
// For files, try to open for writing
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return fmt.Errorf("cannot open for writing: %w", err)
}
f.Close()
return nil
}
// checkCanCreateFile attempts to create and immediately remove a file to verify write permissions.
func checkCanCreateFile(path string) error {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("cannot create file: %w", err)
}
f.Close()
// Remove the test file - we just wanted to check we can create it
// Note: For actual data files, they'll be created by their respective handlers
os.Remove(path)
return nil
}
// printStartupValidation prints the results of file path validation.
func printStartupValidation(results []FileCheckResult, logSink func(string, ...any)) {
logSink("STARTUP file path validation:")
for _, r := range results {
status := "OK"
details := ""
if r.Error != nil {
status = "FAIL"
details = fmt.Sprintf(" - %v", r.Error)
} else if !r.Exists {
status = "OK (will create)"
}
logSink(" %s: %s [%s]%s", r.Description, r.Path, status, details)
}
}
// buildServerAndRun starts the DHCP server and optional console broker, handles reloads and signals.
func buildServerAndRun(cfgPath string, enableConsole bool, overrides PathOverrides) error {
// Load + validate/normalize initial config
raw, reservations, reservationsPath, jerr := config.ParseStrict(cfgPath)
if jerr != nil {
return fmt.Errorf("config error: %w", jerr)
}
// Apply command-line path overrides before validation
applyPathOverrides(&raw, overrides)
// If reservations path was overridden, reload from the new path
if overrides.ReservationsPath != "" && raw.ReservationsPath != reservationsPath {
reservationsPath = raw.ReservationsPath
var err error
reservations, err = config.LoadReservations(reservationsPath)
if err != nil {
return fmt.Errorf("load reservations from override path: %w", err)
}
}
cfg, warns, verr := config.ValidateAndNormalizeConfig(raw)
if verr != nil {
return fmt.Errorf("config validation: %w", verr)
}
// Validate file paths before proceeding
// This checks if all required directories and files are accessible/writable
validationResults, validationErr := validateFilePaths(cfg)
if validationErr != nil {
// Print detailed validation results to console (we can't log yet)
fmt.Fprintln(os.Stderr, aurora.Red("STARTUP VALIDATION FAILED"))
fmt.Fprintln(os.Stderr, "")
for _, r := range validationResults {
status := aurora.Green("✓ OK")
if r.Error != nil {
status = aurora.Red("✗ FAIL")
} else if !r.Exists {
status = aurora.Yellow("○ Will create")
}
fmt.Fprintf(os.Stderr, " %s %s\n", status, r.Description)
fmt.Fprintf(os.Stderr, " Path: %s\n", r.Path)
if r.Error != nil {
fmt.Fprintf(os.Stderr, " %s\n", aurora.Red(fmt.Sprintf("Error: %v", r.Error)))
}
}
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, aurora.Yellow("Suggestions:"))
fmt.Fprintln(os.Stderr, " - Ensure the directories exist and have proper permissions")
fmt.Fprintln(os.Stderr, " - Run with sudo or as root if using system directories")
fmt.Fprintln(os.Stderr, " - Use --leases, --reservations, --log-file flags to specify different paths")
fmt.Fprintln(os.Stderr, " - Or modify the config file to use accessible paths")
fmt.Fprintln(os.Stderr, "")
return validationErr
}
// Migrate leases file if needed
leasePath := cfg.LeaseDBPath
if err := migrateLeasesFile(leasePath); err != nil {
return err
}
// Update leasePath if it was the default "leases.json" (migrated to "dhcplane.leases")
// Also check if the old path doesn't exist but the new one does
if leasePath == "leases.json" {
leasePath = "dhcplane.leases"
} else {
// For custom paths, check if old .json version exists but new .leases doesn't
// This handles cases where config still references old path
leaseDir := filepath.Dir(leasePath)
if leaseDir == "." {
leaseDir, _ = os.Getwd()
}
leaseBase := filepath.Base(leasePath)
if strings.HasSuffix(leaseBase, ".json") && strings.Contains(leaseBase, "lease") {
oldPath := leasePath
newBase := strings.TrimSuffix(leaseBase, ".json") + ".leases"
newPath := filepath.Join(leaseDir, newBase)
if _, err := os.Stat(oldPath); os.IsNotExist(err) {
if _, err := os.Stat(newPath); err == nil {
// Old path doesn't exist but new one does - use new path
leasePath = newPath
}
}
}
}
// Check reservations file migration
checkReservationsFileMigration(reservationsPath)
db := dhcpserver.NewLeaseDB(leasePath)
if err := db.Load(); err != nil {
warnf("lease db load: %v (continuing with empty)", err)
}
// Logger (file or rotating)
lg, closer, err := setupLogger(cfg)
if err != nil {
return fmt.Errorf("logger: %w", err)
}
defer func() {
if closer != nil {
_ = closer.Close()
}
}()
// Optional console broker (exports console over UNIX socket and/or TCP)
var consoleBroker *planeconsole.Broker
if enableConsole {
maxLines := cfg.ConsoleMaxLines
if maxLines <= 0 {
maxLines = planeconsole.DefaultMaxLines
}
var tcpAddr string
consoleBroker, tcpAddr = buildConsoleBroker(maxLines, cfg.ConsoleTCPAddress)
if err := consoleBroker.Start(); err != nil {
return fmt.Errorf("console broker: %w", err)
}
defer consoleBroker.Stop()
// Log which mode we're using
if tcpAddr != "" {
log.Printf("CONSOLE listening on UNIX socket + TCP %s", tcpAddr)
} else {
log.Printf("CONSOLE listening on UNIX socket")
}
}
// Sinks
logSink := func(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
// Write uncolored to log file
if lg != nil {
lg.Printf("%s", msg)
}
ts := time.Now().Format("2006/01/02 15:04:05.000000")
if consoleBroker != nil {
consoleBroker.Append(ts + " " + msg)
}
// Color warnings in console output (but not in logs)
lowerMsg := strings.ToLower(msg)
if strings.Contains(lowerMsg, "warning:") || strings.Contains(lowerMsg, "warn:") {
fmt.Fprintln(os.Stdout, aurora.Yellow(msg))
} else {
fmt.Fprintln(os.Stdout, msg)
}
}
errorSink := func(format string, args ...any) {
msg := fmt.Sprintf("ERROR: "+format, args...)
// Write uncolored to log file
if lg != nil {
lg.Printf("%s", msg)
}
ts := time.Now().Format("2006/01/02 15:04:05.000000")
if consoleBroker != nil {
consoleBroker.Append(ts + " " + msg)
}
// Color errors red in console output (but not in logs)
fmt.Fprintln(os.Stderr, aurora.Red(msg))
}
// Log successful startup validation
printStartupValidation(validationResults, logSink)
// Log initial warnings
for _, w := range warns {
logSink("%s", w)
}
// Atomic config snapshot
var cfgAtomic atomic.Value
cfgAtomic.Store(&cfg)
cfgGet := func() *config.Config { return cfgAtomic.Load().(*config.Config) }
// Atomic reservations snapshot
var reservationsAtomic atomic.Value
reservationsAtomic.Store(reservations)
reservationsGet := func() config.Reservations { return reservationsAtomic.Load().(config.Reservations) }
// Authoritative getter from config (default: true when unset)
effectiveAuthoritative := func(c *config.Config) bool {
if c == nil || c.Authoritative == nil {
return true
}
return *c.Authoritative
}
authorGet := func() bool { return effectiveAuthoritative(cfgGet()) }
// One-shot compaction on initial load ONLY if enabled
if cfg.CompactOnLoad {
sticky := time.Duration(cfg.LeaseStickySeconds) * time.Second
if n := db.CompactNow(sticky); n > 0 {
logSink("LEASE-COMPACT removed=%d (on initial load)", n)
}
}
// Enforce reservations immediately
dhcpserver.EnforceReservationLeaseConsistency(db, reservations)
// PID
if err := writePID(cfg.PIDFile); err != nil {
return fmt.Errorf("write pid: %w", err)
}
// Decoupled DHCP server
s := dhcpserver.NewServer(db, cfgGet, reservationsGet, authorGet, logSink, errorSink)
// Bind + Serve, with rebind support when Interface changes
laddr := &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: 67}
var closerUDP ioCloser
currentIface := cfg.Interface
bind := func(newIface string) error {
if closerUDP != nil {
_ = closerUDP.Close()
closerUDP = nil
}
c, err := s.BindAndServe(newIface, laddr)
if err != nil {
return err
}
closerUDP = c
currentIface = newIface
return nil
}
if err := bind(currentIface); err != nil {
return fmt.Errorf("bind: %w (need root/CAP_NET_BIND_SERVICE)", err)
}
logSink("START iface=%q bind=%s server_ip=%s subnet=%s gateway=%s lease=%s sticky=%s authoritative=%v",
currentIface, laddr.String(), cfg.ServerIP, cfg.SubnetCIDR, cfg.Gateway,
time.Duration(cfg.LeaseSeconds)*time.Second, time.Duration(cfg.LeaseStickySeconds)*time.Second, effectiveAuthoritative(&cfg))
if cfg.AutoReload {
logSink("START auto_reload=true (watching %s)", cfgPath)
}
// DETECT DHCPSERVERS announcement on startup
logDetect(&cfg, currentIface, logSink)
// ARP anomaly scheduler (goroutine-based)
if cfg.ARPAnomalyDetection.Enabled {
first := time.Duration(cfg.ARPAnomalyDetection.FirstScan) * time.Second
ival := time.Duration(cfg.ARPAnomalyDetection.ProbeInterval) * time.Second
stopARP := make(chan struct{})
go func() {
timer := time.NewTimer(first)
defer timer.Stop()
select {
case <-timer.C:
triggerARPScan(cfgGet, reservationsGet, db, currentIface, logSink, errorSink, false)
case <-stopARP:
return
}
tk := time.NewTicker(ival)
defer tk.Stop()
for {
select {
case <-tk.C:
triggerARPScan(cfgGet, reservationsGet, db, currentIface, logSink, errorSink, false)
case <-stopARP:
return
}
}
}()
defer close(stopARP)
}
// Background task scheduler - DHCP server detection
if cfg.DetectDHCPServers.Enabled {
first := time.Duration(cfg.DetectDHCPServers.FirstScan) * time.Second
ival := time.Duration(cfg.DetectDHCPServers.ProbeInterval) * time.Second
stopDHCP := make(chan struct{})
go func() {
timer := time.NewTimer(first)
defer timer.Stop()
select {
case <-timer.C:
triggerDHCPServerScan(cfgGet, currentIface, logSink, errorSink)
case <-stopDHCP:
return
}
tk := time.NewTicker(ival)
defer tk.Stop()
for {
select {
case <-tk.C:
triggerDHCPServerScan(cfgGet, currentIface, logSink, errorSink)
case <-stopDHCP:
return
}
}
}()
defer close(stopDHCP)
}
// Optional auto-reload watcher
var watcher *fsnotify.Watcher
var watcherErr error
if cfg.AutoReload {
watcher, watcherErr = startConfigWatcher(cfgPath, reservationsPath, func(newCfg config.Config, newReservations config.Reservations, newWarns []string) {
// Compare authoritative before swapping
oldAuth := effectiveAuthoritative(cfgGet())
newAuth := effectiveAuthoritative(&newCfg)
cfgAtomic.Store(&newCfg)
reservationsAtomic.Store(newReservations)
for _, w := range newWarns {
logSink("%s", w)
}
dhcpserver.EnforceReservationLeaseConsistency(db, newReservations)
if newCfg.CompactOnLoad {
if n := db.CompactNow(time.Duration(newCfg.LeaseStickySeconds) * time.Second); n > 0 {
logSink("LEASE-COMPACT removed=%d (on auto-reload)", n)
}
}
if newCfg.Interface != currentIface {
if err := bind(newCfg.Interface); err != nil {
logSink("AUTO-RELOAD: rebind failed for iface %q: %v (keeping %q)", newCfg.Interface, err, currentIface)
} else {
logSink("AUTO-RELOAD: rebound to iface=%q", newCfg.Interface)
}
}
if oldAuth != newAuth {
logSink("AUTO-RELOAD: authoritative %v -> %v", oldAuth, newAuth)
} else {
logSink("AUTO-RELOAD: authoritative=%v", newAuth)
}
logSink("AUTO-RELOAD: config applied")
// DETECT announcement after auto-reload apply
logDetect(&newCfg, currentIface, logSink)
}, logSink)
if watcherErr != nil {
logSink("AUTO-RELOAD: watcher failed: %v", watcherErr)
}
}
// Signals: INT/TERM stop; HUP reload
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
for sig := range sigc {
switch sig {
case syscall.SIGHUP:
rawNew, reservationsNew, reservationsPathNew, jerr := config.ParseStrict(cfgPath)
if jerr != nil {
logSink("RELOAD: config invalid, keeping old settings: %v", jerr)
continue
}
nowEpoch := time.Now().Unix()
reservationsChanged := false
for k, v := range reservationsNew {
if v.FirstSeen == 0 {
v.FirstSeen = nowEpoch
reservationsNew[k] = v
reservationsChanged = true
}
}
if rawNew.BannedMACs == nil {
rawNew.BannedMACs = make(map[string]config.DeviceMeta)
}
bannedChanged := false
for k, v := range rawNew.BannedMACs {
if v.FirstSeen == 0 {
v.FirstSeen = nowEpoch
rawNew.BannedMACs[k] = v
bannedChanged = true
}
}
if reservationsChanged {
// Save reservations to separate file
if err := config.SaveReservations(reservationsPathNew, reservationsNew); err != nil {
logSink("RELOAD: failed to persist reservations first_seen update: %v", err)
}
}
if bannedChanged {
// Save banned MACs back to config file
tmp := cfgPath + ".tmp"
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err == nil {
if f2, err := os.Create(tmp); err == nil {
enc := json.NewEncoder(f2)
enc.SetIndent("", " ")
if err := enc.Encode(&rawNew); err == nil {
_ = f2.Sync()
_ = f2.Close()
_ = os.Rename(tmp, cfgPath)
} else {
_ = f2.Close()
_ = os.Remove(tmp)
logSink("RELOAD: failed to persist banned_macs first_seen update: %v", err)
}
}
}
}
newCfg, newWarns, verr := config.ValidateAndNormalizeConfig(rawNew)
if verr != nil {
logSink("RELOAD: validation failed, keeping old settings: %v", verr)
continue
}
for _, w := range newWarns {
logSink("%s", w)
}
// Compare before swap
oldAuth := effectiveAuthoritative(cfgGet())
newAuth := effectiveAuthoritative(&newCfg)
cfgAtomic.Store(&newCfg)
reservationsAtomic.Store(reservationsNew)
dhcpserver.EnforceReservationLeaseConsistency(db, reservationsNew)
if newCfg.CompactOnLoad {
if n := db.CompactNow(time.Duration(newCfg.LeaseStickySeconds) * time.Second); n > 0 {
logSink("LEASE-COMPACT removed=%d (on config reload)", n)
}
}
if newCfg.Interface != currentIface {
if err := bind(newCfg.Interface); err != nil {
logSink("RELOAD: rebind failed for iface %q: %v (keeping %q)", newCfg.Interface, err, currentIface)
} else {
logSink("RELOAD: rebound to iface=%q", newCfg.Interface)
}
}
if oldAuth != newAuth {
logSink("RELOAD: authoritative %v -> %v", oldAuth, newAuth)
} else {
logSink("RELOAD: authoritative=%v", newAuth)
}
logSink("RELOAD: config applied")
// DETECT DHCPSERVERS announcement after manual reload
logDetect(&newCfg, currentIface, logSink)
case syscall.SIGINT, syscall.SIGTERM:
logSink("SIGNAL received, shutting down")
_ = s.Close()
_ = db.Save()
if watcher != nil {
_ = watcher.Close()
}
return nil
}
}
return nil
}
/* ----------------- Watcher ----------------- */
// startConfigWatcher watches cfgPath and reservations file, calls onApply(validatedCfg,reservations,warns) after successful parses.
// It also performs the first_seen stamping persist just like the HUP path.
func startConfigWatcher(
cfgPath string,
reservationsPath string,
onApply func(config.Config, config.Reservations, []string),
logf func(string, ...any),
) (*fsnotify.Watcher, error) {
w, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
dir := filepath.Dir(cfgPath)
if err := w.Add(dir); err != nil {
_ = w.Close()
return nil, err
}
// Also watch reservations file directory if different
if reservationsPath != "" && filepath.Dir(reservationsPath) != dir {
reservationsDir := filepath.Dir(reservationsPath)
if err := w.Add(reservationsDir); err != nil {
_ = w.Close()
return nil, err
}
}
go func() {
for {
select {
case ev, ok := <-w.Events:
if !ok {
return
}
evName := filepath.Clean(ev.Name)
cfgPathClean := filepath.Clean(cfgPath)
reservationsPathClean := ""
if reservationsPath != "" {
reservationsPathClean = filepath.Clean(reservationsPath)
}
// Watch both config and reservations file
if evName != cfgPathClean && evName != reservationsPathClean {
continue
}
if ev.Op&(fsnotify.Write|fsnotify.Create|fsnotify.Rename|fsnotify.Chmod) == 0 {
continue
}
time.Sleep(150 * time.Millisecond)
// Reload config and reservations
cfgNew, reservationsNew, reservationsPathNew, jerr := config.ParseStrict(cfgPath)
if jerr != nil {