0
0
mirror of https://github.com/Doodle3D/doodle3d-firmware.git synced 2024-12-22 11:03:48 +01:00

Split debug flags into DEBUG_PCALLS and DEBUG_API; fix more quotation style and import naming.

This commit is contained in:
Wouter R 2013-07-24 18:49:07 +02:00
parent 9fd13dda65
commit d4b9c39d60
5 changed files with 221 additions and 164 deletions

51
TODO.md
View File

@ -1,3 +1,54 @@
## te doen voor werkend prototype
- auto-update (zowel package als geheel image; <- kijken hoe luci dat doet)
- tekenen op redelijke subset van apparaten (wat hebben beta-testers?)
- printen (printserver; via dirpad gcode/commando's sturen en uitlezen via voortgangsbestand; zoals UltiFi; REST reageert op rq met poll-url in data waar voortgang te volgen is…eindigt met 'done')
## NU MEE BEZIG
- auto-update
- source-url in Makefile aanpassen (type aanpassen naar git en dan direct naar github repo)
- toevoegen aan /etc/opkg.conf via files in image: `src/gz wifibox http://doodle3d.com/static/wifibox-packages`
- of lokaal: `src/gz wifibox file:///tmp/wifibox-packages`
- (info) feed update-script: /Volumes/openwrt-image-10gb/update-feed-dir.sh
- (info) package-url: <http://doodle3d.com/static/wifibox-packages>
- (info) image-url: <http://doodle3d.com/static/wifibox-images>
- API:
api/info/currentVersion
api/info/latestVersion [beta=true]
api/system/update
api/system/flash
* wat als wij een verkeerd package releasen waardoor de API niet meer werkt?
- (ref) <http://wiki.openwrt.org/doc/devel/packages/opkg>
- (ref) <http://wiki.openwrt.org/doc/techref/opkg>
- (ref) <http://downloads.openwrt.org/snapshots/trunk/ar71xx/packages/>
- waar moeten debugvlaggen etc naartoe? (run_flags.lua?)
- require vars checken op conflicten
- in package postinst: hostname van kastje instellen op wifibox (met mac?)
- wiki bijwerken (links, structuur, API)
- Code documenteren <http://keplerproject.github.io/luadoc/>
- Lua programmeerstijl? (enkele quotes gebruiken behalve voor i18n)
- zoals het nu werkt wordt het lastig om een hiërarchische api te ondersteunen zoals dit: <http://www.restapitutorial.com/lessons/restfulresourcenaming.html>
- uhttpd ondersteunt geen PUT en DELETE, wel status codes. Beschrijving CGI-antwoorden: <http://docstore.mik.ua/orelly/linux/cgi/ch03_03.htm>
- voor captive portal: cgi 'Location' header voor redirect naar goede url?
- http statuscodes <https://blog.apigee.com/detail/restful_api_design_what_about_errors>; met relevante link in antwoord (meer: <https://blog.apigee.com/taglist/restful>)
- proposed status handling in response.lua:
fucntion setStatus(code, <msg>) -> sets http status+dfl msg and optional errmsg in data
## lokale notities
- in menuconfig: enabled uhttpd-mod-lua, disabled uhttpd-mod-ubus
- menuconfig: disable Network->6relayd and Network->odhcp6c
then disable Kernel modules->Network support->kmod ipv6
- menuconfig: disable Network->ppp, then disable Kernel modules->Network support->kmod-{ppp,pppoe,pppox}
- menuconfig: enabled Kernel Modules -> USB Support -> usb-kmod-serial -> …ftdi
- enabled luafilesystem, luasocket (luaposix results in a build error)
- <http://stackoverflow.com/questions/11732934/serial-connection-with-arduino-php-openwrt-bug>
- versies toevoegen als eerste padelement?
# TODO (new functionality) # TODO (new functionality)
- fix init script handling as described here: http://wiki.openwrt.org/doc/devel/packages#packaging.a.service - fix init script handling as described here: http://wiki.openwrt.org/doc/devel/packages#packaging.a.service
- implement (automated) test code where possible - implement (automated) test code where possible

View File

@ -7,6 +7,9 @@ local M = {}
--during debugging. This flag replaces them with a normal call so we can inspect stack traces. --during debugging. This flag replaces them with a normal call so we can inspect stack traces.
M.DEBUG_PCALLS = true M.DEBUG_PCALLS = true
--This enables debugging of the REST API from the command-line, specify the path and optionally the request method as follows: 'p=/mod/func rq=POST'
M.DEBUG_API = true
--REST responses will contain 'module' and 'function' keys describing what was requested --REST responses will contain 'module' and 'function' keys describing what was requested
M.API_INCLUDE_ENDPOINT_INFO = false M.API_INCLUDE_ENDPOINT_INFO = false

View File

@ -1,8 +1,8 @@
package.path = package.path .. ';/usr/share/lua/wifibox/?.lua' package.path = package.path .. ';/usr/share/lua/wifibox/?.lua'
local confDefaults = require('conf_defaults') local confDefaults = require('conf_defaults')
local u = require('util.utils') local util = require('util.utils')
local l = require('util.logger') local log = require('util.logger')
local wifi = require('network.wlanconfig') local wifi = require('network.wlanconfig')
local netconf = require('network.netconfig') local netconf = require('network.netconfig')
local RequestClass = require('rest.request') local RequestClass = require('rest.request')
@ -16,13 +16,19 @@ local function setupAutoWifiMode()
end end
local function init() local function init()
l:init(l.LEVEL.debug) log:init(log.LEVEL.debug)
l:setStream(io.stderr) log:setStream(io.stderr)
if confDefaults.DEBUG_PCALLS then l:info("Wifibox CGI handler started (pcall debugging enabled)") local dbgText = ""
else l:info("Wifibox CGI handler started") if confDefaults.DEBUG_API and confDefaults.DEBUG_PCALLS then dbgText = "pcall and api"
elseif confDefaults.DEBUG_API then dbgText = "api"
elseif confDefaults.DEBUG_PCALL then dbgText = "pcall"
end end
if dbgText ~= "" then dbgText = " (" .. dbgText .. " debugging enabled)" end
log:info("Wifibox CGI handler started" .. dbgText)
if (os.getenv('REQUEST_METHOD') == 'POST') then if (os.getenv('REQUEST_METHOD') == 'POST') then
local n = tonumber(os.getenv('CONTENT_LENGTH')) local n = tonumber(os.getenv('CONTENT_LENGTH'))
postData = io.read(n) postData = io.read(n)
@ -39,27 +45,24 @@ local function init()
end end
local function main() local function main()
local rq = RequestClass.new(postData, confDefaults.DEBUG_PCALLS) local rq = RequestClass.new(postData, confDefaults.DEBUG_API)
l:info("received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>") log:info("received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>")
.. "/" .. (rq:getRealApiFunctionName() or "<unknown>") .. " with arguments: " .. u.dump(rq:getAll())) .. "/" .. (rq:getRealApiFunctionName() or "<unknown>") .. " with arguments: " .. util.dump(rq:getAll()))
if rq:getRequestMethod() ~= 'CMDLINE' then if rq:getRequestMethod() ~= 'CMDLINE' then
l:info("remote IP/port: " .. rq:getRemoteHost() .. "/" .. rq:getRemotePort()) log:info("remote IP/port: " .. rq:getRemoteHost() .. "/" .. rq:getRemotePort())
l:debug("user agent: " .. rq:getUserAgent()) log:debug("user agent: " .. rq:getUserAgent())
end end
if (not confDefaults.DEBUG_PCALLS and rq:getRequestMethod() == 'CMDLINE') then if rq:getRequestMethod() == 'CMDLINE' and rq:get('autowifi') ~= nil then
if rq:get('autowifi') ~= nil then setupAutoWifiMode()
setupAutoWifiMode() elseif rq:getRequestMethod() ~= 'CMDLINE' or confDefaults.DEBUG_API then
else
l:info("Nothing to do...bye.\n")
end
else
local response, err = rq:handle() local response, err = rq:handle()
if err ~= nil then l:error(err) end if err ~= nil then log:error(err) end
response:send() response:send()
else
log:info("Nothing to do...bye.\n")
end end
end end
@ -72,7 +75,7 @@ if s == false then
resp:setError("initialization failed" .. errSuffix) resp:setError("initialization failed" .. errSuffix)
io.write ("Content-type: text/plain\r\n\r\n") io.write ("Content-type: text/plain\r\n\r\n")
resp:send() resp:send()
l:error("initialization failed" .. errSuffix) --NOTE: this assumes the logger has been inited properly, despite init() having failed log:error("initialization failed" .. errSuffix) --NOTE: this assumes the logger has been inited properly, despite init() having failed
os.exit(1) os.exit(1)
else else

View File

@ -1,33 +1,33 @@
local u = require("util.utils") local utils = require('util.utils')
local l = require("util.logger") local log = require('util.logger')
local s = require("util.settings") local settings = require('util.settings')
local wifi = require("network.wlanconfig") local wifi = require('network.wlanconfig')
local uci = require("uci").cursor() local uci = require('uci').cursor()
local M = {} local M = {}
local reconf = {} local reconf = {}
local wifi local wifi
local reloadSilent local reloadSilent
M.WWW_CAPTIVE_PATH = "/usr/share/lua/wifibox/www" M.WWW_CAPTIVE_PATH = '/usr/share/lua/wifibox/www'
M.WWW_CAPTIVE_INDICATOR = "/www/.wifibox-inplace" M.WWW_CAPTIVE_INDICATOR = '/www/.wifibox-inplace'
M.WWW_RENAME_NAME = "/www-regular" M.WWW_RENAME_NAME = '/www-regular'
local function reloadBit(dlist, itemname) local function reloadBit(dlist, itemname)
if dlist[itemname] == nil then dlist[itemname] = "" end if dlist[itemname] == nil then dlist[itemname] = '' end
if dlist[itemname] == "" then dlist[itemname] = "r" if dlist[itemname] == '' then dlist[itemname] = 'r'
elseif dlist[itemname] == "c" then dlist[itemname] = "b" elseif dlist[itemname] == 'c' then dlist[itemname] = 'b'
end end
end end
local function commitBit(dlist, itemname) local function commitBit(dlist, itemname)
if dlist[itemname] == nil then dlist[itemname] = "" end if dlist[itemname] == nil then dlist[itemname] = '' end
if dlist[itemname] == "" then dlist[itemname] = "c" if dlist[itemname] == '' then dlist[itemname] = 'c'
elseif dlist[itemname] == "r" then dlist[itemname] = "b" elseif dlist[itemname] == 'r' then dlist[itemname] = 'b'
end end
end end
local function bothBits(dlist, itemname) dlist[itemname] = "b" end local function bothBits(dlist, itemname) dlist[itemname] = 'b' end
@ -45,33 +45,33 @@ function M.switchConfiguration(components)
local dirtyList = {} -- laundry list, add config/script name as key with value c (commit), r (reload) or b (both) local dirtyList = {} -- laundry list, add config/script name as key with value c (commit), r (reload) or b (both)
for k,v in pairs(components) do for k,v in pairs(components) do
local fname = k .. "_" .. v local fname = k .. '_' .. v
if type(reconf[fname]) == "function" then if type(reconf[fname]) == 'function' then
l:debug("reconfiguring component '" .. k .. "' (" .. v .. ")") log:debug("reconfiguring component '" .. k .. "' (" .. v .. ")")
reconf[fname](dirtyList) reconf[fname](dirtyList)
else else
l:warn("unknown component or action '" .. fname .. "' skipped") log:warn("unknown component or action '" .. fname .. "' skipped")
end end
end end
-- first run all commits, then perform reloads -- first run all commits, then perform reloads
for k,v in pairs(dirtyList) do for k,v in pairs(dirtyList) do
if v == "c" or v == "b" then M.commitComponent(k) end if v == 'c' or v == 'b' then M.commitComponent(k) end
end end
for k,v in pairs(dirtyList) do for k,v in pairs(dirtyList) do
if v == "r" or v == "b" then M.reloadComponent(k, silent) end if v == 'r' or v == 'b' then M.reloadComponent(k, silent) end
end end
end end
function M.commitComponent(c) function M.commitComponent(c)
l:info("committing component '" .. c .. "'") log:info("committing component '" .. c .. "'")
uci:commit(c) uci:commit(c)
end end
function M.reloadComponent(c, silent) function M.reloadComponent(c, silent)
l:info("reloading component '" .. c .. "'") log:info("reloading component '" .. c .. "'")
if silent ~= nil and silent then os.execute("/etc/init.d/" .. c .. " reload &> /dev/null") if silent ~= nil and silent then os.execute('/etc/init.d/' .. c .. ' reload &> /dev/null')
else os.execute("/etc/init.d/" .. c .. " reload") end else os.execute('/etc/init.d/' .. c .. ' reload') end
end end
function M.uciTableSet(config, section, options) function M.uciTableSet(config, section, options)
@ -81,140 +81,140 @@ end
--[[ Issue '/etc/init.d/network reload' command ]] --[[ Issue '/etc/init.d/network reload' command ]]
function reconf.network_reload(dirtyList) reloadBit(dirtyList, "network") end function reconf.network_reload(dirtyList) reloadBit(dirtyList, 'network') end
--[[ Issue '/etc/init.d/wireless reload' command ]] --[[ Issue '/etc/init.d/wireless reload' command ]]
function reconf.wireless_reload(dirtyList) reloadBit(dirtyList, "wireless") end function reconf.wireless_reload(dirtyList) reloadBit(dirtyList, 'wireless') end
--[[ Add wlan interface declaration to /etc/config/network ]] --[[ Add wlan interface declaration to /etc/config/network ]]
function reconf.wifiiface_add(dirtyList) function reconf.wifiiface_add(dirtyList)
uci:set("network", wifi.NET, "interface") uci:set('network', wifi.NET, 'interface')
commitBit(dirtyList, "network") commitBit(dirtyList, 'network')
end end
--[[ Add/remove access point network ]] --[[ Add/remove access point network ]]
function reconf.apnet_add_noreload(dirtyList) reconf.apnet_add(dirtyList, true) end function reconf.apnet_add_noreload(dirtyList) reconf.apnet_add(dirtyList, true) end
function reconf.apnet_add(dirtyList, noReload) function reconf.apnet_add(dirtyList, noReload)
local ourSsid = wifi.getSubstitutedSsid(s.get('apSsid')) local ourSsid = wifi.getSubstitutedSsid(settings.get('apSsid'))
local sname = nil local sname = nil
uci:foreach("wireless", "wifi-iface", function(s) uci:foreach('wireless', 'wifi-iface', function(s)
if s.ssid == ourSsid then sname = s[".name"]; return false end if s.ssid == ourSsid then sname = s['.name']; return false end
end) end)
if sname == nil then sname = uci:add("wireless", "wifi-iface") end if sname == nil then sname = uci:add('wireless', 'wifi-iface') end
M.uciTableSet("wireless", sname, { M.uciTableSet('wireless', sname, {
network = wifi.NET, network = wifi.NET,
ssid = ourSsid, ssid = ourSsid,
encryption = "none", encryption = 'none',
device = "radio0", device = 'radio0',
mode = "ap", mode = 'ap',
}) })
commitBit(dirtyList, "wireless") commitBit(dirtyList, 'wireless')
if noReload == nil or noReload == false then reloadBit(dirtyList, "network") end if noReload == nil or noReload == false then reloadBit(dirtyList, 'network') end
end end
function reconf.apnet_rm(dirtyList) function reconf.apnet_rm(dirtyList)
local sname = nil local sname = nil
uci:foreach("wireless", "wifi-iface", function(s) uci:foreach('wireless', 'wifi-iface', function(s)
if s.ssid == wifi.getSubstitutedSsid(s.get(apSsid)) then sname = s[".name"]; return false end if s.ssid == wifi.getSubstitutedSsid(settings.get('apSsid')) then sname = s['.name']; return false end
end) end)
if sname == nil then return l:info("AP network configuration does not exist, nothing to remove") end if sname == nil then return log:info("AP network configuration does not exist, nothing to remove") end
uci:delete("wireless", sname) uci:delete('wireless', sname)
reloadBit(dirtyList, "network"); commitBit(dirtyList, "wireless") reloadBit(dirtyList, 'network'); commitBit(dirtyList, 'wireless')
end end
--[[ Switch between wireless static IP and DHCP ]] --[[ Switch between wireless static IP and DHCP ]]
function reconf.staticaddr_add(dirtyList) function reconf.staticaddr_add(dirtyList)
uci:set("network", wifi.NET, "interface") uci:set('network', wifi.NET, 'interface')
--TODO: remove ifname on wlan interface? --TODO: remove ifname on wlan interface?
--NOTE: 'type = "bridge"' should -not- be added as this prevents defining a separate dhcp pool (http://wiki.openwrt.org/doc/recipes/routedap) --NOTE: 'type = "bridge"' should -not- be added as this prevents defining a separate dhcp pool (http://wiki.openwrt.org/doc/recipes/routedap)
M.uciTableSet("network", wifi.NET, { M.uciTableSet('network', wifi.NET, {
proto = "static", proto = 'static',
ipaddr = s.get('apAddress'), ipaddr = settings.get('apAddress'),
netmask = s.get('apNetmask') netmask = settings.get('apNetmask')
}) })
bothBits(dirtyList, "network") bothBits(dirtyList, 'network')
end end
--TODO: replace repeated deletes by M.uciTableDelete --TODO: replace repeated deletes by M.uciTableDelete
function reconf.staticaddr_rm(dirtyList) function reconf.staticaddr_rm(dirtyList)
uci:set("network", wifi.NET, "interface") uci:set('network', wifi.NET, 'interface')
uci:set("network", wifi.NET, "proto", "dhcp") uci:set('network', wifi.NET, 'proto', 'dhcp')
uci:delete("network", wifi.NET, "ipaddr") uci:delete('network', wifi.NET, 'ipaddr')
uci:delete("network", wifi.NET, "netmask") uci:delete('network', wifi.NET, 'netmask')
--uci:delete("network", wifi.NET, "type") --do not remove since it is not added anymore --uci:delete('network', wifi.NET, 'type') --do not remove since it is not added anymore
bothBits(dirtyList, "network") bothBits(dirtyList, 'network')
end end
--[[ Add/remove DHCP pool for wireless net ]] --[[ Add/remove DHCP pool for wireless net ]]
function reconf.dhcppool_add(dirtyList) function reconf.dhcppool_add(dirtyList)
uci:set("dhcp", wifi.NET, "dhcp") --create section uci:set('dhcp', wifi.NET, 'dhcp') --create section
M.uciTableSet("dhcp", wifi.NET, { M.uciTableSet('dhcp', wifi.NET, {
interface = wifi.NET, interface = wifi.NET,
start = "100", start = '100',
limit = "150", limit = '150',
leasetime = "12h", leasetime = '12h',
}) })
commitBit(dirtyList, "dhcp"); reloadBit(dirtyList, "dnsmasq") commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
end end
function reconf.dhcppool_rm(dirtyList) function reconf.dhcppool_rm(dirtyList)
uci:delete("dhcp", wifi.NET) uci:delete('dhcp', wifi.NET)
commitBit(dirtyList, "dhcp"); reloadBit(dirtyList, "dnsmasq") commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
end end
--[[ Add/remove webserver 404 redirection and denial of dirlisting ]] --[[ Add/remove webserver 404 redirection and denial of dirlisting ]]
function reconf.wwwredir_add(dirtyList) function reconf.wwwredir_add(dirtyList)
uci:set("uhttpd", "main", "error_page", "/admin/autowifi.html") uci:set('uhttpd', 'main', 'error_page', '/www/index.html')
uci:set("uhttpd", "main", "no_dirlist", "1") uci:set('uhttpd', 'main', 'no_dirlist', '1')
bothBits(dirtyList, "uhttpd") bothBits(dirtyList, 'uhttpd')
end end
function reconf.wwwredir_rm(dirtyList) function reconf.wwwredir_rm(dirtyList)
uci:delete("uhttpd", "main", "error_page") uci:delete('uhttpd', 'main', 'error_page')
uci:delete("uhttpd", "main", "no_dirlist") uci:delete('uhttpd', 'main', 'no_dirlist')
bothBits(dirtyList, "uhttpd") bothBits(dirtyList, 'uhttpd')
end end
--[[ Add/remove redirecton of all DNS requests to self ]] --[[ Add/remove redirecton of all DNS requests to self ]]
function reconf.dnsredir_add(dirtyList) function reconf.dnsredir_add(dirtyList)
local redirText = "/#/" .. s.get('apAddress') local redirText = '/#/' .. settings.get('apAddress')
local sname = u.getUciSectionName("dhcp", "dnsmasq") local sname = utils.getUciSectionName('dhcp', 'dnsmasq')
if sname == nil then return l:error("dhcp config does not contain a dnsmasq section") end if sname == nil then return log:error("dhcp config does not contain a dnsmasq section") end
if uci:get("dhcp", sname, "address") ~= nil then return l:debug("DNS address redirection already in place, not re-adding", false) end if uci:get('dhcp', sname, 'address') ~= nil then return log:debug("DNS address redirection already in place, not re-adding", false) end
uci:set("dhcp", sname, "address", {redirText}) uci:set('dhcp', sname, 'address', {redirText})
commitBit(dirtyList, "dhcp"); reloadBit(dirtyList, "dnsmasq") commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
end end
function reconf.dnsredir_rm(dirtyList) function reconf.dnsredir_rm(dirtyList)
local sname = u.getUciSectionName("dhcp", "dnsmasq") local sname = utils.getUciSectionName('dhcp', 'dnsmasq')
if sname == nil then return l:error("dhcp config does not contain a dnsmasq section") end if sname == nil then return log:error("dhcp config does not contain a dnsmasq section") end
uci:delete("dhcp", sname, "address") uci:delete('dhcp', sname, 'address')
commitBit(dirtyList, "dhcp"); reloadBit(dirtyList, "dnsmasq") commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
end end
--TODO: handle os.rename() return values (nil+msg on error) --TODO: handle os.rename() return values (nil+msg on error)
function reconf.wwwcaptive_add(dirtyList) function reconf.wwwcaptive_add(dirtyList)
if u.exists(M.WWW_CAPTIVE_INDICATOR) then if utils.exists(M.WWW_CAPTIVE_INDICATOR) then
return l:debug("WWW captive directory already in place, not redoing", false) return log:debug("WWW captive directory already in place, not redoing", false)
end end
local rv,reason = os.rename("/www", M.WWW_RENAME_NAME) local rv,reason = os.rename('/www', M.WWW_RENAME_NAME)
if rv == true then if rv == true then
u.symlink(M.WWW_CAPTIVE_PATH, "/www") utils.symlink(M.WWW_CAPTIVE_PATH, '/www')
return true return true
else else
return l:error("Could not rename /www to " .. M.WWW_RENAME_NAME .. "(" .. reason .. ")") return log:error("Could not rename /www to " .. M.WWW_RENAME_NAME .. "(" .. reason .. ")")
end end
end end
function reconf.wwwcaptive_rm(dirtyList) function reconf.wwwcaptive_rm(dirtyList)
if not u.exists(M.WWW_CAPTIVE_INDICATOR) then return l:debug("WWW captive directory not in place, not undoing", false) end if not utils.exists(M.WWW_CAPTIVE_INDICATOR) then return log:debug("WWW captive directory not in place, not undoing", false) end
os.remove("/www") os.remove('/www')
if os.rename(M.WWW_RENAME_NAME, "/www") ~= true then if os.rename(M.WWW_RENAME_NAME, '/www') ~= true then
return l:error("Could not rename " .. M.WWW_RENAME_NAME .. " to /www") return log:error("Could not rename " .. M.WWW_RENAME_NAME .. " to /www")
end end
return true return true
end end
@ -222,20 +222,20 @@ end
--[[ Setup/remove NAT reflection to redirect all IPs ]] --[[ Setup/remove NAT reflection to redirect all IPs ]]
function reconf.natreflect_add(dirtyList) function reconf.natreflect_add(dirtyList)
uci:set("firewall", "portalreflect", "redirect"); uci:set('firewall', 'portalreflect', 'redirect');
M.uciTableSet("firewall", "portalreflect", { M.uciTableSet('firewall', 'portalreflect', {
src = "lan", src = 'lan',
proto = "tcp", proto = 'tcp',
src_dport = "80", src_dport = '80',
dest_port = "80", dest_port = '80',
dest_ip = s.get('apAddress'), dest_ip = settings.get('apAddress'),
target = "DNAT" target = 'DNAT'
}) })
bothBits(dirtyList, "firewall") bothBits(dirtyList, 'firewall')
end end
function reconf.natreflect_rm(dirtyList) function reconf.natreflect_rm(dirtyList)
uci:delete("firewall", "portalreflect") uci:delete('firewall', 'portalreflect')
bothBits(dirtyList, "firewall") bothBits(dirtyList, 'firewall')
end end
return M return M

View File

@ -1,14 +1,13 @@
local util = require("util.utils") local log = require('util.logger')
local l = require("util.logger") local uci = require('uci').cursor()
local uci = require("uci").cursor() local iwinfo = require('iwinfo')
local iwinfo = require("iwinfo")
local M = {} local M = {}
--NOTE: fallback device 'radio0' is required because sometimes the wlan0 device disappears --NOTE: fallback device 'radio0' is required because sometimes the wlan0 device disappears
M.DFL_DEVICE = "wlan0" M.DFL_DEVICE = 'wlan0'
M.DFL_DEVICE_FALLBACK = "radio0" M.DFL_DEVICE_FALLBACK = 'radio0'
M.NET = "wlan" M.NET = 'wlan'
local dev, dev_api local dev, dev_api
@ -17,6 +16,7 @@ local cachedApSsid, baseApSsid = nil, nil
function M.getSubstitutedSsid(unformattedSsid) function M.getSubstitutedSsid(unformattedSsid)
if unformattedSsid == baseApSsid and cachedApSsid ~= nil then return cachedApSsid end if unformattedSsid == baseApSsid and cachedApSsid ~= nil then return cachedApSsid end
if not unformattedSsid or type(unformattedSsid) ~= 'string' then return nil end
local macTail = M.getMacAddress():sub(7) local macTail = M.getMacAddress():sub(7)
@ -33,9 +33,9 @@ end
-- @param masterIsAp set to true to map 'Master' to 'ap' instead of 'sta' (optional) -- @param masterIsAp set to true to map 'Master' to 'ap' instead of 'sta' (optional)
function M.mapDeviceMode(mode, masterIsAp) function M.mapDeviceMode(mode, masterIsAp)
local modeMap = { local modeMap = {
["Master"] = masterIsAp and "ap" or "sta", ['Master'] = masterIsAp and 'ap' or 'sta',
["Client"] = "sta", ['Client'] = 'sta',
["Ad-Hoc"] = "adhoc" ['Ad-Hoc'] = 'adhoc'
} }
return modeMap[mode] or mode return modeMap[mode] or mode
end end
@ -45,10 +45,10 @@ end
- See: http://wiki.openwrt.org/doc/uci/wireless#wpa.modes - See: http://wiki.openwrt.org/doc/uci/wireless#wpa.modes
]] ]]
function M.mapEncryptionType(scanEncrTbl) function M.mapEncryptionType(scanEncrTbl)
local wpaModeMap = { [1] = "psk", [2] = "psk2", [3] = "mixed-psk" } local wpaModeMap = { [1] = 'psk', [2] = 'psk2', [3] = 'mixed-psk' }
if scanEncrTbl.enabled == false then return "none" end if scanEncrTbl.enabled == false then return 'none' end
if scanEncrTbl.wep == true then return "wep" end if scanEncrTbl.wep == true then return 'wep' end
return wpaModeMap[scanEncrTbl.wpa] or scanEncrTbl.description return wpaModeMap[scanEncrTbl.wpa] or scanEncrTbl.description
end end
@ -58,7 +58,7 @@ end
-- @param device wireless device to operate on (optional, defaults to DFL_DEVICE) -- @param device wireless device to operate on (optional, defaults to DFL_DEVICE)
-- @return true on success or false+error on failure -- @return true on success or false+error on failure
function M.init(device) function M.init(device)
-- iwinfo = pcall(require, "iwinfo") -- iwinfo = pcall(require, 'iwinfo')
dev = device or M.DFL_DEVICE dev = device or M.DFL_DEVICE
dev_api = iwinfo.type(dev) dev_api = iwinfo.type(dev)
if not dev_api then if not dev_api then
@ -79,16 +79,16 @@ end
function M.getDeviceState() function M.getDeviceState()
local iw = iwinfo[dev_api] local iw = iwinfo[dev_api]
local result = { local result = {
["ssid"] = iw.ssid(dev), ['ssid'] = iw.ssid(dev),
["bssid"] = iw.bssid(dev), ['bssid'] = iw.bssid(dev),
["channel"] = iw.channel(dev), ['channel'] = iw.channel(dev),
["mode"] = M.mapDeviceMode(iw.mode(dev), true), ['mode'] = M.mapDeviceMode(iw.mode(dev), true),
["encryption"] = M.mapEncryptionType(iw.encryption(dev).description), ['encryption'] = M.mapEncryptionType(iw.encryption(dev).description),
["quality"] = iw.quality(dev), ['quality'] = iw.quality(dev),
["quality_max"] = iw.quality_max(dev), ['quality_max'] = iw.quality_max(dev),
["txpower"] = iw.txpower(dev), ['txpower'] = iw.txpower(dev),
["signal"] = iw.signal(dev), ['signal'] = iw.signal(dev),
["noise"] = iw.noise(dev) ['noise'] = iw.noise(dev)
} }
return result return result
end end
@ -98,7 +98,7 @@ end
function M.getMacAddress() function M.getMacAddress()
local iw = iwinfo[dev_api] local iw = iwinfo[dev_api]
local macText = iw.bssid(dev) local macText = iw.bssid(dev)
local out = "" local out = ''
for i = 0, 5 do for i = 0, 5 do
local bt = string.sub(macText, i*3+1, i*3+2) local bt = string.sub(macText, i*3+1, i*3+2)
@ -136,7 +136,7 @@ end
--- Return all wireless networks configured in UCI --- Return all wireless networks configured in UCI
function M.getConfigs() function M.getConfigs()
local l = {} local l = {}
uci.foreach("wireless", "wifi-iface", function(s) table.insert(l, s) end) uci.foreach('wireless', 'wifi-iface', function(s) table.insert(l, s) end)
return l return l
end end
@ -144,25 +144,25 @@ end
-- @return true if successfully removed, false if no such config exists -- @return true if successfully removed, false if no such config exists
function M.removeConfig(ssid) function M.removeConfig(ssid)
local rv = false local rv = false
uci:foreach("wireless", "wifi-iface", function(s) uci:foreach('wireless', 'wifi-iface', function(s)
if s.ssid == ssid then if s.ssid == ssid then
uci:delete("wireless", s[".name"]) uci:delete('wireless', s['.name'])
rv = true rv = true
return false return false
end end
end) end)
uci:commit("wireless") uci:commit('wireless')
return rv return rv
end end
--- Activate wireless section for given SSID and disable all others --- Activate wireless section for given SSID and disable all others
-- @param ssid SSID of config to enable, or nil to disable all network configs -- @param ssid SSID of config to enable, or nil to disable all network configs
function M.activateConfig(ssid) function M.activateConfig(ssid)
uci:foreach("wireless", "wifi-iface", function(s) uci:foreach('wireless', 'wifi-iface', function(s)
local disabled = s.ssid ~= ssid and "1" or "0" local disabled = s.ssid ~= ssid and '1' or '0'
uci:set("wireless", s[".name"], "disabled", disabled) uci:set('wireless', s['.name'], 'disabled', disabled)
end) end)
uci:commit("wireless") uci:commit('wireless')
end end
--- Create a new UCI network from the given iwinfo data --- Create a new UCI network from the given iwinfo data
@ -176,7 +176,7 @@ function M.createConfigFromScanInfo(info, passphrase, disabled)
local apconfig = { local apconfig = {
network = M.NET, network = M.NET,
device = "radio0", device = 'radio0',
ssid = info.ssid, ssid = info.ssid,
bssid = info.bssid, bssid = info.bssid,
encryption = M.mapEncryptionType(info.encryption), encryption = M.mapEncryptionType(info.encryption),
@ -185,19 +185,19 @@ function M.createConfigFromScanInfo(info, passphrase, disabled)
if passphrase ~= nil then apconfig.key = passphrase end if passphrase ~= nil then apconfig.key = passphrase end
apconfig.disabled = disabled ~= nil and disabled and 1 or 0 apconfig.disabled = disabled ~= nil and disabled and 1 or 0
uci:foreach("wireless", "wifi-iface", function(s) uci:foreach('wireless', 'wifi-iface', function(s)
if s.bssid == info.bssid then if s.bssid == info.bssid then
l:debug("removing old wireless config for net '" .. s.ssid .. "(bssid: " .. s.bssid .. ")'") log:debug("removing old wireless config for net '" .. s.ssid .. "(bssid: " .. s.bssid .. ")'")
uci:delete("wireless", s[".name"]) uci:delete('wireless', s['.name'])
-- return false --keep looking, just in case multiple entries with this bssid exist -- return false --keep looking, just in case multiple entries with this bssid exist
end end
end) end)
local sname = uci:add("wireless", "wifi-iface"); local sname = uci:add('wireless', 'wifi-iface');
for k, v in pairs(apconfig) do for k, v in pairs(apconfig) do
uci:set("wireless", sname, k, v) uci:set('wireless', sname, k, v)
end end
uci:commit("wireless") uci:commit('wireless')
end end
--- Reload network config to reflect contents of config --- Reload network config to reflect contents of config
@ -205,11 +205,11 @@ end
-- * Network reload only restarts interfaces which need to be restarted so no -- * Network reload only restarts interfaces which need to be restarted so no
-- unneccesary interruptions there. -- unneccesary interruptions there.
-- * ubus does not seem to work -- local c=ubus.connect(); -- * ubus does not seem to work -- local c=ubus.connect();
-- c:call("network.interface.wlan", "down"); c:call("network.interface.wlan", "up"); c:close() -- c:call('network.interface.wlan', 'down'); c:call('network.interface.wlan', 'up'); c:close()
-- @param dhcpToo also reload dnsmasq if true -- @param dhcpToo also reload dnsmasq if true
function M.restart(dhcpToo) function M.restart(dhcpToo)
os.execute("/etc/init.d/network reload") --always seems to return 0 os.execute('/etc/init.d/network reload') --always seems to return 0
if dhcpToo ~= nil and dhcpToo then os.execute("/etc/init.d/dnsmasq reload") end if dhcpToo ~= nil and dhcpToo then os.execute('/etc/init.d/dnsmasq reload') end
return 0 return 0
end end