%# Licensed to the public under the Apache License 2.0. -%> <% local fs = require "nixio.fs" local stat = require "luci.tools.status" local dba = luci.model.uci.cursor():get("wrtbwmon", "general", "path") -- Function to generate table from string. local function strToTable(str) local tb = {} local cmd = nil setmetatable(tb, {__index = table.insert}) str:gsub("[^%s,]+", tb) tb.__index = nil return tb end -- Function to update the mac-hostname table. local function getmactable(family) local mactable = {} local leases = (family == 4 and {stat.dhcp_leases()} or {stat.dhcp6_leases()})[1] if fs.access("/etc/wrtbwmon.user") then for line in io.lines("/etc/wrtbwmon.user") do local macpair = strToTable(line) mactable[macpair[1]:lower()] = macpair[2] end end for _, line in pairs(leases) do if line.macaddr and not mactable[line.macaddr:lower()] then mactable[line.macaddr:lower()] = line.hostname end end return mactable end -- Rename the db file for ipv6. local function fileRename(fn, tag) local idx = fn:match(".+()%.%w+$") if(idx) then return fn:sub(1, idx-1) .. tag .. fn:sub(idx, -1) else return fn .. tag end end local function procressData(db, family) local dbc = (family == 6 and {fileRename(db, ".6")} or {db})[1] local cmd_setup = "/etc/init.d/wrtbwmon restart" local cmd_update = "wrtbwmon -" .. family .. " -f " .. db .. " >>/dev/null 2>&1" local data, total, mactable, firstline = {}, {0.0, 0.0, 0.0, 0.0, 0.0}, getmactable(family), true local isshow = luci.http.formvalue("isShow") -- Setup the background update process. if not fs.access("/var/run/wrtbwmon.pid") then io.popen(cmd_setup) else io.popen(cmd_update) end -- Process the database. for line in io.lines(dbc) do if firstline then firstline = false else local tbl = strToTable(line) if isshow == "1" or tbl[8] ~= "0" then tbl[1] = tbl[1]:lower() if mactable[tbl[1]] then tbl[3] = mactable[tbl[1]] else tbl[3] = tbl[1] end for i = 1,#total do total[i] = total[i] + (tbl[i+3] .. ".0") end data[#data+1] = {tbl[3], tbl[1], unpack(tbl, 4)} table.insert(data[#data], tbl[2]) end end end -- Transfer the database to js. luci.http.prepare_content("application/json") luci.http.write_json({data, total}) return end if luci.http.formvalue("proto") == "ipv4" then procressData(dba, 4) return elseif luci.http.formvalue("proto") == "ipv6" then procressData(dba, 6) return end if luci.http.formvalue("reset") == "1" then os.execute("ip -4 neigh flush dev br-lan && ip -6 neigh flush dev br-lan") os.execute("rm -f " .. fileRename(dba, "*") .. " && wrtbwmon -46 -f " .. dba .. " >>/dev/null 2>&1") luci.http.status(200, "OK") return end -%> <%+header%>