gluon/package/gluon-hoodselector/luasrc/usr/sbin/hoodselector
2019-04-23 18:55:25 +02:00

98 lines
2.9 KiB
Lua
Executable File

#!/usr/bin/lua
local bit = require('bit')
local unistd = require('posix.unistd')
local fcntl = require('posix.fcntl')
local uci = require('simple-uci').cursor()
local hoodutil = require("hoodselector.util")
-- PID file to ensure the hoodselector isn't running parallel
local lockfile = '/var/lock/hoodselector.lock'
local lockfd, err = fcntl.open(lockfile, bit.bor(fcntl.O_WRONLY, fcntl.O_CREAT), 384) -- mode 0600
if not lockfd then
io.stderr:write(err, '\n')
os.exit(1)
end
local ok, _ = fcntl.fcntl(lockfd, fcntl.F_SETLK, {
l_start = 0,
l_len = 0,
l_type = fcntl.F_WRLCK,
l_whence = unistd.SEEK_SET,
})
if not ok then
io.stderr:write(string.format(
"Unable to lock file %s. Make sure there is no other instance of the hoodselector running.\n",
lockfile
))
os.exit(1)
end
-- initialisation 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...")
os.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...")
os.exit(1)
end
end
return ret
end
-- INITIALISE AND PREPARE DATA --
-- VPN MODE
-- If we have a VPN connection we will try to get the node's location and
-- select the hood coresponding to this location.
-- If no hood for the location has been defined, we will select
-- the default hood.
-- If we can't determine the node's location, we will continue to the next mode.
if hoodutil.directVPN(get_mesh_vpn_interface()) 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 jhood = hoodutil.get_domains()
local geoHood = hoodutil.getHoodByGeo(jhood, geo)
if geoHood ~= nil then
if hoodutil.set_hoodconfig(geoHood) then
hoodutil.restart_services() -- temporary solution
io.stdout:write('Hood set by VPN mode.\n')
end
os.exit(0)
end
io.stdout:write('No hood has been defined for the current position.\n')
if hoodutil.set_hoodconfig(hoodutil.getDefaultHood(jhood)) then
hoodutil.restart_services() -- TMP solution
io.stdout:write('Hood set by VPN mode.\n')
end
os.exit(0)
else
-- The hoodselector should continue with the next states because there can be other
-- VPN nodes in the local mesh network which provide a position and therefore
-- have set a geo base hood.
io.stdout:write('No position found\n')
end
else
io.stdout:write('No VPN connection found\n')
end
os.exit(0)