Newer
Older
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
From bfb90653c70a1f9c9573b4d0b4efc48702320f62 Mon Sep 17 00:00:00 2001
From: Jan-Tarek Butt <tarek@ring0.de>
Date: Mon, 18 Sep 2017 18:20:28 +0200
Subject: [PATCH 5/5] add pkg gluon-hoodselector
* add pkg Makefile
* add respondd c file
* add respondd Makefile
* add etc config
* add micron.d file
* add upgrade script 540-hoodselector
* add hoodselector lua script
* rm gluon-hoods and gluon-mesh-vpn-fastd from DEPENDS
* config rm static option
* backport tested comunity version:
- Hoodselector: is now able to handle Polygon hoods. !60
- Hoodselector: does not use `scan dump` anymore which
saved airtime
- Hoodselector: L2TP tunneldigger support #47
- Hoodselector: the upgrade script got a refactoring.
Dead code is removed. desing failuer is
fixed, the script use the hood BSSID
instead the possible redundant hood name
for hood identification. #107
- Hoodselector: New state, a router from hood A which is
connected to an another router from hood B
is now able to switch back in its own hood
if a router from hood A viseble. #108
- Hoodselector: in state "radio less" is now ensured that
mesh on LAN / WAN is enabled befor entering
mode. #109
- Hoodselector: A bug in the function get_mesh_if() is
fixed now. This function returns now a list
of all mesh interfaces exzept the VPN
interface #116
- Hoodselector: Old VPN configurations will be deleted now.
If a hood without VPN peers got configured
the old peers from the old hood was still
presend. #117
- Hoodselector: many functions of the hoodselector are now
placed in a lua libary. #118
---
package/gluon-hoodselector/Makefile | 43 +
.../files/etc/config/hoodselector | 3 +
.../files/usr/lib/micron.d/hoodselector | 1 +
.../luasrc/lib/gluon/upgrade/540-hoodselector | 88 ++
.../luasrc/usr/lib/lua/hoodselector/util.lua | 898 +++++++++++++++++++++
.../luasrc/usr/sbin/hoodselector | 622 ++++++++++++++
package/gluon-hoodselector/src/Makefile | 6 +
package/gluon-hoodselector/src/respondd.c | 139 ++++
8 files changed, 1800 insertions(+)
create mode 100644 package/gluon-hoodselector/Makefile
create mode 100644 package/gluon-hoodselector/files/etc/config/hoodselector
create mode 100644 package/gluon-hoodselector/files/usr/lib/micron.d/hoodselector
create mode 100755 package/gluon-hoodselector/luasrc/lib/gluon/upgrade/540-hoodselector
create mode 100644 package/gluon-hoodselector/luasrc/usr/lib/lua/hoodselector/util.lua
create mode 100755 package/gluon-hoodselector/luasrc/usr/sbin/hoodselector
create mode 100644 package/gluon-hoodselector/src/Makefile
create mode 100644 package/gluon-hoodselector/src/respondd.c
diff --git a/package/gluon-hoodselector/Makefile b/package/gluon-hoodselector/Makefile
new file mode 100644
index 00000000..210e5200
--- /dev/null
+++ b/package/gluon-hoodselector/Makefile
@@ -0,0 +1,43 @@
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=gluon-hoodselector
+PKG_VERSION:=1
+PKG_RELEASE:=1
+
+PKG_BUILD_DIR := $(BUILD_DIR)/$(PKG_NAME)
+PKG_BUILD_DEPENDS := respondd
+
+include ../gluon.mk
+
+define Package/gluon-hoodselector
+ SECTION:=network
+ CATEGORY:=Gluon
+ TITLE:=Automatic layer2 networksecmentation depending on geo coordinates
+ DEPENDS:=+luci-lib-jsonc +gluon-mesh-batman-adv-15 +respondd +iwinfo
+endef
+
+define Package/gluon-hoodselector/description
+ Automatic layer2 networksecmentation depending on geo coordinates
+endef
+
+define Build/Prepare
+ mkdir -p $(PKG_BUILD_DIR)
+ $(CP) ./src/* $(PKG_BUILD_DIR)/
+endef
+
+define Build/Configure
+endef
+
+define Build/Compile
+ $(call Build/Compile/Default)
+ $(call GluonSrcDiet,./luasrc,$(PKG_BUILD_DIR)/luadest/)
+endef
+
+define Package/gluon-hoodselector/install
+ $(CP) ./files/* $(1)/
+ $(CP) $(PKG_BUILD_DIR)/luadest/* $(1)/
+ $(INSTALL_DIR) $(1)/lib/gluon/respondd
+ $(CP) $(PKG_BUILD_DIR)/respondd.so $(1)/lib/gluon/respondd/hoodselector.so
+endef
+
+$(eval $(call BuildPackage,gluon-hoodselector))
diff --git a/package/gluon-hoodselector/files/etc/config/hoodselector b/package/gluon-hoodselector/files/etc/config/hoodselector
new file mode 100644
index 00000000..24b2800c
--- /dev/null
+++ b/package/gluon-hoodselector/files/etc/config/hoodselector
@@ -0,0 +1,3 @@
+config settings 'hoodselector'
+ option hoodfile '/lib/gluon/hoods.json'
+ option enabled '1'
diff --git a/package/gluon-hoodselector/files/usr/lib/micron.d/hoodselector b/package/gluon-hoodselector/files/usr/lib/micron.d/hoodselector
new file mode 100644
index 00000000..a4c9916d
--- /dev/null
+++ b/package/gluon-hoodselector/files/usr/lib/micron.d/hoodselector
@@ -0,0 +1 @@
+*/2 * * * * /usr/sbin/hoodselector 2>> /tmp/hoodselector_error
diff --git a/package/gluon-hoodselector/luasrc/lib/gluon/upgrade/540-hoodselector b/package/gluon-hoodselector/luasrc/lib/gluon/upgrade/540-hoodselector
new file mode 100755
index 00000000..a0fe8d65
--- /dev/null
+++ b/package/gluon-hoodselector/luasrc/lib/gluon/upgrade/540-hoodselector
@@ -0,0 +1,88 @@
+#!/usr/bin/lua
+
+local uci = require('simple-uci').cursor()
+local hoodutil = require("hoodselector.util")
+
+-- Retun a table of current peers from /etc/config/fastd
+local function getCurrentPeers()
+ local configPeers = {}
+ local err = uci:foreach('fastd', 'peer',
+ function(s)
+ hoodutil.extrac_fastd_peer(s,configPeers)
+ end
+ )
+ if not err then
+ os.exit(1)
+ end
+ return configPeers
+end
+
+-- START HERE
+local hoodfile = uci:get('hoodselector', 'hoodselector', 'hoodfile')
+local hoodbssid = uci:get('hoodselector', 'hoodselector', 'hood')
+
+if hoodfile == nil then
+ os.exit(1)
+end
+
+local jhood = hoodutil.readHoodfile(hoodfile)
+if jhood == nil then
+ uci:set('hoodselector', 'hoodselector', 'enabled', false)
+ uci:save('hoodselector')
+ os.exit(1)
+end
+
+if hoodbssid == nil then
+ local defaulthood = hoodutil.getDefaultHood(jhood)
+ if defaulthood == nil then
+ os.exit(1)
+ end
+ if defaulthood.bssid == nil then
+ os.exit(1)
+ end
+ hoodbssid = defaulthood.bssid
+end
+
+local hood = hoodutil.gethoodByBssid(jhood,hoodbssid)
+if hood == nil then
+ os.exit(1)
+end
+
+uci:section('hoodselector', 'settings', 'hoodselector', {
+ hood = hoodbssid,
+ hoodfile = hoodfile,
+ enabled = true
+})
+uci:save('hoodselector')
+
+local radios = hoodutil.getWifiDevices()
+-- pre check if fastd conf exsist
+if uci:get('fastd', 'mesh_vpn_backbone', 'net') ~= nil then
+ hoodutil.fastd_reconfigure(hood["servers"],getCurrentPeers())
+end
+-- per check if tunneldigger conf exsist
+if uci:get('tunneldigger', 'mesh_vpn', 'interface') ~= nil then
+ hoodutil.tunneldigger_reconfigure(hood["servers"])
+end
+
+if next(radios) then
+ local ibss_exists = false
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
+ local mesh_exists = false
+ for _,radio in ipairs(radios) do
+ local ifname = uci:get('wireless', 'ibss_' .. radio, 'ifname')
+ if (ifname ~= nil) then
+ ibss_exists = true
+ end
+ ifname = uci:get('wireless', 'mesh_' .. radio, 'ifname')
+ if (ifname ~= nil) then
+ mesh_exists = true
+ end
+ end
+ if ibss_exists then
+ hoodutil.ibss_reconfigure(radios, hood["bssid"])
+ end
+ if mesh_exists then
+ local mesh_prefix = hoodutil.get_mesh_prefix(radios)
+ hoodutil.mesh_reconfigure(radios, mesh_prefix..hood["bssid"]:lower())
+ end
+end
diff --git a/package/gluon-hoodselector/luasrc/usr/lib/lua/hoodselector/util.lua b/package/gluon-hoodselector/luasrc/usr/lib/lua/hoodselector/util.lua
new file mode 100644
index 00000000..05678809
--- /dev/null
+++ b/package/gluon-hoodselector/luasrc/usr/lib/lua/hoodselector/util.lua
@@ -0,0 +1,898 @@
+local json = require ("luci.jsonc")
+local uci = require('simple-uci').cursor()
+
+local M = {}
+
+function M.split(s, delimiter)
+ local result = {};
+ for match in (s..delimiter):gmatch("(.-)"..delimiter) do
+ table.insert(result, match);
+ end
+ return result;
+end
+
+local PID = M.split(io.open("/proc/self/stat", 'r'):read('*a'), " ")[1]
+
+function M.log(msg)
+ if msg then
+ io.stdout:write(msg.."\n")
+ os.execute("logger hoodselector["..PID.."]: "..msg)
+ end
+end
+
+-- Read the full hoodfile. Return nil for wrong format or no such file
+function M.readHoodfile(file)
+ local jhood = io.open(file, 'r')
+ if not jhood then return nil end
+ local obj, _, err = json.parse (jhood:read('*a'), 1, nil)
+ if err then
+ return nil
+ else
+ return obj
+ end
+end
+
+function M.mesh_on_wan_disable()
+ os.execute('ifdown mesh_wan')
+ io.stdout:write('Interface mesh_wan disabled.\n')
+end
+
+function M.mesh_on_wan_enable()
+ os.execute('ifup mesh_wan')
+ io.stdout:write('Interface mesh_wan enabled.\n')
+end
+
+function M.mesh_on_lan_disable()
+ os.execute('ifdown mesh_lan')
+ io.stdout:write('Interface mesh_lan disabled.\n')
+end
+
+function M.mesh_on_lan_enable()
+ os.execute('ifup mesh_lan')
+ io.stdout:write('Interface mesh_lan enabled.\n')
+end
+
+function M.fastd_installed()
+ if io.open("/usr/bin/fastd", 'r') ~= nil then
+ return true
+ end
+ return false
+end
+
+function M.tunneldigger_installed()
+ if io.open("/usr/bin/tunneldigger", 'r') ~= nil then
+ return true
+ end
+ return false
+end
+
+function M.filt_if(filt,str)
+ for _, c in ipairs(filt) do
+ -- check if - is contains because it is a magic character thus it musst be replace)
+ if c:gsub("%-", "0"):match(str:gsub("%-", "0")) then
+ return true
+ end
+ end
+ return false
+end
+
+function M.filter_redundancy(list)
+ local flag = {}
+ local ret = {}
+ for _,element in ipairs(list) do
+ if not flag[element] then
+ ret[#ret+1] = element
+ flag[element] = true
+ end
+ end
+ return ret
+end
+
+function M.trim(s)
+ -- from PiL2 19.4
+ return (s:gsub("^%s*(.-)%s*$", "%1"))
+end
+
+function M.sleep(n)
+ os.execute("sleep " .. tonumber(n))
+end
+
+function M.brclient_restart()
+ os.execute('ifconfig br-client down')
+ os.execute('ifconfig br-client up')
+ io.stdout:write('Interface br-client restarted.\n')
+end
+
+function M.vpn_stop()
+ -- check if fastd installed
+ if M.fastd_installed() then
+ if uci:get_bool('fastd','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/fastd stop')
+ io.stdout:write('Fastd stoped.\n')
+ end
+ end
+ -- check if tunneldigger installed
+ if M.tunneldigger_installed() then
+ if uci:get_bool('tunneldigger','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/tunneldigger stop')
+ io.stdout:write('Tunneldigger stoped.\n')
+ end
+ end
+end
+
+function M.vpn_start()
+ if M.fastd_installed() then
+ if uci:get_bool('fastd','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/fastd start')
+ io.stdout:write('Fastd started.\n')
+ end
+ end
+ if M.tunneldigger_installed() then
+ if uci:get_bool('tunneldigger','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/tunneldigger start')
+ io.stdout:write('Tunneldigger started.\n')
+ end
+ end
+ M.brclient_restart()
+end
+
+function M.vpn_disable()
+ if M.fastd_installed() then
+ if uci:get_bool('fastd','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/fastd disable')
+ io.stdout:write('Fastd disabled.\n')
+ end
+ end
+ if M.tunneldigger_installed() then
+ if uci:get_bool('tunneldigger','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/tunneldigger disable')
+ io.stdout:write('Tunneldigger disabled.\n')
+ end
+ end
+end
+
+function M.vpn_enable()
+ if M.fastd_installed() then
+ if not uci:get_bool('fastd','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/fastd enable')
+ io.stdout:write('Fastd enabled.\n')
+ end
+ end
+ if M.tunneldigger_installed() then
+ if not uci:get_bool('tunneldigger','mesh_vpn','enabled') then
+ os.execute('/etc/init.d/tunneldigger enable')
+ io.stdout:write('Tunneldigger enabled.\n')
+ end
+ end
+end
+
+function M.wireless_restart()
+ os.execute('wifi')
+ io.stdout:write('Wireless restarted.\n')
+end
+
+-- Get a list of wifi devices return an emty table for no divices
+function M.getWifiDevices()
+ local radios = {}
+ uci:foreach('wireless', 'wifi-device',
+ function(s)
+ table.insert(radios, s['.name'])
+ end
+ )
+ return radios
+end
+
+-- get signal strength
+function M.scan_filter_quality(scan_str, redirect)
+ local tmp_quality = redirect
+ if scan_str:match("signal:") then
+ tmp_quality = M.split(scan_str, " ")
+ tmp_quality = M.split(tmp_quality[2], "%.")
+ if tmp_quality[1]:match("-") then
+ tmp_quality = M.split(tmp_quality[1], "-")
+ end
+ tmp_quality = tonumber(tmp_quality[2]:match("(%d%d)"))
+ end
+ return tmp_quality
+end
+
+-- get frequency
+function M.scan_filter_frequency(scan_str, redirect)
+ local tmp_frequency = redirect
+ if scan_str:match("freq") then
+ tmp_frequency = M.split(scan_str, ":")
+ tmp_frequency = tmp_frequency[2]
+ if tmp_frequency ~= nil then
+ tmp_frequency = M.trim(tmp_frequency)
+ end
+ end
+ return tmp_frequency
+end
+
+function M.ibss_scan(radio,ifname,ssid,networks)
+ local wireless_scan = string.format( "iw %s scan", ifname)
+ local row = {}
+ row["radio"] = radio
+ -- loop through each line in the output of iw
+ for wifiscan in io.popen(wireless_scan, 'r'):lines() do
+ -- the following line matches a new network in the output of iw
+ if(row["bssid"] ~= nil and row["quality"] ~= nil and row["ssid"] == ssid) then
+ table.insert(networks, row)
+ row = {}
+ row["radio"] = radio
+ end
+
+ -- get ssid
+ if wifiscan:match("SSID:") then
+ row["ssid"] = M.split(wifiscan, ":")
+ row["ssid"] = row["ssid"][2]
+ if(row["ssid"] ~= nil) then
+ row["ssid"] = M.trim(row["ssid"])
+ end
+ end
+ row["frequency"] = M.scan_filter_frequency(wifiscan, row["frequency"])
+
+ -- get bssid
+ if wifiscan:match("(%w+:%w+:%w+:%w+:%w+:%w+)") then
+ row["bssid"] = wifiscan:match("(%w+:%w+:%w+:%w+:%w+:%w+)")
+ end
+ row["quality"] = M.scan_filter_quality(wifiscan, row["quality"])
+ end
+ return networks
+end
+
+function M.mesh_scan(radio,ifname,meshid,networks)
+ local wireless_scan = string.format( "iw %s scan", ifname)
+ local row = {}
+ row["radio"] = radio
+ -- loop through each line in the output of iw
+ for wifiscan in io.popen(wireless_scan, 'r'):lines() do
+ -- the following line matches a new network in the output of iw
+ if(row["bssid"] ~= nil and row["quality"] ~= nil and row["ssid"] == meshid) then
+ table.insert(networks, row)
+ row = {}
+ row["radio"] = radio
+ end
+ row["frequency"] = M.scan_filter_frequency(wifiscan, row["frequency"])
+ row["quality"] = M.scan_filter_quality(wifiscan, row["quality"])
+
+ -- get mesh-ID(ssid) and hoodbssid
+ if wifiscan:match("MESH ID:") then
+ local meshID = M.split(wifiscan, " ")[3]
+ if meshID ~= nil then
+ meshID = M.split(meshID, "_")
+ if meshID[1] ~= nil then
+ row["ssid"] = meshID[1].."_"
+ end
+ if meshID[2] ~= nil then
+ if meshID[2]:match("(%w+:%w+:%w+:%w+:%w+:%w+)") then
+ row["bssid"] = meshID[2]:match("(%w+:%w+:%w+:%w+:%w+:%w+)")
+ end
+ end
+ end
+ end
+ end
+ return networks
+end
+
+-- Scans for wireless networks and returns a two dimensional array containing
+-- wireless mesh neighbour networks and their properties.
+-- The array is sorted descending by signal strength (strongest signal
+-- first, usually the local signal of the wireless chip of the router)
+function M.wlan_list_sorted(radios, mesh_prefix)
+ local networks = {}
+ for _, radio in ipairs(radios) do
+ local ifname = uci:get('wireless', 'ibss_' .. radio, 'ifname')
+ local ssid = uci:get('wireless', 'ibss_' .. radio, 'ssid')
+ if (ifname ~= nil and ssid ~= nil) then
+ --do ibss scan
+ networks = M.ibss_scan(radio,ifname,ssid,networks)
+ end
+ ifname = uci:get('wireless', 'mesh_' .. radio, 'ifname')
+ if (ifname ~= nil and mesh_prefix ~= nil) then
+ --do mesh scan
+ networks = M.mesh_scan(radio,ifname,mesh_prefix,networks)
+ end
+ end
+ table.sort(networks, function(a,b) return a["quality"] < b["quality"] end)
+ return networks
+end
+
+-- this method removes the wireless network of the router itself
+-- from the wlan_list
+function M.filter_my_wlan_network(wlan_list)
+ for i=#wlan_list,1,-1 do
+ local bssid = uci:get('wireless', 'ibss_' .. wlan_list[i].radio, 'bssid')
+ if bssid ~= nil then
+ if string.lower(wlan_list[i].bssid) == string.lower(bssid) then
+ table.remove(wlan_list, i)
+ end
+ else
+ local mesh = uci:get('wireless', 'mesh_' .. wlan_list[i].radio, 'mesh_id')
+ if mesh ~= nil then
+ if string.lower(wlan_list[i].ssid..wlan_list[i].bssid) == string.lower(mesh) then
+ table.remove(wlan_list, i)
+ end
+ end
+ end
+ end
+ return wlan_list
+end
+
+function M.filter_default_hood_wlan_networks(default_hood, wlan_list)
+ for i=#wlan_list,1,-1 do
+ if(string.lower(default_hood.bssid) == string.lower(wlan_list[i].bssid)) then
+ table.remove(wlan_list, i)
+ end
+ end
+ return wlan_list
+end
+
+-- Get Geoposition. Return nil for no position
+function M.getGeolocation()
+ return {["lat"] = tonumber(uci:get('gluon-node-info', uci:get_first('gluon-node-info', 'location'), 'latitude')),
+ ["lon"] = tonumber(uci:get('gluon-node-info', uci:get_first('gluon-node-info', 'location'), 'longitude')) }
+end
+
+-- Source with pseudocode: https://de.wikipedia.org/wiki/Punkt-in-Polygon-Test_nach_Jordan
+-- see also https://en.wikipedia.org/wiki/Point_in_polygon
+-- parameters: points A = (x_A,y_A), B = (x_B,y_B), C = (x_C,y_C)
+-- return value: −1 if the ray from A to the right bisects the edge [BC] (the lower vortex of [BC]
+-- is not seen as part of [BC]);
+-- 0 if A is on [BC];
+-- +1 else
+function M.crossProdTest(x_A,y_A,x_B,y_B,x_C,y_C)
+ if y_A == y_B and y_B == y_C then
+ if (x_B <= x_A and x_A <= x_C) or (x_C <= x_A and x_A <= x_B) then
+ return 0
+ end
+ return 1
+ end
+ if not ((y_A == y_B) and (x_A == x_B)) then
+ if y_B > y_C then
+ -- swap B and C
+ local h = x_B
+ x_B = x_C
+ x_C = h
+ h = y_B
+ y_B = y_C
+ y_C = h
+ end
+ if (y_A <= y_B) or (y_A > y_C) then
+ return 1
+ end
+ local Delta = (x_B-x_A) * (y_C-y_A) - (y_B-y_A) * (x_C-x_A)
+ if Delta > 0 then
+ return 1
+ elseif Delta < 0 then
+ return -1
+ end
+ end
+ return 0
+end
+
+-- Source with pseudocode: https://de.wikipedia.org/wiki/Punkt-in-Polygon-Test_nach_Jordan
+-- see also: https://en.wikipedia.org/wiki/Point_in_polygon
+-- let P be a 2D Polygon and Q a 2D Point
+-- return value: +1 if Q within P;
+-- −1 if Q outside of P;
+-- 0 if Q on an edge of P
+function M.pointInPolygon(poly, point)
+ local t = -1
+ for i=1,#poly-1 do
+ t = t * M.crossProdTest(point.lon,point.lat,poly[i][2],poly[i][1],poly[i+1][2],poly[i+1][1])
+ if t == 0 then break end
+ end
+ return t
+end
+
+-- Return hood from the hood file based on geo position or nil if no real hood could be determined
+-- First check if an area has > 2 points and is hence a polygon. Else assume it is a rectangular
+-- box defined by two points (south-west and north-east)
+function M.getHoodByGeo(jhood,geo)
+ for _, h in pairs(jhood) do
+ for _, area in pairs(h.boxes) do
+ if #area > 2 then
+ if (M.pointInPolygon(area,geo) == 1) then
+ return h
+ end
+ else
+ if ( geo.lat >= area[1][1] and geo.lat < area[2][1] and geo.lon >= area[1][2] and geo.lon < area[2][2] ) then
+ return h
+ end
+ end
+ end
+ end
+ return nil
+end
+
+-- This method checks if the fastd configuration needs to be rewritten from the
+-- hoodfile. Therefore the method performs 3 checks and returns false if all
+-- checks fail. If one of the checks results to true the method returns true:
+-- 1. Check if the local fastd configuration has a server that does not exist
+-- in the hoodfile.
+-- 2. Check if a server that does exist in the local fastd configuration AND
+-- in the hoodfile has a configuration change.
+-- 3. Check if the hoodfile contains a server that does not exist in the
+-- local fastd configuration.
+function M.fastd_reconfiguration_needed(hood_serverlist,local_serverlist)
+
+ local tmp_hood_serverlist = {}
+ for _,hood_server in pairs(hood_serverlist) do
+ if (hood_server["type"] == "fastd") then
+ table.insert(tmp_hood_serverlist,hood_server)
+ end
+ end
+
+ -- Checks 1. and 2.
+ for local_server_config_name, local_server in pairs(local_serverlist) do
+ local local_server_exists_in_hoodfile = false
+ for _,hood_server in pairs(tmp_hood_serverlist) do
+ if (local_server_config_name == 'mesh_vpn_backbone_peer_'..
+ M.split(hood_server["host"], '.')[1]:gsub("%-", "%_") .. "_" .. hood_server['port']) then
+ local_server_exists_in_hoodfile = true
+ if ( local_server.key ~= hood_server['publickey'] ) then return true end
+ if ( local_server.remote.host ~= '\"'..hood_server["host"]..'\"' ) then return true end
+ if ( local_server.remote.port ~= hood_server['port'] ) then return true end
+ end
+ end
+ if not local_server_exists_in_hoodfile then return true end
+ end
+
+ -- Check 3.
+ for _,hood_server in pairs(tmp_hood_serverlist) do
+ local hood_server_exists_locally = false
+ for local_server_config_name, _ in pairs(local_serverlist) do
+ if (local_server_config_name == 'mesh_vpn_backbone_peer_'..
+ M.split(hood_server["host"], '.')[1]:gsub("%-", "%_") .. "_" .. hood_server['port']) then
+ hood_server_exists_locally = true
+ end
+ end
+ if not hood_server_exists_locally then return true end
+ end
+ return false
+end
+
+function M.tunneldigger_reconfiguration_needed(hood_serverlist,local_serverlist)
+
+ local tmp_hood_serverlist = {}
+ for _,hood_server in pairs(hood_serverlist) do
+ if (hood_server["type"] == "l2tp") then
+ table.insert(tmp_hood_serverlist,hood_server)
+ end
+ end
+
+ -- Checks 1. and 2.
+ for _,local_peer in pairs(local_serverlist) do
+ local local_server_exists_in_hoodfile = false
+ for _,hood_server in pairs(tmp_hood_serverlist) do
+ if (local_peer == hood_server["host"] .. ":" .. hood_server["port"]) then
+ local_server_exists_in_hoodfile = true
+ end
+ end
+ if not local_server_exists_in_hoodfile then return true end
+ end
+
+ -- Check 3.
+ for _,hood_server in pairs(tmp_hood_serverlist) do
+ local hood_server_exists_locally = false
+ for _,local_peer in pairs(local_serverlist) do
+ if (local_peer == hood_server["host"] .. ":" .. hood_server["port"]) then
+ hood_server_exists_locally = true
+ end
+ end
+ if not(hood_server_exists_locally) then return true end
+ end
+ return false
+end
+
+-- Reconfigure fastd
+function M.fastd_reconfigure(hood_serverlist,local_serverlist)
+ -- remove all servers
+ for config_index, _ in pairs(local_serverlist) do
+ uci:delete('fastd',config_index)
+ end
+
+ -- add servers from hoodfile
+ local group = 'mesh_vpn_backbone'
+ for _,hood_server in pairs(hood_serverlist) do
+ if (hood_server["type"] == "fastd") then
+ uci:section('fastd', 'peer', group .. '_peer_' ..
+ M.split(hood_server.host, '.')[1]:gsub("%-", "%_") .. "_" .. hood_server.port,
+ {
+ enabled = 1,
+ net = 'mesh_vpn',
+ group = group,
+ key = hood_server.publickey,
+ remote = {'\"'..hood_server.host..'\"'..' port '..hood_server.port}
+ }
+ )
+ end
+ end
+
+ uci:save('fastd')
+ uci:commit('fastd')
+ io.stdout:write('Fastd needed reconfiguration. Stopped and applied new settings.\n')
+end
+
+function M.tunneldigger_reconfigure(hood_serverlist)
+ -- remove all servers
+ uci:delete('tunneldigger', 'mesh_vpn', 'address')
+
+ -- add servers from hoodfile
+ local addresslist = {}
+ for _,hood_server in pairs(hood_serverlist) do
+ if (hood_server["type"] == "l2tp") then
+ local tmpAdrr =hood_server["host"] .. ":" .. hood_server["port"]
+ table.insert(addresslist, tmpAdrr)
+ end
+ end
+ if next(addresslist) then
+ uci:set('tunneldigger', 'mesh_vpn', 'address', addresslist)
+ end
+ uci:save('tunneldigger')
+ uci:commit('tunneldigger')
+ io.stdout:write('tunneldigger needed reconfiguration. Stopped and applied new settings.\n')
+end
+
+-- Checks if wireless needs a reconfiguration. Returns true if any of the checks
+-- passes. Otherwise the method returns false.
+function M.wireless_reconfiguration_needed(radios, prefix, hood_bssid)
+ local configure_ibss = false
+ local configure_mesh = false
+ for _, radio in ipairs(radios) do
+ if uci:get('wireless', 'ibss_' .. radio, 'ifname') ~= nil then
+ if ( uci:get('wireless', 'ibss_' .. radio, 'bssid') ~= hood_bssid ) then
+ configure_ibss = true
+ end
+ end
+ if uci:get('wireless', 'mesh_' .. radio, 'ifname') ~= nil then
+ if ( uci:get('wireless', 'mesh_' .. radio, 'mesh_id') ~= prefix..hood_bssid:lower() ) then
+ configure_mesh = true
+ end
+ end
+ end
+ if not configure_ibss and not configure_mesh then return 0 end --no changes
+ if configure_ibss and not configure_mesh then return 1 end --ibss changes
+ if not configure_ibss and configure_mesh then return 2 end --mesh changes
+ return 3 --bouth changes
+end
+
+-- Reconfigure wireless
+function M.ibss_reconfigure(radios, hood_bssid)
+ for _, radio in ipairs(radios) do
+ if not ( uci:get('wireless', 'ibss_' .. radio, 'bssid') == hood_bssid ) then
+ uci:section('wireless', 'wifi-iface', 'ibss_' .. radio, {bssid = hood_bssid})
+ end
+ end
+ uci:save('wireless')
+ uci:commit('wireless')
+end
+
+function M.mesh_reconfigure(radios, meshid)
+ for _, radio in ipairs(radios) do
+ if not ( uci:get('wireless', 'mesh_' .. radio, 'mesh_id') == meshid ) then
+ uci:section('wireless', 'wifi-iface', 'mesh_' .. radio, {mesh_id = meshid})
+ end
+ end
+ uci:save('wireless')
+ uci:commit('wireless')
+end
+
+-- Save selected hood to config to make a restore after a sysupgrade possible
+function M.saveHoodToConfig(hoodbssid)
+ uci:set('hoodselector', 'hoodselector', 'hood', hoodbssid)
+ uci:save('hoodselector')
+ uci:commit('hoodselector')
+end
+
+-- Return the default hood in the hood list.
+-- This method can return the following data:
+-- * default hood
+-- * nil if no default hood has been defined
+function M.getDefaultHood(jhood)
+ for _, h in pairs(jhood) do
+ if h.defaulthood then
+ return h
+ end
+ end
+ return nil
+end
+
+-- boolean check if batman-adv has gateways
+function M.batmanHasGateway()
+ local file = io.open("/sys/kernel/debug/batman_adv/bat0/gateways", 'r')
+ if file ~= nil then
+ for gw in file:lines() do
+ if gw:match("Bit") then
+ return true
+ end
+ end
+ end
+ return false
+end
+
+-- Return hood from the hood file based on a given BSSID. nil if no matching hood could be found
+function M.gethoodByBssid(jhood, scan_bssid)
+ for _, h in pairs(jhood) do
+ if scan_bssid:lower():match(h.bssid:lower()) then
+ return h
+ end
+ end
+ return nil
+end
+
+-- Return hood from hood file based on a bssid address. nil if no matching hood could be found
+function M.getCurrentHood(jhood)
+ local hoodbssid = uci:get('hoodselector', 'hoodselector', 'hood')
+ for _, h in pairs(jhood) do
+ if h.bssid == hoodbssid then
+ return h
+ end
+ end
+ return nil
+end
+
+function M.test_batman_mesh_networks(sorted_wlan_list, meshprefix)
+ -- remove the ap network because we cannot change
+ -- the settings of the adhoc network if the ap network is still operating
+ for iface in io.popen(string.format("iw dev"),'r'):lines() do
+ if iface:match("Interface") then
+ iface = M.trim(M.split(iface, "Interface")[2])
+ if not ( iface:match("ibss") or iface:match("mesh")) then
+ os.execute("iw dev "..iface.." del")
+ end
+ end
+ end
+ for _, wireless in pairs(sorted_wlan_list) do
+ local ibss = uci:get('wireless', 'ibss_' .. wireless["radio"], 'ifname')
+ local mesh = uci:get('wireless', 'mesh_' .. wireless["radio"], 'ifname')
+ if wireless["ssid"] == uci:get('wireless', 'ibss_' .. wireless["radio"], 'ssid') then
+ io.stdout:write("Testing IBSS "..wireless["bssid"].."...\n")
+ -- leave the current adhoc network
+ os.execute("iw dev "..ibss.." ibss leave 2> /dev/null")
+ if mesh ~= nil then
+ os.execute("iw dev "..mesh.." mesh leave 2> /dev/null")
+ end
+ -- setup the adhoc network we want to test
+ os.execute("iw dev "..ibss.." ibss join "..wireless["ssid"].." "..wireless["frequency"].." "..wireless["bssid"])
+ end
+ if wireless["ssid"] == meshprefix then
+ io.stdout:write("Testing MESH "..wireless["bssid"].."...\n")
+ -- leave the current mesh network
+ os.execute("iw dev "..mesh.." mesh leave 2> /dev/null")
+ if ibss ~= nil then
+ os.execute("iw dev "..ibss.." ibss leave 2> /dev/null")
+ end
+ -- setup the mesh network we want to test
+ os.execute("iw dev "..mesh.." mesh join "..meshprefix..wireless["bssid"].." freq "..wireless["frequency"])
+ end
+ -- sleep 30 seconds till the connection is fully setup
+ local c = 0;
+ while(not M.batmanHasGateway()) do
+ if(c >= 30) then break end
+ M.sleep(1)
+ c = c +1;
+ end
+ if c < 30 then
+ return wireless["bssid"]
+ end
+ end
+ return nil
+end
+
+function M.get_batman_mesh_network(sorted_wlan_list, defaultHood, meshprefix)
+ io.stdout:write('Testing neighbouring adhoc networks for batman advanced gw connection.\n')
+ io.stdout:write('The following wireless networks have been found:\n')
+ for _, network in pairs(sorted_wlan_list) do
+ print(network["quality"].."\t"..network["frequency"].."\t"..network["bssid"].."\t"..network["ssid"])
+ end
+
+ -- we dont want to test the default hood because if there is no other
+ -- hood present we will connect to the default hood anyway
+ sorted_wlan_list = M.filter_default_hood_wlan_networks(defaultHood, sorted_wlan_list)
+
+ -- we dont want to test duplicated networks
+ sorted_wlan_list = M.filter_redundancy(sorted_wlan_list)
+
+ -- we dont want to get tricked by our signal
+ sorted_wlan_list = M.filter_my_wlan_network(sorted_wlan_list)
+
+ io.stdout:write('After filtering we will test the following wireless networks:\n')
+ for _, network in pairs(sorted_wlan_list) do
+ print(network["quality"].."\t"..network["frequency"].."\t"..network["bssid"].."\t"..network["ssid"])
+ end
+
+ local bssid = nil
+ if(next(sorted_wlan_list)) then
+ io.stdout:write("Prepare configuration for testing wireless networks...\n")
+ -- Notice:
+ -- we will use iw for testing the wireless networks because using iw does
+ -- not need any changes inside the uci config. This approach allows the
+ -- router to automatically reset to previous configuration in case
+ -- someone disconnects the router from power during test.
+
+ -- stop vpn to prevent two hoods from beeing connected in case
+ -- the router gets internet unexpectedly during test.
+ M.vpn_stop()
+ bssid = M.test_batman_mesh_networks(sorted_wlan_list, meshprefix)
+ M.vpn_start()
+ M.wireless_restart()
+ io.stdout:write("Finished testing wireless networks, restored previous configuration\n")
+ end
+
+ return bssid
+end
+
+function M.get_batman_GW_interface()
+ for gw in io.open("/sys/kernel/debug/batman_adv/bat0/gateways", 'r'):lines() do
+ if gw:match("=>") then
+ return M.trim(gw:match("%[.-%]"):gsub("%[", ""):gsub("%]", ""))
+ end
+ end
+ return nil
+end
+
+function M.get_radio_to_bssid(radios,iface,jhood)
+ for _, radio in ipairs(radios) do
+ local ifname = uci:get('wireless', 'ibss_' .. radio, 'ifname')
+ if ifname == iface then
+ return M.gethoodByBssid(jhood, uci:get('wireless', 'ibss_' .. radio, 'bssid'))
+ end
+ ifname = uci:get('wireless', 'mesh_' .. radio, 'ifname')
+ if ifname == iface then
+ local meshid = uci:get('wireless', 'mesh_' .. radio, 'mesh_id')
+ meshid = M.split(meshid, '_')
+ if meshid[2] ~= nil then
+ if meshid[2]:match("(%w+:%w+:%w+:%w+:%w+:%w+)") then
+ return M.gethoodByBssid(jhood, meshid[2]:match("(%w+:%w+:%w+:%w+:%w+:%w+)"))
+ end
+ end
+ end
+ end
+ return nil
+end
+
+function M.mesh_lan_wan(iface)
+ if uci:get('network', 'mesh_wan') then
+ local if_wan = io.popen(string.format("ifstatus mesh_wan"), 'r'):read('*a')
+ if if_wan ~= nil then
+ local wan, _, _ = json.parse(if_wan, 1, nil)
+ if wan["device"] == iface then
+ io.stdout:write("gw source is wan\n")
+ return true
+ end
+ end
+ end
+ if uci:get('network', 'mesh_lan') then
+ local if_lan = io.popen(string.format("ifstatus mesh_lan"), 'r'):read('*a')
+ if if_lan ~= nil then
+ local lan, _, _ = json.parse(if_lan, 1, nil)
+ if lan["device"] == iface then
+ io.stdout:write("gw source is lan\n")
+ return true
+ end
+ end
+ end
+ return false
+end
+
+function M.conditional_increment(table,index)
+ if index["bssid"] ~= nil then
+ if not table[index["bssid"]] then
+ table[index["bssid"]] = 1
+ else
+ table[index["bssid"]] = table[index["bssid"]] + 1
+ end
+ end
+end
+
+-- Get BSSID from neighbour hoods over respondd
+function M.molw_get_bssid(iface)
+ -- differentiate between VPN and mesh only routers
+ local vpn_router_neighbour_bssids = {}
+ local mesh_router_neighbour_bssids = {}
+ local own_mac = uci:get('network', 'client', 'macaddr')
+ for _,respondd_if in ipairs(iface) do
+ local respondd = string.format("gluon-neighbour-info -i " ..
+ respondd_if .. " -p 1001 -d ff02::2 -r hoodselector -t 0.5")
+ print(respondd)
+ for line in io.popen(respondd, 'r'):lines() do
+ local obj, _, err = json.parse (line, 1, nil)
+ if err then
+ io.stdout:write("json parse error!\n")
+ else
+ if obj["mac"] ~= own_mac then
+ if obj["hoodinfo"] ~= nil then
+ if obj["hoodinfo"]["vpnrouter"] ~= nil then
+ if obj["hoodinfo"]["vpnrouter"]:match("true") then
+ if obj["mesh"] ~= nil then
+ M.conditional_increment(vpn_router_neighbour_bssids, obj["mesh"])
+ end
+ else
+ if obj["mesh"] ~= nil then
+ M.conditional_increment(mesh_router_neighbour_bssids, obj["mesh"])
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ local neighbour_bssids
+ if next(vpn_router_neighbour_bssids) then
+ -- molwm VPN router founds.
+ print("Found VPN routers over mesh on lan or wan")
+ neighbour_bssids = vpn_router_neighbour_bssids
+ else
+ -- molwm VPN router not founds. Get most presented bssid
+ print("No VPN routers over mesh on lan or wan")
+ neighbour_bssids = mesh_router_neighbour_bssids
+ end
+
+ local bssid = nil
+ local value = 0
+ for b,c in pairs(neighbour_bssids) do
+ io.stdout:write(b.."\t"..c.."\n")
+ if value < c then
+ bssid = b
+ value = c
+ end
+ end
+ local eq_cost_entrys = {}
+ for b,c in pairs(neighbour_bssids) do
+ if b == bssid then
+ table.insert(eq_cost_entrys,b)
+ end
+ if c == value and b ~= bssid then
+ table.insert(eq_cost_entrys,b)
+ end
+ end
+ if #eq_cost_entrys ~= 0 then
+ bssid = eq_cost_entrys[math.random(#eq_cost_entrys)]
+ end
+ return bssid
+end
+
+function M.get_mesh_prefix(radios)
+ local mesh_prefix = nil
+ for _,radio in ipairs(radios) do
+ local mesh_id = uci:get('wireless', 'mesh_' .. radio, 'mesh_id')
+ if mesh_id ~= nil then
+ mesh_id = M.split(mesh_id, '_')
+ if mesh_id[1] ~= "" then
+ mesh_prefix = mesh_id[1].."_"
+ else
+ if mesh_id[2] ~= "" then
+ mesh_prefix = mesh_id[2].."_"
+ end
+ end
+ end
+ end
+ return mesh_prefix
+end
+
+function M.extrac_fastd_peer(s,configPeers)
+ if s['.name'] then
+ for prefix,peer in pairs(s) do
+ local tmpPeer = {}
+ if prefix:match(".name") then
+ if peer:match("mesh_vpn_backbone_peer_") then
+ -- val tmpRemote does not need uci exception check because its already include by "uci:foreach"
+ local tmpRemote = uci:get('fastd', peer, 'remote')
+ tmpRemote = M.split(tmpRemote[1], " ")
+ local remote = {}
+ remote['host'] = tmpRemote[1]
+ remote[tmpRemote[2]] = tmpRemote[3]
+ -- uci:get does not need uci exception check because its already include by "uci:foreach"
+ tmpPeer['key'] = tostring(uci:get('fastd', peer, 'key'))
+ tmpPeer['remote'] = remote
+ configPeers[peer] = tmpPeer
+ end
+ end
+ end
+ end
+end
+
+return M
diff --git a/package/gluon-hoodselector/luasrc/usr/sbin/hoodselector b/package/gluon-hoodselector/luasrc/usr/sbin/hoodselector
new file mode 100755
index 00000000..b74f0362
--- /dev/null
+++ b/package/gluon-hoodselector/luasrc/usr/sbin/hoodselector
@@ -0,0 +1,622 @@
+#!/usr/bin/lua
+
+-- This is the hoodselector. The hoodselector is one of the main components for
+-- splitting a layer 2 mesh network into seperated network segments (hoods).
+-- The job of the hoodselector is to automatically detect in which hood
+-- the router is located based on geo settings or by scanning its environment.
+-- Based on these informations the hoodselector should select a hood from a
+-- list of known hoods (hoodlist) and adjust vpn, wireless and mesh on lan
+-- configuration based on the settings given for the selected hood.
+--
+-- The hoodlist containing all hood settings is located in a seperate hoodfile
+-- in the hoods package.
+--
+-- The hoodselector works with the folowing additional software:
+-- * fastd (vpn configuration) see getCurrentFastdPeers()
+-- * tunneldigger (vpn configuration) see getCurrentTunneldiggerPeers()
+-- * iw (wireless network scanning) see get_batman_mesh_network()
+-- * batman-adv (mesh protocol) see directVPN(), get_batman_GW_interface()
+-- * respondd (mesh on LAN or WAN) see molwm()
+--
+-- To detect the current hood the hoodselector knows 5 modes containing
+-- * 1. VPN mode (VPN Router)
+-- - set hood dependent on geo position.
+-- * 2. Gateway mode
+-- - set hood dependent on gateway source
+-- * 3. Scan mode
+-- - Set wifi conf on scanned BSSID
+-- - Set vpn conf getting by BSSID (if no VPN conf exsist disable vpn)
+-- * 4. Radio less mode
+-- - Set hood via mesh on lan wan managemand
+-- * 5. Default mode
+-- - Set default hood if no other hood matchs
+
+-- When selecting a hood, the hoodselector has the following priorities:
+-- 1. Selecting a hood by geo position depending on direct VPN connection.
+-- 2. force creating one mesh cloud with neighbour mesh routers
+-- 3. if routers had only mesh setting vpn config depends on the BSSID
+--
+-- Resources
+-- * https://wireless.wiki.kernel.org/en/users/documentation/iw
+
+-- MOLWM respondd file
+local molwmFile="/tmp/.hoodselector"
+
+local molwmtable = {}
+molwmtable["md5hash"] = ""
+molwmtable["vpnrouter"] = ""
+molwmtable["hoodname"] = ""
+molwmtable["bssid"] = ""
+
+-- PID file to ensure the hoodselector isn't running parallel
+local pidPath="/var/run/hoodselector.pid"
+
+local json = require ("luci.jsonc")
+local uci = require('simple-uci').cursor()
+local hash = require("hash")
+local hoodutil = require("hoodselector.util")
+
+if not uci:get_bool('hoodselector', 'hoodselector', 'enabled') then
+ io.stdout:write("Hoodselector is disabled by UCI\n")
+ os.exit(0)
+end
+
+if io.open(pidPath, "r") ~=nil then
+ hoodutil.log("The hoodselector is still running.")
+ os.exit(1)
+else
+ if io.open(pidPath, "w") ==nil then
+ hoodutil.log("Can`t create pid file on "..pidPath)
+ os.exit(1)
+ end
+end
+
+-- Program terminating function including removing of PID file
+local function exit(exc)
+ if io.open(pidPath, "r") ~=nil then
+ os.remove(pidPath)
+ end
+ os.exit(tonumber(exc))
+end
+
+local FILE = uci:get('hoodselector', 'hoodselector', 'hoodfile')
+if FILE == nil then
+ hoodutil.log("No hood file in config")
+ exit(1)
+end
+
+-- initialization done
+
+local function get_mesh_vpn_interface()
+ local ret = {}
+ if hoodutil.fastd_installed() then
+ local vpnifac = uci:get('fastd', 'mesh_vpn_backbone', 'net')
+ if vpnifac ~= nil then
+ vpnifac = vpnifac:gsub("%_",'-')
+ table.insert(ret,vpnifac)
+ else
+ hoodutil.log("fastd uci config broken! abort...")
+ exit(1)
+ end
+ end
+ if hoodutil.tunneldigger_installed() then
+ local vpnifac = uci:get('tunneldigger', 'mesh_vpn', 'interface')
+ if vpnifac ~= nil then
+ table.insert(ret,vpnifac)
+ else
+ hoodutil.log("tunneldigger uci config broken! abort...")
+ exit(1)
+ end
+ end
+ return ret
+end
+
+-- Give a list of interfaces where respondd is listening
+local function get_mesh_if(radios)
+ -- get VPN interfaces
+ local filtert_if = get_mesh_vpn_interface()
+
+ -- get Wifi interfaces
+ for _, radio in ipairs(radios) do
+ local ifname = uci:get('wireless', 'ibss_' .. radio, 'ifname')
+ if ifname ~= nil then
+ table.insert(filtert_if,ifname)
+ end
+ ifname = uci:get('wireless', 'mesh_' .. radio, 'ifname')
+ if ifname ~= nil then
+ table.insert(filtert_if,ifname)
+ end
+ end
+
+ local respondd_if = {}
+ for line in io.popen(string.format("ubus call network.interface dump | jsonfilter -e \"@.interface[@.proto='gluon_mesh' && @.up=true].device\" -e \"@.interface[@.interface='$(cat /lib/gluon/respondd/client.dev 2>/dev/null)' && @.up=true].device\""), "r"):lines() do
+ -- filter vpn and wifi interfaces
+ if not hoodutil.filt_if(filtert_if,line) then
+ table.insert(respondd_if,line)
+ end
+ end
+
+ return hoodutil.filter_redundancy(respondd_if)
+end
+
+local function molwm(radios)
+ if uci:get_bool("network", "mesh_lan", "auto") or uci:get_bool("network", "mesh_wan", "auto") then
+ local mesh_en = true
+ for _,respondd_if in ipairs(get_mesh_if(radios)) do
+ local respondd = string.format("gluon-neighbour-info -i " .. respondd_if .. " -p 1001 -d ff02::2 -r hoodselector -t 0.5")
+ for line in io.popen(respondd, 'r'):lines() do
+ local obj, _, err = json.parse (line, 1, nil)
+ if err then
+ io.stdout:write("json parse error!\n")
+ mesh_en = false
+ break
+ else
+ if obj["hoodinfo"] ~= nil then
+ if obj["mesh"] ~= nil then
+ if ( obj["mesh"]["lan"] or obj["mesh"]["wan"] ) then
+ if not ( obj["hoodinfo"]["md5hash"] == molwmtable["md5hash"]:gsub('\"', '') ) then
+ io.stdout:write("hashes are not equal! Souce " .. respondd .. "\n")
+ mesh_en = false
+ break
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ if uci:get('network', 'mesh_wan') then
+ local ifstatus_wan = io.popen(string.format("ifstatus mesh_wan"), 'r'):read('*a')
+ if ifstatus_wan ~= nil then
+ local wan, _, _ = json.parse (ifstatus_wan, 1, nil)
+ if wan["up"] and not mesh_en then
+ hoodutil.mesh_on_wan_disable()
+ end
+ if not wan["up"] and mesh_en then
+ hoodutil.mesh_on_wan_enable()
+ end
+ end
+ end
+ if uci:get('network', 'mesh_lan') then
+ local ifstatus_lan = io.popen(string.format("ifstatus mesh_lan"), 'r'):read('*a')
+ if ifstatus_lan ~= nil then
+ local lan, _, _ = json.parse (ifstatus_lan, 1, nil)
+ if lan["up"] and not mesh_en then
+ hoodutil.mesh_on_lan_disable()
+ end
+ if not lan["up"] and mesh_en then
+ hoodutil.mesh_on_lan_enable()
+ end
+ end
+ end
+ end
+end
+
+function table.val_to_str ( v )
+ if "string" == type( v ) then
+ v = string.gsub( v, "\n", "\\n" )
+ if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
+ return "'" .. v .. "'"
+ end
+ return '"' .. string.gsub(v,'"', '\\"' ) .. '"'
+ else
+ return "table" == type( v ) and table.tostring( v ) or tostring( v )
+ end
+end
+
+function table.key_to_str ( k )
+ if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then
+ return k
+ else
+ return "[" .. table.val_to_str( k ) .. "]"
+ end
+end
+
+function table.tostring( tbl )
+ local result, done = {}, {}
+ for k, v in ipairs( tbl ) do
+ table.insert( result, table.val_to_str( v ) )
+ done[ k ] = true
+ end
+ for k, v in pairs( tbl ) do
+ if not done[ k ] then
+ table.insert( result, table.key_to_str( k ) .. "=" .. table.val_to_str( v ) )
+ end
+ end
+ return "{" .. table.concat( result, "," ) .. "}"
+end
+
+local function molwm_to_file()
+ local file = io.open(molwmFile, "w")
+ if not file then
+ hoodutil.log(molwmFile ..' not found or not createble!')
+ else
+ file:write("\"md5hash\": " .. molwmtable["md5hash"] .. "\n")
+ file:write("\"vpnrouter\": " .. molwmtable["vpnrouter"] .. "\n")
+ file:write("\"hoodname\": " .. molwmtable["hoodname"] .. "\n")
+ file:write("\"bssid\": " .. molwmtable["bssid"] .. "\n")
+ file:close()
+ end
+end
+
+-- Write MOLWM content into file
+local function write_molwm(hood,radios)
+ if hood ~= nil then
+ molwmtable["md5hash"] = "\"" .. string.format(hash.md5(table.tostring(hood))) .. "\""
+ molwmtable["hoodname"] = "\"" .. hood["name"] .. "\""
+ molwmtable["bssid"] = "\"" .. hood["bssid"] .. "\""
+ end
+ molwm(radios)
+ molwm_to_file()
+end
+
+-- bool if direct VPN. The detection is realaise by searching the fastd network interface inside the originator table
+local function directVPN()
+ local vpnIfaceList = get_mesh_vpn_interface()
+ for _,vpnIface in ipairs(vpnIfaceList) do
+ local file = io.open("/sys/kernel/debug/batman_adv/bat0/originators", 'r')
+ if file ~= nil then
+ for outgoingIF in file:lines() do
+ -- escape special chars "[]-"
+ if outgoingIF:match(string.gsub("%[ " .. vpnIface .. "%]","%-", "%%-")) then
+ molwmtable["vpnrouter"] = "\"true\""
+ return true
+ end
+ end
+ end
+ end
+ molwmtable["vpnrouter"] = "\"false\""
+ return false
+end
+
+-- Retun a table of current peers from /etc/config/fastd
+local function getFastdCurrentPeers()
+ local configPeers = {}
+ local err = uci:foreach('fastd', 'peer',
+ function(s)
+ hoodutil.extrac_fastd_peer(s,configPeers)
+ end
+ )
+ if not err then
+ hoodutil.log("fastd uci config broken! abort...")
+ exit(1)
+ end
+ return configPeers
+end
+
+-- Retun a table of current peers from /etc/config/tunneldigger
+local function getTunneldiggerCurrentPeers()
+ local configPeers = {}
+ local err = uci:foreach('tunneldigger', 'broker',
+ function(s)
+ if s["address"] then
+ for _, peer in pairs(s["address"]) do
+ table.insert(configPeers, peer)
+ end
+ end
+ end
+ )
+ if not err then
+ hoodutil.log("tunneldigger uci config broken! abort...")
+ exit(1)
+ end
+ return configPeers
+end
+
+-- This method sets a new hoodconfig and takes care that services are only
+-- stopped or restarted if reconfiguration is needed.
+-- Process:
+-- * Check if wireless needs reconfiguration and prepare reconfiguration
+-- * Check if vpn needs reconfiguration and prepare reconfiguration
+-- * If vpn needs reconfiguration, stop vpn and apply new settings but
+-- dont restart it before wireless has been reconfigured
+-- * If wireless needs reconfiguration apply new settings and restart wireless
+-- * If vpn needed reconfiguration start fastd now
+local function set_hoodconfig(hood, prefix, radios)
+ local fastd_serverlist = {}
+ local fastd_reconf_needed = false
+ local tunneldigger_reconf_needed = false
+
+ -- pre check if fastd conf exsist
+ if uci:get('fastd', 'mesh_vpn_backbone', 'net') ~= nil then
+ fastd_serverlist = getFastdCurrentPeers()
+ -- Check if fastd needs reconfiguration because in case of reconfiguration we
+ -- need to stop fastd before we can reconfigure any other connection.
+ fastd_reconf_needed = hoodutil.fastd_reconfiguration_needed(hood["servers"], fastd_serverlist);
+ else
+ -- check if fastd uci conf broken
+ if hoodutil.fastd_installed() then
+ hoodutil.log("fastd uci config broken! abort...")
+ exit(1)
+ end
+ end
+
+ -- per check if tunneldigger conf exsist
+ if uci:get('tunneldigger', 'mesh_vpn', 'interface') ~= nil then
+ local tunneldigger_serverlist = getTunneldiggerCurrentPeers()
+ tunneldigger_reconf_needed = hoodutil.tunneldigger_reconfiguration_needed(hood["servers"], tunneldigger_serverlist)
+ else
+ -- check if tunneldigger uci conf broken
+ if hoodutil.tunneldigger_installed() then
+ hoodutil.log("tunneldigger uci config broken! abort...")
+ exit(1)
+ end
+ end
+
+ if fastd_reconf_needed or tunneldigger_reconf_needed then
+ hoodutil.vpn_stop()
+ end
+
+ -- reconfigure wireless
+ local wifi_reconf = hoodutil.wireless_reconfiguration_needed(radios, prefix, hood["bssid"])
+ if(wifi_reconf == 1 or wifi_reconf == 3) then
+ hoodutil.ibss_reconfigure(radios, hood["bssid"])
+ hoodutil.wireless_restart()
+ io.stdout:write('IBSS needed reconfiguration. Applied new settings and restarted.\n')
+ end
+ if(wifi_reconf == 2 or wifi_reconf == 3) then
+ hoodutil.mesh_reconfigure(radios, prefix..hood["bssid"]:lower())
+ hoodutil.wireless_restart()
+ io.stdout:write('MESH needed reconfiguration. Applied new settings and restarted.\n')
+ end
+
+ -- reconfigure fastd
+ if fastd_reconf_needed then
+ hoodutil.fastd_reconfigure(hood["servers"],fastd_serverlist)
+ io.stdout:write('fastd needed reconfiguration. Applied new settings and restarted.\n')
+ end
+
+ if tunneldigger_reconf_needed then
+ hoodutil.tunneldigger_reconfigure(hood["servers"])
+ io.stdout:write('tunneldigger needed reconfiguration. Applied new settings and restarted.\n')
+ end
+
+ if fastd_reconf_needed or tunneldigger_reconf_needed then
+ -- scan mode can disable VPN so we need to make shure that VPN is enabled
+ -- if the router selects a hood
+ hoodutil.vpn_enable()
+ hoodutil.vpn_start()
+ end
+
+ io.stdout:write("Set hood \""..hood["name"].."\"\n")
+ molwmtable["hoodname"] = "\"" .. hood["name"] .. "\""
+
+ if(uci:get('hoodselector', 'hoodselector' , 'hood') ~= hood["bssid"]) then
+ hoodutil.saveHoodToConfig(hood["bssid"])
+ end
+ return true
+end
+
+-- INITIALIZE AND PREPARE DATA --
+-- read hoodfile, exit if reading the hoodfile fails
+local jhood = hoodutil.readHoodfile(FILE)
+if jhood == nil then
+ hoodutil.log('There seems to have gone something wrong while reading hoodfile from ' .. FILE)
+ exit(1)
+end
+
+-- check if a default hood has been defined and exit if none has been defined
+local defaultHood = hoodutil.getDefaultHood(jhood)
+if defaultHood == nil then
+ hoodutil.log('No defaulthood defined.')
+ exit(1)
+end
+
+-- Get list of wifi devices
+local radios = hoodutil.getWifiDevices()
+
+local mesh_prefix = hoodutil.get_mesh_prefix(radios)
+
+-- VPN MODE
+-- If we have a VPN connection then we will try to get the routers location and
+-- select the hood coresponding to our location.
+-- If no hood for the location has been defined, we will select
+-- the default hood.
+-- If we can not get our routers location, we will fallback to scan mode.
+if directVPN() then
+ io.stdout:write('VPN connection found.\n')
+ local geo = hoodutil.getGeolocation()
+ if geo.lat ~= nil and geo.lon ~= nil then
+ io.stdout:write('Position found.\n')
+ local geoHood = hoodutil.getHoodByGeo(jhood, geo)
+ if geoHood ~= nil then
+ set_hoodconfig(geoHood, mesh_prefix, radios)
+ io.stdout:write('Hood set by VPN mode.\n')
+ write_molwm(geoHood,radios)
+ exit(0)
+ end
+ io.stdout:write('No hood has been defined for current position.\n')
+ else
+ io.stdout:write('No position found\n')
+ end
+ set_hoodconfig(defaultHood, mesh_prefix, radios)
+ io.stdout:write('Set defaulthood.\n')
+ write_molwm(defaultHood,radios)
+ exit(0)
+else
+ io.stdout:write('No VPN connection found\n')
+end
+
+if hoodutil.batmanHasGateway() then
+ io.stdout:write('Batman gateways found\n')
+ local gw_intf = {}
+ table.insert(gw_intf,hoodutil.get_batman_GW_interface())
+
+ if next(gw_intf) then
+ -- wifi interface
+ local bssidHood = hoodutil.get_radio_to_bssid(radios,gw_intf[1], jhood)
+ if bssidHood ~= nil then
+ --check if hood inside geo pos
+ local geo = hoodutil.getGeolocation()
+ if geo.lat ~= nil and geo.lon ~= nil then
+ io.stdout:write('Position found.\n')
+ local geoHood = hoodutil.getHoodByGeo(jhood, geo)
+ if geoHood ~= nil then
+ if string.format(hash.md5(table.tostring(bssidHood))) ~= string.format(hash.md5(table.tostring(geoHood))) then
+ io.stdout:write('Geo hood and bssid hood are not equal, do wifi scan...\n')
+ local sortedWlanList = hoodutil.wlan_list_sorted(radios, mesh_prefix)
+ for i=#sortedWlanList,1,-1 do
+ if(string.lower(geoHood.bssid) ~= string.lower(sortedWlanList[i].bssid)) then
+ table.remove(sortedWlanList, i)
+ end
+ end
+ if next(sortedWlanList) then
+ io.stdout:write('Try to switch back in our real hood!\n')
+ io.stdout:write('After filtering we will test the following wireless networks:\n')
+ for _, network in pairs(sortedWlanList) do
+ print(network["quality"].."\t"..network["frequency"].."\t"..network["bssid"].."\t"..network["ssid"])
+ end
+ io.stdout:write("Prepare configuration for testing wireless networks...\n")
+ local bssid = hoodutil.test_batman_mesh_networks(sortedWlanList, mesh_prefix)
+ hoodutil.wireless_restart()
+ io.stdout:write("Finished testing wireless networks, restored previous configuration\n")
+ if bssid ~= nil then
+ set_hoodconfig(geoHood, mesh_prefix, radios)
+ hoodutil.vpn_enable()
+ hoodutil.vpn_start()
+ io.stdout:write('Set Geo Hood by Gateway mode\n')
+ write_molwm(geoHood, radios)
+ exit(0)
+ else
+ io.stdout:write('No neighboring freifunk batman advanced mesh found.\n')
+ end
+ else
+ io.stdout:write('No networks left after filtering!\n')
+ end --end next(sortedWlanList)
+ else
+ io.stdout:write('Geo hood are equal to bssid hood no wifi scan necessary.\n')
+ end --end bssidHood ~= geoHood
+ else
+ io.stdout:write('No hood has been defined for current position.\n')
+ end --end geoHood ~= nil
+ else
+ io.stdout:write('No position found.\n')
+ end --end geo.lat ~= nil and geo.lon ~= nil
+ set_hoodconfig(bssidHood, mesh_prefix, radios)
+ io.stdout:write('Hood set by batmanHasGateway mode, GW source is wifi\n')
+ write_molwm(bssidHood,radios)
+ exit(0)
+ end --end bssidHood ~= nil
+
+ -- mesh lan or wan interface
+ if hoodutil.mesh_lan_wan(gw_intf[1]) then
+ -- if mesh_lan/wan try to get hood by selected bssid of neightbour vpnRouters
+ local neighbourBssid = hoodutil.molw_get_bssid(gw_intf)
+ if neighbourBssid ~= nil then
+ bssidHood = hoodutil.gethoodByBssid(jhood, neighbourBssid)
+ if bssidHood ~= nil then
+ set_hoodconfig(bssidHood, mesh_prefix, radios)
+ io.stdout:write('Hood set by batmanHasGateway mode, GW source is mesh on lan/wan\n')
+ molwmtable["md5hash"] = "\"" .. string.format(hash.md5(table.tostring(bssidHood))) .. "\""
+ molwmtable["hoodname"] = "\"" .. bssidHood["name"] .. "\""
+ molwmtable["bssid"] = "\"" .. bssidHood["bssid"] .. "\""
+ molwm_to_file()
+ exit(0)
+ end
+ end
+ end
+ end --end next(gw_intf)
+ local currendHood = hoodutil.getCurrentHood(jhood)
+ if currendHood ~= nil then
+ write_molwm(currendHood,radios)
+ end
+end
+
+-- SCAN MODE
+if next(radios) then
+ -- check if there exist a neighbouring freifunk batman advanced mesh
+ -- network with an active connection to a batman advanced gateway
+ local sortedWlanList = hoodutil.wlan_list_sorted(radios, mesh_prefix)
+ local meshBSSID = hoodutil.get_batman_mesh_network(sortedWlanList, defaultHood, mesh_prefix)
+ if meshBSSID ~= nil then
+ io.stdout:write("Neighoring freifunk batman advanced mesh with BSSID "..meshBSSID.." found\n")
+ local bssidHood = hoodutil.gethoodByBssid(jhood, meshBSSID)
+ if bssidHood ~= nil then
+ set_hoodconfig(bssidHood, mesh_prefix, radios)
+ io.stdout:write('Hood set by scan mode\n')
+ write_molwm(bssidHood,radios)
+ exit(0)
+ end
+
+ -- if the bssid does not corespond to any hood, we disable vpn and
+ -- just establish a wireless connection to the mesh without any vpn or
+ hoodutil.vpn_stop()
+ hoodutil.vpn_disable()
+ local ibss_exists = false
+ local mesh_exists = false
+ for _,radio in ipairs(radios) do
+ local ifname = uci:get('wireless', 'ibss_' .. radio, 'ifname')
+ if (ifname ~= nil) then
+ ibss_exists = true
+ end
+ ifname = uci:get('wireless', 'mesh_' .. radio, 'ifname')
+ if (ifname ~= nil) then
+ mesh_exists = true
+ end
+ end
+ if ibss_exists then
+ hoodutil.ibss_reconfigure(radios, meshBSSID)
+ end
+ if mesh_exists then
+ hoodutil.mesh_reconfigure(radios, mesh_prefix..meshBSSID:lower())
+ end
+ hoodutil.wireless_restart()
+ io.stdout:write('Could not select a hood but established a connection via wireless mesh.\n')
+ io.stdout:write('Disabled all connections except connections via wireless mesh.\n')
+ exit(0)
+ end
+ io.stdout:write('No neighbouring freifunk batman advanced mesh found.\n')
+end
+
+--Radio less router have mesh lan/wan neighbours
+local mesh_inf = get_mesh_if(radios);
+if next(mesh_inf) then
+ local wait_for_mesh_lan_wan = false
+ if uci:get('network', 'mesh_wan') then
+ local ifstatus_wan = io.popen(string.format("ifstatus mesh_wan"), 'r'):read('*a')
+ if ifstatus_wan ~= nil then
+ local wan, _, _ = json.parse (ifstatus_wan, 1, nil)
+ if not wan["up"] and uci:get_bool("network", "mesh_wan", "auto") then
+ hoodutil.mesh_on_wan_enable()
+ wait_for_mesh_lan_wan = true
+ end
+ end
+ end
+ if uci:get('network', 'mesh_lan') then
+ local ifstatus_lan = io.popen(string.format("ifstatus mesh_lan"), 'r'):read('*a')
+ if ifstatus_lan ~= nil then
+ local lan, _, _ = json.parse (ifstatus_lan, 1, nil)
+ if not lan["up"] and uci:get_bool("network", "mesh_lan", "auto") then
+ hoodutil.mesh_on_lan_enable()
+ wait_for_mesh_lan_wan = true
+ end
+ end
+ end
+ -- wait for network delay
+ if wait_for_mesh_lan_wan then
+ hoodutil.sleep(5)
+ end
+ local neighbourBssid = hoodutil.molw_get_bssid(mesh_inf)
+ if neighbourBssid ~= nil then
+ local bssidHood = hoodutil.gethoodByBssid(jhood, neighbourBssid)
+ if bssidHood ~= nil then
+ set_hoodconfig(bssidHood, mesh_prefix, radios)
+ io.stdout:write('Hood set by "Radio less router have mesh lan/wan neighbours"\n')
+ molwmtable["md5hash"] = "\"" .. string.format(hash.md5(table.tostring(bssidHood) )) .. "\""
+ molwmtable["hoodname"] = "\"" .. bssidHood["name"] .. "\""
+ molwmtable["bssid"] = "\"" .. bssidHood["bssid"] .. "\""
+ molwm_to_file()
+ exit(0)
+ end
+ end
+ io.stdout:write('No molwm neighbours found\n')
+end
+
+-- DEFAULT-HOOD MODE
+-- If we do NOT have a VPN connection AND found no freifunk mesh network while
+-- scanning then we set the default hood if no current hood set.
+io.stdout:write("ENV does not give enough information set default hood\n")
+set_hoodconfig(defaultHood, mesh_prefix, radios)
+io.stdout:write('Set defaulthood.\n')
+write_molwm(defaultHood,radios)
+exit(0)
diff --git a/package/gluon-hoodselector/src/Makefile b/package/gluon-hoodselector/src/Makefile
new file mode 100644
index 00000000..3ddc8a58
--- /dev/null
+++ b/package/gluon-hoodselector/src/Makefile
@@ -0,0 +1,6 @@
+all: respondd.so
+
+CFLAGS += -Wall
+
+respondd.so: respondd.c
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -shared -fPIC -D_GNU_SOURCE -o $@ $^ $(LDLIBS) -lgluonutil -luci
diff --git a/package/gluon-hoodselector/src/respondd.c b/package/gluon-hoodselector/src/respondd.c
new file mode 100644
index 00000000..cc864a1c
--- /dev/null
+++ b/package/gluon-hoodselector/src/respondd.c
@@ -0,0 +1,139 @@
+#include <respondd.h>
+#include <json-c/json.h>
+#include <libgluonutil.h>
+#include <uci.h>
+#include <string.h>
+#include <net/if.h>
+
+#define _STRINGIFY(s) #s
+#define STRINGIFY(s) _STRINGIFY(s)
+
+bool strstw(const char *pre, const char *str) {
+ size_t lenpre = strlen(pre);
+ return strlen(str) < lenpre ? false : strncmp(pre, str, lenpre) == 0;
+}
+
+bool strrmbs(char *line, int begin, int end) { // <- ist es hier sinvoller pointer auf die ints zu setzen??
+ size_t len = strlen(line);
+ if (len < begin)
+ return false;
+
+ memmove(line, line+begin, len - begin + 1);
+ if (len < end)
+ return false;
+
+ line[len-end] = 0; //remove val of end characters on the end
+ return true;
+}
+
+// extract hood informations
+static struct json_object * get_hoodselector(void) {
+ FILE *f = fopen("/tmp/.hoodselector", "r");
+ if (!f)
+ return NULL;
+
+ struct json_object *ret = json_object_new_object();
+ char *line = NULL;
+ size_t len = 0;
+ while (getline(&line, &len, f) >= 0) {
+ //1. Get md5 hash from current selected hood.
+ if (strstw("\"md5hash\": ",line)) {
+ if (!strrmbs(line, 12, 14))
+ continue;
+
+ json_object_object_add(ret, "md5hash", gluonutil_wrap_string(line));
+ }
+ //2. Get true or false string for VPN Router.
+ if (strstw("\"vpnrouter\": ",line)) {
+ if (!strrmbs(line, 14, 16))
+ continue;
+
+ json_object_object_add(ret, "vpnrouter", gluonutil_wrap_string(line));
+ }
+ //3. Get hoodname
+ if (strstw("\"hoodname\": ",line)) {
+ if (!strrmbs(line, 13, 15))
+ continue;
+
+ json_object_object_add(ret, "hoodname", gluonutil_wrap_string(line));
+ }
+ }
+ free(line);
+ fclose(f);
+ return ret;
+}
+
+//Get uci mesh on lan wan
+static struct json_object * get_mesh_on_lan_wan(void){
+ struct uci_context *ctx = uci_alloc_context();
+ ctx->flags &= ~UCI_FLAG_STRICT;
+ struct uci_package *p;
+
+ if (!uci_load(ctx, "wireless", &p)) {
+ struct uci_element *e;
+ uci_foreach_element(&p->sections, e) {
+ struct uci_section *s = uci_to_section(e);
+ if (strcmp(s->type, "wifi-iface"))
+ continue;
+
+ if (strncmp(e->name, "ibss_", 5))
+ continue;
+
+ const char *bssid = uci_lookup_option_string(ctx, s, "bssid");
+ if (!bssid)
+ continue;
+
+ struct json_object *ret = json_object_new_object();
+ json_object_object_add(ret, "bssid", gluonutil_wrap_string(bssid));
+ free((char*)bssid);
+ if(ret) {
+ uci_free_context(ctx);
+ return ret;
+ }
+ }
+ }
+ uci_free_context(ctx);
+ FILE *f = fopen("/tmp/.hoodselector", "r");
+ if (!f)
+ return NULL;
+
+ struct json_object *ret = json_object_new_object();
+ char *line = NULL;
+ size_t len = 0;
+ while (getline(&line, &len, f) >= 0) {
+ //Get bssid from current selected hood.
+ if (strstw("\"bssid\": ",line)) {
+ if (!strrmbs(line, 10, 12))
+ continue;
+ json_object_object_add(ret, "bssid", gluonutil_wrap_string(line));
+ free(line);
+ fclose(f);
+ return ret;
+ }
+ }
+ free(line);
+ fclose(f);
+ return NULL;
+}
+
+// create final obj with logical structure
+static struct json_object * respondd_provider_hoodselector(void) {
+ struct json_object *ret = json_object_new_object();
+
+ struct json_object *hoodinfo = get_hoodselector();
+ if(hoodinfo)
+ json_object_object_add(ret, "hoodinfo", hoodinfo);
+
+ struct json_object *mesh_on_lan_wan = get_mesh_on_lan_wan();
+ if(mesh_on_lan_wan)
+ json_object_object_add(ret, "mesh", mesh_on_lan_wan);
+
+ json_object_object_add(ret, "mac", gluonutil_wrap_and_free_string(gluonutil_get_sysconfig("primary_mac")));
+ return ret;
+}
+
+// related to respondd_provider_hoodselector
+const struct respondd_provider_info respondd_providers[] = {
+ {"hoodselector", respondd_provider_hoodselector},
+ {}
+};
--
2.15.1