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