Skip to content
Snippets Groups Projects
0005-add-pkg-gluon-hoodselector.patch 63.8 KiB
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 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
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
+  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