luci-base-ucode: add initial ucode based LuCI runtime

This commits introduces an initial ucode based LuCI runtime. It supports
JSON menu files as used by Lua based LuCI and the template, call, view and
alias dispatch targets.

It is able to render a basic LuCI installation without errors. An embedded
Lua VM is lazily loaded when Lua based resources are encountered, such as
`*.htm` templates or server side Lua call targets.

When a template is requested, the ucode runtime first tries to render an
`/usr/share/ucode/luci/template/${path}.uc` ucode template and falls back
to rendering the corresponding `/usr/lib/lua/luci/view/${path}.htm` Lua
template in case no suitable ucode replacement is found. This allows for
gradual migration of existing Lua based tmeplates to ucode.

Furthermore, a set of stripped down LuCI libraries is shipped in the
`/usr/lib/lua/luci/ucodebridge/` directory. Those libraries provide
compatibility shims for the current Lua API towards Lua templates and Lua
based server side actions while utilizing the ucode request runtime state
internally.

Signed-off-by: Jo-Philipp Wich <jo@mein.io>
This commit is contained in:
Jo-Philipp Wich 2022-08-29 17:09:22 +02:00
parent f2133059e1
commit ded8ccf93e
30 changed files with 12165 additions and 0 deletions

View file

@ -0,0 +1,45 @@
#
# Copyright (C) 2022 Jo-Philipp Wich <jo@mein.io>
#
# This is free software, licensed under the Apache License, Version 2.0 .
#
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-base-ucode
LUCI_TYPE:=mod
LUCI_BASENAME:=base-ucode
LUCI_TITLE:=LuCI core ucode runtime
LUCI_DEPENDS:=\
+luci-base \
+ucode \
+ucode-mod-fs \
+ucode-mod-uci \
+ucode-mod-ubus \
+ucode-mod-math \
+ucode-mod-lua \
+ucode-mod-html \
+rpcd-mod-ucode \
+liblucihttp-ucode
PKG_LICENSE:=MIT
define Package/luci-base-ucode/postinst
#!/bin/sh
if [ -z "$${PKG_INSTROOT}" ] && [ -f /etc/config/uhttpd ]; then
if ! uci -q get uhttpd.main.ucode_prefix | grep -sq /cgi-bin/luci-ucode; then
uci add_list uhttpd.main.ucode_prefix='/cgi-bin/luci-ucode=/usr/share/ucode/luci/uhttpd.uc'
uci commit uhttpd
service uhttpd reload
fi
fi
exit 0
endef
include ../../luci.mk
# call BuildPackage - OpenWrt buildroot signature

View file

@ -0,0 +1,41 @@
#!/usr/bin/env ucode
'use strict';
import { stdin, stdout } from 'fs';
import dispatch from 'luci.dispatcher';
import request from 'luci.http';
const input_bufsize = 4096;
let input_available = +getenv('CONTENT_LENGTH') || 0;
function read(len) {
if (input_available == 0) {
stdin.close();
return null;
}
let chunk = stdin.read(min(input_available, len ?? input_bufsize, input_bufsize));
if (chunk == null) {
input_available = 0;
stdin.close();
}
else {
input_available -= length(chunk);
}
return chunk;
}
function write(data) {
return stdout.write(data);
}
let req = request(getenv(), read, write);
dispatch(req);
req.close();

View file

@ -0,0 +1,457 @@
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.dispatcher", package.seeall)
local http = _G.L.http
context = setmetatable({
request = _G.L.ctx.request_path;
requested = _G.L.node;
dispatched = _G.L.node;
}, {
__index = function(t, k)
if k == "requestpath" then
return _G.L.ctx.request_path
elseif k == "requestargs" then
return _G.L.ctx.request_args
else
return _G.L.ctx[k]
end
end
})
uci = require "luci.model.uci"
uci:set_session_id(_G.L.ctx.authsession)
i18n = require "luci.i18n"
i18n.setlanguage(_G.L.dispatcher.lang)
build_url = _G.L.dispatcher.build_url
menu_json = _G.L.dispatcher.menu_json
error404 = _G.L.dispatcher.error404
error500 = _G.L.dispatcher.error500
function is_authenticated(auth)
local session = _G.L.dispatcher.is_authenticated(auth)
if session then
return session.sid, session.data, session.acls
end
end
function assign(path, clone, title, order)
local obj = node(unpack(path))
obj.title = title
obj.order = order
setmetatable(obj, {__index = node(unpack(clone))})
return obj
end
function entry(path, target, title, order)
local c = node(unpack(path))
c.title = title
c.order = order
c.action = target
return c
end
-- enabling the node.
function get(...)
return node(...)
end
function node(...)
local p = table.concat({ ... }, "/")
if not __entries[p] then
__entries[p] = {}
end
return __entries[p]
end
function lookup(...)
local i, path = nil, {}
for i = 1, select('#', ...) do
local name, arg = nil, tostring(select(i, ...))
for name in arg:gmatch("[^/]+") do
path[#path+1] = name
end
end
local node = menu_json()
for i = 1, #path do
node = node.children[path[i]]
if not node then
return nil
elseif node.leaf then
break
end
end
return node, build_url(unpack(path))
end
function process_lua_controller(path)
local base = "/usr/lib/lua/luci/controller/"
local modname = "luci.controller." .. path:sub(#base+1, #path-4):gsub("/", ".")
local mod = require(modname)
assert(mod ~= true,
"Invalid controller file found\n" ..
"The file '" .. path .. "' contains an invalid module line.\n" ..
"Please verify whether the module name is set to '" .. modname ..
"' - It must correspond to the file path!")
local idx = mod.index
if type(idx) ~= "function" then
return nil
end
local entries = {}
__entries = entries
__controller = modname
setfenv(idx, setmetatable({}, { __index = luci.dispatcher }))()
__entries = nil
__controller = nil
-- fixup gathered node specs
for path, entry in pairs(entries) do
if entry.leaf then
entry.wildcard = true
end
if type(entry.file_depends) == "table" then
for _, v in ipairs(entry.file_depends) do
entry.depends = entry.depends or {}
entry.depends.fs = entry.depends.fs or {}
local ft = fs.stat(v, "type")
if ft == "dir" then
entry.depends.fs[v] = "directory"
elseif v:match("/s?bin/") then
entry.depends.fs[v] = "executable"
else
entry.depends.fs[v] = "file"
end
end
end
if type(entry.uci_depends) == "table" then
for k, v in pairs(entry.uci_depends) do
entry.depends = entry.depends or {}
entry.depends.uci = entry.depends.uci or {}
entry.depends.uci[k] = v
end
end
if type(entry.acl_depends) == "table" then
for _, acl in ipairs(entry.acl_depends) do
entry.depends = entry.depends or {}
entry.depends.acl = entry.depends.acl or {}
entry.depends.acl[#entry.depends.acl + 1] = acl
end
end
if (entry.sysauth_authenticator ~= nil) or
(entry.sysauth ~= nil and entry.sysauth ~= false)
then
if entry.sysauth_authenticator == "htmlauth" then
entry.auth = {
login = true,
methods = { "cookie:sysauth_https", "cookie:sysauth_http" }
}
elseif subname == "rpc" and entry.module == "luci.controller.rpc" then
entry.auth = {
login = false,
methods = { "query:auth", "cookie:sysauth_https", "cookie:sysauth_http" }
}
elseif entry.module == "luci.controller.admin.uci" then
entry.auth = {
login = false,
methods = { "param:sid" }
}
end
elseif entry.sysauth == false then
entry.auth = {}
end
entry.leaf = nil
entry.file_depends = nil
entry.uci_depends = nil
entry.acl_depends = nil
entry.sysauth = nil
entry.sysauth_authenticator = nil
end
return entries
end
function invoke_cbi_action(model, config, ...)
local cbi = require "luci.cbi"
local tpl = require "luci.template"
local util = require "luci.util"
if not config then
config = {}
end
local maps = cbi.load(model, ...)
local state = nil
local function has_uci_access(config, level)
local rv = util.ubus("session", "access", {
ubus_rpc_session = context.authsession,
scope = "uci", object = config,
["function"] = level
})
return (type(rv) == "table" and rv.access == true) or false
end
local i, res
for i, res in ipairs(maps) do
if util.instanceof(res, cbi.SimpleForm) then
io.stderr:write("Model %s returns SimpleForm but is dispatched via cbi(),\n"
% model)
io.stderr:write("please change %s to use the form() action instead.\n"
% table.concat(context.request, "/"))
end
res.flow = config
local cstate = res:parse()
if cstate and (not state or cstate < state) then
state = cstate
end
end
local function _resolve_path(path)
return type(path) == "table" and build_url(unpack(path)) or path
end
if config.on_valid_to and state and state > 0 and state < 2 then
http:redirect(_resolve_path(config.on_valid_to))
return
end
if config.on_changed_to and state and state > 1 then
http:redirect(_resolve_path(config.on_changed_to))
return
end
if config.on_success_to and state and state > 0 then
http:redirect(_resolve_path(config.on_success_to))
return
end
if config.state_handler then
if not config.state_handler(state, maps) then
return
end
end
http:header("X-CBI-State", state or 0)
if not config.noheader then
tpl.render("cbi/header", {state = state})
end
local redirect
local messages
local applymap = false
local pageaction = true
local parsechain = { }
local writable = false
for i, res in ipairs(maps) do
if res.apply_needed and res.parsechain then
local c
for _, c in ipairs(res.parsechain) do
parsechain[#parsechain+1] = c
end
applymap = true
end
if res.redirect then
redirect = redirect or res.redirect
end
if res.pageaction == false then
pageaction = false
end
if res.message then
messages = messages or { }
messages[#messages+1] = res.message
end
end
for i, res in ipairs(maps) do
local is_readable_map = has_uci_access(res.config, "read")
local is_writable_map = has_uci_access(res.config, "write")
writable = writable or is_writable_map
res:render({
firstmap = (i == 1),
redirect = redirect,
messages = messages,
pageaction = pageaction,
parsechain = parsechain,
readable = is_readable_map,
writable = is_writable_map
})
end
if not config.nofooter then
tpl.render("cbi/footer", {
flow = config,
pageaction = pageaction,
redirect = redirect,
state = state,
autoapply = config.autoapply,
trigger_apply = applymap,
writable = writable
})
end
end
function invoke_form_action(model, ...)
local cbi = require "luci.cbi"
local tpl = require "luci.template"
local maps = luci.cbi.load(model, ...)
local state = nil
local i, res
for i, res in ipairs(maps) do
local cstate = res:parse()
if cstate and (not state or cstate < state) then
state = cstate
end
end
http:header("X-CBI-State", state or 0)
tpl.render("header")
for i, res in ipairs(maps) do
res:render()
end
tpl.render("footer")
end
function call(name, ...)
return {
["type"] = "call",
["module"] = __controller,
["function"] = name,
["parameters"] = select('#', ...) > 0 and {...} or nil
}
end
function post(name, ...)
return {
["type"] = "call",
["module"] = __controller,
["function"] = name,
["parameters"] = select('#', ...) > 0 and {...} or nil,
["post"] = true
}
end
function view(name)
return {
["type"] = "view",
["path"] = name
}
end
function template(name)
return {
["type"] = "template",
["path"] = name
}
end
function cbi(model, config)
return {
["type"] = "call",
["module"] = "luci.dispatcher",
["function"] = "invoke_cbi_action",
["parameters"] = { model, config },
["post"] = {
["cbi.submit"] = true
}
}
end
function form(model)
return {
["type"] = "call",
["module"] = "luci.dispatcher",
["function"] = "invoke_form_action",
["parameters"] = { model },
["post"] = {
["cbi.submit"] = true
}
}
end
function firstchild()
return {
["type"] = "firstchild"
}
end
function firstnode()
return {
["type"] = "firstchild",
["recurse"] = true
}
end
function arcombine(trg1, trg2)
return {
["type"] = "arcombine",
["targets"] = { trg1, trg2 } --,
--env = getfenv(),
}
end
function alias(...)
return {
["type"] = "alias",
["path"] = table.concat({ ... }, "/")
}
end
function rewrite(n, ...)
return {
["type"] = "rewrite",
["path"] = table.concat({ ... }, "/"),
["remove"] = n
}
end
translate = i18n.translate
-- This function does not actually translate the given argument but
-- is used by build/i18n-scan.pl to find translatable entries.
function _(text)
return text
end

View file

@ -0,0 +1,144 @@
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2010-2018 Jo-Philipp Wich <jo@mein.io>
-- Licensed to the public under the Apache License 2.0.
local util = require "luci.util"
local coroutine = require "coroutine"
local table = require "table"
local lhttp = require "lucihttp"
local L, table, ipairs, pairs, type, error = _G.L, table, ipairs, pairs, type, error
module "luci.http"
HTTP_MAX_CONTENT = 1024*100 -- 100 kB maximum content size
function close()
L.http:close()
end
function content()
return L.http:content()
end
function formvalue(name, noparse)
return L.http:formvalue(name, noparse)
end
function formvaluetable(prefix)
return L.http:formvaluetable(prefix)
end
function getcookie(name)
return L.http:getcookie(name)
end
-- or the environment table itself.
function getenv(name)
return L.http:getenv(name)
end
function setfilehandler(callback)
return L.http:setfilehandler(callback)
end
function header(key, value)
L.http:header(key, value)
end
function prepare_content(mime)
L.http:prepare_content(mime)
end
function source()
return L.http.input
end
function status(code, message)
L.http:status(code, message)
end
-- This function is as a valid LTN12 sink.
-- If the content chunk is nil this function will automatically invoke close.
function write(content, src_err)
if src_err then
error(src_err)
end
return L.print(content)
end
function splice(fd, size)
coroutine.yield(6, fd, size)
end
function redirect(url)
L.http:redirect(url)
end
function build_querystring(q)
local s, n, k, v = {}, 1, nil, nil
for k, v in pairs(q) do
s[n+0] = (n == 1) and "?" or "&"
s[n+1] = util.urlencode(k)
s[n+2] = "="
s[n+3] = util.urlencode(v)
n = n + 4
end
return table.concat(s, "")
end
urldecode = util.urldecode
urlencode = util.urlencode
function write_json(x)
L.printf('%J', x)
end
-- separated by "&". Tables are encoded as parameters with multiple values by
-- repeating the parameter name with each value.
function urlencode_params(tbl)
local k, v
local n, enc = 1, {}
for k, v in pairs(tbl) do
if type(v) == "table" then
local i, v2
for i, v2 in ipairs(v) do
if enc[1] then
enc[n] = "&"
n = n + 1
end
enc[n+0] = lhttp.urlencode(k)
enc[n+1] = "="
enc[n+2] = lhttp.urlencode(v2)
n = n + 3
end
else
if enc[1] then
enc[n] = "&"
n = n + 1
end
enc[n+0] = lhttp.urlencode(k)
enc[n+1] = "="
enc[n+2] = lhttp.urlencode(v)
n = n + 3
end
end
return table.concat(enc, "")
end
context = {
request = {
formvalue = function(self, ...) return formvalue(...) end;
formvaluetable = function(self, ...) return formvaluetable(...) end;
content = function(self, ...) return content(...) end;
getcookie = function(self, ...) return getcookie(...) end;
setfilehandler = function(self, ...) return setfilehandler(...) end;
}
}

View file

@ -0,0 +1,184 @@
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local util = require "luci.util"
local config = require "luci.config"
local tparser = require "luci.template.parser"
local tostring, pairs, loadstring = tostring, pairs, loadstring
local setmetatable, loadfile = setmetatable, loadfile
local getfenv, setfenv, rawget = getfenv, setfenv, rawget
local assert, type, error = assert, type, error
local table, string, unpack = table, string, unpack
---
--- bootstrap
---
local _G = _G
local L = _G.L
local http = _G.L.http
local disp = require "luci.dispatcher"
local i18n = require "luci.i18n"
local xml = require "luci.xml"
local fs = require "nixio.fs"
--- LuCI template library.
module "luci.template"
config.template = config.template or {}
viewdir = config.template.viewdir or util.libpath() .. "/view"
-- Define the namespace for template modules
context = {} --util.threadlocal()
--- Render a certain template.
-- @param name Template name
-- @param scope Scope to assign to template (optional)
function render(name, scope)
return Template(name):render(scope or getfenv(2))
end
--- Render a template from a string.
-- @param template Template string
-- @param scope Scope to assign to template (optional)
function render_string(template, scope)
return Template(nil, template):render(scope or getfenv(2))
end
-- Template class
Template = util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = setmetatable({}, {__mode = "v"})
local function _ifattr(cond, key, val, noescape)
if cond then
local env = getfenv(3)
local scope = (type(env.self) == "table") and env.self
if type(val) == "table" then
if not next(val) then
return ''
else
val = util.serialize_json(val)
end
end
val = tostring(val or
(type(env[key]) ~= "function" and env[key]) or
(scope and type(scope[key]) ~= "function" and scope[key]) or "")
if noescape ~= true then
val = xml.pcdata(val)
end
return string.format(' %s="%s"', tostring(key), val)
else
return ''
end
end
context.viewns = setmetatable({
include = function(name)
if fs.access(viewdir .. "/" .. name .. ".htm") then
Template(name):render(getfenv(2))
else
L.include(name, getfenv(2))
end
end;
translate = i18n.translate;
translatef = i18n.translatef;
export = function(k, v) if tpl.context.viewns[k] == nil then tpl.context.viewns[k] = v end end;
striptags = xml.striptags;
pcdata = xml.pcdata;
ifattr = function(...) return _ifattr(...) end;
attr = function(...) return _ifattr(true, ...) end;
url = disp.build_url;
}, {__index=function(tbl, key)
if key == "controller" then
return disp.build_url()
elseif key == "REQUEST_URI" then
return disp.build_url(unpack(disp.context.requestpath))
elseif key == "FULL_REQUEST_URI" then
local url = { http:getenv("SCRIPT_NAME") or "", http:getenv("PATH_INFO") }
local query = http:getenv("QUERY_STRING")
if query and #query > 0 then
url[#url+1] = "?"
url[#url+1] = query
end
return table.concat(url, "")
elseif key == "token" then
return disp.context.authtoken
elseif key == "theme" then
return L.media and fs.basename(L.media) or tostring(L)
elseif key == "resource" then
return L.config.main.resourcebase
else
return rawget(tbl, key) or _G[key] or L[key]
end
end})
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name, template)
if name then
self.template = self.cache[name]
self.name = name
else
self.name = "[string]"
end
-- Create a new namespace for this template
self.viewns = context.viewns
-- If we have a cached template, skip compiling and loading
if not self.template then
-- Compile template
local err
local sourcefile
if name then
sourcefile = viewdir .. "/" .. name .. ".htm"
self.template, _, err = tparser.parse(sourcefile)
else
sourcefile = "[string]"
self.template, _, err = tparser.parse_string(template)
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error("Failed to load template '" .. self.name .. "'.\n" ..
"Error while parsing template '" .. sourcefile .. "':\n" ..
(err or "Unknown syntax error"))
elseif name then
self.cache[name] = self.template
end
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Put our predefined objects in the scope of the template
setfenv(self.template, setmetatable({}, {__index =
function(tbl, key)
return rawget(tbl, key) or self.viewns[key] or scope[key]
end}))
-- Now finally render the thing
local stat, err = util.copcall(self.template)
if not stat then
error("Failed to execute template '" .. self.name .. "'.\n" ..
"A runtime error occurred: " .. tostring(err or "(nil)"))
end
end

View file

@ -0,0 +1,52 @@
-- Copyright 2022 Jo-Philipp Wich <jo@mein.io>
-- Licensed to the public under the Apache License 2.0.
local coroutine, assert, error, type, require = coroutine, assert, error, type, require
local tmpl = require "luci.template"
local util = require "luci.util"
local http = require "luci.http"
--- LuCI ucode bridge library.
module "luci.ucodebridge"
local function run(fn, ...)
local co = coroutine.create(fn)
local ok, ret
while coroutine.status(co) ~= "dead" do
ok, ret = coroutine.resume(co, ...)
if not ok then
error(ret)
end
end
return ret
end
function compile(path)
run(function(path)
return tmpl.Template(path)
end, path)
end
function render(path, scope)
run(tmpl.render, path, scope)
end
function call(modname, method, ...)
return run(function(module, method, ...)
local mod = require(modname)
local func = mod[method]
assert(func ~= nil,
'Cannot resolve function "' .. method .. '". Is it misspelled or local?')
assert(type(func) == "function",
'The symbol "' .. method .. '" does not refer to a function but data ' ..
'of type "' .. type(func) .. '".')
return func(...)
end, modname, method, ...)
end

View file

@ -0,0 +1,786 @@
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local io = require "io"
local math = require "math"
local table = require "table"
local debug = require "debug"
local ldebug = require "luci.debug"
local string = require "string"
local coroutine = require "coroutine"
local tparser = require "luci.template.parser"
local json = require "luci.jsonc"
local lhttp = require "lucihttp"
local _ubus = require "ubus"
local _ubus_connection = nil
local getmetatable, setmetatable = getmetatable, setmetatable
local rawget, rawset, unpack, select = rawget, rawset, unpack, select
local tostring, type, assert, error = tostring, type, assert, error
local ipairs, pairs, next, loadstring = ipairs, pairs, next, loadstring
local require, pcall, xpcall = require, pcall, xpcall
local collectgarbage, get_memory_limit = collectgarbage, get_memory_limit
local L = _G.L
module "luci.util"
--
-- Pythonic string formatting extension
--
getmetatable("").__mod = function(a, b)
local ok, res
if not b then
return a
elseif type(b) == "table" then
local k, _
for k, _ in pairs(b) do if type(b[k]) == "userdata" then b[k] = tostring(b[k]) end end
ok, res = pcall(a.format, a, unpack(b))
if not ok then
error(res, 2)
end
return res
else
if type(b) == "userdata" then b = tostring(b) end
ok, res = pcall(a.format, a, b)
if not ok then
error(res, 2)
end
return res
end
end
--
-- Class helper routines
--
-- Instantiates a class
local function _instantiate(class, ...)
local inst = setmetatable({}, {__index = class})
if inst.__init__ then
inst:__init__(...)
end
return inst
end
-- The class object can be instantiated by calling itself.
-- Any class functions or shared parameters can be attached to this object.
-- Attaching a table to the class object makes this table shared between
-- all instances of this class. For object parameters use the __init__ function.
-- Classes can inherit member functions and values from a base class.
-- Class can be instantiated by calling them. All parameters will be passed
-- to the __init__ function of this class - if such a function exists.
-- The __init__ function must be used to set any object parameters that are not shared
-- with other objects of this class. Any return values will be ignored.
function class(base)
return setmetatable({}, {
__call = _instantiate,
__index = base
})
end
function instanceof(object, class)
local meta = getmetatable(object)
while meta and meta.__index do
if meta.__index == class then
return true
end
meta = getmetatable(meta.__index)
end
return false
end
--
-- Scope manipulation routines
--
coxpt = setmetatable({}, { __mode = "kv" })
local tl_meta = {
__mode = "k",
__index = function(self, key)
local t = rawget(self, coxpt[coroutine.running()]
or coroutine.running() or 0)
L.http:write("<!-- __index(%s/%s, %s): %s -->\n" %{ tostring(self), tostring(coxpt[coroutine.running()] or coroutine.running() or 0), key, tostring(t and t[key]) })
return t and t[key]
end,
__newindex = function(self, key, value)
L.http:write("<!-- __newindex(%s/%s, %s, %s) -->\n" %{ tostring(self), tostring(coxpt[coroutine.running()] or coroutine.running() or 0), key, tostring(value) })
local c = coxpt[coroutine.running()] or coroutine.running() or 0
local r = rawget(self, c)
if not r then
rawset(self, c, { [key] = value })
else
r[key] = value
end
end
}
-- the current active coroutine. A thread local store is private a table object
-- whose values can't be accessed from outside of the running coroutine.
function threadlocal(tbl)
return tbl or {} --setmetatable(tbl or {}, tl_meta)
end
--
-- Debugging routines
--
function perror(obj)
return io.stderr:write(tostring(obj) .. "\n")
end
function dumptable(t, maxdepth, i, seen)
i = i or 0
seen = seen or setmetatable({}, {__mode="k"})
for k,v in pairs(t) do
perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
if type(v) == "table" and (not maxdepth or i < maxdepth) then
if not seen[v] then
seen[v] = true
dumptable(v, maxdepth, i+1, seen)
else
perror(string.rep("\t", i) .. "*** RECURSION ***")
end
end
end
end
--
-- String and data manipulation routines
--
-- compatibility wrapper for xml.pcdata
function pcdata(value)
local xml = require "luci.xml"
perror("luci.util.pcdata() has been replaced by luci.xml.pcdata() - Please update your code.")
return xml.pcdata(value)
end
function urlencode(value)
if value ~= nil then
local str = tostring(value)
return lhttp.urlencode(str, lhttp.ENCODE_IF_NEEDED + lhttp.ENCODE_FULL)
or str
end
return nil
end
function urldecode(value, decode_plus)
if value ~= nil then
local flag = decode_plus and lhttp.DECODE_PLUS or 0
local str = tostring(value)
return lhttp.urldecode(str, lhttp.DECODE_IF_NEEDED + flag)
or str
end
return nil
end
-- compatibility wrapper for xml.striptags
function striptags(value)
local xml = require "luci.xml"
perror("luci.util.striptags() has been replaced by luci.xml.striptags() - Please update your code.")
return xml.striptags(value)
end
function shellquote(value)
return string.format("'%s'", string.gsub(value or "", "'", "'\\''"))
end
-- for bash, ash and similar shells single-quoted strings are taken
-- literally except for single quotes (which terminate the string)
-- (and the exception noted below for dash (-) at the start of a
-- command line parameter).
function shellsqescape(value)
local res
res, _ = string.gsub(value, "'", "'\\''")
return res
end
-- bash, ash and other similar shells interpret a dash (-) at the start
-- of a command-line parameters as an option indicator regardless of
-- whether it is inside a single-quoted string. It must be backlash
-- escaped to resolve this. This requires in some funky special-case
-- handling. It may actually be a property of the getopt function
-- rather than the shell proper.
function shellstartsqescape(value)
res, _ = string.gsub(value, "^%-", "\\-")
return shellsqescape(res)
end
-- containing the resulting substrings. The optional max parameter specifies
-- the number of bytes to process, regardless of the actual length of the given
-- string. The optional last parameter, regex, specifies whether the separator
-- sequence is interpreted as regular expression.
-- pattern as regular expression (optional, default is false)
function split(str, pat, max, regex)
pat = pat or "\n"
max = max or #str
local t = {}
local c = 1
if #str == 0 then
return {""}
end
if #pat == 0 then
return nil
end
if max == 0 then
return str
end
repeat
local s, e = str:find(pat, c, not regex)
max = max - 1
if s and max < 0 then
t[#t+1] = str:sub(c)
else
t[#t+1] = str:sub(c, s and s - 1)
end
c = e and e + 1 or #str + 1
until not s or max < 0
return t
end
function trim(str)
return (str:gsub("^%s*(.-)%s*$", "%1"))
end
function cmatch(str, pat)
local count = 0
for _ in str:gmatch(pat) do count = count + 1 end
return count
end
-- one token per invocation, the tokens are separated by whitespace. If the
-- input value is a table, it is transformed into a string first. A nil value
-- will result in a valid iterator which aborts with the first invocation.
function imatch(v)
if type(v) == "table" then
local k = nil
return function()
k = next(v, k)
return v[k]
end
elseif type(v) == "number" or type(v) == "boolean" then
local x = true
return function()
if x then
x = false
return tostring(v)
end
end
elseif type(v) == "userdata" or type(v) == "string" then
return tostring(v):gmatch("%S+")
end
return function() end
end
-- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
-- Recognized units are:
-- o "y" - one year (60*60*24*366)
-- o "m" - one month (60*60*24*31)
-- o "w" - one week (60*60*24*7)
-- o "d" - one day (60*60*24)
-- o "h" - one hour (60*60)
-- o "min" - one minute (60)
-- o "kb" - one kilobyte (1024)
-- o "mb" - one megabyte (1024*1024)
-- o "gb" - one gigabyte (1024*1024*1024)
-- o "kib" - one si kilobyte (1000)
-- o "mib" - one si megabyte (1000*1000)
-- o "gib" - one si gigabyte (1000*1000*1000)
function parse_units(ustr)
local val = 0
-- unit map
local map = {
-- date stuff
y = 60 * 60 * 24 * 366,
m = 60 * 60 * 24 * 31,
w = 60 * 60 * 24 * 7,
d = 60 * 60 * 24,
h = 60 * 60,
min = 60,
-- storage sizes
kb = 1024,
mb = 1024 * 1024,
gb = 1024 * 1024 * 1024,
-- storage sizes (si)
kib = 1000,
mib = 1000 * 1000,
gib = 1000 * 1000 * 1000
}
-- parse input string
for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
local num = spec:gsub("[^0-9%.]+$","")
local spn = spec:gsub("^[0-9%.]+", "")
if map[spn] or map[spn:sub(1,1)] then
val = val + num * ( map[spn] or map[spn:sub(1,1)] )
else
val = val + num
end
end
return val
end
-- also register functions above in the central string class for convenience
string.split = split
string.trim = trim
string.cmatch = cmatch
string.parse_units = parse_units
function append(src, ...)
for i, a in ipairs({...}) do
if type(a) == "table" then
for j, v in ipairs(a) do
src[#src+1] = v
end
else
src[#src+1] = a
end
end
return src
end
function combine(...)
return append({}, ...)
end
function contains(table, value)
for k, v in pairs(table) do
if value == v then
return k
end
end
return false
end
-- Both table are - in fact - merged together.
function update(t, updates)
for k, v in pairs(updates) do
t[k] = v
end
end
function keys(t)
local keys = { }
if t then
for k, _ in kspairs(t) do
keys[#keys+1] = k
end
end
return keys
end
function clone(object, deep)
local copy = {}
for k, v in pairs(object) do
if deep and type(v) == "table" then
v = clone(v, deep)
end
copy[k] = v
end
return setmetatable(copy, getmetatable(object))
end
-- Serialize the contents of a table value.
function _serialize_table(t, seen)
assert(not seen[t], "Recursion detected.")
seen[t] = true
local data = ""
local idata = ""
local ilen = 0
for k, v in pairs(t) do
if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
k = serialize_data(k, seen)
v = serialize_data(v, seen)
data = data .. ( #data > 0 and ", " or "" ) ..
'[' .. k .. '] = ' .. v
elseif k > ilen then
ilen = k
end
end
for i = 1, ilen do
local v = serialize_data(t[i], seen)
idata = idata .. ( #idata > 0 and ", " or "" ) .. v
end
return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
end
-- with loadstring().
function serialize_data(val, seen)
seen = seen or setmetatable({}, {__mode="k"})
if val == nil then
return "nil"
elseif type(val) == "number" then
return val
elseif type(val) == "string" then
return "%q" % val
elseif type(val) == "boolean" then
return val and "true" or "false"
elseif type(val) == "function" then
return "loadstring(%q)" % get_bytecode(val)
elseif type(val) == "table" then
return "{ " .. _serialize_table(val, seen) .. " }"
else
return '"[unhandled data type:' .. type(val) .. ']"'
end
end
function restore_data(str)
return loadstring("return " .. str)()
end
--
-- Byte code manipulation routines
--
-- will be stripped before it is returned.
function get_bytecode(val)
local code
if type(val) == "function" then
code = string.dump(val)
else
code = string.dump( loadstring( "return " .. serialize_data(val) ) )
end
return code -- and strip_bytecode(code)
end
-- numbers and debugging numbers will be discarded. Original version by
-- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
function strip_bytecode(code)
local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
local subint
if endian == 1 then
subint = function(code, i, l)
local val = 0
for n = l, 1, -1 do
val = val * 256 + code:byte(i + n - 1)
end
return val, i + l
end
else
subint = function(code, i, l)
local val = 0
for n = 1, l, 1 do
val = val * 256 + code:byte(i + n - 1)
end
return val, i + l
end
end
local function strip_function(code)
local count, offset = subint(code, 1, size)
local stripped = { string.rep("\0", size) }
local dirty = offset + count
offset = offset + count + int * 2 + 4
offset = offset + int + subint(code, offset, int) * ins
count, offset = subint(code, offset, int)
for n = 1, count do
local t
t, offset = subint(code, offset, 1)
if t == 1 then
offset = offset + 1
elseif t == 4 then
offset = offset + size + subint(code, offset, size)
elseif t == 3 then
offset = offset + num
elseif t == 254 or t == 9 then
offset = offset + lnum
end
end
count, offset = subint(code, offset, int)
stripped[#stripped+1] = code:sub(dirty, offset - 1)
for n = 1, count do
local proto, off = strip_function(code:sub(offset, -1))
stripped[#stripped+1] = proto
offset = offset + off - 1
end
offset = offset + subint(code, offset, int) * int + int
count, offset = subint(code, offset, int)
for n = 1, count do
offset = offset + subint(code, offset, size) + size + int * 2
end
count, offset = subint(code, offset, int)
for n = 1, count do
offset = offset + subint(code, offset, size) + size
end
stripped[#stripped+1] = string.rep("\0", int * 3)
return table.concat(stripped), offset
end
return code:sub(1,12) .. strip_function(code:sub(13,-1))
end
--
-- Sorting iterator functions
--
function _sortiter( t, f )
local keys = { }
local k, v
for k, v in pairs(t) do
keys[#keys+1] = k
end
local _pos = 0
table.sort( keys, f )
return function()
_pos = _pos + 1
if _pos <= #keys then
return keys[_pos], t[keys[_pos]], _pos
end
end
end
-- the provided callback function.
function spairs(t,f)
return _sortiter( t, f )
end
-- The table pairs are sorted by key.
function kspairs(t)
return _sortiter( t )
end
-- The table pairs are sorted by value.
function vspairs(t)
return _sortiter( t, function (a,b) return t[a] < t[b] end )
end
--
-- System utility functions
--
function bigendian()
return string.byte(string.dump(function() end), 7) == 0
end
function exec(command)
local pp = io.popen(command)
local data = pp:read("*a")
pp:close()
return data
end
function execi(command)
local pp = io.popen(command)
return pp and function()
local line = pp:read()
if not line then
pp:close()
end
return line
end
end
-- Deprecated
function execl(command)
local pp = io.popen(command)
local line = ""
local data = {}
while true do
line = pp:read()
if (line == nil) then break end
data[#data+1] = line
end
pp:close()
return data
end
local ubus_codes = {
"INVALID_COMMAND",
"INVALID_ARGUMENT",
"METHOD_NOT_FOUND",
"NOT_FOUND",
"NO_DATA",
"PERMISSION_DENIED",
"TIMEOUT",
"NOT_SUPPORTED",
"UNKNOWN_ERROR",
"CONNECTION_FAILED"
}
local function ubus_return(...)
if select('#', ...) == 2 then
local rv, err = select(1, ...), select(2, ...)
if rv == nil and type(err) == "number" then
return nil, err, ubus_codes[err]
end
end
return ...
end
function ubus(object, method, data, path, timeout)
if not _ubus_connection then
_ubus_connection = _ubus.connect(path, timeout)
assert(_ubus_connection, "Unable to establish ubus connection")
end
if object and method then
if type(data) ~= "table" then
data = { }
end
return ubus_return(_ubus_connection:call(object, method, data))
elseif object then
return _ubus_connection:signatures(object)
else
return _ubus_connection:objects()
end
end
function serialize_json(x, cb)
local js = json.stringify(x)
if type(cb) == "function" then
cb(js)
else
return js
end
end
function libpath()
return require "nixio.fs".dirname(ldebug.__file__)
end
function checklib(fullpathexe, wantedlib)
local fs = require "nixio.fs"
local haveldd = fs.access('/usr/bin/ldd')
local haveexe = fs.access(fullpathexe)
if not haveldd or not haveexe then
return false
end
local libs = exec(string.format("/usr/bin/ldd %s", shellquote(fullpathexe)))
if not libs then
return false
end
for k, v in ipairs(split(libs)) do
if v:find(wantedlib) then
return true
end
end
return false
end
-------------------------------------------------------------------------------
-- Coroutine safe xpcall and pcall versions
--
-- Encapsulates the protected calls with a coroutine based loop, so errors can
-- be dealed without the usual Lua 5.x pcall/xpcall issues with coroutines
-- yielding inside the call to pcall or xpcall.
--
-- Authors: Roberto Ierusalimschy and Andre Carregal
-- Contributors: Thomas Harning Jr., Ignacio Burgueño, Fabio Mascarenhas
--
-- Copyright 2005 - Kepler Project
--
-- $Id: coxpcall.lua,v 1.13 2008/05/19 19:20:02 mascarenhas Exp $
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Implements xpcall with coroutines
-------------------------------------------------------------------------------
local coromap = setmetatable({}, { __mode = "k" })
local function handleReturnValue(err, co, status, ...)
if not status then
return false, err(debug.traceback(co, (...)), ...)
end
if coroutine.status(co) == 'suspended' then
return performResume(err, co, coroutine.yield(...))
else
return true, ...
end
end
function performResume(err, co, ...)
return handleReturnValue(err, co, coroutine.resume(co, ...))
end
local function id(trace, ...)
return trace
end
function coxpcall(f, err, ...)
local current = coroutine.running()
if not current then
if err == id then
return pcall(f, ...)
else
if select("#", ...) > 0 then
local oldf, params = f, { ... }
f = function() return oldf(unpack(params)) end
end
return xpcall(f, err)
end
else
local res, co = pcall(coroutine.create, f)
if not res then
local newf = function(...) return f(...) end
co = coroutine.create(newf)
end
coromap[co] = current
coxpt[co] = coxpt[current] or current or 0
return performResume(err, co, ...)
end
end
function copcall(f, ...)
return coxpcall(f, id, ...)
end

View file

@ -0,0 +1,512 @@
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.
'use strict';
import { stdin, access, dirname, basename, open, popen, glob, lsdir, readfile, readlink, error } from 'fs';
import { cursor } from 'uci';
import { init_list, init_index, init_enabled, init_action, conntrack_list, process_list } from 'luci.sys';
import { statvfs } from 'luci.core';
import timezones from 'luci.zoneinfo';
function shellquote(s) {
return `'${replace(s, "'", "'\\''")}'`;
}
const methods = {
getInitList: {
args: { name: 'name' },
call: function(request) {
let scripts = {};
for (let name in filter(init_list(), i => !request.args.name || i == request.args.name)) {
let idx = init_index(name);
scripts[name] = {
index: idx[0],
stop: idx[1],
enabled: init_enabled(name)
};
}
return length(scripts) ? scripts : { error: 'No such init script' };
}
},
setInitAction: {
args: { name: 'name', action: 'action' },
call: function(request) {
switch (request.args.action) {
case 'enable':
case 'disable':
case 'start':
case 'stop':
case 'restart':
case 'reload':
const rc = init_action(request.args.name, request.args.action);
if (rc === false)
return { error: 'No such init script' };
return { result: rc == 0 };
default:
return { error: 'Invalid action' };
}
}
},
getLocaltime: {
call: function(request) {
return { result: time() };
}
},
setLocaltime: {
args: { localtime: 0 },
call: function(request) {
let t = localtime(request.args.localtime);
if (t) {
system(sprintf('date -s "%04d-%02d-%02d %02d:%02d:%02d" >/dev/null', t.year, t.mon, t.mday, t.hour, t.min, t.sec));
system('/etc/init.d/sysfixtime restart >/dev/null');
}
return { result: request.args.localtime };
}
},
getTimezones: {
call: function(request) {
let tz = trim(readfile('/etc/TZ'));
let zn = cursor()?.get?.('system', '@system[0]', 'zonename');
let result = {};
for (let zone, tzstring in timezones) {
result[zone] = { tzstring };
if (zn == zone)
result[zone].active = true;
};
return result;
}
},
getLEDs: {
call: function() {
let result = {};
for (let led in lsdir('/sys/class/leds')) {
let s;
result[led] = { triggers: [] };
s = trim(readfile(`/sys/class/leds/${led}/trigger`));
for (let trigger in split(s, ' ')) {
push(result[led].triggers, trim(trigger, '[]'));
if (trigger != result[led].triggers[-1])
result[led].active_trigger = result[led].triggers[-1];
}
s = readfile(`/sys/class/leds/${led}/brightness`);
result[led].brightness = +s;
s = readfile(`/sys/class/leds/${led}/max_brightness`);
result[led].max_brightness = +s;
}
return result;
}
},
getUSBDevices: {
call: function() {
let result = { devices: [], ports: [] };
for (let path in glob('/sys/bus/usb/devices/[0-9]*/manufacturer')) {
let id = basename(dirname(path));
push(result.devices, {
id,
vid: trim(readfile(`/sys/bus/usb/devices/${id}/idVendor`)),
pid: trim(readfile(`/sys/bus/usb/devices/${id}/idProduct`)),
vendor: trim(readfile(path)),
product: trim(readfile(`/sys/bus/usb/devices/${id}/product`)),
speed: +readfile(`/sys/bus/usb/devices/${id}/speed`)
});
}
for (let path in glob('/sys/bus/usb/devices/*/*-port[0-9]*')) {
let port = basename(path);
let link = readlink(`${path}/device`);
push(result.ports, {
port,
device: basename(link)
});
}
return result;
}
},
getConntrackHelpers: {
call: function() {
const uci = cursor();
let helpers = [];
uci.load('/usr/share/firewall4/helpers');
uci.load('/usr/share/fw3/helpers.conf');
uci.foreach('helpers', 'helper', (s) => {
push(helpers, {
name: s.name,
description: s.description,
module: s.module,
family: s.family,
proto: s.proto,
port: s.port
});
});
return { result: helpers };
}
},
getFeatures: {
call: function() {
let result = {
firewall: access('/sbin/fw3') == true,
firewall4: access('/sbin/fw4') == true,
opkg: access('/bin/opkg') == true,
offloading: access('/sys/module/xt_FLOWOFFLOAD/refcnt') == true || access('/sys/module/nft_flow_offload/refcnt') == true,
br2684ctl: access('/usr/sbin/br2684ctl') == true,
swconfig: access('/sbin/swconfig') == true,
odhcpd: access('/usr/sbin/odhcpd') == true,
zram: access('/sys/class/zram-control') == true,
sysntpd: readlink('/usr/sbin/ntpd') != null,
ipv6: access('/proc/net/ipv6_route') == true,
dropbear: access('/usr/sbin/dropbear') == true,
cabundle: access('/etc/ssl/certs/ca-certificates.crt') == true,
relayd: access('/usr/sbin/relayd') == true,
};
const wifi_features = [ 'eap', '11n', '11ac', '11r', 'acs', 'sae', 'owe', 'suiteb192', 'wep', 'wps' ];
if (access('/usr/sbin/hostapd')) {
result.hostapd = { cli: access('/usr/sbin/hostapd_cli') == true };
for (let feature in wifi_features)
result.hostapd[feature] = system(`/usr/sbin/hostapd -v${feature} >/dev/null 2>/dev/null`) == 0;
}
if (access('/usr/sbin/wpa_supplicant')) {
result.wpasupplicant = { cli: access('/usr/sbin/wpa_cli') == true };
for (let feature in wifi_features)
result.wpasupplicant[feature] = system(`/usr/sbin/wpa_supplicant -v${feature} >/dev/null 2>/dev/null`) == 0;
}
let fd = popen('dnsmasq --version 2>/dev/null');
if (fd) {
const m = match(fd.read('all'), /^Compile time options: (.+)$/s);
for (let opt in split(m?.[1], ' ')) {
let f = replace(opt, 'no-', '', 1);
result.dnsmasq ??= {};
result.dnsmasq[lc(f)] = (f == opt);
}
fd.close();
}
fd = popen('ipset --help 2>/dev/null');
if (fd) {
for (let line = fd.read('line'), flag = false; length(line); line = fd.read('line')) {
if (line == 'Supported set types:\n') {
flag = true;
}
else if (flag) {
const m = match(line, /^ +([\w:,]+)\t+([0-9]+)\t/);
if (m) {
result.ipset ??= {};
result.ipset[m[1]] ??= +m[2];
}
}
}
fd.close();
}
return result;
}
},
getSwconfigFeatures: {
args: { switch: 'switch0' },
call: function(request) {
// Parse some common switch properties from swconfig help output.
const swc = popen(`swconfig dev ${shellquote(request.args.switch)} help 2>/dev/null`);
if (swc) {
let is_port_attr = false;
let is_vlan_attr = false;
let result = {};
for (let line = swc.read('line'); length(line); line = swc.read('line')) {
if (match(line, /^\s+--vlan/)) {
is_vlan_attr = true;
}
else if (match(line, /^\s+--port/)) {
is_vlan_attr = false;
is_port_attr = true;
}
else if (match(line, /cpu @/)) {
result.switch_title = match(line, /^switch[0-9]+: \w+\((.+)\)/)?.[1];
result.num_vlans = match(line, /vlans: ([0-9]+)/)?.[1] ?? 16;
result.min_vid = 1;
}
else if (match(line, /: (pvid|tag|vid)/)) {
if (is_vlan_attr)
result.vid_option = match(line, /: (\w+)/)?.[1];
}
else if (match(line, /: enable_vlan4k/)) {
result.vlan4k_option = 'enable_vlan4k';
}
else if (match(line, /: enable_vlan/)) {
result.vlan_option = 'enable_vlan';
}
else if (match(line, /: enable_learning/)) {
result.learning_option = 'enable_learning';
}
else if (match(line, /: enable_mirror_rx/)) {
result.mirror_option = 'enable_mirror_rx';
}
else if (match(line, /: max_length/)) {
result.jumbo_option = 'max_length';
}
}
swc.close();
if (!length(result))
return { error: 'No such switch' };
return result;
}
else {
return { error: error() };
}
}
},
getSwconfigPortState: {
args: { switch: 'switch0' },
call: function(request) {
const swc = popen(`swconfig dev ${shellquote(request.args.switch)} show 2>/dev/null`);
if (swc) {
let ports = [], port;
for (let line = swc.read('line'); length(line); line = swc.read('line')) {
if (match(line, /^VLAN [0-9]+:/) && length(ports))
break;
let pnum = match(line, /^Port ([0-9]+):/)?.[1];
if (pnum) {
port = {
port: +pnum,
duplex: false,
speed: 0,
link: false,
auto: false,
rxflow: false,
txflow: false
};
push(ports, port);
}
if (port) {
let m;
if (match(line, /full[ -]duplex/))
port.duplex = true;
if ((m = match(line, / speed:([0-9]+)/)) != null)
port.speed = +m[1];
if ((m = match(line, /([0-9]+) Mbps/)) != null && !port.speed)
port.speed = +m[1];
if ((m = match(line, /link: ([0-9]+)/)) != null && !port.speed)
port.speed = +m[1];
if (match(line, /(link|status): ?up/))
port.link = true;
if (match(line, /auto-negotiate|link:.*auto/))
port.auto = true;
if (match(line, /link:.*rxflow/))
port.rxflow = true;
if (match(line, /link:.*txflow/))
port.txflow = true;
}
}
swc.close();
if (!length(ports))
return { error: 'No such switch' };
return { result: ports };
}
else {
return { error: error() };
}
}
},
setPassword: {
args: { username: 'root', password: 'password' },
call: function(request) {
const u = shellquote(request.args.username);
const p = shellquote(request.args.password);
return {
result: system(`(echo ${p}; sleep 1; echo ${p}) | /bin/busybox passwd ${u} >/dev/null 2>&1`) == 0
};
}
},
getBlockDevices: {
call: function() {
const block = popen('/sbin/block info 2>/dev/null');
if (block) {
let result = {};
for (let line = block.read('line'); length(line); line = block.read('line')) {
let dev = match(line, /^\/dev\/([^:]+):/)?.[1];
if (dev) {
let e = result[dev] = {
dev: `/dev/${dev}`,
size: +readfile(`/sys/class/block/${dev}/size`) * 512
};
for (m in match(line, / (\w+)="([^"]+)"/g))
e[lc(m[1])] = m[2];
}
}
block.close();
return result;
}
else {
return { error: 'Unable to execute block utility' };
}
}
},
setBlockDetect: {
call: function() {
return { result: system('/sbin/block detect > /etc/config/fstab') == 0 };
}
},
getMountPoints: {
call: function() {
const fd = open('/proc/mounts', 'r');
if (fd) {
let result = [];
for (let line = fd.read('line'); length(line); line = fd.read('line')) {
const m = split(line, ' ');
const device = replace(m[0], /\\([0-9][0-9][0-9])/g, (m, n) => char(int(n, 8)));
const mount = replace(m[1], /\\([0-9][0-9][0-9])/g, (m, n) => char(int(n, 8)));
const stat = statvfs(mount);
if (stat?.blocks > 0) {
push(result, {
device, mount,
size: stat.bsize * stat.blocks,
avail: stat.bsize * stat.bavail,
free: stat.bsize * stat.bfree
});
}
}
fd.close();
return { result };
}
else {
return { error: error() };
}
}
},
getRealtimeStats: {
args: { mode: 'interface', device: 'eth0' },
call: function(request) {
let flags;
if (request.args.mode == 'interface')
flags = `-i ${shellquote(request.args.device)}`;
else if (request.args.mode == 'wireless')
flags = `-r ${shellquote(request.args.device)}`;
else if (request.args.mode == 'conntrack')
flags = '-c';
else if (request.args.mode == 'load')
flags = '-l';
else
return { error: 'Invalid mode' };
const fd = popen(`luci-bwc ${flags}`, 'r');
if (fd) {
let result;
try {
result = { result: json(`[${fd.read('all')}]`) };
}
catch (err) {
result = { error: err };
}
return result;
}
else {
return { error: error() };
}
}
},
getConntrackList: {
call: function() {
return { result: conntrack_list() };
}
},
getProcessList: {
call: function() {
return { result: process_list() };
}
}
};
return { luci: methods };

View file

@ -0,0 +1,28 @@
%.o: %.c
$(CC) $(CPPFLAGS) $(CFLAGS) $(FPIC) -DNDEBUG -c -o $@ $<
contrib/lemon: contrib/lemon.c contrib/lempar.c
cc -o contrib/lemon $<
lib/plural_formula.c: lib/plural_formula.y contrib/lemon
./contrib/lemon -q $<
lib/lmo.c: lib/plural_formula.c
core.so: lib/luci.o lib/lmo.o lib/plural_formula.o
$(CC) $(LDFLAGS) -shared -o $@ $^
version.uc:
echo "export const revision = '$(LUCI_VERSION)', branch = '$(LUCI_GITBRANCH)';" > $@
clean:
rm -f contrib/lemon lib/*.o lib/plural_formula.c lib/plural_formula.h core.so version.uc
compile: core.so version.uc
install: compile
mkdir -p $(DESTDIR)/usr/lib/ucode/luci
cp core.so $(DESTDIR)/usr/lib/ucode/luci/core.so
mkdir -p $(DESTDIR)/usr/share/ucode/luci
cp version.uc $(DESTDIR)/usr/share/ucode/luci/version.uc

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,851 @@
/* Driver template for the LEMON parser generator.
** The author disclaims copyright to this source code.
*/
/* First off, code is included that follows the "include" declaration
** in the input grammar file. */
#include <stdio.h>
%%
/* Next is all token values, in a form suitable for use by makeheaders.
** This section will be null unless lemon is run with the -m switch.
*/
/*
** These constants (all generated automatically by the parser generator)
** specify the various kinds of tokens (terminals) that the parser
** understands.
**
** Each symbol here is a terminal symbol in the grammar.
*/
%%
/* Make sure the INTERFACE macro is defined.
*/
#ifndef INTERFACE
# define INTERFACE 1
#endif
/* The next thing included is series of defines which control
** various aspects of the generated parser.
** YYCODETYPE is the data type used for storing terminal
** and nonterminal numbers. "unsigned char" is
** used if there are fewer than 250 terminals
** and nonterminals. "int" is used otherwise.
** YYNOCODE is a number of type YYCODETYPE which corresponds
** to no legal terminal or nonterminal number. This
** number is used to fill in empty slots of the hash
** table.
** YYFALLBACK If defined, this indicates that one or more tokens
** have fall-back values which should be used if the
** original value of the token will not parse.
** YYACTIONTYPE is the data type used for storing terminal
** and nonterminal numbers. "unsigned char" is
** used if there are fewer than 250 rules and
** states combined. "int" is used otherwise.
** ParseTOKENTYPE is the data type used for minor tokens given
** directly to the parser from the tokenizer.
** YYMINORTYPE is the data type used for all minor tokens.
** This is typically a union of many types, one of
** which is ParseTOKENTYPE. The entry in the union
** for base tokens is called "yy0".
** YYSTACKDEPTH is the maximum depth of the parser's stack. If
** zero the stack is dynamically sized using realloc()
** ParseARG_SDECL A static variable declaration for the %extra_argument
** ParseARG_PDECL A parameter declaration for the %extra_argument
** ParseARG_STORE Code to store %extra_argument into yypParser
** ParseARG_FETCH Code to extract %extra_argument from yypParser
** YYNSTATE the combined number of states.
** YYNRULE the number of rules in the grammar
** YYERRORSYMBOL is the code number of the error symbol. If not
** defined, then do no error processing.
*/
%%
#define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
#define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
/* The yyzerominor constant is used to initialize instances of
** YYMINORTYPE objects to zero. */
static const YYMINORTYPE yyzerominor = { 0 };
/* Define the yytestcase() macro to be a no-op if is not already defined
** otherwise.
**
** Applications can choose to define yytestcase() in the %include section
** to a macro that can assist in verifying code coverage. For production
** code the yytestcase() macro should be turned off. But it is useful
** for testing.
*/
#ifndef yytestcase
# define yytestcase(X)
#endif
/* Next are the tables used to determine what action to take based on the
** current state and lookahead token. These tables are used to implement
** functions that take a state number and lookahead value and return an
** action integer.
**
** Suppose the action integer is N. Then the action is determined as
** follows
**
** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
** token onto the stack and goto state N.
**
** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
**
** N == YYNSTATE+YYNRULE A syntax error has occurred.
**
** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
**
** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
** slots in the yy_action[] table.
**
** The action table is constructed as a single large table named yy_action[].
** Given state S and lookahead X, the action is computed as
**
** yy_action[ yy_shift_ofst[S] + X ]
**
** If the index value yy_shift_ofst[S]+X is out of range or if the value
** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
** and that yy_default[S] should be used instead.
**
** The formula above is for computing the action when the lookahead is
** a terminal symbol. If the lookahead is a non-terminal (as occurs after
** a reduce action) then the yy_reduce_ofst[] array is used in place of
** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
** YY_SHIFT_USE_DFLT.
**
** The following are the tables generated in this section:
**
** yy_action[] A single table containing all actions.
** yy_lookahead[] A table containing the lookahead for each entry in
** yy_action. Used to detect hash collisions.
** yy_shift_ofst[] For each state, the offset into yy_action for
** shifting terminals.
** yy_reduce_ofst[] For each state, the offset into yy_action for
** shifting non-terminals after a reduce.
** yy_default[] Default action for each state.
*/
%%
/* The next table maps tokens into fallback tokens. If a construct
** like the following:
**
** %fallback ID X Y Z.
**
** appears in the grammar, then ID becomes a fallback token for X, Y,
** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
** but it does not parse, the type of the token is changed to ID and
** the parse is retried before an error is thrown.
*/
#ifdef YYFALLBACK
static const YYCODETYPE yyFallback[] = {
%%
};
#endif /* YYFALLBACK */
/* The following structure represents a single element of the
** parser's stack. Information stored includes:
**
** + The state number for the parser at this level of the stack.
**
** + The value of the token stored at this level of the stack.
** (In other words, the "major" token.)
**
** + The semantic value stored at this level of the stack. This is
** the information used by the action routines in the grammar.
** It is sometimes called the "minor" token.
*/
struct yyStackEntry {
YYACTIONTYPE stateno; /* The state-number */
YYCODETYPE major; /* The major token value. This is the code
** number for the token at this stack level */
YYMINORTYPE minor; /* The user-supplied minor token value. This
** is the value of the token */
};
typedef struct yyStackEntry yyStackEntry;
/* The state of the parser is completely contained in an instance of
** the following structure */
struct yyParser {
int yyidx; /* Index of top element in stack */
#ifdef YYTRACKMAXSTACKDEPTH
int yyidxMax; /* Maximum value of yyidx */
#endif
int yyerrcnt; /* Shifts left before out of the error */
ParseARG_SDECL /* A place to hold %extra_argument */
#if YYSTACKDEPTH<=0
int yystksz; /* Current side of the stack */
yyStackEntry *yystack; /* The parser's stack */
#else
yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
#endif
};
typedef struct yyParser yyParser;
#ifndef NDEBUG
#include <stdio.h>
static FILE *yyTraceFILE = 0;
static char *yyTracePrompt = 0;
#endif /* NDEBUG */
#ifndef NDEBUG
/*
** Turn parser tracing on by giving a stream to which to write the trace
** and a prompt to preface each trace message. Tracing is turned off
** by making either argument NULL
**
** Inputs:
** <ul>
** <li> A FILE* to which trace output should be written.
** If NULL, then tracing is turned off.
** <li> A prefix string written at the beginning of every
** line of trace output. If NULL, then tracing is
** turned off.
** </ul>
**
** Outputs:
** None.
*/
void ParseTrace(FILE *TraceFILE, char *zTracePrompt);
void ParseTrace(FILE *TraceFILE, char *zTracePrompt){
yyTraceFILE = TraceFILE;
yyTracePrompt = zTracePrompt;
if( yyTraceFILE==0 ) yyTracePrompt = 0;
else if( yyTracePrompt==0 ) yyTraceFILE = 0;
}
#endif /* NDEBUG */
#ifndef NDEBUG
/* For tracing shifts, the names of all terminals and nonterminals
** are required. The following table supplies these names */
static const char *const yyTokenName[] = {
%%
};
#endif /* NDEBUG */
#ifndef NDEBUG
/* For tracing reduce actions, the names of all rules are required.
*/
static const char *const yyRuleName[] = {
%%
};
#endif /* NDEBUG */
#if YYSTACKDEPTH<=0
/*
** Try to increase the size of the parser stack.
*/
static void yyGrowStack(yyParser *p){
int newSize;
yyStackEntry *pNew;
newSize = p->yystksz*2 + 100;
pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
if( pNew ){
p->yystack = pNew;
p->yystksz = newSize;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
yyTracePrompt, p->yystksz);
}
#endif
}
}
#endif
/*
** This function allocates a new parser.
** The only argument is a pointer to a function which works like
** malloc.
**
** Inputs:
** A pointer to the function used to allocate memory.
**
** Outputs:
** A pointer to a parser. This pointer is used in subsequent calls
** to Parse and ParseFree.
*/
void *ParseAlloc(void *(*mallocProc)(size_t)){
yyParser *pParser;
pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
if( pParser ){
pParser->yyidx = -1;
#ifdef YYTRACKMAXSTACKDEPTH
pParser->yyidxMax = 0;
#endif
#if YYSTACKDEPTH<=0
pParser->yystack = NULL;
pParser->yystksz = 0;
yyGrowStack(pParser);
#endif
}
return pParser;
}
/* The following function deletes the value associated with a
** symbol. The symbol can be either a terminal or nonterminal.
** "yymajor" is the symbol code, and "yypminor" is a pointer to
** the value.
*/
static void yy_destructor(
yyParser *yypParser, /* The parser */
YYCODETYPE yymajor, /* Type code for object to destroy */
YYMINORTYPE *yypminor /* The object to be destroyed */
){
ParseARG_FETCH;
switch( yymajor ){
/* Here is inserted the actions which take place when a
** terminal or non-terminal is destroyed. This can happen
** when the symbol is popped from the stack during a
** reduce or during error processing or when a parser is
** being destroyed before it is finished parsing.
**
** Note: during a reduce, the only symbols destroyed are those
** which appear on the RHS of the rule, but which are not used
** inside the C code.
*/
%%
default: break; /* If no destructor action specified: do nothing */
}
}
/*
** Pop the parser's stack once.
**
** If there is a destructor routine associated with the token which
** is popped from the stack, then call it.
**
** Return the major token number for the symbol popped.
*/
static int yy_pop_parser_stack(yyParser *pParser){
YYCODETYPE yymajor;
yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
if( pParser->yyidx<0 ) return 0;
#ifndef NDEBUG
if( yyTraceFILE && pParser->yyidx>=0 ){
fprintf(yyTraceFILE,"%sPopping %s\n",
yyTracePrompt,
yyTokenName[yytos->major]);
}
#endif
yymajor = yytos->major;
yy_destructor(pParser, yymajor, &yytos->minor);
pParser->yyidx--;
return yymajor;
}
/*
** Deallocate and destroy a parser. Destructors are all called for
** all stack elements before shutting the parser down.
**
** Inputs:
** <ul>
** <li> A pointer to the parser. This should be a pointer
** obtained from ParseAlloc.
** <li> A pointer to a function used to reclaim memory obtained
** from malloc.
** </ul>
*/
void ParseFree(
void *p, /* The parser to be deleted */
void (*freeProc)(void*) /* Function used to reclaim memory */
){
yyParser *pParser = (yyParser*)p;
if( pParser==0 ) return;
while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
#if YYSTACKDEPTH<=0
free(pParser->yystack);
#endif
(*freeProc)((void*)pParser);
}
/*
** Return the peak depth of the stack for a parser.
*/
#ifdef YYTRACKMAXSTACKDEPTH
int ParseStackPeak(void *p){
yyParser *pParser = (yyParser*)p;
return pParser->yyidxMax;
}
#endif
/*
** Find the appropriate action for a parser given the terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead. If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_shift_action(
yyParser *pParser, /* The parser */
YYCODETYPE iLookAhead /* The look-ahead token */
){
int i;
int stateno = pParser->yystack[pParser->yyidx].stateno;
if( stateno>YY_SHIFT_COUNT
|| (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
return yy_default[stateno];
}
assert( iLookAhead!=YYNOCODE );
i += iLookAhead;
if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
if( iLookAhead>0 ){
#ifdef YYFALLBACK
YYCODETYPE iFallback; /* Fallback token */
if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
&& (iFallback = yyFallback[iLookAhead])!=0 ){
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
}
#endif
return yy_find_shift_action(pParser, iFallback);
}
#endif
#ifdef YYWILDCARD
{
int j = i - iLookAhead + YYWILDCARD;
if(
#if YY_SHIFT_MIN+YYWILDCARD<0
j>=0 &&
#endif
#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
j<YY_ACTTAB_COUNT &&
#endif
yy_lookahead[j]==YYWILDCARD
){
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
}
#endif /* NDEBUG */
return yy_action[j];
}
}
#endif /* YYWILDCARD */
}
return yy_default[stateno];
}else{
return yy_action[i];
}
}
/*
** Find the appropriate action for a parser given the non-terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead. If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_reduce_action(
int stateno, /* Current state number */
YYCODETYPE iLookAhead /* The look-ahead token */
){
int i;
#ifdef YYERRORSYMBOL
if( stateno>YY_REDUCE_COUNT ){
return yy_default[stateno];
}
#else
assert( stateno<=YY_REDUCE_COUNT );
#endif
i = yy_reduce_ofst[stateno];
assert( i!=YY_REDUCE_USE_DFLT );
assert( iLookAhead!=YYNOCODE );
i += iLookAhead;
#ifdef YYERRORSYMBOL
if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
return yy_default[stateno];
}
#else
assert( i>=0 && i<YY_ACTTAB_COUNT );
assert( yy_lookahead[i]==iLookAhead );
#endif
return yy_action[i];
}
/*
** The following routine is called if the stack overflows.
*/
static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
ParseARG_FETCH;
yypParser->yyidx--;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
}
#endif
while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
/* Here code is inserted which will execute if the parser
** stack every overflows */
%%
ParseARG_STORE; /* Suppress warning about unused %extra_argument var */
}
/*
** Perform a shift action.
*/
static void yy_shift(
yyParser *yypParser, /* The parser to be shifted */
int yyNewState, /* The new state to shift in */
int yyMajor, /* The major token to shift in */
YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
){
yyStackEntry *yytos;
yypParser->yyidx++;
#ifdef YYTRACKMAXSTACKDEPTH
if( yypParser->yyidx>yypParser->yyidxMax ){
yypParser->yyidxMax = yypParser->yyidx;
}
#endif
#if YYSTACKDEPTH>0
if( yypParser->yyidx>=YYSTACKDEPTH ){
yyStackOverflow(yypParser, yypMinor);
return;
}
#else
if( yypParser->yyidx>=yypParser->yystksz ){
yyGrowStack(yypParser);
if( yypParser->yyidx>=yypParser->yystksz ){
yyStackOverflow(yypParser, yypMinor);
return;
}
}
#endif
yytos = &yypParser->yystack[yypParser->yyidx];
yytos->stateno = (YYACTIONTYPE)yyNewState;
yytos->major = (YYCODETYPE)yyMajor;
yytos->minor = *yypMinor;
#ifndef NDEBUG
if( yyTraceFILE && yypParser->yyidx>0 ){
int i;
fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
for(i=1; i<=yypParser->yyidx; i++)
fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
fprintf(yyTraceFILE,"\n");
}
#endif
}
/* The following table contains information about every rule that
** is used during the reduce.
*/
static const struct {
YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
unsigned char nrhs; /* Number of right-hand side symbols in the rule */
} yyRuleInfo[] = {
%%
};
static void yy_accept(yyParser*); /* Forward Declaration */
/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.
*/
static void yy_reduce(
yyParser *yypParser, /* The parser */
int yyruleno /* Number of the rule by which to reduce */
){
int yygoto; /* The next state */
int yyact; /* The next action */
YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
yyStackEntry *yymsp; /* The top of the parser's stack */
int yysize; /* Amount to pop the stack */
ParseARG_FETCH;
yymsp = &yypParser->yystack[yypParser->yyidx];
#ifndef NDEBUG
if( yyTraceFILE && yyruleno>=0
&& yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
yyRuleName[yyruleno]);
}
#endif /* NDEBUG */
/* Silence complaints from purify about yygotominor being uninitialized
** in some cases when it is copied into the stack after the following
** switch. yygotominor is uninitialized when a rule reduces that does
** not set the value of its left-hand side nonterminal. Leaving the
** value of the nonterminal uninitialized is utterly harmless as long
** as the value is never used. So really the only thing this code
** accomplishes is to quieten purify.
**
** 2007-01-16: The wireshark project (www.wireshark.org) reports that
** without this code, their parser segfaults. I'm not sure what there
** parser is doing to make this happen. This is the second bug report
** from wireshark this week. Clearly they are stressing Lemon in ways
** that it has not been previously stressed... (SQLite ticket #2172)
*/
/*memset(&yygotominor, 0, sizeof(yygotominor));*/
yygotominor = yyzerominor;
switch( yyruleno ){
/* Beginning here are the reduction cases. A typical example
** follows:
** case 0:
** #line <lineno> <grammarfile>
** { ... } // User supplied code
** #line <lineno> <thisfile>
** break;
*/
%%
};
yygoto = yyRuleInfo[yyruleno].lhs;
yysize = yyRuleInfo[yyruleno].nrhs;
yypParser->yyidx -= yysize;
yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
if( yyact < YYNSTATE ){
#ifdef NDEBUG
/* If we are not debugging and the reduce action popped at least
** one element off the stack, then we can push the new element back
** onto the stack here, and skip the stack overflow test in yy_shift().
** That gives a significant speed improvement. */
if( yysize ){
yypParser->yyidx++;
yymsp -= yysize-1;
yymsp->stateno = (YYACTIONTYPE)yyact;
yymsp->major = (YYCODETYPE)yygoto;
yymsp->minor = yygotominor;
}else
#endif
{
yy_shift(yypParser,yyact,yygoto,&yygotominor);
}
}else{
assert( yyact == YYNSTATE + YYNRULE + 1 );
yy_accept(yypParser);
}
}
/*
** The following code executes when the parse fails
*/
#ifndef YYNOERRORRECOVERY
static void yy_parse_failed(
yyParser *yypParser /* The parser */
){
ParseARG_FETCH;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
}
#endif
while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
/* Here code is inserted which will be executed whenever the
** parser fails */
%%
ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
#endif /* YYNOERRORRECOVERY */
/*
** The following code executes when a syntax error first occurs.
*/
static void yy_syntax_error(
yyParser *yypParser, /* The parser */
int yymajor, /* The major type of the error token */
YYMINORTYPE yyminor /* The minor type of the error token */
){
ParseARG_FETCH;
#define TOKEN (yyminor.yy0)
%%
ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
/*
** The following is executed when the parser accepts
*/
static void yy_accept(
yyParser *yypParser /* The parser */
){
ParseARG_FETCH;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
}
#endif
while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
/* Here code is inserted which will be executed whenever the
** parser accepts */
%%
ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
/* The main parser program.
** The first argument is a pointer to a structure obtained from
** "ParseAlloc" which describes the current state of the parser.
** The second argument is the major token number. The third is
** the minor token. The fourth optional argument is whatever the
** user wants (and specified in the grammar) and is available for
** use by the action routines.
**
** Inputs:
** <ul>
** <li> A pointer to the parser (an opaque structure.)
** <li> The major token number.
** <li> The minor token number.
** <li> An option argument of a grammar-specified type.
** </ul>
**
** Outputs:
** None.
*/
void Parse(
void *yyp, /* The parser */
int yymajor, /* The major token code number */
ParseTOKENTYPE yyminor /* The value for the token */
ParseARG_PDECL /* Optional %extra_argument parameter */
){
YYMINORTYPE yyminorunion;
int yyact; /* The parser action. */
int yyendofinput; /* True if we are at the end of input */
#ifdef YYERRORSYMBOL
int yyerrorhit = 0; /* True if yymajor has invoked an error */
#endif
yyParser *yypParser; /* The parser */
/* (re)initialize the parser, if necessary */
yypParser = (yyParser*)yyp;
if( yypParser->yyidx<0 ){
#if YYSTACKDEPTH<=0
if( yypParser->yystksz <=0 ){
/*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
yyminorunion = yyzerominor;
yyStackOverflow(yypParser, &yyminorunion);
return;
}
#endif
yypParser->yyidx = 0;
yypParser->yyerrcnt = -1;
yypParser->yystack[0].stateno = 0;
yypParser->yystack[0].major = 0;
}
yyminorunion.yy0 = yyminor;
yyendofinput = (yymajor==0);
ParseARG_STORE;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
}
#endif
do{
yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
if( yyact<YYNSTATE ){
assert( !yyendofinput ); /* Impossible to shift the $ token */
yy_shift(yypParser,yyact,yymajor,&yyminorunion);
yypParser->yyerrcnt--;
yymajor = YYNOCODE;
}else if( yyact < YYNSTATE + YYNRULE ){
yy_reduce(yypParser,yyact-YYNSTATE);
}else{
assert( yyact == YY_ERROR_ACTION );
#ifdef YYERRORSYMBOL
int yymx;
#endif
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
}
#endif
#ifdef YYERRORSYMBOL
/* A syntax error has occurred.
** The response to an error depends upon whether or not the
** grammar defines an error token "ERROR".
**
** This is what we do if the grammar does define ERROR:
**
** * Call the %syntax_error function.
**
** * Begin popping the stack until we enter a state where
** it is legal to shift the error symbol, then shift
** the error symbol.
**
** * Set the error count to three.
**
** * Begin accepting and shifting new tokens. No new error
** processing will occur until three tokens have been
** shifted successfully.
**
*/
if( yypParser->yyerrcnt<0 ){
yy_syntax_error(yypParser,yymajor,yyminorunion);
}
yymx = yypParser->yystack[yypParser->yyidx].major;
if( yymx==YYERRORSYMBOL || yyerrorhit ){
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sDiscard input token %s\n",
yyTracePrompt,yyTokenName[yymajor]);
}
#endif
yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
yymajor = YYNOCODE;
}else{
while(
yypParser->yyidx >= 0 &&
yymx != YYERRORSYMBOL &&
(yyact = yy_find_reduce_action(
yypParser->yystack[yypParser->yyidx].stateno,
YYERRORSYMBOL)) >= YYNSTATE
){
yy_pop_parser_stack(yypParser);
}
if( yypParser->yyidx < 0 || yymajor==0 ){
yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
yy_parse_failed(yypParser);
yymajor = YYNOCODE;
}else if( yymx!=YYERRORSYMBOL ){
YYMINORTYPE u2;
u2.YYERRSYMDT = 0;
yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
}
}
yypParser->yyerrcnt = 3;
yyerrorhit = 1;
#elif defined(YYNOERRORRECOVERY)
/* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
** do any kind of error recovery. Instead, simply invoke the syntax
** error routine and continue going as if nothing had happened.
**
** Applications can set this macro (for example inside %include) if
** they intend to abandon the parse upon the first syntax error seen.
*/
yy_syntax_error(yypParser,yymajor,yyminorunion);
yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
yymajor = YYNOCODE;
#else /* YYERRORSYMBOL is not defined */
/* This is what we do if the grammar does not define ERROR:
**
** * Report an error message, and throw away the input token.
**
** * If the input token is $, then fail the parse.
**
** As before, subsequent error messages are suppressed until
** three input tokens have been successfully shifted.
*/
if( yypParser->yyerrcnt<=0 ){
yy_syntax_error(yypParser,yymajor,yyminorunion);
}
yypParser->yyerrcnt = 3;
yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
if( yyendofinput ){
yy_parse_failed(yypParser);
}
yymajor = YYNOCODE;
#endif
}
}while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
return;
}

View file

@ -0,0 +1,636 @@
/*
* lmo - Lua Machine Objects - Base functions
*
* Copyright (C) 2009-2010 Jo-Philipp Wich <jow@openwrt.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lmo.h"
#include "plural_formula.h"
/*
* Hash function from http://www.azillionmonkeys.com/qed/hash.html
* Copyright (C) 2004-2008 by Paul Hsieh
*/
uint32_t sfh_hash(const char *data, size_t len, uint32_t init)
{
uint32_t hash = init, tmp;
int rem;
if (len <= 0 || data == NULL) return 0;
rem = len & 3;
len >>= 2;
/* Main loop */
for (;len > 0; len--) {
hash += sfh_get16(data);
tmp = (sfh_get16(data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof(uint16_t);
hash += hash >> 11;
}
/* Handle end cases */
switch (rem) {
case 3: hash += sfh_get16(data);
hash ^= hash << 16;
hash ^= (signed char)data[sizeof(uint16_t)] << 18;
hash += hash >> 11;
break;
case 2: hash += sfh_get16(data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += (signed char)*data;
hash ^= hash << 10;
hash += hash >> 1;
}
/* Force "avalanching" of final 127 bits */
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
uint32_t lmo_canon_hash(const char *str, int len,
const char *ctx, int ctxlen, int plural)
{
char res[4096];
char *ptr, *end, prev;
int off;
if (!str)
return 0;
ptr = res;
end = res + sizeof(res);
if (ctx)
{
for (prev = ' ', off = 0; off < ctxlen; prev = *ctx, off++, ctx++)
{
if (ptr >= end)
return 0;
if (isspace(*ctx))
{
if (!isspace(prev))
*ptr++ = ' ';
}
else
{
*ptr++ = *ctx;
}
}
if ((ptr > res) && isspace(*(ptr-1)))
ptr--;
if (ptr >= end)
return 0;
*ptr++ = '\1';
}
for (prev = ' ', off = 0; off < len; prev = *str, off++, str++)
{
if (ptr >= end)
return 0;
if (isspace(*str))
{
if (!isspace(prev))
*ptr++ = ' ';
}
else
{
*ptr++ = *str;
}
}
if ((ptr > res) && isspace(*(ptr-1)))
ptr--;
if (plural > -1)
{
if (plural >= 100 || ptr + 3 >= end)
return 0;
ptr += snprintf(ptr, 3, "\2%d", plural);
}
return sfh_hash(res, ptr - res, ptr - res);
}
lmo_archive_t * lmo_open(const char *file)
{
int in = -1;
uint32_t idx_offset = 0;
struct stat s;
lmo_archive_t *ar = NULL;
if (stat(file, &s) == -1)
goto err;
if ((in = open(file, O_RDONLY)) == -1)
goto err;
if ((ar = (lmo_archive_t *)malloc(sizeof(*ar))) != NULL)
{
memset(ar, 0, sizeof(*ar));
ar->fd = in;
ar->size = s.st_size;
fcntl(ar->fd, F_SETFD, fcntl(ar->fd, F_GETFD) | FD_CLOEXEC);
if ((ar->mmap = mmap(NULL, ar->size, PROT_READ, MAP_SHARED, ar->fd, 0)) == MAP_FAILED)
goto err;
idx_offset = ntohl(*((const uint32_t *)
(ar->mmap + ar->size - sizeof(uint32_t))));
if (idx_offset >= ar->size)
goto err;
ar->index = (lmo_entry_t *)(ar->mmap + idx_offset);
ar->length = (ar->size - idx_offset - sizeof(uint32_t)) / sizeof(lmo_entry_t);
ar->end = ar->mmap + ar->size;
return ar;
}
err:
if (in > -1)
close(in);
if (ar != NULL)
{
if ((ar->mmap != NULL) && (ar->mmap != MAP_FAILED))
munmap(ar->mmap, ar->size);
free(ar);
}
return NULL;
}
void lmo_close(lmo_archive_t *ar)
{
if (ar != NULL)
{
if ((ar->mmap != NULL) && (ar->mmap != MAP_FAILED))
munmap(ar->mmap, ar->size);
close(ar->fd);
free(ar);
ar = NULL;
}
}
lmo_catalog_t *_lmo_catalogs = NULL;
lmo_catalog_t *_lmo_active_catalog = NULL;
int lmo_load_catalog(const char *lang, const char *dir)
{
DIR *dh = NULL;
char pattern[16];
char path[PATH_MAX];
struct dirent *de = NULL;
lmo_archive_t *ar = NULL;
lmo_catalog_t *cat = NULL;
if (!lmo_change_catalog(lang))
return 0;
if (!dir || !(dh = opendir(dir)))
goto err;
if (!(cat = malloc(sizeof(*cat))))
goto err;
memset(cat, 0, sizeof(*cat));
snprintf(cat->lang, sizeof(cat->lang), "%s", lang);
snprintf(pattern, sizeof(pattern), "*.%s.lmo", lang);
while ((de = readdir(dh)) != NULL)
{
if (!fnmatch(pattern, de->d_name, 0))
{
snprintf(path, sizeof(path), "%s/%s", dir, de->d_name);
ar = lmo_open(path);
if (ar)
{
ar->next = cat->archives;
cat->archives = ar;
}
}
}
closedir(dh);
cat->next = _lmo_catalogs;
_lmo_catalogs = cat;
if (!_lmo_active_catalog)
_lmo_active_catalog = cat;
return cat->archives ? 0 : -1;
err:
if (dh) closedir(dh);
if (cat) free(cat);
return -1;
}
int lmo_change_catalog(const char *lang)
{
lmo_catalog_t *cat;
for (cat = _lmo_catalogs; cat; cat = cat->next)
{
if (!strncmp(cat->lang, lang, sizeof(cat->lang)))
{
_lmo_active_catalog = cat;
return 0;
}
}
return -1;
}
static lmo_entry_t * lmo_find_entry(lmo_archive_t *ar, uint32_t hash)
{
unsigned int m, l, r;
uint32_t k;
l = 0;
r = ar->length - 1;
while (1)
{
m = l + ((r - l) / 2);
if (r < l)
break;
k = ntohl(ar->index[m].key_id);
if (k == hash)
return &ar->index[m];
if (k > hash)
{
if (!m)
break;
r = m - 1;
}
else
{
l = m + 1;
}
}
return NULL;
}
void *pluralParseAlloc(void *(*)(size_t));
void pluralParse(void *, int, int, void *);
void pluralParseFree(void *, void (*)(void *));
static int lmo_eval_plural(const char *expr, int len, int val)
{
struct { int num; int res; } s = { .num = val, .res = -1 };
const char *p = NULL;
void *pParser = NULL;
int t, n;
char c;
while (len > 7) {
if (*expr == 'p') {
if (!strncmp(expr, "plural=", 7)) {
p = expr + 7;
len -= 7;
break;
}
}
expr++;
len--;
}
if (!p)
goto out;
pParser = pluralParseAlloc(malloc);
if (!pParser)
goto out;
while (len-- > 0) {
c = *p++;
t = -1;
n = 0;
switch (c) {
case ' ':
case '\t':
continue;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
t = T_NUM;
n = c - '0';
while (*p >= '0' && *p <= '9') {
n *= 10;
n += *p - '0';
p++;
}
break;
case '=':
if (*p == '=') {
t = T_EQ;
p++;
}
break;
case '!':
if (*p == '=') {
t = T_NE;
p++;
}
else {
t = T_NOT;
}
break;
case '&':
if (*p == '&') {
t = T_AND;
p++;
}
break;
case '|':
if (*p == '|') {
t = T_OR;
p++;
}
break;
case '<':
if (*p == '=') {
t = T_LE;
p++;
}
else {
t = T_LT;
}
break;
case '>':
if (*p == '=') {
t = T_GE;
p++;
}
else {
t = T_GT;
}
break;
case '*':
t = T_MUL;
break;
case '/':
t = T_DIV;
break;
case '%':
t = T_MOD;
break;
case '+':
t = T_ADD;
break;
case '-':
t = T_SUB;
break;
case 'n':
t = T_N;
break;
case '?':
t = T_QMARK;
break;
case ':':
t = T_COLON;
break;
case '(':
t = T_LPAREN;
break;
case ')':
t = T_RPAREN;
break;
case ';':
case '\n':
case '\0':
t = 0;
break;
}
/* syntax error */
if (t < 0)
goto out;
pluralParse(pParser, t, n, &s);
/* eof */
if (t == 0)
break;
}
pluralParse(pParser, 0, 0, &s);
out:
pluralParseFree(pParser, free);
return s.res;
}
int lmo_translate(const char *key, int keylen, char **out, int *outlen)
{
return lmo_translate_ctxt(key, keylen, NULL, 0, out, outlen);
}
int lmo_translate_ctxt(const char *key, int keylen,
const char *ctx, int ctxlen,
char **out, int *outlen)
{
uint32_t hash;
lmo_entry_t *e;
lmo_archive_t *ar;
if (!key || !_lmo_active_catalog)
return -2;
hash = lmo_canon_hash(key, keylen, ctx, ctxlen, -1);
if (hash > 0)
{
for (ar = _lmo_active_catalog->archives; ar; ar = ar->next)
{
if ((e = lmo_find_entry(ar, hash)) != NULL)
{
*out = ar->mmap + ntohl(e->offset);
*outlen = ntohl(e->length);
return 0;
}
}
}
return -1;
}
int lmo_translate_plural(int n, const char *skey, int skeylen,
const char *pkey, int pkeylen,
char **out, int *outlen)
{
return lmo_translate_plural_ctxt(n, skey, skeylen, pkey, pkeylen,
NULL, 0, out, outlen);
}
int lmo_translate_plural_ctxt(int n, const char *skey, int skeylen,
const char *pkey, int pkeylen,
const char *ctx, int ctxlen,
char **out, int *outlen)
{
int pid = -1;
uint32_t hash;
lmo_entry_t *e;
lmo_archive_t *ar;
if (!skey || !pkey || !_lmo_active_catalog)
return -2;
for (ar = _lmo_active_catalog->archives; ar; ar = ar->next) {
e = lmo_find_entry(ar, 0);
if (e != NULL) {
pid = lmo_eval_plural(ar->mmap + ntohl(e->offset), ntohl(e->length), n);
break;
}
}
if (pid == -1)
pid = (n != 1);
hash = lmo_canon_hash(skey, skeylen, ctx, ctxlen, pid);
if (hash == 0)
return -1;
for (ar = _lmo_active_catalog->archives; ar; ar = ar->next)
{
if ((e = lmo_find_entry(ar, hash)) != NULL)
{
*out = ar->mmap + ntohl(e->offset);
*outlen = ntohl(e->length);
return 0;
}
}
if (n != 1)
{
*out = (char *)pkey;
*outlen = pkeylen;
}
else
{
*out = (char *)skey;
*outlen = skeylen;
}
return 0;
}
void lmo_iterate(lmo_iterate_cb_t cb, void *priv)
{
unsigned int i;
lmo_entry_t *e;
lmo_archive_t *ar;
if (!_lmo_active_catalog)
return;
for (ar = _lmo_active_catalog->archives; ar; ar = ar->next)
for (i = 0, e = &ar->index[0]; i < ar->length; e = &ar->index[++i])
cb(ntohl(e->key_id), ar->mmap + ntohl(e->offset), ntohl(e->length), priv);
}
void lmo_close_catalog(const char *lang)
{
lmo_archive_t *ar, *next;
lmo_catalog_t *cat, *prev;
for (prev = NULL, cat = _lmo_catalogs; cat; prev = cat, cat = cat->next)
{
if (!strncmp(cat->lang, lang, sizeof(cat->lang)))
{
if (prev)
prev->next = cat->next;
else
_lmo_catalogs = cat->next;
for (ar = cat->archives; ar; ar = next)
{
next = ar->next;
lmo_close(ar);
}
free(cat);
break;
}
}
}

View file

@ -0,0 +1,108 @@
/*
* lmo - Lua Machine Objects - General header
*
* Copyright (C) 2009-2012 Jo-Philipp Wich <jow@openwrt.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _TEMPLATE_LMO_H_
#define _TEMPLATE_LMO_H_
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <fnmatch.h>
#include <dirent.h>
#include <ctype.h>
#include <limits.h>
#if (defined(__GNUC__) && defined(__i386__))
#define sfh_get16(d) (*((const uint16_t *) (d)))
#else
#define sfh_get16(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
+(uint32_t)(((const uint8_t *)(d))[0]) )
#endif
#ifndef __hidden
#define __hidden __attribute__((visibility("hidden")))
#endif
struct lmo_entry {
uint32_t key_id;
uint32_t val_id;
uint32_t offset;
uint32_t length;
} __attribute__((packed));
typedef struct lmo_entry lmo_entry_t;
struct lmo_archive {
int fd;
int length;
uint32_t size;
lmo_entry_t *index;
char *mmap;
char *end;
struct lmo_archive *next;
};
typedef struct lmo_archive lmo_archive_t;
struct lmo_catalog {
char lang[6];
struct lmo_archive *archives;
struct lmo_catalog *next;
};
typedef struct lmo_catalog lmo_catalog_t;
typedef void (*lmo_iterate_cb_t)(uint32_t, const char *, int, void *);
__hidden uint32_t sfh_hash(const char *data, size_t len, uint32_t init);
__hidden uint32_t lmo_canon_hash(const char *data, int len,
const char *ctx, int ctxlen, int plural);
__hidden lmo_archive_t * lmo_open(const char *file);
__hidden void lmo_close(lmo_archive_t *ar);
__hidden extern lmo_catalog_t *_lmo_catalogs;
__hidden extern lmo_catalog_t *_lmo_active_catalog;
__hidden int lmo_load_catalog(const char *lang, const char *dir);
__hidden int lmo_change_catalog(const char *lang);
__hidden int lmo_translate(const char *key, int keylen, char **out, int *outlen);
__hidden int lmo_translate_ctxt(const char *key, int keylen,
const char *ctx, int ctxlen, char **out, int *outlen);
__hidden int lmo_translate_plural(int n, const char *skey, int skeylen,
const char *pkey, int pkeylen,
char **out, int *outlen);
__hidden int lmo_translate_plural_ctxt(int n, const char *skey, int skeylen,
const char *pkey, int pkeylen,
const char *ctx, int ctxlen,
char **out, int *outlen);
__hidden void lmo_iterate(lmo_iterate_cb_t cb, void *priv);
__hidden void lmo_close_catalog(const char *lang);
#endif

View file

@ -0,0 +1,383 @@
/*
* LuCI low level routines - ucode binding
*
* Copyright (C) 2009-2022 Jo-Philipp Wich <jo@mein.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lmo.h"
#include <pwd.h>
#include <crypt.h>
#include <shadow.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/sysinfo.h>
#include <sys/statvfs.h>
#include <ucode/module.h>
/* translation catalog functions */
static uc_value_t *
uc_luci_load_catalog(uc_vm_t *vm, size_t nargs) {
uc_value_t *lang = uc_fn_arg(0);
uc_value_t *dir = uc_fn_arg(1);
if (lang && ucv_type(lang) != UC_STRING)
return NULL;
if (dir && ucv_type(dir) != UC_STRING)
return NULL;
return ucv_boolean_new(lmo_load_catalog(
lang ? ucv_string_get(lang) : "en",
ucv_string_get(dir)) == 0);
}
static uc_value_t *
uc_luci_close_catalog(uc_vm_t *vm, size_t nargs) {
uc_value_t *lang = uc_fn_arg(0);
if (lang && ucv_type(lang) != UC_STRING)
return NULL;
lmo_close_catalog(lang ? ucv_string_get(lang) : "en");
return ucv_boolean_new(true);
}
static uc_value_t *
uc_luci_change_catalog(uc_vm_t *vm, size_t nargs) {
uc_value_t *lang = uc_fn_arg(0);
if (lang && ucv_type(lang) != UC_STRING)
return NULL;
return ucv_boolean_new(lmo_change_catalog(
lang ? ucv_string_get(lang) : "en") == 0);
}
static void
uc_luci_get_translations_cb(uint32_t key, const char *val, int len, void *priv) {
uc_vm_t *vm = priv;
uc_vm_stack_push(vm, ucv_get(uc_vm_stack_peek(vm, 0)));
uc_vm_stack_push(vm, ucv_uint64_new(key));
uc_vm_stack_push(vm, ucv_string_new_length(val, (size_t)len));
if (uc_vm_call(vm, false, 2) == EXCEPTION_NONE)
ucv_put(uc_vm_stack_pop(vm));
}
static uc_value_t *
uc_luci_get_translations(uc_vm_t *vm, size_t nargs) {
lmo_iterate(uc_luci_get_translations_cb, vm);
return ucv_boolean_new(true);
}
static uc_value_t *
uc_luci_translate(uc_vm_t *vm, size_t nargs) {
uc_value_t *key = uc_fn_arg(0);
uc_value_t *ctx = uc_fn_arg(1);
int trlen;
char *tr;
if (ucv_type(key) != UC_STRING)
return NULL;
if (ctx && ucv_type(ctx) != UC_STRING)
return NULL;
if (lmo_translate_ctxt(ucv_string_get(key), ucv_string_length(key),
ucv_string_get(ctx), ucv_string_length(ctx),
&tr, &trlen) != 0)
return NULL;
return ucv_string_new_length(tr, (size_t)trlen);
}
static uc_value_t *
uc_luci_ntranslate(uc_vm_t *vm, size_t nargs) {
uc_value_t *cnt = uc_fn_arg(0);
uc_value_t *skey = uc_fn_arg(1);
uc_value_t *pkey = uc_fn_arg(2);
uc_value_t *ctx = uc_fn_arg(3);
int trlen;
char *tr;
if (ucv_type(skey) != UC_STRING || ucv_type(pkey) != UC_STRING)
return NULL;
if (ctx && ucv_type(ctx) != UC_STRING)
return NULL;
if (lmo_translate_plural_ctxt(ucv_int64_get(cnt),
ucv_string_get(skey), ucv_string_length(skey),
ucv_string_get(pkey), ucv_string_length(pkey),
ucv_string_get(ctx), ucv_string_length(ctx),
&tr, &trlen) != 0)
return NULL;
return ucv_string_new_length(tr, (size_t)trlen);
}
static uc_value_t *
uc_luci_hash(uc_vm_t *vm, size_t nargs) {
uc_value_t *key = uc_fn_arg(0);
uc_value_t *init = uc_fn_arg(1);
if (ucv_type(key) != UC_STRING)
return NULL;
if (init && ucv_type(init) != UC_INTEGER)
return NULL;
return ucv_uint64_new(sfh_hash(ucv_string_get(key), ucv_string_length(key),
init ? ucv_uint64_get(init) : ucv_string_length(key)));
}
/* user functions */
static uc_value_t *
uc_luci_getspnam(uc_vm_t *vm, size_t nargs) {
uc_value_t *name = uc_fn_arg(0), *rv;
struct spwd *s;
if (ucv_type(name) != UC_STRING)
return NULL;
s = getspnam(ucv_string_get(name));
if (!s)
return NULL;
rv = ucv_object_new(vm);
ucv_object_add(rv, "namp", ucv_string_new(s->sp_namp));
ucv_object_add(rv, "pwdp", ucv_string_new(s->sp_pwdp));
ucv_object_add(rv, "lstchg", ucv_int64_new(s->sp_lstchg));
ucv_object_add(rv, "min", ucv_int64_new(s->sp_min));
ucv_object_add(rv, "max", ucv_int64_new(s->sp_max));
ucv_object_add(rv, "warn", ucv_int64_new(s->sp_warn));
ucv_object_add(rv, "inact", ucv_int64_new(s->sp_inact));
ucv_object_add(rv, "expire", ucv_int64_new(s->sp_expire));
return rv;
}
static uc_value_t *
uc_luci_getpwnam(uc_vm_t *vm, size_t nargs) {
uc_value_t *name = uc_fn_arg(0), *rv;
struct passwd *p;
if (ucv_type(name) != UC_STRING)
return NULL;
p = getpwnam(ucv_string_get(name));
if (!p)
return NULL;
rv = ucv_object_new(vm);
ucv_object_add(rv, "name", ucv_string_new(p->pw_name));
ucv_object_add(rv, "passwd", ucv_string_new(p->pw_passwd));
ucv_object_add(rv, "uid", ucv_int64_new(p->pw_uid));
ucv_object_add(rv, "gid", ucv_int64_new(p->pw_gid));
ucv_object_add(rv, "gecos", ucv_string_new(p->pw_gecos));
ucv_object_add(rv, "dir", ucv_string_new(p->pw_dir));
ucv_object_add(rv, "shell", ucv_string_new(p->pw_shell));
return rv;
}
static uc_value_t *
uc_luci_crypt(uc_vm_t *vm, size_t nargs) {
uc_value_t *phrase = uc_fn_arg(0);
uc_value_t *setting = uc_fn_arg(1);
char *hash;
if (ucv_type(phrase) != UC_STRING || ucv_type(setting) != UC_STRING)
return NULL;
errno = 0;
hash = crypt(ucv_string_get(phrase), ucv_string_get(setting));
if (hash == NULL || errno != 0)
return NULL;
return ucv_string_new(hash);
}
static uc_value_t *
uc_luci_getuid(uc_vm_t *vm, size_t nargs) {
return ucv_int64_new(getuid());
}
static uc_value_t *
uc_luci_getgid(uc_vm_t *vm, size_t nargs) {
return ucv_int64_new(getgid());
}
static uc_value_t *
uc_luci_setuid(uc_vm_t *vm, size_t nargs) {
uc_value_t *uid = uc_fn_arg(0);
if (ucv_type(uid) != UC_INTEGER)
return NULL;
return ucv_boolean_new(setuid(ucv_int64_get(uid)) == 0);
}
static uc_value_t *
uc_luci_setgid(uc_vm_t *vm, size_t nargs) {
uc_value_t *gid = uc_fn_arg(0);
if (ucv_type(gid) != UC_INTEGER)
return NULL;
return ucv_boolean_new(setgid(ucv_int64_get(gid)) == 0);
}
/* misc functions */
static uc_value_t *
uc_luci_kill(uc_vm_t *vm, size_t nargs) {
uc_value_t *pid = uc_fn_arg(0);
uc_value_t *sig = uc_fn_arg(1);
if (ucv_type(pid) != UC_INTEGER || ucv_type(sig) != UC_INTEGER)
return NULL;
return ucv_boolean_new(kill(ucv_int64_get(pid), ucv_int64_get(sig)) == 0);
}
static uc_value_t *
uc_luci_uname(uc_vm_t *vm, size_t nargs) {
struct utsname u;
uc_value_t *rv;
if (uname(&u) == -1)
return NULL;
rv = ucv_object_new(vm);
ucv_object_add(rv, "sysname", ucv_string_new(u.sysname));
ucv_object_add(rv, "nodename", ucv_string_new(u.nodename));
ucv_object_add(rv, "release", ucv_string_new(u.release));
ucv_object_add(rv, "version", ucv_string_new(u.version));
ucv_object_add(rv, "machine", ucv_string_new(u.machine));
return rv;
}
static uc_value_t *
uc_luci_sysinfo(uc_vm_t *vm, size_t nargs) {
uc_value_t *rv, *loads;
struct sysinfo i;
if (sysinfo(&i) == -1)
return NULL;
rv = ucv_object_new(vm);
loads = ucv_array_new_length(vm, 3);
ucv_array_push(loads, ucv_uint64_new(i.loads[0]));
ucv_array_push(loads, ucv_uint64_new(i.loads[1]));
ucv_array_push(loads, ucv_uint64_new(i.loads[2]));
ucv_object_add(rv, "uptime", ucv_int64_new(i.uptime));
ucv_object_add(rv, "loads", loads);
ucv_object_add(rv, "totalram", ucv_uint64_new(i.totalram));
ucv_object_add(rv, "freeram", ucv_uint64_new(i.freeram));
ucv_object_add(rv, "sharedram", ucv_uint64_new(i.sharedram));
ucv_object_add(rv, "bufferram", ucv_uint64_new(i.bufferram));
ucv_object_add(rv, "totalswap", ucv_uint64_new(i.totalswap));
ucv_object_add(rv, "freeswap", ucv_uint64_new(i.freeswap));
ucv_object_add(rv, "procs", ucv_uint64_new(i.procs));
ucv_object_add(rv, "totalhigh", ucv_uint64_new(i.totalhigh));
ucv_object_add(rv, "freehigh", ucv_uint64_new(i.freehigh));
ucv_object_add(rv, "mem_unit", ucv_uint64_new(i.mem_unit));
return rv;
}
static uc_value_t *
uc_luci_statvfs(uc_vm_t *vm, size_t nargs) {
uc_value_t *path = uc_fn_arg(0), *rv;
struct statvfs s;
if (ucv_type(path) != UC_STRING)
return NULL;
if (statvfs(ucv_string_get(path), &s) == -1)
return NULL;
rv = ucv_object_new(vm);
ucv_object_add(rv, "bsize", ucv_uint64_new(s.f_bsize));
ucv_object_add(rv, "frsize", ucv_uint64_new(s.f_frsize));
ucv_object_add(rv, "blocks", ucv_uint64_new(s.f_blocks));
ucv_object_add(rv, "bfree", ucv_uint64_new(s.f_bfree));
ucv_object_add(rv, "bavail", ucv_uint64_new(s.f_bavail));
ucv_object_add(rv, "files", ucv_uint64_new(s.f_files));
ucv_object_add(rv, "ffree", ucv_uint64_new(s.f_ffree));
ucv_object_add(rv, "favail", ucv_uint64_new(s.f_favail));
ucv_object_add(rv, "fsid", ucv_uint64_new(s.f_fsid));
ucv_object_add(rv, "flag", ucv_uint64_new(s.f_flag));
ucv_object_add(rv, "namemax", ucv_uint64_new(s.f_namemax));
return rv;
}
static const uc_function_list_t luci_fns[] = {
{ "load_catalog", uc_luci_load_catalog },
{ "close_catalog", uc_luci_close_catalog },
{ "change_catalog", uc_luci_change_catalog },
{ "get_translations", uc_luci_get_translations },
{ "translate", uc_luci_translate },
{ "ntranslate", uc_luci_ntranslate },
{ "hash", uc_luci_hash },
{ "getspnam", uc_luci_getspnam },
{ "getpwnam", uc_luci_getpwnam },
{ "crypt", uc_luci_crypt },
{ "getuid", uc_luci_getuid },
{ "setuid", uc_luci_setuid },
{ "getgid", uc_luci_getgid },
{ "setgid", uc_luci_setgid },
{ "kill", uc_luci_kill },
{ "uname", uc_luci_uname },
{ "sysinfo", uc_luci_sysinfo },
{ "statvfs", uc_luci_statvfs },
};
void uc_module_init(uc_vm_t *vm, uc_value_t *scope)
{
uc_function_list_register(scope, luci_fns);
}

View file

@ -0,0 +1,43 @@
%name pluralParse
%token_type {int}
%extra_argument {struct parse_state *s}
%right T_QMARK.
%left T_OR.
%left T_AND.
%left T_EQ T_NE.
%left T_LT T_LE T_GT T_GE.
%left T_ADD T_SUB.
%left T_MUL T_DIV T_MOD.
%right T_NOT.
%nonassoc T_COLON T_N T_LPAREN T_RPAREN.
%include {
#include <assert.h>
struct parse_state {
int num;
int res;
};
}
input ::= expr(A). { s->res = A; }
expr(A) ::= expr(B) T_QMARK expr(C) T_COLON expr(D). { A = B ? C : D; }
expr(A) ::= expr(B) T_OR expr(C). { A = B || C; }
expr(A) ::= expr(B) T_AND expr(C). { A = B && C; }
expr(A) ::= expr(B) T_EQ expr(C). { A = B == C; }
expr(A) ::= expr(B) T_NE expr(C). { A = B != C; }
expr(A) ::= expr(B) T_LT expr(C). { A = B < C; }
expr(A) ::= expr(B) T_LE expr(C). { A = B <= C; }
expr(A) ::= expr(B) T_GT expr(C). { A = B > C; }
expr(A) ::= expr(B) T_GE expr(C). { A = B >= C; }
expr(A) ::= expr(B) T_ADD expr(C). { A = B + C; }
expr(A) ::= expr(B) T_SUB expr(C). { A = B - C; }
expr(A) ::= expr(B) T_MUL expr(C). { A = B * C; }
expr(A) ::= expr(B) T_DIV expr(C). { A = B / C; }
expr(A) ::= expr(B) T_MOD expr(C). { A = B % C; }
expr(A) ::= T_NOT expr(B). { A = !B; }
expr(A) ::= T_N. { A = s->num; }
expr(A) ::= T_NUM(B). { A = B; }
expr(A) ::= T_LPAREN expr(B) T_RPAREN. { A = B; }

View file

@ -0,0 +1,158 @@
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.
import { load_catalog, change_catalog, get_translations } from 'luci.core';
const ubus_types = [
null,
'array',
'object',
'string',
null, // INT64
'number',
null, // INT16,
'boolean',
'double'
];
function ubus_reply(id, data, code, errmsg) {
const reply = { jsonrpc: '2.0', id };
if (errmsg)
reply.error = { code, message: errmsg };
else if (type(code) == 'object')
reply.result = code;
else
reply.result = [ code, data ];
return reply;
}
function ubus_access(sid, obj, fun) {
return (ubus.call('session', 'access', {
ubus_rpc_session: sid,
scope: 'ubus',
object: obj,
function: fun
})?.access == true);
}
function ubus_request(req) {
if (type(req?.method) != 'string' || req?.jsonrpc != '2.0' || req?.id == null)
return ubus_reply(null, null, -32600, 'Invalid request');
if (req.method == 'call') {
if (type(req?.params) != 'array' || length(req.params) < 3)
return ubus_reply(null, null, -32600, 'Invalid parameters');
let sid = req.params[0],
obj = req.params[1],
fun = req.params[2],
arg = req.params[3] ?? {};
if (type(arg) != 'object' || exists(arg, 'ubus_rpc_session'))
return ubus_reply(req.id, null, -32602, 'Invalid parameters');
if (sid == '00000000000000000000000000000000' && ctx.authsession)
sid = ctx.authsession;
if (!ubus_access(sid, obj, fun))
return ubus_reply(req.id, null, -32002, 'Access denied');
arg.ubus_rpc_session = sid;
// clear error
ubus.error();
const res = ubus.call(obj, fun, arg);
return ubus_reply(req.id, res, ubus.error(true) ?? 0);
}
if (req.method == 'list') {
if (req?.params == null || (type(req.params) == 'array' && length(req.params) == 0)) {
return ubus_reply(req.id, null, ubus.list());
}
else if (type(req.params) == 'array') {
const rv = {};
for (let param in req.params) {
if (type(param) != 'string')
return ubus_reply(req.id, null, -32602, 'Invalid parameters');
for (let m, p in ubus.list(param)?.[0]) {
for (let pn, pt in p) {
rv[param] ??= {};
rv[param][m] ??= {};
rv[param][m][pn] = ubus_types[pt] ?? 'unknown';
}
}
}
return ubus_reply(req.id, null, rv);
}
else {
return ubus_reply(req.id, null, -32602, 'Invalid parameters')
}
}
return ubus_reply(req.id, null, -32601, 'Method not found')
}
return {
action_ubus: function() {
let request;
try { request = json(http.content()); }
catch { request = null; }
http.prepare_content('application/json; charset=UTF-8');
if (type(request) == 'object')
http.write_json(ubus_request(request));
else if (type(request) == 'array')
http.write_json(map(request, ubus_request));
else
http.write_json(ubus_reply(null, null, -32700, 'Parse error'))
},
action_translations: function(reqlang) {
if (reqlang != null && reqlang != dispatcher.lang) {
load_catalog(reqlang, '/usr/lib/lua/luci/i18n');
change_catalog(reqlang);
}
http.prepare_content('application/javascript; charset=UTF-8');
http.write('window.TR={');
get_translations((key, val) => http.write(sprintf('"%08x":%J,', key, val)));
http.write('};');
},
action_logout: function() {
const url = dispatcher.build_url();
if (ctx.authsession) {
ubus.call('session', 'destroy', { ubus_rpc_session: ctx.authsession });
if (http.getenv('HTTPS') == 'on')
http.header('Set-Cookie', `sysauth_https=; expires=Thu, 01 Jan 1970 01:00:00 GMT; path=${url}`);
http.header('Set-Cookie', `sysauth_http=; expires=Thu, 01 Jan 1970 01:00:00 GMT; path=${url}`);
}
http.redirect(url);
},
action_menu: function() {
const session = dispatcher.is_authenticated({ methods: [ 'cookie:sysauth_https', 'cookie:sysauth_http' ] });
const menu = dispatcher.menu_json(session?.acls ?? {}) ?? {};
http.prepare_content('application/json; charset=UTF-8');
http.write_json(menu);
}
};

View file

@ -0,0 +1,150 @@
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.
import { STATUS_NO_DATA, STATUS_PERMISSION_DENIED } from 'ubus';
let last_ubus_error;
const ubus_error_map = [
200, 'OK',
400, 'Invalid command',
400, 'Invalid argument',
404, 'Method not found',
404, 'Not found',
204, 'No data',
403, 'Permission denied',
504, 'Timeout',
500, 'Not supported',
500, 'Unknown error',
503, 'Connection failed',
500, 'Out of memory',
400, 'Parse error',
500, 'System error',
];
function ubus_call(object, method, args) {
ubus.error(); // clear previous error
let res = ubus.call(object, method, args);
last_ubus_error = ubus.error(true);
return res ?? !last_ubus_error;
}
function ubus_state_to_http(err) {
let code = ubus_error_map[(err << 1) + 0] ?? 200;
let msg = ubus_error_map[(err << 1) + 1] ?? 'OK';
http.status(code, msg);
if (code != 204) {
http.prepare_content('text/plain');
http.write(msg);
}
}
function uci_apply(rollback) {
if (rollback) {
const timeout = +(config?.apply?.rollback ?? 90) || 0;
const success = ubus_call('uci', 'apply', {
ubus_rpc_session: ctx.authsession,
timeout: max(timeout, 90),
rollback: true
});
if (success) {
const token = dispatcher.randomid(16);
ubus.call('session', 'set', {
ubus_rpc_session: '00000000000000000000000000000000',
values: {
rollback: {
token,
session: ctx.authsession,
timeout: time() + timeout
}
}
});
return token;
}
return null;
}
else {
let changes = ubus_call('uci', 'changes', { ubus_rpc_session: ctx.authsession })?.changes;
for (let config in changes)
if (!ubus_call('uci', 'commit', { ubus_rpc_session: ctx.authsession, config }))
return false;
return ubus_call('uci', 'apply', {
ubus_rpc_session: ctx.authsession,
rollback: false
});
}
}
function uci_confirm(token) {
const data = ubus.call('session', 'get', {
ubus_rpc_session: '00000000000000000000000000000000',
keys: [ 'rollback' ]
})?.values?.rollback;
if (type(data?.token) != 'string' || type(data?.session) != 'string' ||
type(data?.timeout) != 'int' || data.timeout < time()) {
last_ubus_error = STATUS_NO_DATA;
return false;
}
if (token != data.token) {
last_ubus_error = STATUS_PERMISSION_DENIED;
return false;
}
if (!ubus_call('uci', 'confirm', { ubus_rpc_session: data.session }))
return false;
ubus_call('session', 'set', {
ubus_rpc_session: '00000000000000000000000000000000',
values: { rollback: {} }
});
return true;
}
return {
action_apply_rollback: function() {
const token = uci_apply(true);
if (token) {
http.prepare_content('application/json; charset=UTF-8');
http.write_json({ token });
}
else {
ubus_state_to_http(last_ubus_error);
}
},
action_apply_unchecked: function() {
uci_apply(false);
ubus_state_to_http(last_ubus_error);
},
action_confirm: function() {
uci_confirm(http.formvalue('token'));
ubus_state_to_http(last_ubus_error);
},
action_revert: function() {
for (let config in ubus_call('uci', 'changes', { ubus_rpc_session: ctx.authsession })?.changes)
if (!ubus_call('uci', 'revert', { ubus_rpc_session: ctx.authsession, config }))
break;
ubus_state_to_http(last_ubus_error);
}
};

View file

@ -0,0 +1,942 @@
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.
import { open, stat, glob, lsdir, unlink, basename } from 'fs';
import { striptags, entityencode } from 'html';
import { connect } from 'ubus';
import { cursor } from 'uci';
import { rand } from 'math';
import { hash, load_catalog, change_catalog, translate, ntranslate, getuid } from 'luci.core';
import { revision as luciversion, branch as luciname } from 'luci.version';
import { default as LuCIRuntime } from 'luci.runtime';
import { urldecode } from 'luci.http';
let ubus = connect();
let uci = cursor();
let indexcache = "/tmp/luci-indexcache";
let http, runtime, tree, luabridge;
function error404(msg) {
http.status(404, 'Not Found');
try {
runtime.render('error404', { message: msg ?? 'Not found' });
}
catch {
http.header('Content-Type', 'text/plain; charset=UTF-8');
http.write(msg ?? 'Not found');
}
return false;
}
function error500(msg, ex) {
if (!http.eoh) {
http.status(500, 'Internal Server Error');
http.header('Content-Type', 'text/html; charset=UTF-8');
}
try {
runtime.render('error500', {
title: ex?.type ?? 'Runtime exception',
message: replace(
msg,
/(\s)((\/[A-Za-z0-9_.-]+)+:\d+|\[string "[^"]+"\]:\d+)/g,
'$1<code>$2</code>'
),
exception: ex
});
}
catch {
http.write('<!--]]>--><!--\'>--><!--">-->\n');
http.write(`<p>${trim(ex)}</p>\n`);
if (ex) {
http.write(`<p>${trim(ex.message)}</p>\n`);
http.write(`<pre>${trim(ex.stacktrace[0].context)}</pre>\n`);
}
}
exit(0);
}
function load_luabridge(optional) {
if (luabridge == null) {
try {
luabridge = require('lua');
}
catch (ex) {
luabridge = false;
if (!optional)
error500('No Lua runtime installed');
}
}
return luabridge;
}
function determine_request_language() {
let lang = uci.get('luci', 'main', 'lang') || 'auto';
if (lang == 'auto') {
for (let tag in split(http.getenv('HTTP_ACCEPT_LANGUAGE'), ',')) {
tag = split(trim(split(tag, ';')?.[0]), '-');
if (tag) {
let cc = tag[1] ? `${tag[0]}_${lc(tag[1])}` : null;
if (cc && uci.get('luci', 'languages', cc)) {
lang = cc;
break;
}
else if (uci.get('luci', 'languages', tag[0])) {
lang = tag[0];
break;
}
}
}
}
if (lang == 'auto')
lang = 'en';
if (load_catalog(lang, '/usr/lib/lua/luci/i18n'))
change_catalog(lang);
return lang;
}
function determine_version() {
let res = { luciname, luciversion };
for (let f = open("/etc/os-release"), l = f?.read?.("line"); l; l = f.read?.("line")) {
let kv = split(l, '=', 2);
switch (kv[0]) {
case 'NAME':
res.distname = trim(kv[1], '"\' \n');
break;
case 'VERSION':
res.distversion = trim(kv[1], '"\' \n');
break;
case 'HOME_URL':
res.disturl = trim(kv[1], '"\' \n');
break;
case 'BUILD_ID':
res.distrevision = trim(kv[1], '"\' \n');
break;
}
}
return res;
}
function read_jsonfile(path, defval) {
let rv;
try {
rv = json(open(path, "r"));
}
catch (e) {
rv = defval;
}
return rv;
}
function read_cachefile(file, reader) {
let euid = getuid(),
fstat = stat(file),
fuid = fstat?.uid,
perm = fstat?.perm;
if (euid != fuid ||
perm?.group_read || perm?.group_write || perm?.group_exec ||
perm?.other_read || perm?.other_write || perm?.other_exec)
return null;
return reader(file);
}
function check_fs_depends(spec) {
for (let path, kind in spec) {
if (kind == 'directory') {
if (!length(lsdir(path)))
return false;
}
else if (kind == 'executable') {
let fstat = stat(path);
if (fstat?.type != 'file' || fstat?.user_exec == false)
return false;
}
else if (kind == 'file') {
let fstat = stat(path);
if (fstat?.type != 'file')
return false;
}
}
return true;
}
function check_uci_depends_options(conf, s, opts) {
if (type(opts) == 'string') {
return (s['.type'] == opts);
}
else if (opts === true) {
for (let option, value in s)
if (ord(option) != 46)
return true;
}
else if (type(opts) == 'object') {
for (let option, value in opts) {
let sval = s[option];
if (type(sval) == 'array') {
if (!(value in sval))
return false;
}
else if (value === true) {
if (sval == null)
return false;
}
else {
if (sval != value)
return false;
}
}
}
return true;
}
function check_uci_depends_section(conf, sect) {
for (let section, options in sect) {
let stype = match(section, /^@([A-Za-z0-9_-]+)$/);
if (stype) {
let found = false;
uci.load(conf);
uci.foreach(conf, stype[1], (s) => {
if (check_uci_depends_options(conf, s, options)) {
found = true;
return false;
}
});
if (!found)
return false;
}
else {
let s = uci.get_all(conf, section);
if (!s || !check_uci_depends_options(conf, s, options))
return false;
}
}
return true;
}
function check_uci_depends(conf) {
for (let config, values in conf) {
if (values == true) {
let found = false;
uci.load(config);
uci.foreach(config, null, () => { found = true });
if (!found)
return false;
}
else if (type(values) == 'object') {
if (!check_uci_depends_section(config, values))
return false;
}
}
return true;
}
function check_depends(spec) {
if (type(spec?.depends?.fs) in ['array', 'object']) {
let satisfied = false;
let alternatives = (type(spec.depends.fs) == 'array') ? spec.depends.fs : [ spec.depends.fs ];
for (let alternative in alternatives) {
if (check_fs_depends(alternative)) {
satisfied = true;
break;
}
}
if (!satisfied)
return false;
}
if (type(spec?.depends?.uci) in ['array', 'object']) {
let satisfied = false;
let alternatives = (type(spec.depends.uci) == 'array') ? spec.depends.uci : [ spec.depends.uci ];
for (let alternative in alternatives) {
if (check_uci_depends(alternative)) {
satisfied = true;
break;
}
}
if (!satisfied)
return false;
}
return true;
}
function check_acl_depends(require_groups, groups) {
if (length(require_groups)) {
let writable = false;
for (let group in require_groups) {
let read = ('read' in groups?.[group]);
let write = ('write' in groups?.[group]);
if (!read && !write)
return null;
if (write)
writable = true;
}
return writable;
}
return true;
}
function hash_filelist(files) {
let hashval = 0x1b756362;
for (let file in files) {
let st = stat(file);
if (st)
hashval = hash(sprintf("%x|%x|%x", st.ino, st.mtime, st.size), hashval);
}
return hashval;
}
function build_pagetree() {
let tree = { action: { type: 'firstchild' } };
let schema = {
action: 'object',
auth: 'object',
cors: 'bool',
depends: 'object',
order: 'int',
setgroup: 'string',
setuser: 'string',
title: 'string',
wildcard: 'bool',
firstchild_ineligible: 'bool'
};
let files = glob('/usr/share/luci/menu.d/*.json', '/usr/lib/lua/luci/controller/*.lua', '/usr/lib/lua/luci/controller/*/*.lua');
let cachefile;
if (indexcache) {
cachefile = sprintf('%s.%08x.json', indexcache, hash_filelist(files));
let res = read_cachefile(cachefile, read_jsonfile);
if (res)
return res;
for (let path in glob(indexcache + '.*.json'))
unlink(path);
}
for (let file in files) {
let data;
if (substr(file, -5) == '.json')
data = read_jsonfile(file);
else if (load_luabridge(true))
data = runtime.call('luci.dispatcher', 'process_lua_controller', file);
else
warn(`Lua controller ${file} present but no Lua runtime installed.\n`);
if (type(data) == 'object') {
for (let path, spec in data) {
if (type(spec) == 'object') {
let node = tree;
for (let s in match(path, /[^\/]+/g)) {
if (s[0] == '*') {
node.wildcard = true;
break;
}
node.children ??= {};
node.children[s[0]] ??= {};
node = node.children[s[0]];
}
if (node !== tree) {
for (let k, t in schema)
if (type(spec[k]) == t)
node[k] = spec[k];
node.satisfied = check_depends(spec);
}
}
}
}
}
if (cachefile) {
let fd = open(cachefile, 'w', 0600);
if (fd) {
fd.write(tree);
fd.close();
}
}
return tree;
}
function menu_json(acl) {
tree ??= build_pagetree();
return tree;
}
function ctx_append(ctx, name, node) {
ctx.path ??= [];
push(ctx.path, name);
ctx.acls ??= [];
push(ctx.acls, ...(node?.depends?.acl || []));
ctx.auth = node.auth || ctx.auth;
ctx.cors = node.cors || ctx.cors;
ctx.suid = node.setuser || ctx.suid;
ctx.sgid = node.setgroup || ctx.sgid;
return ctx;
}
function session_retrieve(sid, allowed_users) {
let sdat = ubus.call("session", "get", { ubus_rpc_session: sid });
let sacl = ubus.call("session", "access", { ubus_rpc_session: sid });
if (type(sdat?.values?.token) == 'string' &&
(!length(allowed_users) || sdat?.values?.username in allowed_users)) {
// uci:set_session_id(sid)
return {
sid,
data: sdat.values,
acls: length(sacl) ? sacl : {}
};
}
return null;
}
function randomid(num_bytes) {
let bytes = [];
while (num_bytes-- > 0)
push(bytes, sprintf('%02x', rand() % 256));
return join('', bytes);
}
function syslog(prio, msg) {
warn(sprintf("[%s] %s\n", prio, msg));
}
function session_setup(user, pass, path) {
let timeout = uci.get('luci', 'sauth', 'sessiontime');
let login = ubus.call("session", "login", {
username: user,
password: pass,
timeout: timeout ? +timeout : null
});
if (type(login?.ubus_rpc_session) == 'string') {
ubus.call("session", "set", {
ubus_rpc_session: login.ubus_rpc_session,
values: { token: randomid(16) }
});
syslog("info", sprintf("luci: accepted login on /%s for %s from %s",
join('/', path), user || "?", http.getenv("REMOTE_ADDR") || "?"));
return session_retrieve(login.ubus_rpc_session);
}
syslog("info", sprintf("luci: failed login on /%s for %s from %s",
join('/', path), user || "?", http.getenv("REMOTE_ADDR") || "?"));
}
function check_authentication(method) {
let m = match(method, /^([[:alpha:]]+):(.+)$/);
let sid;
switch (m?.[1]) {
case 'cookie':
sid = http.getcookie(m[2]);
break;
case 'param':
sid = http.formvalue(m[2]);
break;
case 'query':
sid = http.formvalue(m[2], true);
break;
}
return sid ? session_retrieve(sid) : null;
}
function is_authenticated(auth) {
for (let method in auth?.methods) {
let session = check_authentication(method);
if (session)
return session;
}
return null;
}
function node_weight(node) {
let weight = min(node.order ?? 9999, 9999);
if (node.auth?.login)
weight += 10000;
return weight;
}
function clone(src) {
switch (type(src)) {
case 'array':
return map(src, clone);
case 'object':
let dest = {};
for (let k, v in src)
dest[k] = clone(v);
return dest;
default:
return src;
}
}
function resolve_firstchild(node, session, login_allowed, ctx) {
let candidate, candidate_ctx;
for (let name, child in node.children) {
if (!child.satisfied)
continue;
if (!session)
session = is_authenticated(node.auth);
let cacl = child.depends?.acl;
let login = login_allowed || child.auth?.login;
if (login || check_acl_depends(cacl, session?.acls?.["access-group"]) != null) {
if (child.title && type(child.action) == "object") {
let child_ctx = ctx_append(clone(ctx), name, child);
if (child.action.type == "firstchild") {
if (!candidate || node_weight(candidate) > node_weight(child)) {
let have_grandchild = resolve_firstchild(child, session, login, child_ctx);
if (have_grandchild) {
candidate = child;
candidate_ctx = child_ctx;
}
}
}
else if (!child.firstchild_ineligible) {
if (!candidate || node_weight(candidate) > node_weight(child)) {
candidate = child;
candidate_ctx = child_ctx;
}
}
}
}
}
if (!candidate)
return false;
for (let k, v in candidate_ctx)
ctx[k] = v;
return true;
}
function resolve_page(tree, request_path) {
let node = tree;
let login = false;
let session = null;
let ctx = {};
for (let i, s in request_path) {
node = node.children?.[s];
if (!node?.satisfied)
break;
ctx_append(ctx, s, node);
if (!session)
session = is_authenticated(node.auth);
if (!login && node.auth?.login)
login = true;
if (node.wildcard) {
ctx.request_args = [];
ctx.request_path = ctx.path ? [ ...ctx.path ] : [];
while (++i < length(request_path)) {
push(ctx.request_path, request_path[i]);
push(ctx.request_args, request_path[i]);
}
break;
}
}
if (node?.action?.type == 'firstchild')
resolve_firstchild(node, session, login, ctx);
ctx.acls ??= {};
ctx.path ??= [];
ctx.request_args ??= [];
ctx.request_path ??= request_path ? [ ...request_path ] : [];
ctx.authsession = session?.sid;
ctx.authtoken = session?.data?.token;
ctx.authuser = session?.data?.username;
ctx.authacl = session?.acls;
node = tree;
for (let s in ctx.path) {
node = node.children[s];
assert(node, "Internal node resolve error");
}
return { node, ctx, session };
}
function require_post_security(target, args) {
if (target?.type == 'arcombine')
return require_post_security(length(args) ? target?.targets?.[1] : target?.targets?.[0], args);
if (type(target?.post) == 'object') {
for (let param_name, required_val in target.post) {
let request_val = http.formvalue(param_name);
if ((type(required_val) == 'string' && request_val != required_val) ||
(required_val == true && request_val == null))
return false;
}
return true;
}
return (target?.post == true);
}
function test_post_security(authtoken) {
if (http.getenv("REQUEST_METHOD") != "POST") {
http.status(405, "Method Not Allowed");
http.header("Allow", "POST");
return false;
}
if (http.formvalue("token") != authtoken) {
http.status(403, "Forbidden");
runtime.render("csrftoken");
return false;
}
return true;
}
function build_url(...path) {
let url = [ http.getenv('SCRIPT_NAME') ?? '' ];
for (let p in path)
if (match(p, /^[A-Za-z0-9_%.\/,;-]+$/))
push(url, '/', p);
if (length(url) == 1)
push(url, '/');
return join('', url);
}
function lookup(...segments) {
let node = menu_json();
let path = [];
for (let segment in segments)
for (let name in split(segment, '/'))
push(path, name);
for (let name in path) {
node = node.children[name];
if (!node)
return null;
if (node.leaf)
break;
}
return { node, url: build_url(...path) };
}
function rollback_pending() {
const now = time();
const rv = ubus.call('session', 'get', {
ubus_rpc_session: '00000000000000000000000000000000',
keys: [ 'rollback' ]
});
if (type(rv?.values?.rollback?.token) != 'string' ||
type(rv?.values?.rollback?.session) != 'string' ||
type(rv?.values?.rollback?.timeout) != 'int' ||
rv.values.rollback.timeout <= now)
return false;
return {
remaining: rv.values.rollback.timeout - now,
session: rv.values.rollback.session,
token: rv.values.rollback.token
};
}
let dispatch;
function run_action(request_path, lang, tree, resolved, action) {
switch (action?.type) {
case 'template':
runtime.render(action.path, {});
break;
case 'view':
runtime.render('view', { view: action.path });
break;
case 'call':
http.write(render(() => {
runtime.call(action.module, action.function,
...(action.parameters ?? []),
...resolved.ctx.request_args
);
}));
break;
case 'function':
const mod = require(action.module);
assert(type(mod[action.function]) == 'function',
`Module '${action.module}' does not export function '${action.function}'`);
http.write(render(() => {
call(mod[action.function], mod, runtime.env,
...(action.parameters ?? []),
...resolved.ctx.request_args
);
}));
break;
case 'alias':
dispatch(http, [ ...split(action.path, '/'), ...resolved.ctx.request_args ]);
break;
case 'rewrite':
dispatch(http, [
...splice([ ...request_path ], 0, action.remove),
...split(action.path, '/'),
...resolved.ctx.request_args
]);
break;
case 'firstchild':
if (!length(tree.children))
error404("No root node was registered, this usually happens if no module was installed.\n" +
"Install luci-mod-admin-full and retry. " +
"If the module is already installed, try removing the /tmp/luci-indexcache file.");
else
error404(`No page is registered at '/${join("/", resolved.ctx.request_path)}'.\n` +
"If this url belongs to an extension, make sure it is properly installed.\n" +
"If the extension was recently installed, try removing the /tmp/luci-indexcache file.");
break;
default:
error500(`Unhandled action type ${action?.type ?? '?'}`);
}
}
dispatch = function(_http, path) {
http = _http;
let version = determine_version();
let lang = determine_request_language();
runtime = LuCIRuntime({
http,
ubus,
uci,
ctx: {},
version,
config: {
main: uci.get_all('luci', 'main') ?? {},
apply: uci.get_all('luci', 'apply') ?? {}
},
dispatcher: {
rollback_pending,
is_authenticated,
load_luabridge,
lookup,
menu_json,
build_url,
randomid,
error404,
error500,
lang
},
striptags,
entityencode,
_: (...args) => translate(...args) ?? args[0],
N_: (...args) => ntranslate(...args) ?? (n[0] == 1 ? n[1] : n[2]),
});
try {
let menu = menu_json();
path ??= map(match(http.getenv('PATH_INFO'), /[^\/]+/g), m => m[0]);
let resolved = resolve_page(menu, path);
runtime.env.ctx = resolved.ctx;
runtime.env.node = resolved.node;
if (length(resolved.ctx.auth)) {
let session = is_authenticated(resolved.ctx.auth);
if (!session && resolved.ctx.auth.login) {
let user = http.getenv('HTTP_AUTH_USER');
let pass = http.getenv('HTTP_AUTH_PASS');
if (user == null && pass == null) {
user = http.formvalue('luci_username');
pass = http.formvalue('luci_password');
}
if (user != null && pass != null)
session = session_setup(user, pass, resolved.ctx.request_path);
if (!session) {
resolved.ctx.path = [];
http.status(403, 'Forbidden');
http.header('X-LuCI-Login-Required', 'yes');
let scope = { duser: 'root', fuser: user };
try {
runtime.render(`themes/${basename(runtime.env.media)}/sysauth`, scope);
}
catch (e) {
runtime.render('sysauth', scope);
}
return;
}
let cookie_name = (http.getenv('HTTPS') == 'on') ? 'sysauth_https' : 'sysauth_http',
cookie_secure = (http.getenv('HTTPS') == 'on') ? '; secure' : '';
http.header('Set-Cookie', `${cookie_name}=${session.sid}; path=${build_url()}; SameSite=strict; HttpOnly${cookie_secure}`);
http.redirect(build_url(...resolved.ctx.request_path));
return;
}
if (!session) {
http.status(403, 'Forbidden');
http.header('X-LuCI-Login-Required', 'yes');
return;
}
resolved.ctx.authsession ??= session.sid;
resolved.ctx.authtoken ??= session.data?.token;
resolved.ctx.authuser ??= session.data?.username;
resolved.ctx.authacl ??= session.acls;
}
if (length(resolved.ctx.acls)) {
let perm = check_acl_depends(resolved.ctx.acls, resolved.ctx.authacl?.['access-group']);
if (perm == null) {
http.status(403, 'Forbidden');
return;
}
if (resolved.node)
resolved.node.readonly = !perm;
}
let action = resolved.node.action;
if (action?.type == 'arcombine')
action = length(resolved.ctx.request_args) ? action.targets?.[1] : action.targets?.[0];
if (resolved.ctx.cors && http.getenv('REQUEST_METHOD') == 'OPTIONS') {
http.status(200, 'OK');
http.header('Access-Control-Allow-Origin', http.getenv('HTTP_ORIGIN') ?? '*');
http.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
return;
}
if (require_post_security(action) && !test_post_security(resolved.ctx.authtoken))
return;
run_action(path, lang, menu, resolved, action);
}
catch (ex) {
error500('Unhandled exception during request dispatching', ex);
}
};
export default dispatch;

View file

@ -0,0 +1,574 @@
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.
import {
urlencode as _urlencode,
urldecode as _urldecode,
urlencoded_parser, multipart_parser, header_attribute,
ENCODE_IF_NEEDED, ENCODE_FULL, DECODE_IF_NEEDED, DECODE_PLUS
} from 'lucihttp';
import {
error as fserror,
stdin, stdout, mkstemp
} from 'fs';
// luci.http module scope
export let HTTP_MAX_CONTENT = 1024*100; // 100 kB maximum content size
// Decode a mime encoded http message body with multipart/form-data
// Content-Type. Stores all extracted data associated with its parameter name
// in the params table within the given message object. Multiple parameter
// values are stored as tables, ordinary ones as strings.
// If an optional file callback function is given then it is fed with the
// file contents chunk by chunk and only the extracted file name is stored
// within the params table. The callback function will be called subsequently
// with three arguments:
// o Table containing decoded (name, file) and raw (headers) mime header data
// o String value containing a chunk of the file data
// o Boolean which indicates whether the current chunk is the last one (eof)
export function mimedecode_message_body(src, msg, file_cb) {
let len = 0, maxlen = +msg.env.CONTENT_LENGTH;
let header, field, parser;
parser = multipart_parser(msg.env.CONTENT_TYPE, function(what, buffer, length) {
if (what == parser.PART_INIT) {
field = {};
}
else if (what == parser.HEADER_NAME) {
header = lc(buffer);
}
else if (what == parser.HEADER_VALUE && header) {
if (lc(header) == 'content-disposition' &&
header_attribute(buffer, null) == 'form-data') {
field.name = header_attribute(buffer, 'name');
field.file = header_attribute(buffer, 'filename');
field[1] = field.file;
}
field.headers = field.headers || {};
field.headers[header] = buffer;
}
else if (what == parser.PART_BEGIN) {
return !field.file;
}
else if (what == parser.PART_DATA && field.name && length > 0) {
if (field.file) {
if (file_cb) {
file_cb(field, buffer, false);
msg.params[field.name] = msg.params[field.name] || field;
}
else {
if (!field.fd)
field.fd = mkstemp(field.name);
if (field.fd) {
field.fd.write(buffer);
msg.params[field.name] = msg.params[field.name] || field;
}
}
}
else {
field.value = buffer;
}
}
else if (what == parser.PART_END && field.name) {
if (field.file && msg.params[field.name]) {
if (file_cb)
file_cb(field, '', true);
else if (field.fd)
field.fd.seek(0);
}
else {
let val = msg.params[field.name];
if (type(val) == 'array')
push(val, field.value || '');
else if (val != null)
msg.params[field.name] = [ val, field.value || '' ];
else
msg.params[field.name] = field.value || '';
}
field = null;
}
else if (what == parser.ERROR) {
err = buffer;
}
return true;
}, HTTP_MAX_CONTENT);
while (true) {
let chunk = src();
len += length(chunk);
if (maxlen && len > maxlen + 2)
die('Message body size exceeds Content-Length');
if (!parser.parse(chunk))
die(err);
if (chunk == null)
break;
}
};
// Decode an urlencoded http message body with application/x-www-urlencoded
// Content-Type. Stores all extracted data associated with its parameter name
// in the params table within the given message object. Multiple parameter
// values are stored as tables, ordinary ones as strings.
export function urldecode_message_body(src, msg) {
let len = 0, maxlen = +msg.env.CONTENT_LENGTH;
let err, name, value, parser;
parser = urlencoded_parser(function (what, buffer, length) {
if (what == parser.TUPLE) {
name = null;
value = null;
}
else if (what == parser.NAME) {
name = _urldecode(buffer, DECODE_PLUS);
}
else if (what == parser.VALUE && name) {
let val = msg.params[name];
if (type(val) == 'array')
push(val, _urldecode(buffer, DECODE_PLUS) || '');
else if (val != null)
msg.params[name] = [ val, _urldecode(buffer, DECODE_PLUS) || '' ];
else
msg.params[name] = _urldecode(buffer, DECODE_PLUS) || '';
}
else if (what == parser.ERROR) {
err = buffer;
}
return true;
}, HTTP_MAX_CONTENT);
while (true) {
let chunk = src();
len += length(chunk);
if (maxlen && len > maxlen + 2)
die('Message body size exceeds Content-Length');
if (!parser.parse(chunk))
die(err);
if (chunk == null)
break;
}
};
// This function will examine the Content-Type within the given message object
// to select the appropriate content decoder.
// Currently the application/x-www-urlencoded and application/form-data
// mime types are supported. If the encountered content encoding can't be
// handled then the whole message body will be stored unaltered as 'content'
// property within the given message object.
export function parse_message_body(src, msg, filecb) {
if (msg.env.CONTENT_LENGTH || msg.env.REQUEST_METHOD == 'POST') {
let ctype = header_attribute(msg.env.CONTENT_TYPE, null);
// Is it multipart/mime ?
if (ctype == 'multipart/form-data')
return mimedecode_message_body(src, msg, filecb);
// Is it application/x-www-form-urlencoded ?
else if (ctype == 'application/x-www-form-urlencoded')
return urldecode_message_body(src, msg);
// Unhandled encoding
// If a file callback is given then feed it chunk by chunk, else
// store whole buffer in message.content
let sink;
// If we have a file callback then feed it
if (type(filecb) == 'function') {
let meta = {
name: 'raw',
encoding: msg.env.CONTENT_TYPE
};
sink = (chunk) => {
if (chunk != null)
return filecb(meta, chunk, false);
else
return filecb(meta, null, true);
};
}
// ... else append to .content
else {
let chunks = [], len = 0;
sink = (chunk) => {
len += length(chunk);
if (len > HTTP_MAX_CONTENT)
die('POST data exceeds maximum allowed length');
if (chunk != null) {
push(chunks, chunk);
}
else {
msg.content = join('', chunks);
msg.content_length = len;
}
};
}
// Pump data...
while (true) {
let chunk = src();
sink(chunk);
if (chunk == null)
break;
}
return true;
}
return false;
};
export function build_querystring(q) {
let s = [];
for (let k, v in q) {
push(s,
length(s) ? '&' : '?',
_urlencode(k, ENCODE_IF_NEEDED | ENCODE_FULL) || k,
'=',
_urlencode(v, ENCODE_IF_NEEDED | ENCODE_FULL) || v
);
}
return join('', s);
};
export function urlencode(value) {
if (value == null)
return null;
value = '' + value;
return _urlencode(value, ENCODE_IF_NEEDED | ENCODE_FULL) || value;
};
export function urldecode(value, decode_plus) {
if (value == null)
return null;
value = '' + value;
return _urldecode(value, DECODE_IF_NEEDED | (decode_plus ? DECODE_PLUS : 0)) || value;
};
// Extract and split urlencoded data pairs, separated bei either "&" or ";"
// from given url or string. Returns a table with urldecoded values.
// Simple parameters are stored as string values associated with the parameter
// name within the table. Parameters with multiple values are stored as array
// containing the corresponding values.
export function urldecode_params(url, tbl) {
let parser, name, value;
let params = tbl || {};
parser = urlencoded_parser(function(what, buffer, length) {
if (what == parser.TUPLE) {
name = null;
value = null;
}
else if (what == parser.NAME) {
name = _urldecode(buffer);
}
else if (what == parser.VALUE && name) {
params[name] = _urldecode(buffer) || '';
}
return true;
});
if (parser) {
let m = match(('' + (url || '')), /[^?]*$/);
parser.parse(m ? m[0] : '');
parser.parse(null);
}
return params;
};
// Encode each key-value-pair in given table to x-www-urlencoded format,
// separated by '&'. Tables are encoded as parameters with multiple values by
// repeating the parameter name with each value.
export function urlencode_params(tbl) {
let enc = [];
for (let k, v in tbl) {
if (type(v) == 'array') {
for (let v2 in v) {
if (length(enc))
push(enc, '&');
push(enc,
_urlencode(k),
'=',
_urlencode('' + v2));
}
}
else {
if (length(enc))
push(enc, '&');
push(enc,
_urlencode(k),
'=',
_urlencode('' + v));
}
}
return join(enc, '');
};
// Default IO routines suitable for CGI invocation
let avail_len = +getenv('CONTENT_LENGTH');
const default_source = () => {
let rlen = min(avail_len, 4096);
if (rlen == 0) {
stdin.close();
return null;
}
let chunk = stdin.read(rlen);
if (chunk == null)
die(`Input read error: ${fserror()}`);
avail_len -= length(chunk);
return chunk;
};
const default_sink = (...chunks) => {
for (let chunk in chunks)
stdout.write(chunk);
stdout.flush();
};
const Class = {
formvalue: function(name, noparse) {
if (!noparse && !this.parsed_input)
this._parse_input();
if (name != null)
return this.message.params[name];
else
return this.message.params;
},
formvaluetable: function(prefix) {
let vals = {};
prefix = (prefix || '') + '.';
if (!this.parsed_input)
this._parse_input();
for (let k, v in this.message.params)
if (index(k, prefix) == 0)
vals[substr(k, length(prefix))] = '' + v;
return vals;
},
content: function() {
if (!this.parsed_input)
this._parse_input();
return this.message.content;
},
getcookie: function(name) {
return header_attribute(`cookie; ${this.getenv('HTTP_COOKIE') ?? ''}`, name);
},
getenv: function(name) {
if (name != null)
return this.message.env[name];
else
return this.message.env;
},
setfilehandler: function(callback) {
if (type(callback) == 'resource' && type(callback.call) == 'function')
this.filehandler = (...args) => callback.call(...args);
else if (type(callback) == 'function')
this.filehandler = callback;
else
die('Invalid callback argument for setfilehandler()');
if (!this.parsed_input)
return;
// If input has already been parsed then uploads are stored as unlinked
// temporary files pointed to by open file handles in the parameter
// value table. Loop all params, and invoke the file callback for any
// param with an open file handle.
for (let name, value in this.message.params) {
while (value?.fd) {
let data = value.fd.read(1024);
let eof = (data == null || data == '');
callback(value, data, eof);
if (eof) {
value.fd.close();
value.fd = null;
}
}
}
},
_parse_input: function() {
parse_message_body(
this.input,
this.message,
this.filehandler
);
this.parsed_input = true;
},
close: function() {
this.write_headers();
this.closed = true;
},
header: function(key, value) {
this.headers ??= {};
this.headers[lc(key)] = value;
},
prepare_content: function(mime) {
if (!this.headers?.['content-type']) {
if (mime == 'application/xhtml+xml') {
if (index(this.getenv('HTTP_ACCEPT'), mime) == -1) {
mime = 'text/html; charset=UTF-8';
this.header('Vary', 'Accept');
}
}
this.header('Content-Type', mime);
}
},
status: function(code, message) {
this.status_code = code ?? 200;
this.status_message = message ?? 'OK';
},
write_headers: function() {
if (this.eoh)
return;
if (!this.status_code)
this.status();
if (!this.headers?.['content-type'])
this.header('Content-Type', 'text/html; charset=UTF-8');
if (!this.headers?.['cache-control']) {
this.header('Cache-Control', 'no-cache');
this.header('Expires', '0');
}
if (!this.headers?.['x-frame-options'])
this.header('X-Frame-Options', 'SAMEORIGIN');
if (!this.headers?.['x-xss-protection'])
this.header('X-XSS-Protection', '1; mode=block');
if (!this.headers?.['x-content-type-options'])
this.header('X-Content-Type-Options', 'nosniff');
this.output('Status: ');
this.output(this.status_code);
this.output(' ');
this.output(this.status_message);
this.output('\r\n');
for (let k, v in this.headers) {
this.output(k);
this.output(': ');
this.output(v);
this.output('\r\n');
}
this.output('\r\n');
this.eoh = true;
},
// If the content chunk is nil this function will automatically invoke close.
write: function(content) {
if (content != null) {
this.write_headers();
this.output(content);
return true;
}
else {
this.close();
}
},
redirect: function(url) {
this.status(302, 'Found');
this.header('Location', url ?? '/');
this.close();
},
write_json: function(value) {
this.write(sprintf('%.J', value));
},
urlencode,
urlencode_params,
urldecode,
urldecode_params,
build_querystring
};
export default function(env, sourcein, sinkout) {
return proto({
input: sourcein ?? default_source,
output: sinkout ?? default_sink,
// File handler nil by default to let .content() work
file: null,
// HTTP-Message table
message: {
env,
headers: {},
params: urldecode_params(env?.QUERY_STRING ?? '')
},
parsed_input: false
}, Class);
};

View file

@ -0,0 +1,163 @@
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.
import { access, basename } from 'fs';
import { cursor } from 'uci';
const template_directory = '/usr/share/ucode/luci/template';
function cut_message(msg) {
return trim(replace(msg, /\n--\n.*$/, ''));
}
function format_nested_exception(ex) {
let msg = replace(cut_message(ex.message), /(\n+( \|[^\n]*(\n|$))+)/, (m, m1) => {
m1 = replace(m1, /(^|\n) \| ?/g, '$1');
m = match(m1, /^(.+?)\n(In.*line \d+, byte \d+:.+)$/);
return `
<div class="exception">
<div class="message">${cut_message(m ? m[1] : m1)}</div>
${m ? `<pre class="context">${trim(m[2])}</pre>` : ''}
</div>
`;
});
return `
<div class="exception">
<div class="message">${cut_message(msg)}</div>
<pre class="context">${trim(ex.stacktrace[0].context)}</pre>
</div>
`;
}
function format_lua_exception(ex) {
let m = match(ex.message, /^(.+)\nstack traceback:\n(.+)$/);
return `
<div class="exception">
<div class="message">${cut_message(m ? m[1] : ex.message)}</div>
<pre class="context">${m ? trim(replace(m[2], /(^|\n)\t/g, '$1')) : ex.stacktrace[0].context}</pre>
</div>
`;
}
const Class = {
init_lua: function() {
if (!this.L) {
this.L = this.env.dispatcher.load_luabridge().create();
this.L.set('L', proto({ write: print }, this.env));
this.L.eval('package.path = "/usr/lib/lua/luci/ucodebridge/?.lua;" .. package.path');
this.L.invoke('require', 'luci.ucodebridge');
this.env.lua_active = true;
}
return this.L;
},
render_ucode: function(path, scope) {
let tmplfunc = loadfile(path, { raw_mode: false });
call(tmplfunc, null, scope ?? {});
},
render_lua: function(path, scope) {
let vm = this.init_lua();
let render = vm.get('_G', 'luci', 'ucodebridge', 'render');
render.call(path, scope ?? {});
},
trycompile: function(path) {
let ucode_path = `${template_directory}/${path}.ut`;
if (access(ucode_path)) {
try {
loadfile(ucode_path, { raw_mode: false });
}
catch (ucode_err) {
return `Unable to compile '${path}' as ucode template: ${format_nested_exception(ucode_err)}`;
}
}
else {
try {
let vm = this.init_lua();
let compile = vm.get('_G', 'luci', 'ucodebridge', 'compile');
compile.call(path);
}
catch (lua_err) {
return `Unable to compile '${path}' as Lua template: ${format_lua_exception(lua_err)}`;
}
}
return true;
},
render_any: function(path, scope) {
let ucode_path = `${template_directory}/${path}.ut`;
scope = proto(scope ?? {}, this.scopes[-1]);
push(this.scopes, scope);
try {
if (access(ucode_path))
this.render_ucode(ucode_path, scope);
else
this.render_lua(path, scope);
}
catch (ex) {
pop(this.scopes);
die(ex);
}
pop(this.scopes);
},
render: function(path, scope) {
let self = this;
this.env.http.write(render(() => self.render_any(path, scope)));
},
call: function(modname, method, ...args) {
let vm = this.init_lua();
let lcall = vm.get('_G', 'luci', 'ucodebridge', 'call');
return lcall.call(modname, method, ...args);
}
};
export default function(env) {
const self = proto({ env: env ??= {}, scopes: [ proto(env, global) ], global }, Class);
const uci = cursor();
// determine theme
let media = uci.get('luci', 'main', 'mediaurlbase');
let status = self.trycompile(`themes/${basename(media)}/header`);
if (status !== true) {
media = null;
for (let k, v in uci.get_all('luci', 'themes')) {
if (substr(k, 0, 1) != '.') {
status = self.trycompile(`themes/${basename(v)}/header`);
if (status === true) {
media = v;
break;
}
}
}
if (!media)
error500(`Unable to render any theme header template, last error was:\n${status}`);
}
self.env.media = media;
self.env.theme = basename(media);
self.env.resource = uci.get('luci', 'main', 'resourcebase');
self.env.include = (...args) => self.render_any(...args);
return self;
};

View file

@ -0,0 +1,157 @@
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.
import { basename, readlink, readfile, open, popen, stat, glob } from 'fs';
export function process_list() {
const top = popen('/bin/busybox top -bn1');
let line, list = [];
for (let line = top.read('line'); length(line); line = top.read('line')) {
let m = match(trim(line), /^([0-9]+) +([0-9]+) +(.+) +([RSDZTWI][<NW ][<N ]) +([0-9]+m?) +([0-9]+%) +([0-9]+%) +(.+)$/);
if (m && m[8] != '/bin/busybox top -bn1') {
push(list, {
PID: m[1],
PPID: m[2],
USER: trim(m[3]),
STAT: m[4],
VSZ: m[5],
'%MEM': m[6],
'%CPU': m[7],
COMMAND: m[8]
});
}
}
top.close();
return list;
};
export function conntrack_list(callback) {
const etcpr = open('/etc/protocols');
const protos = {};
if (etcpr) {
for (let line = etcpr.read('line'); length(line); line = etcpr.read('line')) {
const m = match(line, /^([^# \t\n]+)\s+([0-9]+)\s+/);
if (m)
protos[m[2]] = m[1];
}
etcpr.close();
}
const nfct = open('/proc/net/nf_conntrack', 'r');
let connt;
if (nfct) {
for (let line = nfct.read('line'); length(line); line = nfct.read('line')) {
let m = match(line, /^(ipv[46]) +([0-9]+) +\S+ +([0-9]+) +(.+)\n$/);
if (!m)
continue;
let fam = m[1];
let l3 = m[2];
let l4 = m[3];
let tuples = m[4];
let timeout = null;
m = match(tuples, /^([0-9]+) (.+)$/);
if (m) {
timeout = m[1];
tuples = m[2];
}
if (index(tuples, 'TIME_WAIT ') === 0)
continue;
let e = {
bytes: 0,
packets: 0,
layer3: fam,
layer4: protos[l4] ?? 'unknown',
timeout: +timeout
};
for (let kv in match(tuples, / (\w+)=(\S+)/g)) {
switch (kv[1]) {
case 'bytes':
case 'packets':
e[kv[1]] += +kv[2];
break;
case 'src':
case 'dst':
e[kv[1]] ??= arrtoip(iptoarr(kv[2]));
break;
case 'sport':
case 'dport':
e[kv[1]] ??= +kv[2];
break;
default:
e[kv[1]] = kv[2];
}
}
if (callback)
callback(e);
else
push(connt ??= [], e);
}
nfct.close();
}
return callback ? true : (connt ?? []);
};
export function init_list() {
return map(filter(glob('/etc/init.d/*'), path => {
const s = stat(path);
return s?.type == 'file' && s?.perm?.user_exec;
}), basename);
};
export function init_index(name) {
const src = readfile(`/etc/init.d/${basename(name)}`, 1024);
const idx = [];
for (let m in match(src, /^[[:space:]]*(START|STOP)=('[0-9][0-9]'|"[0-9][0-9]"|[0-9][0-9])[[:space:]]*$/gs)) {
switch (m[1]) {
case 'START': idx[0] = +trim(m[2], '"\''); break;
case 'STOP': idx[1] = +trim(m[2], '"\''); break;
}
}
return length(idx) ? idx : null;
};
export function init_enabled(name) {
for (let path in glob(`/etc/rc.d/[SK][0-9][0-9]${basename(name)}`)) {
const ln = readlink(path);
const s1 = stat(index(ln, '/') == 0 ? ln : `/etc/rc.d/${ln}`);
const s2 = stat(`/etc/init.d/${basename(name)}`);
if (s1?.inode == s2?.inode && s1?.type == 'file' && s1?.perm?.user_exec)
return true;
}
return false;
};
export function init_action(name, action) {
const s = stat(`/etc/init.d/${basename(name)}`);
if (s?.type != 'file' || s?.user_exec == false)
return false;
return system(`env -i /etc/init.d/${basename(name)} ${action} >/dev/null`);
};

View file

@ -0,0 +1,24 @@
{#
Copyright 2015-2022 Jo-Philipp Wich <jo@mein.io>
Licensed to the public under the Apache License 2.0.
-#}
{% include('header') %}
<h2 name="content">{{ _('Form token mismatch') }}</h2>
<br />
<p class="alert-message">{{ _('The submitted security token is invalid or already expired!') }}</p>
<p>{{ _(`
In order to prevent unauthorized access to the system, your request has
been blocked. Click "Continue »" below to return to the previous page.
`) }}</p>
<hr />
<p class="right">
<strong><a href="#" onclick="window.history.back();">Continue »</a></strong>
</p>
{% include('footer') %}

View file

@ -0,0 +1,14 @@
{#
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-2022 Jo-Philipp Wich <jo@mein.io>
Licensed to the public under the Apache License 2.0.
-#}
{% include('header') %}
<h2 name="content">404 {{ _('Not Found') }}</h2>
<p>{{ _('Sorry, the object you requested was not found.') }}</p>
<p>{{ message }}</p>
<tt>{{ _('Unable to dispatch') }}: {{ dispatcher.build_url(...ctx.request_path) }}</tt>
{% include('footer') %}

View file

@ -0,0 +1,67 @@
{#
Copyright 2022 Jo-Philipp Wich <jo@mein.io>
Licensed to the public under the Apache License 2.0.
-#}
<!--]]>--><!--'>--><!--">-->
<style type="text/css">
body {
line-height: 1.5;
font-size: 14px;
font-family: sans-serif;
}
.error500 * {
margin: 0;
padding: 0;
color: inherit;
}
.error500 {
box-sizing: border-box;
position: fixed;
z-index: 999999;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
overflow: auto;
background: #ffe;
color: #f00 !important;
padding: 1em;
}
.error500 h1 {
margin-bottom: .5em;
}
.error500 .exception {
font-weight: normal;
white-space: normal;
margin: .25em;
padding: .5em;
border: 1px solid #f00;
background: rgba(204, 204, 204, .2);
}
.error500 .message {
font-weight: bold;
white-space: pre-line;
}
.error500 .context {
margin-top: 2em;
}
</style>
<div class="error500">
<h1>{{ title }}</h1>
<div class="message">{{ message }}</div>
{% if (exception): %}
<div class="exception">
<div class="message">{{ exception.message }}</div>
<pre class="context">{{ exception.stacktrace[0].context }}</pre>
</div>
{% endif %}
</div>

View file

@ -0,0 +1,23 @@
{#
Copyright 2022 Jo-Philipp Wich <jo@mein.io>
Licensed to the public under the Apache License 2.0.
-#}
{% const rollback = dispatcher.rollback_pending() %}
{% if (rollback || trigger_apply || trigger_revert): %}
<script type="text/javascript">
document.addEventListener("luci-loaded", function() {
{% if (trigger_apply): %}
L.ui.changes.apply(true);
{% elif (trigger_revert): %}
L.ui.changes.revert();
{% else %}
L.ui.changes.confirm(true, Date.now() + {{rollback.remaining * 1000}}, {{sprintf('%J', rollback.token)}});
{% endif %}
});
</script>
{% endif %}
{% include(`themes/${theme}/footer`) %}
<!-- Lua compatibility mode active: {{ lua_active ? 'yes' : 'no' }} -->

View file

@ -0,0 +1,32 @@
{#
Copyright 2022 Jo-Philipp Wich <jo@mein.io>
Licensed to the public under the Apache License 2.0.
-#}
{%
include(`themes/${theme}/header`);
-%}
<script type="text/javascript" src="{{ resource }}/promis.min.js"></script>
<script type="text/javascript" src="{{ resource }}/luci.js"></script>
<script type="text/javascript">
L = new LuCI({{ {
media : media,
resource : resource,
scriptname : http.getenv("SCRIPT_NAME"),
pathinfo : http.getenv("PATH_INFO"),
documentroot : http.getenv("DOCUMENT_ROOT"),
requestpath : ctx.request_path,
dispatchpath : ctx.path,
pollinterval : +config.main.pollinterval || 5,
ubuspath : config.main.ubuspath || '/ubus/',
sessionid : ctx.authsession,
token : ctx.authtoken,
nodespec : node,
apply_rollback : max(+config.apply.rollback || 90, 90),
apply_holdoff : max(+config.apply.holdoff || 4, 1),
apply_timeout : max(+config.apply.timeout || 5, 1),
apply_display : max(+config.apply.display || 1.5, 1),
rollback_token : rollback_token
} }});
</script>

View file

@ -0,0 +1,74 @@
{#
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-2012 Jo-Philipp Wich <jow@openwrt.org>
Licensed to the public under the Apache License 2.0.
-#}
{% include('header') %}
<form method="post">
{% if (fuser): %}
<div class="alert-message warning">
<p>{{ _('Invalid username and/or password! Please try again.') }}</p>
</div>
{% endif %}
<div class="cbi-map">
<h2 name="content">{{ _('Authorization Required') }}</h2>
<div class="cbi-map-descr">
{{ _('Please enter your username and password.') }}
</div>
<div class="cbi-section"><div class="cbi-section-node">
<div class="cbi-value">
<label class="cbi-value-title">{{ _('Username') }}</label>
<div class="cbi-value-field">
<input class="cbi-input-text" type="text" name="luci_username" value="{{ entityencode(duser, true) }}" />
</div>
</div>
<div class="cbi-value cbi-value-last">
<label class="cbi-value-title">{{ _('Password') }}</label>
<div class="cbi-value-field">
<input class="cbi-input-text" type="password" name="luci_password" />
</div>
</div>
</div></div>
</div>
<div class="cbi-page-actions">
<input type="submit" value="{{ _('Login') }}" class="btn cbi-button cbi-button-apply" />
<input type="reset" value="{{ _('Reset') }}" class="btn cbi-button cbi-button-reset" />
</div>
</form>
{%
let https_ports = uci.get('uhttpd', 'main', 'listen_https') ?? [];
https_ports = uniq(filter(
map(
(type(https_ports) == 'string') ? split(https_port, /\s+/) : https_ports,
e => +match(e, /\d+$/)?.[0]
),
p => (p >= 0 && p <= 65535)
));
%}
<script type="text/javascript">//<![CDATA[
var input = document.getElementsByName('luci_password')[0];
if (input)
input.focus();
if (document.location.protocol != 'https:') {
{{ https_ports }}.forEach(function(port) {
var url = 'https://' + window.location.hostname + ':' + port + window.location.pathname;
var img = new Image();
img.onload = function() { window.location = url };
img.src = 'https://' + window.location.hostname + ':' + port + '{{ resource }}/icons/loading.gif?' + Math.random();
setTimeout(function() { img.src = '' }, 5000);
});
}
//]]></script>
{% include('footer') %}

View file

@ -0,0 +1,12 @@
{% include('header') %}
<div id="view">
<div class="spinning">{{ _('Loading view…') }}</div>
<script type="text/javascript">
L.require('ui').then(function(ui) {
ui.instantiateView('{{ view }}');
});
</script>
</div>
{% include('footer') %}

View file

@ -0,0 +1,12 @@
{%
import dispatch from 'luci.dispatcher';
import request from 'luci.http';
global.handle_request = function(env) {
let req = request(env, uhttpd.recv, uhttpd.send);
dispatch(req);
req.close();
};

View file

@ -0,0 +1,453 @@
// Autogenerated by zoneinfo2ucode.pl
export default {
'Africa/Abidjan': 'GMT0',
'Africa/Accra': 'GMT0',
'Africa/Addis Ababa': 'EAT-3',
'Africa/Algiers': 'CET-1',
'Africa/Asmara': 'EAT-3',
'Africa/Bamako': 'GMT0',
'Africa/Bangui': 'WAT-1',
'Africa/Banjul': 'GMT0',
'Africa/Bissau': 'GMT0',
'Africa/Blantyre': 'CAT-2',
'Africa/Brazzaville': 'WAT-1',
'Africa/Bujumbura': 'CAT-2',
'Africa/Cairo': 'EET-2',
'Africa/Casablanca': '<+01>-1',
'Africa/Ceuta': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Africa/Conakry': 'GMT0',
'Africa/Dakar': 'GMT0',
'Africa/Dar es Salaam': 'EAT-3',
'Africa/Djibouti': 'EAT-3',
'Africa/Douala': 'WAT-1',
'Africa/El Aaiun': '<+01>-1',
'Africa/Freetown': 'GMT0',
'Africa/Gaborone': 'CAT-2',
'Africa/Harare': 'CAT-2',
'Africa/Johannesburg': 'SAST-2',
'Africa/Juba': 'CAT-2',
'Africa/Kampala': 'EAT-3',
'Africa/Khartoum': 'CAT-2',
'Africa/Kigali': 'CAT-2',
'Africa/Kinshasa': 'WAT-1',
'Africa/Lagos': 'WAT-1',
'Africa/Libreville': 'WAT-1',
'Africa/Lome': 'GMT0',
'Africa/Luanda': 'WAT-1',
'Africa/Lubumbashi': 'CAT-2',
'Africa/Lusaka': 'CAT-2',
'Africa/Malabo': 'WAT-1',
'Africa/Maputo': 'CAT-2',
'Africa/Maseru': 'SAST-2',
'Africa/Mbabane': 'SAST-2',
'Africa/Mogadishu': 'EAT-3',
'Africa/Monrovia': 'GMT0',
'Africa/Nairobi': 'EAT-3',
'Africa/Ndjamena': 'WAT-1',
'Africa/Niamey': 'WAT-1',
'Africa/Nouakchott': 'GMT0',
'Africa/Ouagadougou': 'GMT0',
'Africa/Porto-Novo': 'WAT-1',
'Africa/Sao Tome': 'GMT0',
'Africa/Tripoli': 'EET-2',
'Africa/Tunis': 'CET-1',
'Africa/Windhoek': 'CAT-2',
'America/Adak': 'HST10HDT,M3.2.0,M11.1.0',
'America/Anchorage': 'AKST9AKDT,M3.2.0,M11.1.0',
'America/Anguilla': 'AST4',
'America/Antigua': 'AST4',
'America/Araguaina': '<-03>3',
'America/Argentina/Buenos Aires': '<-03>3',
'America/Argentina/Catamarca': '<-03>3',
'America/Argentina/Cordoba': '<-03>3',
'America/Argentina/Jujuy': '<-03>3',
'America/Argentina/La Rioja': '<-03>3',
'America/Argentina/Mendoza': '<-03>3',
'America/Argentina/Rio Gallegos': '<-03>3',
'America/Argentina/Salta': '<-03>3',
'America/Argentina/San Juan': '<-03>3',
'America/Argentina/San Luis': '<-03>3',
'America/Argentina/Tucuman': '<-03>3',
'America/Argentina/Ushuaia': '<-03>3',
'America/Aruba': 'AST4',
'America/Asuncion': '<-04>4<-03>,M10.1.0/0,M3.4.0/0',
'America/Atikokan': 'EST5',
'America/Bahia': '<-03>3',
'America/Bahia Banderas': 'CST6CDT,M4.1.0,M10.5.0',
'America/Barbados': 'AST4',
'America/Belem': '<-03>3',
'America/Belize': 'CST6',
'America/Blanc-Sablon': 'AST4',
'America/Boa Vista': '<-04>4',
'America/Bogota': '<-05>5',
'America/Boise': 'MST7MDT,M3.2.0,M11.1.0',
'America/Cambridge Bay': 'MST7MDT,M3.2.0,M11.1.0',
'America/Campo Grande': '<-04>4',
'America/Cancun': 'EST5',
'America/Caracas': '<-04>4',
'America/Cayenne': '<-03>3',
'America/Cayman': 'EST5',
'America/Chicago': 'CST6CDT,M3.2.0,M11.1.0',
'America/Chihuahua': 'MST7MDT,M4.1.0,M10.5.0',
'America/Costa Rica': 'CST6',
'America/Creston': 'MST7',
'America/Cuiaba': '<-04>4',
'America/Curacao': 'AST4',
'America/Danmarkshavn': 'GMT0',
'America/Dawson': 'MST7',
'America/Dawson Creek': 'MST7',
'America/Denver': 'MST7MDT,M3.2.0,M11.1.0',
'America/Detroit': 'EST5EDT,M3.2.0,M11.1.0',
'America/Dominica': 'AST4',
'America/Edmonton': 'MST7MDT,M3.2.0,M11.1.0',
'America/Eirunepe': '<-05>5',
'America/El Salvador': 'CST6',
'America/Fort Nelson': 'MST7',
'America/Fortaleza': '<-03>3',
'America/Glace Bay': 'AST4ADT,M3.2.0,M11.1.0',
'America/Goose Bay': 'AST4ADT,M3.2.0,M11.1.0',
'America/Grand Turk': 'EST5EDT,M3.2.0,M11.1.0',
'America/Grenada': 'AST4',
'America/Guadeloupe': 'AST4',
'America/Guatemala': 'CST6',
'America/Guayaquil': '<-05>5',
'America/Guyana': '<-04>4',
'America/Halifax': 'AST4ADT,M3.2.0,M11.1.0',
'America/Havana': 'CST5CDT,M3.2.0/0,M11.1.0/1',
'America/Hermosillo': 'MST7',
'America/Indiana/Indianapolis': 'EST5EDT,M3.2.0,M11.1.0',
'America/Indiana/Knox': 'CST6CDT,M3.2.0,M11.1.0',
'America/Indiana/Marengo': 'EST5EDT,M3.2.0,M11.1.0',
'America/Indiana/Petersburg': 'EST5EDT,M3.2.0,M11.1.0',
'America/Indiana/Tell City': 'CST6CDT,M3.2.0,M11.1.0',
'America/Indiana/Vevay': 'EST5EDT,M3.2.0,M11.1.0',
'America/Indiana/Vincennes': 'EST5EDT,M3.2.0,M11.1.0',
'America/Indiana/Winamac': 'EST5EDT,M3.2.0,M11.1.0',
'America/Inuvik': 'MST7MDT,M3.2.0,M11.1.0',
'America/Iqaluit': 'EST5EDT,M3.2.0,M11.1.0',
'America/Jamaica': 'EST5',
'America/Juneau': 'AKST9AKDT,M3.2.0,M11.1.0',
'America/Kentucky/Louisville': 'EST5EDT,M3.2.0,M11.1.0',
'America/Kentucky/Monticello': 'EST5EDT,M3.2.0,M11.1.0',
'America/Kralendijk': 'AST4',
'America/La Paz': '<-04>4',
'America/Lima': '<-05>5',
'America/Los Angeles': 'PST8PDT,M3.2.0,M11.1.0',
'America/Lower Princes': 'AST4',
'America/Maceio': '<-03>3',
'America/Managua': 'CST6',
'America/Manaus': '<-04>4',
'America/Marigot': 'AST4',
'America/Martinique': 'AST4',
'America/Matamoros': 'CST6CDT,M3.2.0,M11.1.0',
'America/Mazatlan': 'MST7MDT,M4.1.0,M10.5.0',
'America/Menominee': 'CST6CDT,M3.2.0,M11.1.0',
'America/Merida': 'CST6CDT,M4.1.0,M10.5.0',
'America/Metlakatla': 'AKST9AKDT,M3.2.0,M11.1.0',
'America/Mexico City': 'CST6CDT,M4.1.0,M10.5.0',
'America/Miquelon': '<-03>3<-02>,M3.2.0,M11.1.0',
'America/Moncton': 'AST4ADT,M3.2.0,M11.1.0',
'America/Monterrey': 'CST6CDT,M4.1.0,M10.5.0',
'America/Montevideo': '<-03>3',
'America/Montserrat': 'AST4',
'America/Nassau': 'EST5EDT,M3.2.0,M11.1.0',
'America/New York': 'EST5EDT,M3.2.0,M11.1.0',
'America/Nipigon': 'EST5EDT,M3.2.0,M11.1.0',
'America/Nome': 'AKST9AKDT,M3.2.0,M11.1.0',
'America/Noronha': '<-02>2',
'America/North Dakota/Beulah': 'CST6CDT,M3.2.0,M11.1.0',
'America/North Dakota/Center': 'CST6CDT,M3.2.0,M11.1.0',
'America/North Dakota/New Salem': 'CST6CDT,M3.2.0,M11.1.0',
'America/Nuuk': '<-03>3<-02>,M3.5.0/-2,M10.5.0/-1',
'America/Ojinaga': 'MST7MDT,M3.2.0,M11.1.0',
'America/Panama': 'EST5',
'America/Pangnirtung': 'EST5EDT,M3.2.0,M11.1.0',
'America/Paramaribo': '<-03>3',
'America/Phoenix': 'MST7',
'America/Port of Spain': 'AST4',
'America/Port-au-Prince': 'EST5EDT,M3.2.0,M11.1.0',
'America/Porto Velho': '<-04>4',
'America/Puerto Rico': 'AST4',
'America/Punta Arenas': '<-03>3',
'America/Rainy River': 'CST6CDT,M3.2.0,M11.1.0',
'America/Rankin Inlet': 'CST6CDT,M3.2.0,M11.1.0',
'America/Recife': '<-03>3',
'America/Regina': 'CST6',
'America/Resolute': 'CST6CDT,M3.2.0,M11.1.0',
'America/Rio Branco': '<-05>5',
'America/Santarem': '<-03>3',
'America/Santiago': '<-04>4<-03>,M9.1.6/24,M4.1.6/24',
'America/Santo Domingo': 'AST4',
'America/Sao Paulo': '<-03>3',
'America/Scoresbysund': '<-01>1<+00>,M3.5.0/0,M10.5.0/1',
'America/Sitka': 'AKST9AKDT,M3.2.0,M11.1.0',
'America/St Barthelemy': 'AST4',
'America/St Johns': 'NST3:30NDT,M3.2.0,M11.1.0',
'America/St Kitts': 'AST4',
'America/St Lucia': 'AST4',
'America/St Thomas': 'AST4',
'America/St Vincent': 'AST4',
'America/Swift Current': 'CST6',
'America/Tegucigalpa': 'CST6',
'America/Thule': 'AST4ADT,M3.2.0,M11.1.0',
'America/Thunder Bay': 'EST5EDT,M3.2.0,M11.1.0',
'America/Tijuana': 'PST8PDT,M3.2.0,M11.1.0',
'America/Toronto': 'EST5EDT,M3.2.0,M11.1.0',
'America/Tortola': 'AST4',
'America/Vancouver': 'PST8PDT,M3.2.0,M11.1.0',
'America/Whitehorse': 'MST7',
'America/Winnipeg': 'CST6CDT,M3.2.0,M11.1.0',
'America/Yakutat': 'AKST9AKDT,M3.2.0,M11.1.0',
'America/Yellowknife': 'MST7MDT,M3.2.0,M11.1.0',
'Antarctica/Casey': '<+11>-11',
'Antarctica/Davis': '<+07>-7',
'Antarctica/DumontDUrville': '<+10>-10',
'Antarctica/Macquarie': 'AEST-10AEDT,M10.1.0,M4.1.0/3',
'Antarctica/Mawson': '<+05>-5',
'Antarctica/McMurdo': 'NZST-12NZDT,M9.5.0,M4.1.0/3',
'Antarctica/Palmer': '<-03>3',
'Antarctica/Rothera': '<-03>3',
'Antarctica/Syowa': '<+03>-3',
'Antarctica/Troll': '<+00>0<+02>-2,M3.5.0/1,M10.5.0/3',
'Antarctica/Vostok': '<+06>-6',
'Arctic/Longyearbyen': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Asia/Aden': '<+03>-3',
'Asia/Almaty': '<+06>-6',
'Asia/Amman': '<+03>-3',
'Asia/Anadyr': '<+12>-12',
'Asia/Aqtau': '<+05>-5',
'Asia/Aqtobe': '<+05>-5',
'Asia/Ashgabat': '<+05>-5',
'Asia/Atyrau': '<+05>-5',
'Asia/Baghdad': '<+03>-3',
'Asia/Bahrain': '<+03>-3',
'Asia/Baku': '<+04>-4',
'Asia/Bangkok': '<+07>-7',
'Asia/Barnaul': '<+07>-7',
'Asia/Beirut': 'EET-2EEST,M3.5.0/0,M10.5.0/0',
'Asia/Bishkek': '<+06>-6',
'Asia/Brunei': '<+08>-8',
'Asia/Chita': '<+09>-9',
'Asia/Choibalsan': '<+08>-8',
'Asia/Colombo': '<+0530>-5:30',
'Asia/Damascus': '<+03>-3',
'Asia/Dhaka': '<+06>-6',
'Asia/Dili': '<+09>-9',
'Asia/Dubai': '<+04>-4',
'Asia/Dushanbe': '<+05>-5',
'Asia/Famagusta': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Asia/Gaza': 'EET-2EEST,M3.4.4/50,M10.4.4/50',
'Asia/Hebron': 'EET-2EEST,M3.4.4/50,M10.4.4/50',
'Asia/Ho Chi Minh': '<+07>-7',
'Asia/Hong Kong': 'HKT-8',
'Asia/Hovd': '<+07>-7',
'Asia/Irkutsk': '<+08>-8',
'Asia/Jakarta': 'WIB-7',
'Asia/Jayapura': 'WIT-9',
'Asia/Jerusalem': 'IST-2IDT,M3.4.4/26,M10.5.0',
'Asia/Kabul': '<+0430>-4:30',
'Asia/Kamchatka': '<+12>-12',
'Asia/Karachi': 'PKT-5',
'Asia/Kathmandu': '<+0545>-5:45',
'Asia/Khandyga': '<+09>-9',
'Asia/Kolkata': 'IST-5:30',
'Asia/Krasnoyarsk': '<+07>-7',
'Asia/Kuala Lumpur': '<+08>-8',
'Asia/Kuching': '<+08>-8',
'Asia/Kuwait': '<+03>-3',
'Asia/Macau': 'CST-8',
'Asia/Magadan': '<+11>-11',
'Asia/Makassar': 'WITA-8',
'Asia/Manila': 'PST-8',
'Asia/Muscat': '<+04>-4',
'Asia/Nicosia': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Asia/Novokuznetsk': '<+07>-7',
'Asia/Novosibirsk': '<+07>-7',
'Asia/Omsk': '<+06>-6',
'Asia/Oral': '<+05>-5',
'Asia/Phnom Penh': '<+07>-7',
'Asia/Pontianak': 'WIB-7',
'Asia/Pyongyang': 'KST-9',
'Asia/Qatar': '<+03>-3',
'Asia/Qostanay': '<+06>-6',
'Asia/Qyzylorda': '<+05>-5',
'Asia/Riyadh': '<+03>-3',
'Asia/Sakhalin': '<+11>-11',
'Asia/Samarkand': '<+05>-5',
'Asia/Seoul': 'KST-9',
'Asia/Shanghai': 'CST-8',
'Asia/Singapore': '<+08>-8',
'Asia/Srednekolymsk': '<+11>-11',
'Asia/Taipei': 'CST-8',
'Asia/Tashkent': '<+05>-5',
'Asia/Tbilisi': '<+04>-4',
'Asia/Tehran': '<+0330>-3:30',
'Asia/Thimphu': '<+06>-6',
'Asia/Tokyo': 'JST-9',
'Asia/Tomsk': '<+07>-7',
'Asia/Ulaanbaatar': '<+08>-8',
'Asia/Urumqi': '<+06>-6',
'Asia/Ust-Nera': '<+10>-10',
'Asia/Vientiane': '<+07>-7',
'Asia/Vladivostok': '<+10>-10',
'Asia/Yakutsk': '<+09>-9',
'Asia/Yangon': '<+0630>-6:30',
'Asia/Yekaterinburg': '<+05>-5',
'Asia/Yerevan': '<+04>-4',
'Atlantic/Azores': '<-01>1<+00>,M3.5.0/0,M10.5.0/1',
'Atlantic/Bermuda': 'AST4ADT,M3.2.0,M11.1.0',
'Atlantic/Canary': 'WET0WEST,M3.5.0/1,M10.5.0',
'Atlantic/Cape Verde': '<-01>1',
'Atlantic/Faroe': 'WET0WEST,M3.5.0/1,M10.5.0',
'Atlantic/Madeira': 'WET0WEST,M3.5.0/1,M10.5.0',
'Atlantic/Reykjavik': 'GMT0',
'Atlantic/South Georgia': '<-02>2',
'Atlantic/St Helena': 'GMT0',
'Atlantic/Stanley': '<-03>3',
'Australia/Adelaide': 'ACST-9:30ACDT,M10.1.0,M4.1.0/3',
'Australia/Brisbane': 'AEST-10',
'Australia/Broken Hill': 'ACST-9:30ACDT,M10.1.0,M4.1.0/3',
'Australia/Darwin': 'ACST-9:30',
'Australia/Eucla': '<+0845>-8:45',
'Australia/Hobart': 'AEST-10AEDT,M10.1.0,M4.1.0/3',
'Australia/Lindeman': 'AEST-10',
'Australia/Lord Howe': '<+1030>-10:30<+11>-11,M10.1.0,M4.1.0',
'Australia/Melbourne': 'AEST-10AEDT,M10.1.0,M4.1.0/3',
'Australia/Perth': 'AWST-8',
'Australia/Sydney': 'AEST-10AEDT,M10.1.0,M4.1.0/3',
'Etc/GMT': 'GMT0',
'Etc/GMT+1': '<-01>1',
'Etc/GMT+10': '<-10>10',
'Etc/GMT+11': '<-11>11',
'Etc/GMT+12': '<-12>12',
'Etc/GMT+2': '<-02>2',
'Etc/GMT+3': '<-03>3',
'Etc/GMT+4': '<-04>4',
'Etc/GMT+5': '<-05>5',
'Etc/GMT+6': '<-06>6',
'Etc/GMT+7': '<-07>7',
'Etc/GMT+8': '<-08>8',
'Etc/GMT+9': '<-09>9',
'Etc/GMT-1': '<+01>-1',
'Etc/GMT-10': '<+10>-10',
'Etc/GMT-11': '<+11>-11',
'Etc/GMT-12': '<+12>-12',
'Etc/GMT-13': '<+13>-13',
'Etc/GMT-14': '<+14>-14',
'Etc/GMT-2': '<+02>-2',
'Etc/GMT-3': '<+03>-3',
'Etc/GMT-4': '<+04>-4',
'Etc/GMT-5': '<+05>-5',
'Etc/GMT-6': '<+06>-6',
'Etc/GMT-7': '<+07>-7',
'Etc/GMT-8': '<+08>-8',
'Etc/GMT-9': '<+09>-9',
'Europe/Amsterdam': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Andorra': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Astrakhan': '<+04>-4',
'Europe/Athens': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Belgrade': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Berlin': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Bratislava': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Brussels': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Bucharest': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Budapest': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Busingen': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Chisinau': 'EET-2EEST,M3.5.0,M10.5.0/3',
'Europe/Copenhagen': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Dublin': 'IST-1GMT0,M10.5.0,M3.5.0/1',
'Europe/Gibraltar': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Guernsey': 'GMT0BST,M3.5.0/1,M10.5.0',
'Europe/Helsinki': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Isle of Man': 'GMT0BST,M3.5.0/1,M10.5.0',
'Europe/Istanbul': '<+03>-3',
'Europe/Jersey': 'GMT0BST,M3.5.0/1,M10.5.0',
'Europe/Kaliningrad': 'EET-2',
'Europe/Kirov': '<+03>-3',
'Europe/Kyiv': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Lisbon': 'WET0WEST,M3.5.0/1,M10.5.0',
'Europe/Ljubljana': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/London': 'GMT0BST,M3.5.0/1,M10.5.0',
'Europe/Luxembourg': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Madrid': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Malta': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Mariehamn': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Minsk': '<+03>-3',
'Europe/Monaco': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Moscow': 'MSK-3',
'Europe/Oslo': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Paris': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Podgorica': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Prague': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Riga': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Rome': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Samara': '<+04>-4',
'Europe/San Marino': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Sarajevo': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Saratov': '<+04>-4',
'Europe/Simferopol': 'MSK-3',
'Europe/Skopje': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Sofia': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Stockholm': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Tallinn': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Tirane': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Ulyanovsk': '<+04>-4',
'Europe/Vaduz': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Vatican': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Vienna': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Vilnius': 'EET-2EEST,M3.5.0/3,M10.5.0/4',
'Europe/Volgograd': '<+03>-3',
'Europe/Warsaw': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Zagreb': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Europe/Zurich': 'CET-1CEST,M3.5.0,M10.5.0/3',
'Indian/Antananarivo': 'EAT-3',
'Indian/Chagos': '<+06>-6',
'Indian/Christmas': '<+07>-7',
'Indian/Cocos': '<+0630>-6:30',
'Indian/Comoro': 'EAT-3',
'Indian/Kerguelen': '<+05>-5',
'Indian/Mahe': '<+04>-4',
'Indian/Maldives': '<+05>-5',
'Indian/Mauritius': '<+04>-4',
'Indian/Mayotte': 'EAT-3',
'Indian/Reunion': '<+04>-4',
'Pacific/Apia': '<+13>-13',
'Pacific/Auckland': 'NZST-12NZDT,M9.5.0,M4.1.0/3',
'Pacific/Bougainville': '<+11>-11',
'Pacific/Chatham': '<+1245>-12:45<+1345>,M9.5.0/2:45,M4.1.0/3:45',
'Pacific/Chuuk': '<+10>-10',
'Pacific/Easter': '<-06>6<-05>,M9.1.6/22,M4.1.6/22',
'Pacific/Efate': '<+11>-11',
'Pacific/Fakaofo': '<+13>-13',
'Pacific/Fiji': '<+12>-12<+13>,M11.2.0,M1.2.3/99',
'Pacific/Funafuti': '<+12>-12',
'Pacific/Galapagos': '<-06>6',
'Pacific/Gambier': '<-09>9',
'Pacific/Guadalcanal': '<+11>-11',
'Pacific/Guam': 'ChST-10',
'Pacific/Honolulu': 'HST10',
'Pacific/Kanton': '<+13>-13',
'Pacific/Kiritimati': '<+14>-14',
'Pacific/Kosrae': '<+11>-11',
'Pacific/Kwajalein': '<+12>-12',
'Pacific/Majuro': '<+12>-12',
'Pacific/Marquesas': '<-0930>9:30',
'Pacific/Midway': 'SST11',
'Pacific/Nauru': '<+12>-12',
'Pacific/Niue': '<-11>11',
'Pacific/Norfolk': '<+11>-11<+12>,M10.1.0,M4.1.0/3',
'Pacific/Noumea': '<+11>-11',
'Pacific/Pago Pago': 'SST11',
'Pacific/Palau': '<+09>-9',
'Pacific/Pitcairn': '<-08>8',
'Pacific/Pohnpei': '<+11>-11',
'Pacific/Port Moresby': '<+10>-10',
'Pacific/Rarotonga': '<-10>10',
'Pacific/Saipan': 'ChST-10',
'Pacific/Tahiti': '<-10>10',
'Pacific/Tarawa': '<+12>-12',
'Pacific/Tongatapu': '<+13>-13',
'Pacific/Wake': '<+12>-12',
'Pacific/Wallis': '<+12>-12',
};