|
| 1 | +#!/usr/bin/env lua |
| 2 | + |
| 3 | +local logger,posix,ubus,uloop = require("tch.logger"),require("tch.posix"),require('ubus'),require('uloop') |
| 4 | +local log = logger.new("static-wan-routes-monitor",3,posix.LOG_DAEMON) |
| 5 | +local ipairs = ipairs |
| 6 | + |
| 7 | +local monitored = {} |
| 8 | +for _,pair in ipairs(arg or {}) do |
| 9 | + local interface,gateway = string.match(pair,"([^,]+),(.+)") |
| 10 | + if interface then |
| 11 | + if not monitored[interface] then |
| 12 | + monitored[interface] = { } |
| 13 | + end |
| 14 | + monitored[interface][#monitored[interface]+1] = gateway |
| 15 | + log:notice("Adding monitoring for static WAN interface on "..interface.." (gateway = "..gateway..")") |
| 16 | + end |
| 17 | +end |
| 18 | + |
| 19 | +local conn = ubus.connect() |
| 20 | +if conn then |
| 21 | + log:notice("Connected to ubusd") |
| 22 | + |
| 23 | + local function fix_default_routes(interface,gateway,action) |
| 24 | + local family = "4" |
| 25 | + local metric = "1" |
| 26 | + if string.find(gateway,":") then |
| 27 | + family = "6" |
| 28 | + metric = "512" |
| 29 | + end |
| 30 | + if action == "down" then |
| 31 | + local cmd,err = io.popen("ip -"..family.." route show default dev "..interface) |
| 32 | + if cmd then |
| 33 | + for line in cmd:lines() do |
| 34 | + local remove_cmd = "ip -"..family.." route del "..line |
| 35 | + log:notice(remove_cmd) |
| 36 | + os.execute(remove_cmd) |
| 37 | + end |
| 38 | + cmd:close() |
| 39 | + else |
| 40 | + log:error("Failed to retrieve IPv"..family.." routes for interface "..interface..": "..err) |
| 41 | + end |
| 42 | + else -- up |
| 43 | + local add_cmd = "ip -"..family.." route add default via "..gateway.." dev "..interface.." proto static metric "..metric |
| 44 | + log:notice(add_cmd) |
| 45 | + os.execute(add_cmd) |
| 46 | + end |
| 47 | + end |
| 48 | + |
| 49 | + uloop.init() |
| 50 | + |
| 51 | + local events = {} |
| 52 | + events['network.link'] = function(data) |
| 53 | + if data then |
| 54 | + if monitored[data.interface] then |
| 55 | + log:notice("Interface "..data.interface.." is "..data.action) |
| 56 | + for _,gateway in pairs(monitored[data.interface]) do |
| 57 | + if gateway then |
| 58 | + fix_default_routes(data.interface,gateway,data.action) |
| 59 | + end |
| 60 | + end |
| 61 | + else |
| 62 | + log:notice("Interface "..data.interface.." is "..data.action.." (Ignored)") |
| 63 | + end |
| 64 | + end |
| 65 | + end |
| 66 | + conn:listen(events) |
| 67 | + |
| 68 | + log:notice("Waiting for network.link events...") |
| 69 | + while true do |
| 70 | + uloop.run() |
| 71 | + end |
| 72 | +else |
| 73 | + log:error("Failed to connect to ubusd - aborting") |
| 74 | + os.exit(2) |
| 75 | +end |
| 76 | + |
0 commit comments