#!/usr/bin/lua -- Created by jiaqiang.ye@lnxall.com -- Check whether Network configuration has changed -- If Network configuration has changed, restart network services -- 2023/04/11 -- load external modules local posix = require "posix" local cjson = require "cjson" local invoker = require "invoker" local ubuslog = require "ubuslog" -- global variables local CFG_FILES = {} -- configuration files that should be checking local CHECK_INFO = "/app/config/network_checksum.json" CFG_FILES[#CFG_FILES + 0x1] = "/etc/config/dhcp" CFG_FILES[#CFG_FILES + 0x1] = "/etc/config/network" CFG_FILES[#CFG_FILES + 0x1] = "/etc/config/wireless" CFG_FILES[#CFG_FILES + 0x1] = "/etc/config/firewall" CFG_FILES[#CFG_FILES + 0x1] = "/etc/config/network" local function load_checksum() local ch = io.open(CHECK_INFO, "rb") if not ch then return false end local chdat = ch:read("*a") ch:close(); ch = nil if type(chdat) ~= "string" or #chdat == 0 then return false end local okay, chsum = pcall(cjson.decode, chdat) if not okay or type(chsum) ~= "table" then return false end return chsum end local function get_md5sum(filp) local filst = posix.stat(filp) if not filst then return "" end local eval, output = invoker.invoke(invoker.OUTPUT + invoker.NOSTDIO, "md5sum", filp) if eval ~= 0 or type(output) ~= "string" or #output == 0 then return "" end local md5sum = string.match(output, "^(%x+)") if not md5sum then return "" end return md5sum end local function mainfunc() posix.chdir('/') invoker.setname('NETWORK_RESTART') local nowtim = invoker.uptime() -- fork child process before continuing -- local pid = posix.fork() -- if type(pid) == "number" and pid > 0 then os.exit(0) end local untim = nowtim + 60 -- delay 60 seconds nowtim = invoker.uptime() while nowtim < untim do invoker.waitsec(untim - nowtim) nowtim = invoker.uptime() end ubuslog.reinit("NETWORK_RESTART", 1); local oldchsum = load_checksum() if not oldchsum then oldchsum = {} end local newchsum, changed = {}, false for _, cfgfile in ipairs(CFG_FILES) do local md5 = get_md5sum(cfgfile) newchsum[cfgfile] = md5 if md5 ~= oldchsum[cfgfile] then changed = true end end if changed then local filh = io.open(CHECK_INFO, "wb") if filh then filh:write(cjson.encode(newchsum)) filh:close(); filh = nil; posix.sync() end ubuslog.log(ubuslog.LOG_ERR, "Warning, restarting network!") invoker.msleep(1000) -- delay one second invoker.invoke(invoker.NOSTDIO, "/etc/init.d/network", "restart") invoker.invoke(invoker.NOSTDIO, "/etc/init.d/dnsmasq", "restart") invoker.invoke(invoker.NOSTDIO, "/etc/init.d/firewall", "restart") else ubuslog.log(ubuslog.LOG_ERR, "Warning, no need to restart network!") end return true end mainfunc() os.exit(0)