1 // Copyright 2022 Jo-Philipp Wich <jo@mein.io>
2 // Licensed to the public under the Apache License 2.0.
4 import { open, stat, glob, lsdir, unlink, basename } from 'fs';
5 import { striptags, entityencode } from 'html';
6 import { connect } from 'ubus';
7 import { cursor } from 'uci';
8 import { rand } from 'math';
10 import { hash, load_catalog, change_catalog, translate, ntranslate, getuid } from 'luci.core';
11 import { revision as luciversion, branch as luciname } from 'luci.version';
12 import { default as LuCIRuntime } from 'luci.runtime';
13 import { urldecode } from 'luci.http';
18 let indexcache = "/tmp/luci-indexcache";
20 let http, runtime, tree, luabridge;
22 function error404(msg) {
23 http.status(404, 'Not Found');
26 runtime.render('error404', { message: msg ?? 'Not found' });
29 http.header('Content-Type', 'text/plain; charset=UTF-8');
30 http.write(msg ?? 'Not found');
36 function error500(msg, ex) {
38 http.status(500, 'Internal Server Error');
39 http.header('Content-Type', 'text/html; charset=UTF-8');
43 runtime.render('error500', {
44 title: ex?.type ?? 'Runtime exception',
47 /(\s)((\/[A-Za-z0-9_.-]+)+:\d+|\[string "[^"]+"\]:\d+)/g,
54 http.write('<!--]]>--><!--\'>--><!--">-->\n');
55 http.write(`<p>${trim(msg)}</p>\n`);
58 http.write(`<p>${trim(ex.message)}</p>\n`);
59 http.write(`<pre>${trim(ex.stacktrace[0].context)}</pre>\n`);
66 function load_luabridge(optional) {
67 if (luabridge == null) {
69 luabridge = require('lua');
75 error500('No Lua runtime installed');
82 function determine_request_language() {
83 let lang = uci.get('luci', 'main', 'lang') || 'auto';
86 for (let tag in split(http.getenv('HTTP_ACCEPT_LANGUAGE'), ',')) {
87 tag = split(trim(split(tag, ';')?.[0]), '-');
90 let cc = tag[1] ? `${tag[0]}_${lc(tag[1])}` : null;
92 if (cc && uci.get('luci', 'languages', cc)) {
96 else if (uci.get('luci', 'languages', tag[0])) {
107 lang = replace(lang, '_', '-');
109 if (load_catalog(lang, '/usr/lib/lua/luci/i18n'))
110 change_catalog(lang);
115 function determine_version() {
116 let res = { luciname, luciversion };
118 for (let f = open("/etc/os-release"), l = f?.read?.("line"); l; l = f.read?.("line")) {
119 let kv = split(l, '=', 2);
123 res.distname = trim(kv[1], '"\' \n');
127 res.distversion = trim(kv[1], '"\' \n');
131 res.disturl = trim(kv[1], '"\' \n');
135 res.distrevision = trim(kv[1], '"\' \n');
143 function read_jsonfile(path, defval) {
147 rv = json(open(path, "r"));
156 function read_cachefile(file, reader) {
163 perm?.group_read || perm?.group_write || perm?.group_exec ||
164 perm?.other_read || perm?.other_write || perm?.other_exec)
170 function check_fs_depends(spec) {
171 for (let path, kind in spec) {
172 if (kind == 'directory') {
173 if (!length(lsdir(path)))
176 else if (kind == 'executable') {
177 let fstat = stat(path);
179 if (fstat?.type != 'file' || fstat?.user_exec == false)
182 else if (kind == 'file') {
183 let fstat = stat(path);
185 if (fstat?.type != 'file')
188 else if (kind == 'absent') {
189 if (stat(path) != null)
197 function check_uci_depends_options(conf, s, opts) {
198 if (type(opts) == 'string') {
199 return (s['.type'] == opts);
201 else if (opts === true) {
202 for (let option, value in s)
203 if (ord(option) != 46)
206 else if (type(opts) == 'object') {
207 for (let option, value in opts) {
208 let sval = s[option];
210 if (type(sval) == 'array') {
211 if (!(value in sval))
214 else if (value === true) {
228 function check_uci_depends_section(conf, sect) {
229 for (let section, options in sect) {
230 let stype = match(section, /^@([A-Za-z0-9_-]+)$/);
236 uci.foreach(conf, stype[1], (s) => {
237 if (check_uci_depends_options(conf, s, options)) {
247 let s = uci.get_all(conf, section);
249 if (!s || !check_uci_depends_options(conf, s, options))
257 function check_uci_depends(conf) {
258 for (let config, values in conf) {
259 if (values == true) {
263 uci.foreach(config, null, () => { found = true });
268 else if (type(values) == 'object') {
269 if (!check_uci_depends_section(config, values))
277 function check_depends(spec) {
278 if (type(spec?.depends?.fs) in ['array', 'object']) {
279 let satisfied = false;
280 let alternatives = (type(spec.depends.fs) == 'array') ? spec.depends.fs : [ spec.depends.fs ];
282 for (let alternative in alternatives) {
283 if (check_fs_depends(alternative)) {
293 if (type(spec?.depends?.uci) in ['array', 'object']) {
294 let satisfied = false;
295 let alternatives = (type(spec.depends.uci) == 'array') ? spec.depends.uci : [ spec.depends.uci ];
297 for (let alternative in alternatives) {
298 if (check_uci_depends(alternative)) {
311 function check_acl_depends(require_groups, groups) {
312 if (length(require_groups)) {
313 let writable = false;
315 for (let group in require_groups) {
316 let read = ('read' in groups?.[group]);
317 let write = ('write' in groups?.[group]);
332 function hash_filelist(files) {
333 let hashval = 0x1b756362;
335 for (let file in files) {
339 hashval = hash(sprintf("%x|%x|%x", st.ino, st.mtime, st.size), hashval);
345 function build_pagetree() {
346 let tree = { action: { type: 'firstchild' } };
358 firstchild_ineligible: 'bool'
361 let files = glob('/usr/share/luci/menu.d/*.json', '/usr/lib/lua/luci/controller/*.lua', '/usr/lib/lua/luci/controller/*/*.lua');
365 cachefile = sprintf('%s.%08x.json', indexcache, hash_filelist(files));
367 let res = read_cachefile(cachefile, read_jsonfile);
372 for (let path in glob(indexcache + '.*.json'))
376 for (let file in files) {
379 if (substr(file, -5) == '.json')
380 data = read_jsonfile(file);
381 else if (load_luabridge(true))
382 data = runtime.call('luci.dispatcher', 'process_lua_controller', file);
384 warn(`Lua controller ${file} present but no Lua runtime installed.\n`);
386 if (type(data) == 'object') {
387 for (let path, spec in data) {
388 if (type(spec) == 'object') {
391 for (let s in match(path, /[^\/]+/g)) {
393 node.wildcard = true;
397 node.children ??= {};
398 node.children[s[0]] ??= {};
399 node = node.children[s[0]];
403 for (let k, t in schema)
404 if (type(spec[k]) == t)
407 node.satisfied = check_depends(spec);
415 let fd = open(cachefile, 'w', 0600);
426 function apply_tree_acls(node, acl) {
427 for (let name, spec in node?.children)
428 apply_tree_acls(spec, acl);
430 if (node?.depends?.acl) {
431 switch (check_acl_depends(node.depends.acl, acl["access-group"])) {
432 case null: node.satisfied = false; break;
433 case false: node.readonly = true; break;
438 function menu_json(acl) {
439 tree ??= build_pagetree();
442 apply_tree_acls(tree, acl);
447 function ctx_append(ctx, name, node) {
449 push(ctx.path, name);
452 push(ctx.acls, ...(node?.depends?.acl || []));
454 ctx.auth = node.auth || ctx.auth;
455 ctx.cors = node.cors || ctx.cors;
456 ctx.suid = node.setuser || ctx.suid;
457 ctx.sgid = node.setgroup || ctx.sgid;
462 function session_retrieve(sid, allowed_users) {
463 let sdat = ubus.call("session", "get", { ubus_rpc_session: sid });
464 let sacl = ubus.call("session", "access", { ubus_rpc_session: sid });
466 if (type(sdat?.values?.token) == 'string' &&
467 (!length(allowed_users) || sdat?.values?.username in allowed_users)) {
468 // uci:set_session_id(sid)
472 acls: length(sacl) ? sacl : {}
479 function randomid(num_bytes) {
482 while (num_bytes-- > 0)
483 push(bytes, sprintf('%02x', rand() % 256));
485 return join('', bytes);
488 function syslog(prio, msg) {
489 warn(sprintf("[%s] %s\n", prio, msg));
492 function session_setup(user, pass, path) {
493 let timeout = uci.get('luci', 'sauth', 'sessiontime');
494 let login = ubus.call("session", "login", {
497 timeout: timeout ? +timeout : null
500 if (type(login?.ubus_rpc_session) == 'string') {
501 ubus.call("session", "set", {
502 ubus_rpc_session: login.ubus_rpc_session,
503 values: { token: randomid(16) }
505 syslog("info", sprintf("luci: accepted login on /%s for %s from %s",
506 join('/', path), user || "?", http.getenv("REMOTE_ADDR") || "?"));
508 return session_retrieve(login.ubus_rpc_session);
511 syslog("info", sprintf("luci: failed login on /%s for %s from %s",
512 join('/', path), user || "?", http.getenv("REMOTE_ADDR") || "?"));
515 function check_authentication(method) {
516 let m = match(method, /^([[:alpha:]]+):(.+)$/);
521 sid = http.getcookie(m[2]);
525 sid = http.formvalue(m[2]);
529 sid = http.formvalue(m[2], true);
533 return sid ? session_retrieve(sid) : null;
536 function is_authenticated(auth) {
537 for (let method in auth?.methods) {
538 let session = check_authentication(method);
547 function node_weight(node) {
548 let weight = min(node.order ?? 9999, 9999);
550 if (node.auth?.login)
556 function clone(src) {
559 return map(src, clone);
564 for (let k, v in src)
574 function resolve_firstchild(node, session, login_allowed, ctx) {
575 let candidate, candidate_ctx;
577 for (let name, child in node.children) {
578 if (!child.satisfied)
582 session = is_authenticated(node.auth);
584 let cacl = child.depends?.acl;
585 let login = login_allowed || child.auth?.login;
587 if (login || check_acl_depends(cacl, session?.acls?.["access-group"]) != null) {
588 if (child.title && type(child.action) == "object") {
589 let child_ctx = ctx_append(clone(ctx), name, child);
590 if (child.action.type == "firstchild") {
591 if (!candidate || node_weight(candidate) > node_weight(child)) {
592 let have_grandchild = resolve_firstchild(child, session, login, child_ctx);
593 if (have_grandchild) {
595 candidate_ctx = child_ctx;
599 else if (!child.firstchild_ineligible) {
600 if (!candidate || node_weight(candidate) > node_weight(child)) {
602 candidate_ctx = child_ctx;
612 for (let k, v in candidate_ctx)
618 function resolve_page(tree, request_path) {
624 for (let i, s in request_path) {
625 node = node.children?.[s];
627 if (!node?.satisfied)
630 ctx_append(ctx, s, node);
633 session = is_authenticated(node.auth);
635 if (!login && node.auth?.login)
639 ctx.request_args = [];
640 ctx.request_path = ctx.path ? [ ...ctx.path ] : [];
642 while (++i < length(request_path)) {
643 push(ctx.request_path, request_path[i]);
644 push(ctx.request_args, request_path[i]);
651 if (node?.action?.type == 'firstchild')
652 resolve_firstchild(node, session, login, ctx);
656 ctx.request_args ??= [];
657 ctx.request_path ??= request_path ? [ ...request_path ] : [];
659 ctx.authsession = session?.sid;
660 ctx.authtoken = session?.data?.token;
661 ctx.authuser = session?.data?.username;
662 ctx.authacl = session?.acls;
666 for (let s in ctx.path) {
667 node = node.children[s];
668 assert(node, "Internal node resolve error");
671 return { node, ctx, session };
674 function require_post_security(target, args) {
675 if (target?.type == 'arcombine')
676 return require_post_security(length(args) ? target?.targets?.[1] : target?.targets?.[0], args);
678 if (type(target?.post) == 'object') {
679 for (let param_name, required_val in target.post) {
680 let request_val = http.formvalue(param_name);
682 if ((type(required_val) == 'string' && request_val != required_val) ||
683 (required_val == true && request_val == null))
690 return (target?.post == true);
693 function test_post_security(authtoken) {
694 if (http.getenv("REQUEST_METHOD") != "POST") {
695 http.status(405, "Method Not Allowed");
696 http.header("Allow", "POST");
701 if (http.formvalue("token") != authtoken) {
702 http.status(403, "Forbidden");
703 runtime.render("csrftoken");
711 function build_url(...path) {
712 let url = [ http.getenv('SCRIPT_NAME') ?? '' ];
715 if (match(p, /^[A-Za-z0-9_%.\/,;-]+$/))
718 if (length(url) == 1)
721 return join('', url);
724 function lookup(...segments) {
725 let node = menu_json();
728 for (let segment in segments)
729 for (let name in split(segment, '/'))
732 for (let name in path) {
733 node = node.children[name];
742 return { node, url: build_url(...path) };
745 function rollback_pending() {
747 const rv = ubus.call('session', 'get', {
748 ubus_rpc_session: '00000000000000000000000000000000',
752 if (type(rv?.values?.rollback?.token) != 'string' ||
753 type(rv?.values?.rollback?.session) != 'string' ||
754 type(rv?.values?.rollback?.timeout) != 'int' ||
755 rv.values.rollback.timeout <= now)
759 remaining: rv.values.rollback.timeout - now,
760 session: rv.values.rollback.session,
761 token: rv.values.rollback.token
767 function render_action(fn) {
768 const data = render(fn);
770 http.write_headers();
774 function run_action(request_path, lang, tree, resolved, action) {
775 switch (action?.type) {
777 if (runtime.is_ucode_template(action.path))
778 runtime.render(action.path, {});
780 render_action(() => {
781 runtime.call('luci.dispatcher', 'render_lua_template', action.path);
786 runtime.render('view', { view: action.path });
790 render_action(() => {
791 runtime.call(action.module, action.function,
792 ...(action.parameters ?? []),
793 ...resolved.ctx.request_args
799 const mod = require(action.module);
801 assert(type(mod[action.function]) == 'function',
802 `Module '${action.module}' does not export function '${action.function}'`);
804 render_action(() => {
805 call(mod[action.function], mod, runtime.env,
806 ...(action.parameters ?? []),
807 ...resolved.ctx.request_args
813 render_action(() => {
814 runtime.call('luci.dispatcher', 'invoke_cbi_action',
816 ...resolved.ctx.request_args
822 render_action(() => {
823 runtime.call('luci.dispatcher', 'invoke_form_action',
825 ...resolved.ctx.request_args
831 dispatch(http, [ ...split(action.path, '/'), ...resolved.ctx.request_args ]);
836 ...splice([ ...request_path ], 0, action.remove),
837 ...split(action.path, '/'),
838 ...resolved.ctx.request_args
843 if (!length(tree.children))
844 error404("No root node was registered, this usually happens if no module was installed.\n" +
845 "Install luci-mod-admin-full and retry. " +
846 "If the module is already installed, try removing the /tmp/luci-indexcache file.");
848 error404(`No page is registered at '/${entityencode(join("/", resolved.ctx.request_path))}'.\n` +
849 "If this url belongs to an extension, make sure it is properly installed.\n" +
850 "If the extension was recently installed, try removing the /tmp/luci-indexcache file.");
854 error500(`Unhandled action type ${action?.type ?? '?'}`);
858 dispatch = function(_http, path) {
861 let version = determine_version();
862 let lang = determine_request_language();
864 runtime = runtime || LuCIRuntime({
871 main: uci.get_all('luci', 'main') ?? {},
872 apply: uci.get_all('luci', 'apply') ?? {}
888 _: (...args) => translate(...args) ?? args[0],
889 N_: (...args) => ntranslate(...args) ?? (args[0] == 1 ? args[1] : args[2]),
893 let menu = menu_json();
895 path ??= map(match(http.getenv('PATH_INFO'), /[^\/]+/g), m => urldecode(m[0]));
897 let resolved = resolve_page(menu, path);
899 runtime.env.ctx = resolved.ctx;
900 runtime.env.dispatched = resolved.node;
901 runtime.env.requested ??= resolved.node;
903 if (length(resolved.ctx.auth)) {
904 let session = is_authenticated(resolved.ctx.auth);
906 if (!session && resolved.ctx.auth.login) {
907 let user = http.getenv('HTTP_AUTH_USER');
908 let pass = http.getenv('HTTP_AUTH_PASS');
910 if (user == null && pass == null) {
911 user = http.formvalue('luci_username');
912 pass = http.formvalue('luci_password');
915 if (user != null && pass != null)
916 session = session_setup(user, pass, resolved.ctx.request_path);
919 resolved.ctx.path = [];
921 http.status(403, 'Forbidden');
922 http.header('X-LuCI-Login-Required', 'yes');
924 let scope = { duser: 'root', fuser: user };
925 let theme_sysauth = `themes/${basename(runtime.env.media)}/sysauth`;
927 if (runtime.is_ucode_template(theme_sysauth) || runtime.is_lua_template(theme_sysauth)) {
929 return runtime.render(theme_sysauth, scope);
932 runtime.env.media_error = `${e}`;
936 return runtime.render('sysauth', scope);
939 let cookie_name = (http.getenv('HTTPS') == 'on') ? 'sysauth_https' : 'sysauth_http',
940 cookie_secure = (http.getenv('HTTPS') == 'on') ? '; secure' : '';
942 http.header('Set-Cookie', `${cookie_name}=${session.sid}; path=${build_url()}; SameSite=strict; HttpOnly${cookie_secure}`);
943 http.redirect(build_url(...resolved.ctx.request_path));
949 http.status(403, 'Forbidden');
950 http.header('X-LuCI-Login-Required', 'yes');
955 resolved.ctx.authsession ??= session.sid;
956 resolved.ctx.authtoken ??= session.data?.token;
957 resolved.ctx.authuser ??= session.data?.username;
958 resolved.ctx.authacl ??= session.acls;
960 /* In case the Lua runtime was already initialized, e.g. by probing legacy
961 * theme header templates, make sure to update the session ID of the uci
964 runtime.L.invoke('require', 'luci.model.uci');
965 runtime.L.get('luci', 'model', 'uci').invoke('set_session_id', session.sid);
969 if (length(resolved.ctx.acls)) {
970 let perm = check_acl_depends(resolved.ctx.acls, resolved.ctx.authacl?.['access-group']);
973 http.status(403, 'Forbidden');
979 resolved.node.readonly = !perm;
982 let action = resolved.node.action;
984 if (action?.type == 'arcombine')
985 action = length(resolved.ctx.request_args) ? action.targets?.[1] : action.targets?.[0];
987 if (resolved.ctx.cors && http.getenv('REQUEST_METHOD') == 'OPTIONS') {
988 http.status(200, 'OK');
989 http.header('Access-Control-Allow-Origin', http.getenv('HTTP_ORIGIN') ?? '*');
990 http.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
995 if (require_post_security(action) && !test_post_security(resolved.ctx.authtoken))
998 run_action(path, lang, menu, resolved, action);
1001 error500('Unhandled exception during request dispatching', ex);
1005 export default dispatch;