-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathopensoho.go
More file actions
3267 lines (2939 loc) · 97.1 KB
/
Copy pathopensoho.go
File metadata and controls
3267 lines (2939 loc) · 97.1 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 (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"database/sql"
"embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"image/png"
"io"
"io/fs"
"log"
"math/big"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/endobit/oui"
"github.com/go-ozzo/ozzo-validation/v4"
"github.com/google/uuid"
"github.com/pocketbase/dbx"
"github.com/rubenbe/pocketbase"
"github.com/rubenbe/pocketbase/apis"
"github.com/rubenbe/pocketbase/core"
//"github.com/rubenbe/pocketbase/plugins/ghupdate"
"github.com/reugn/wifiqr"
"github.com/rubenbe/opensoho/frequencyplan"
"github.com/rubenbe/opensoho/lldp"
"github.com/rubenbe/opensoho/mqtt"
"github.com/rubenbe/opensoho/poe"
"github.com/rubenbe/opensoho/ui"
"github.com/rubenbe/pocketbase/plugins/jsvm"
"github.com/rubenbe/pocketbase/plugins/migratecmd"
"github.com/rubenbe/pocketbase/tools/filesystem"
"github.com/rubenbe/pocketbase/tools/hook"
"github.com/rubenbe/pocketbase/tools/security"
"github.com/rubenbe/pocketbase/tools/types"
)
// Files that need to be extracted at startup
//
//go:embed pb_migrations/**
var embeddedFiles embed.FS
// Files that can be served directly from the binary
//
//go:embed favicon.png logo.svg
var internalFiles embed.FS
// Hotplug script pushed to the router at /etc/hotplug.d/openwisp/opensoho
//
//go:embed scripts/dump-radios.sh
var dumpRadiosScript string
// Hotplug script pushed to the router at /etc/hotplug.d/openwisp/opensoho-poe
//
//go:embed scripts/dump-poe.sh
var dumpPoeScript string
func copyEmbedDirToDisk(embedFS fs.FS, targetDir string) error {
return fs.WalkDir(embedFS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
targetPath := filepath.Join(targetDir, path)
if d.IsDir() {
return os.MkdirAll(targetPath, os.ModePerm)
}
// Ensure parent directory exists
if err := os.MkdirAll(filepath.Dir(targetPath), os.ModePerm); err != nil {
return err
}
// Open embedded file
srcFile, err := embedFS.Open(path)
if err != nil {
return err
}
defer srcFile.Close()
// Create or overwrite file on disk
dstFile, err := os.Create(targetPath)
if err != nil {
return err
}
defer dstFile.Close()
_, err = io.Copy(dstFile, srcFile)
return err
})
}
func extractRadioNumber(s string) (int, error) {
re := regexp.MustCompile(`^(?:phy|wl)(\d+)-`)
match := re.FindStringSubmatch(s)
if len(match) < 2 {
return 0, fmt.Errorf("radio number not found in string: %s", s)
}
return strconv.Atoi(match[1])
}
// parseRadioName extracts the radio index from an OpenSoho dump radio name
// (the UCI wifi-device section name, e.g. "radio0" -> 0).
func parseRadioName(name string) (int, error) {
return strconv.Atoi(strings.TrimPrefix(name, "radio"))
}
func updateDeviceHealth(app core.App, currenttime types.DateTime) {
oldesttime := currenttime.Add(-60 * time.Second)
// Collect the devices that are about to transition to unhealthy so we can
// flip their Home Assistant availability to offline.
var transitioning []struct {
Id string `db:"id"`
}
err := app.DB().
NewQuery("select id from devices where health_status != \"unhealthy\" and last_seen <= {:offset}").
Bind(dbx.Params{"offset": oldesttime.String()}).All(&transitioning)
if err != nil {
fmt.Println("Failed to query transitioning devices")
fmt.Println(err)
}
_, err = app.DB().
NewQuery("update devices set health_status = \"unhealthy\" where last_seen <= {:offset}").
Bind(dbx.Params{"offset": oldesttime.String()}).Execute()
if err != nil {
fmt.Println("Failed to update device health")
fmt.Println(err)
return
}
for _, d := range transitioning {
mqtt.PublishDeviceOffline(d.Id)
}
}
func updateLastSeen(e *core.RequestEvent, record *core.Record) error {
record.Set("last_seen", time.Now())
record.Set("health_status", "healthy")
record.Set("ip_address", e.RealIP())
return e.App.Save(record)
}
func frequencyToBand(frequency int) string {
return frequencyplan.FrequencyToBand(frequency)
}
// frequencyToUciBand maps a frequency to the value UCI expects for the
// wifi-device "band" option (e.g. 2412 -> "2g"). Returns "" for unknown bands.
func frequencyToUciBand(frequency int) string {
switch frequencyToBand(frequency) {
case "2.4":
return "2g"
case "5":
return "5g"
case "6":
return "6g"
case "60":
return "60g"
default:
return ""
}
}
func isRandomizedMAC(mac string) bool {
parts := strings.SplitN(mac, ":", 2)
if len(parts) == 0 {
return false
}
b, err := strconv.ParseUint(parts[0], 16, 8)
if err != nil {
return false
}
return b&0x02 != 0
}
func lookupVendor(mac string) string {
if isRandomizedMAC(mac) {
return "randomized"
}
return oui.Vendor(mac)
}
func maxInt(a int, b int) int {
if a > b {
return a
} else {
return b
}
}
func frequencyToChannel(freqMHz int) (int, bool) {
return frequencyplan.FrequencyToChannel(freqMHz)
}
func validateRadioHtModeBandCombo(band string, htmode string) error {
validHtModes := map[string][]string{
"2.4": {"HT20", "HT40", "HE20", "HE40", "EHT20", "EHT40"},
"5": {"HT20", "HT40", "VHT20", "VHT40", "VHT80", "VHT160", "HE20", "HE40", "HE80", "HE160", "EHT20", "EHT40", "EHT80", "EHT160"},
"6": {"HE20", "HE40", "HE80", "HE160", "EHT20", "EHT40", "EHT80", "EHT160", "EHT320"},
}
htmodes, ok := validHtModes[band]
if !ok {
return validation.NewError("validation_invalid_value", "Invalid band")
}
for _, h := range htmodes {
if h == htmode {
return nil
}
}
return validation.NewError("validation_invalid_value", "HT mode does not match selected band")
}
// validateRadioFrequency checks the user-set frequency against the frequencies
// the device actually advertised in the radio_frequencies collection. If the
// device hasn't reported a freqlist for this radio yet (no rows), validation is
// skipped so the radio can still be configured.
func validateRadioFrequency(app core.App, device string, radio int, frequency int) error {
freqs, err := app.FindAllRecords("radio_frequencies",
dbx.HashExp{"device": device, "radio": radio})
if err != nil {
return validation.NewError("validation_invalid_value", "Failed to look up supported frequencies")
}
if len(freqs) == 0 {
return nil
}
for _, f := range freqs {
if f.GetInt("frequency") == frequency {
return nil
}
}
return validation.NewError("validation_invalid_value", "Frequency is not supported by this radio")
}
// lookupTxPowerDbm returns the highest advertised dBm whose mW value equals mw,
// for the given device+radio. found is false when the device has no matching
// radio_tx_powers row (or none at all).
func lookupTxPowerDbm(app core.App, device string, radio int, mw int) (int, bool, error) {
rows, err := app.FindAllRecords("radio_tx_powers",
dbx.HashExp{"device": device, "radio": radio, "mw": mw})
if err != nil {
return 0, false, err
}
best, found := 0, false
for _, r := range rows {
if d := r.GetInt("dbm"); !found || d > best {
best, found = d, true
}
}
return best, found, nil
}
// nearestTxPower scans radio_tx_powers for device+radio and reports whether
// value exactly matches the field column ("mw" or "dbm"), plus the row whose
// field value is closest to it. closest is nil only when the radio has no rows.
// Distance is compared as the squared difference: tx power values are
// non-negative but v-value is not, and squaring avoids an abs helper while
// giving the same nearest result.
func nearestTxPower(app core.App, device string, radio int, field string, value int) (bool, *core.Record, error) {
rows, err := app.FindAllRecords("radio_tx_powers",
dbx.HashExp{"device": device, "radio": radio})
if err != nil {
return false, nil, err
}
exact := false
var closest *core.Record
bestDist := 0
for _, r := range rows {
v := r.GetInt(field)
if v == value {
exact = true
}
if dist := (v - value) * (v - value); closest == nil || dist < bestDist {
closest, bestDist = r, dist
}
}
return exact, closest, nil
}
// validateRadioTxPower checks a mW- or dBm-mode tx_power against the device's
// advertised radio_tx_powers table. Any value without a matching row is
// rejected, with a hint at the closest supported level (or a note that the
// radio has reported none). auto/empty modes need no lookup.
func validateRadioTxPower(app core.App, device string, radio int, mode string, txpower int) error {
var field string
switch mode {
case "mW":
field = "mw"
case "dBm":
field = "dbm"
default: // auto / empty — no lookup
return nil
}
exact, closest, err := nearestTxPower(app, device, radio, field, txpower)
if err != nil {
return validation.NewError("validation_invalid_value", "Failed to look up supported tx powers")
}
if exact {
return nil
}
if closest == nil {
return validation.NewError("validation_invalid_value", fmt.Sprintf(
"%d %s is not a supported tx power; this radio has not reported any supported power levels yet",
txpower, mode))
}
return validation.NewError("validation_invalid_value", fmt.Sprintf(
"%d %s is not a supported tx power for this radio; closest supported value is %d mW (%d dBm)",
txpower, mode, closest.GetInt("mw"), closest.GetInt("dbm")))
}
// validateRadioHtModeFlags rejects channel widths the device flagged as unusable on the configured channel.
// If the device hasn't a row for this frequency, validation is skipped As such the radio can still be configured.
func validateRadioHtModeFlags(app core.App, device string, radio int, frequency int, htmode string) error {
rows, err := app.FindAllRecords("radio_frequencies",
dbx.HashExp{"device": device, "radio": radio, "frequency": frequency})
if err != nil {
return validation.NewError("validation_invalid_value", "Failed to look up supported frequencies")
}
if len(rows) == 0 {
return nil
}
flags := rows[0].GetStringSlice("flags")
switch {
case strings.HasSuffix(htmode, "40"):
if slices.Contains(flags, "no_ht40-") && slices.Contains(flags, "no_ht40+") {
// A 40 MHz width needs an adjacent secondary channel, so it is not allowed when both no_ht40- and no_ht40+ are set
return validation.NewError("validation_invalid_value", "40 MHz width not allowed on this channel")
}
case strings.HasSuffix(htmode, "320"):
if slices.Contains(flags, "no_320mhz") {
return validation.NewError("validation_invalid_value", "320 MHz width not allowed on this channel")
}
case strings.HasSuffix(htmode, "160"):
if slices.Contains(flags, "no_160mhz") {
return validation.NewError("validation_invalid_value", "160 MHz width not allowed on this channel")
}
case strings.HasSuffix(htmode, "80"):
if slices.Contains(flags, "no_80mhz") {
return validation.NewError("validation_invalid_value", "80 MHz width not allowed on this channel")
}
}
return nil
}
func validateRadio(app core.App, record *core.Record) error {
errs := validation.Errors{}
frequency := record.GetInt("frequency")
err := validateRadioFrequency(app, record.GetString("device"), record.GetInt("radio"), frequency)
if err != nil {
errs["frequency"] = err
}
band := frequencyToBand(frequency)
htmode := record.GetString("htmode")
err = validateRadioHtModeBandCombo(band, htmode)
if err != nil {
errs["htmode"] = err
} else if err = validateRadioHtModeFlags(app, record.GetString("device"), record.GetInt("radio"), frequency, htmode); err != nil {
errs["htmode"] = err
}
if err := validateRadioTxPower(app, record.GetString("device"), record.GetInt("radio"),
record.GetString("tx_power_mode"), record.GetInt("tx_power")); err != nil {
errs["tx_power"] = err
}
if len(errs) > 0 {
return apis.NewBadRequestError("Failed to create record.", errs)
}
return nil
}
type Client struct {
MAC string `json:"mac"`
Assoc bool `json:"assoc"`
Signal int `json:"signal"`
Bytes struct {
Rx uint64 `json:"rx"`
Tx uint64 `json:"tx"`
} `json:"bytes"`
Rate struct {
Rx uint64 `json:"rx"`
Tx uint64 `json:"tx"`
} `json:"rate"`
}
type Radio struct {
Frequency int `json:"frequency"`
Channel int `json:"channel"`
HTmode string `json:"htmode"`
TxPower int `json:"tx_power"`
}
type Wireless struct {
Clients []Client `json:"clients"`
SSID string `json:"ssid"`
Frequency int `json:"frequency"`
Channel int `json:"channel"`
HTmode string `json:"htmode"`
TxPower int `json:"tx_power"`
}
type DHCPLease struct {
MACAddress string `json:"mac"`
ClientID string `json:"client_id,omitempty"`
Hostname string `json:"client_name,omitempty"`
IPAddress string `json:"ip"`
Expiry int `json:"expiry"`
}
type Statistics struct {
RxFrameErrors uint64 `json:"rx_frame_errors"`
RxCrcErrors uint64 `json:"rx_crc_errors"`
TxHeartbeatErrors uint64 `json:"tx_heartbeat_errors"`
RxOverErrors uint64 `json:"rx_over_errors"`
RxErrors uint64 `json:"rx_errors"`
TxPackets uint64 `json:"tx_packets"`
TxCarrierErrors uint64 `json:"tx_carrier_errors"`
RxPackets uint64 `json:"rx_packets"`
RxLengthErrors uint64 `json:"rx_length_errors"`
TxErrors uint64 `json:"tx_errors"`
TxAbortedErrors uint64 `json:"tx_aborted_errors"`
TxWindowErrors uint64 `json:"tx_window_errors"`
TxBytes uint64 `json:"tx_bytes"`
Collisions uint64 `json:"collisions"`
RxBytes uint64 `json:"rx_bytes"`
RxFifoErrors uint64 `json:"rx_fifo_errors"`
RxDropped uint64 `json:"rx_dropped"`
TxFifoErrors uint64 `json:"tx_fifo_errors"`
RxCompressed uint64 `json:"rx_compressed"`
Multicast uint64 `json:"multicast"`
TxCompressed uint64 `json:"tx_compressed"`
RxMissedErrors uint64 `json:"rx_missed_errors"`
TxDropped uint64 `json:"tx_dropped"`
}
type Interface struct {
MAC string `json:"mac"`
Type string `json:"type"`
Name string `json:"name"`
Wireless *Wireless `json:"wireless,omitempty"`
Statistics *Statistics `json:"statistics,omitempty"`
Speed string `json:"speed,omitempty"`
BridgeMembers []string `json:"bridge_members,omitempty"`
}
type Resources struct {
Load []float32 `json:"load"`
}
type Neighbor struct {
MAC string `json:"mac"`
State string `json:"state"`
Interface string `json:"Interface"`
IP string `json:"ip"`
}
type GeneralInfo struct {
LocalTime int `json:"local_time"`
Uptime int `json:"uptime"`
}
type MonitoringData struct {
Type string `json:"type"`
General GeneralInfo `json:"general"`
Interfaces []Interface `json:"interfaces"`
Resources Resources `json:"resources"`
DNSServers []string `json:"dns_servers"`
Neighbors []Neighbor `json:"neighbors"`
DHCPLeases []DHCPLease `json:"dhcp_leases,omitempty"`
}
// OpenSoho monitoring payload, produced by scripts/dump-radios.sh.
// Shape: {"type":"OpenSoho","radios":[{"name":"radio0",...},...]} where each
// entry mirrors a UCI wifi-device augmented with iwinfo info / freqlist.
// IwinfoInfo holds the subset of `ubus call iwinfo info` we care about.
type IwinfoInfo struct {
Channel int `json:"channel"`
Frequency int `json:"frequency"`
TxPower int `json:"txpower"`
Country string `json:"country"`
HwModes []string `json:"hwmodes"`
HtModes []string `json:"htmodes"`
}
// IwinfoFreq is a single entry of `ubus call iwinfo freqlist`.
type IwinfoFreq struct {
Channel int `json:"channel"`
MHz int `json:"mhz"`
Restricted bool `json:"restricted"`
Flags []string `json:"flags"`
}
// IwinfoTxPower is a single entry of `ubus call iwinfo txpowerlist`.
type IwinfoTxPower struct {
Dbm int `json:"dbm"`
Mw int `json:"mw"`
}
// OpenSohoRadio is one wifi-device entry of the OpenSoho payload.
type OpenSohoRadio struct {
Name string `json:"name"`
Phy string `json:"phy"`
Disabled string `json:"disabled"`
Info IwinfoInfo `json:"info"`
FreqList struct {
Results []IwinfoFreq `json:"results"`
} `json:"freqlist"`
TxPowerList struct {
Results []IwinfoTxPower `json:"results"`
} `json:"txpowerlist"`
}
// OpenSohoData is the decoded OpenSoho payload. The radios dump
// (scripts/dump-radios.sh) carries "radios"; the PoE dump
// (scripts/dump-poe.sh) carries "poe". Both share type "OpenSoho", so one
// struct decodes either: the absent key simply stays nil/empty.
type OpenSohoData struct {
Type string `json:"type"`
Radios []OpenSohoRadio `json:"radios"`
Poe *poe.Info `json:"poe"`
Lldp *lldp.Info `json:"lldp"`
}
// radioBands returns the distinct Wi-Fi bands a radio supports, derived from
// its advertised frequency list. The result is sorted for deterministic output
// and excludes the "unknown" sentinel from frequencyToBand.
func radioBands(radio OpenSohoRadio) []string {
seen := map[string]struct{}{}
for _, freq := range radio.FreqList.Results {
band := frequencyToBand(freq.MHz)
if band == "unknown" {
continue
}
seen[band] = struct{}{}
}
bands := make([]string, 0, len(seen))
for band := range seen {
bands = append(bands, band)
}
sort.Strings(bands)
return bands
}
// handleOpenSohoMonitoring is the entry point for parsed OpenSoho radio dumps.
// It persists each radio's advertised frequency list into the
// radio_frequencies collection, keyed by (device, radio index).
func handleOpenSohoMonitoring(app core.App, device *core.Record, data OpenSohoData, current bool) {
coll, err := app.FindCollectionByNameOrId("radio_frequencies")
if err != nil {
app.Logger().Error("Failed to find radio_frequencies collection", "error", err)
return
}
txColl, err := app.FindCollectionByNameOrId("radio_tx_powers")
if err != nil {
app.Logger().Error("Failed to find radio_tx_powers collection", "error", err)
return
}
for _, radio := range data.Radios {
idx, err := parseRadioName(radio.Name)
if err != nil {
app.Logger().Error("Skipping radio with unparseable name",
"device", device.GetString("id"), "radio", radio.Name, "error", err)
continue
}
if err := syncRadioFrequencies(app, coll, device, idx, radio.FreqList.Results); err != nil {
app.Logger().Error("Failed to sync radio frequencies",
"device", device.GetString("id"), "radio", radio.Name, "error", err)
continue
}
if err := syncRadioTxPowers(app, txColl, device, idx, radio.TxPowerList.Results); err != nil {
app.Logger().Error("Failed to sync radio tx powers",
"device", device.GetString("id"), "radio", radio.Name, "error", err)
continue
}
}
if data.Poe != nil {
if err := poe.Sync(app, device, *data.Poe); err != nil {
app.Logger().Error("Failed to sync poe ports",
"device", device.GetString("id"), "error", err)
}
if current {
mqtt.PublishPoE(device, *data.Poe)
}
}
if data.Lldp != nil {
if err := lldp.Sync(app, device, *data.Lldp); err != nil {
app.Logger().Error("Failed to sync lldp neighbors",
"device", device.GetString("id"), "error", err)
}
}
}
// syncRadioFrequencies reconciles the radio_frequencies rows for a single
// (device, radio) with the supplied freqlist. Rows are matched by frequency and
// adjusted in place; only newly advertised frequencies are inserted and only
// dropped frequencies are deleted, so the stored set always reflects the latest
// dump without churning unchanged rows.
func syncRadioFrequencies(app core.App, coll *core.Collection, device *core.Record, idx int, freqs []IwinfoFreq) error {
// The flags field is a select with a fixed set of accepted values; drop any
// flag the schema doesn't know about so an unexpected one doesn't fail the
// whole save.
var allowedFlags []string
if field, ok := coll.Fields.GetByName("flags").(*core.SelectField); ok {
allowedFlags = field.Values
}
return app.RunInTransaction(func(txApp core.App) error {
existing, err := txApp.FindAllRecords("radio_frequencies",
dbx.HashExp{"device": device.Id, "radio": idx})
if err != nil {
return err
}
// Index the existing rows by frequency. Together with the (device, radio)
// scope of the query above this is the (device, radio, frequency) key we
// upsert against, so unchanged frequencies keep their row instead of being
// deleted and re-created.
byFreq := make(map[int]*core.Record, len(existing))
for _, rec := range existing {
byFreq[rec.GetInt("frequency")] = rec
}
for _, f := range freqs {
rec, ok := byFreq[f.MHz]
if ok {
// Adjust the existing row in place and remove it from the map so it
// isn't treated as stale below.
delete(byFreq, f.MHz)
} else {
rec = core.NewRecord(coll)
rec.Set("device", device.Id)
rec.Set("radio", idx)
rec.Set("frequency", f.MHz)
}
rec.Set("channel", f.Channel)
rec.Set("flags", knownFlags(f.Flags, allowedFlags))
if err := txApp.Save(rec); err != nil {
return err
}
}
// Whatever frequencies remain are no longer advertised; drop them.
for _, rec := range byFreq {
if err := txApp.Delete(rec); err != nil {
return err
}
}
return nil
})
}
func syncRadioTxPowers(app core.App, coll *core.Collection, device *core.Record, idx int, powers []IwinfoTxPower) error {
return app.RunInTransaction(func(txApp core.App) error {
existing, err := txApp.FindAllRecords("radio_tx_powers",
dbx.HashExp{"device": device.Id, "radio": idx})
if err != nil {
return err
}
byDbm := make(map[int]*core.Record, len(existing))
for _, rec := range existing {
byDbm[rec.GetInt("dbm")] = rec
}
for _, p := range powers {
rec, ok := byDbm[p.Dbm]
if ok {
// Adjust the existing row in place and remove it from the map so it
// isn't treated as stale below.
delete(byDbm, p.Dbm)
} else {
rec = core.NewRecord(coll)
rec.Set("device", device.Id)
rec.Set("radio", idx)
rec.Set("dbm", p.Dbm)
}
rec.Set("mw", p.Mw)
if err := txApp.Save(rec); err != nil {
return err
}
}
// Whatever power levels remain are no longer advertised; drop them.
for _, rec := range byDbm {
if err := txApp.Delete(rec); err != nil {
return err
}
}
return nil
})
}
// knownFlags returns the subset of flags that appear in allowed, preserving
// order. When allowed is empty no filtering is applied.
func knownFlags(flags, allowed []string) []string {
if len(allowed) == 0 {
return flags
}
kept := make([]string, 0, len(flags))
for _, f := range flags {
if slices.Contains(allowed, f) {
kept = append(kept, f)
}
}
return kept
}
type WifiRecord struct {
Record *core.Record
}
func updateRadios(device *core.Record, app core.App, newradios map[int]Radio) {
// Radio has radio number as index, it is not an index in a list.
// Function modifies the existing newradios list, important for tests
oldradios, err := app.FindAllRecords("radios", dbx.HashExp{"device": device.GetString("id")})
if err != nil {
fmt.Println(err)
return
}
// Loop over the existing (old) radios for this device, and update if not found.
// Update the MAC address and set it to enabled
for _, oldradio := range oldradios {
fmt.Println("oldradio:", oldradio)
oldradionum := oldradio.GetInt("radio")
if newradio, ok := newradios[oldradionum]; ok {
// Old radio exists within the updated list (newradios)
fmt.Println("EXISTS", newradio, oldradio)
dirty := false
if oldradio.GetBool("enabled") == false {
oldradio.Set("enabled", true)
dirty = true
}
// tx_power_mode is a required field; rows created before it existed
// hold an empty value that fails validation on save. Normalise the
// empty value (which means auto) so the record can be saved again.
mode := oldradio.GetString("tx_power_mode")
if mode == "" {
oldradio.Set("tx_power_mode", "auto")
mode = "auto"
dirty = true
}
// In auto mode the txpower option is omitted and the driver picks the
// power; record the value it reports so tx_power reflects what the
// radio is actually transmitting at. Never overwrite a value the user
// pinned in dBm/mW mode.
if mode == "auto" && newradio.TxPower > 0 &&
oldradio.GetInt("tx_power") != newradio.TxPower {
oldradio.Set("tx_power", newradio.TxPower)
dirty = true
}
if dirty {
if err := app.Save(oldradio); err != nil {
fmt.Println("Failed to update radio:", err)
}
}
delete(newradios, oldradionum)
} else {
fmt.Println("Not in list:", oldradio)
// Old radio does not exist within the updated list
if oldradio.GetBool("enabled") == true {
oldradio.Set("enabled", false)
err := app.Save(oldradio)
if err != nil {
fmt.Println("Failed to mark radio as disabled:", err)
}
}
}
}
if len(newradios) == 0 {
return
}
radiocollection, err := app.FindCollectionByNameOrId("radios")
if err != nil {
fmt.Println("Failed to find radio collection")
}
for numradio, radio := range newradios {
fmt.Println(numradio, radio, device.GetString("id"))
record := core.NewRecord(radiocollection)
record.Set("device", device.GetString("id"))
record.Set("radio", numradio)
record.Set("channel", radio.Channel)
record.Set("frequency", radio.Frequency)
record.Set("enabled", true)
// New radios default to auto power; store the reported value (in dBm) so
// tx_power reflects what the driver chose.
record.Set("tx_power_mode", "auto")
if radio.TxPower > 0 {
record.Set("tx_power", radio.TxPower)
}
err := app.Save(record)
if err != nil {
fmt.Println("Failed to save radio config")
}
}
}
func generateLedConfig(led *core.Record) string {
name := led.GetString("name")
return fmt.Sprintf(`
config led 'led_%s'
option name '%s'
option sysfs '%s'
option trigger '%s'
`, strings.ToLower(name), name, led.GetString("led_name"), led.GetString("trigger"))
}
func generateRadioConfig(app core.App, radio *core.Record, country_code string) string {
frequency_txt := " option channel 'auto'\n"
band_txt := ""
if radio.GetBool("auto_frequency") != true {
frequency := radio.GetInt("frequency")
if channel, ok := frequencyToChannel(frequency); ok == true {
frequency_txt = fmt.Sprintf(" option channel '%d'\n", channel)
}
// A specific frequency pins the band; emit it so the driver picks
// the right radio band (e.g. option band '2g').
if band := frequencyToUciBand(frequency); len(band) > 0 {
band_txt = fmt.Sprintf(" option band '%[1]s'\n", band)
}
}
htmode_txt := ""
if htmode := radio.GetString("htmode"); len(htmode) > 0 {
htmode_txt = fmt.Sprintf(" option htmode '%[1]s'\n", htmode)
}
country_txt := ""
if len(country_code) > 0 {
country_txt = fmt.Sprintf(" option country '%[1]s'\n", country_code)
}
// txpower in UCI is always dBm. mW mode is translated via the device's
// advertised radio_tx_powers table; anything else omits the option so the
// driver picks the power ("auto" is not a valid UCI value).
txpower_txt := ""
switch radio.GetString("tx_power_mode") {
case "dBm":
txpower_txt = fmt.Sprintf(" option txpower '%d'\n", radio.GetInt("tx_power"))
case "mW":
if dbm, found, _ := lookupTxPowerDbm(app, radio.GetString("device"),
radio.GetInt("radio"), radio.GetInt("tx_power")); found {
txpower_txt = fmt.Sprintf(" option txpower '%d'\n", dbm)
}
}
return fmt.Sprintf(`
config wifi-device 'radio%[1]d'
%[2]s%[6]s%[3]s%[4]s%[5]s`, radio.GetInt("radio"), frequency_txt, country_txt, htmode_txt, txpower_txt, band_txt)
}
func getRadiosForDevice(device *core.Record, app core.App) ([]*core.Record, error) {
records := []*core.Record{}
err := app.RecordQuery("radios").AndWhere(dbx.HashExp{"device": device.GetString("id")}).OrderBy("radio ASC").All(&records)
return records, err
}
func generateRadioConfigs(device *core.Record, app core.App) string {
countryrecord, err := app.FindFirstRecordByData("settings", "name", "country")
country := ""
if err == nil {
country = countryrecord.GetString("value")
}
output := ""
records, err := getRadiosForDevice(device, app)
if err != nil {
fmt.Println("Error finding Radios", err)
return ""
}
for _, record := range records {
output += generateRadioConfig(app, record, country)
}
return output
}
func getVlan(wifi *core.Record, app core.App) string {
errs := app.ExpandRecord(wifi, []string{"network"}, nil)
if len(errs) > 0 {
log.Println(errs)
return "lan"
}
networkentry := wifi.ExpandedOne("network")
if networkentry == nil {
return "lan"
}
networkname := networkentry.GetString("name")
if len(networkname) == 0 {
return "lan"
}
return networkname
}
func generateOpenWispConfig() string {
return fmt.Sprintf(`
config controller 'http'
option enabled 'monitoring'
option interval '30'
`)
}
func generateMonitoringConfig() string {
return fmt.Sprintf(`
config monitoring 'monitoring'
option interval '15'
`)
}
func JoinLines(lines []string) string {
if len(lines) == 0 {
return ""
}
return strings.Join(lines, "\n") + "\n"
}
func generateSshKeyConfig(app core.App) string {
keys, err := app.FindAllRecords("ssh_keys")
if err != nil {
fmt.Println(err)
return ""
}
output := []string{}
for _, key := range keys {
output = append(output, strings.TrimSpace(key.GetString("key")))
}
return JoinLines(output)
}
func getTimeAdvertisementValues(vta string) (int, string) {
vta_flag := 0
if len(vta) > 0 && vta != "Disabled" {
vta_flag = 2
}
return vta_flag, GetTzData(vta)
}
// uciQuote escapes a value for inclusion inside a single-quoted UCI option.
func uciQuote(value string) string {
return strings.ReplaceAll(value, "'", `'\''`)
}
func generateWifiConfig(wifirecord WifiRecord, wifiid int, radio uint, app core.App, device *core.Record) (string, bool) {
wifi := wifirecord.Record
ssid := wifi.GetString("ssid")
key := wifi.GetString("key")
encryption := wifi.GetString("encryption")
if len(encryption) == 0 {
encryption = "psk2+ccmp"
}
ifaceName := fmt.Sprintf("wifi_%d_radio%d", wifiid, radio)
vlanName := getVlan(wifi, app)
steeringconfig, err := generateMacClientSteeringConfig(app, wifi, device)
if err != nil {
fmt.Println("Steering error:", err)
}
clientpskconfig := generateHostApdPskForWifi(app, wifi, ifaceName)
vta_flag, vta_tz := getTimeAdvertisementValues(wifi.GetString("ieee80211v_time_advertisement"))
rDeadLine := max(1000, wifi.GetInt("ieee80211r_reassoc_deadline"))
dtim := maxInt(1, wifi.GetInt("dtim_period"))
disabled := 0
if !wifi.GetBool("enabled") {
disabled = 1
}