dispatcher.uc 21 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. // Copyright 2022 Jo-Philipp Wich <jo@mein.io>
  2. // Licensed to the public under the Apache License 2.0.
  3. import { open, stat, glob, lsdir, unlink, basename } from 'fs';
  4. import { striptags, entityencode } from 'html';
  5. import { connect } from 'ubus';
  6. import { cursor } from 'uci';
  7. import { rand } from 'math';
  8. import { hash, load_catalog, change_catalog, translate, ntranslate, getuid } from 'luci.core';
  9. import { revision as luciversion, branch as luciname } from 'luci.version';
  10. import { default as LuCIRuntime } from 'luci.runtime';
  11. import { urldecode } from 'luci.http';
  12. let ubus = connect();
  13. let uci = cursor();
  14. let indexcache = "/tmp/luci-indexcache";
  15. let http, runtime, tree, luabridge;
  16. function error404(msg) {
  17. http.status(404, 'Not Found');
  18. try {
  19. runtime.render('error404', { message: msg ?? 'Not found' });
  20. }
  21. catch {
  22. http.header('Content-Type', 'text/plain; charset=UTF-8');
  23. http.write(msg ?? 'Not found');
  24. }
  25. return false;
  26. }
  27. function error500(msg, ex) {
  28. if (!http.eoh) {
  29. http.status(500, 'Internal Server Error');
  30. http.header('Content-Type', 'text/html; charset=UTF-8');
  31. }
  32. try {
  33. runtime.render('error500', {
  34. title: ex?.type ?? 'Runtime exception',
  35. message: replace(
  36. msg,
  37. /(\s)((\/[A-Za-z0-9_.-]+)+:\d+|\[string "[^"]+"\]:\d+)/g,
  38. '$1<code>$2</code>'
  39. ),
  40. exception: ex
  41. });
  42. }
  43. catch {
  44. http.write('<!--]]>--><!--\'>--><!--">-->\n');
  45. http.write(`<p>${trim(msg)}</p>\n`);
  46. if (ex) {
  47. http.write(`<p>${trim(ex.message)}</p>\n`);
  48. http.write(`<pre>${trim(ex.stacktrace[0].context)}</pre>\n`);
  49. }
  50. }
  51. exit(0);
  52. }
  53. function load_luabridge(optional) {
  54. if (luabridge == null) {
  55. try {
  56. luabridge = require('lua');
  57. }
  58. catch (ex) {
  59. luabridge = false;
  60. if (!optional)
  61. error500('No Lua runtime installed');
  62. }
  63. }
  64. return luabridge;
  65. }
  66. function determine_request_language() {
  67. let lang = uci.get('luci', 'main', 'lang') || 'auto';
  68. if (lang == 'auto') {
  69. for (let tag in split(http.getenv('HTTP_ACCEPT_LANGUAGE'), ',')) {
  70. tag = split(trim(split(tag, ';')?.[0]), '-');
  71. if (tag) {
  72. let cc = tag[1] ? `${tag[0]}_${lc(tag[1])}` : null;
  73. if (cc && uci.get('luci', 'languages', cc)) {
  74. lang = cc;
  75. break;
  76. }
  77. else if (uci.get('luci', 'languages', tag[0])) {
  78. lang = tag[0];
  79. break;
  80. }
  81. }
  82. }
  83. }
  84. if (lang == 'auto')
  85. lang = 'en';
  86. else
  87. lang = replace(lang, '_', '-');
  88. if (load_catalog(lang, '/usr/lib/lua/luci/i18n'))
  89. change_catalog(lang);
  90. return lang;
  91. }
  92. function determine_version() {
  93. let res = { luciname, luciversion };
  94. for (let f = open("/etc/os-release"), l = f?.read?.("line"); l; l = f.read?.("line")) {
  95. let kv = split(l, '=', 2);
  96. switch (kv[0]) {
  97. case 'NAME':
  98. res.distname = trim(kv[1], '"\' \n');
  99. break;
  100. case 'VERSION':
  101. res.distversion = trim(kv[1], '"\' \n');
  102. break;
  103. case 'HOME_URL':
  104. res.disturl = trim(kv[1], '"\' \n');
  105. break;
  106. case 'BUILD_ID':
  107. res.distrevision = trim(kv[1], '"\' \n');
  108. break;
  109. }
  110. }
  111. return res;
  112. }
  113. function read_jsonfile(path, defval) {
  114. let rv;
  115. try {
  116. rv = json(open(path, "r"));
  117. }
  118. catch (e) {
  119. rv = defval;
  120. }
  121. return rv;
  122. }
  123. function read_cachefile(file, reader) {
  124. let euid = getuid(),
  125. fstat = stat(file),
  126. fuid = fstat?.uid,
  127. perm = fstat?.perm;
  128. if (euid != fuid ||
  129. perm?.group_read || perm?.group_write || perm?.group_exec ||
  130. perm?.other_read || perm?.other_write || perm?.other_exec)
  131. return null;
  132. return reader(file);
  133. }
  134. function check_fs_depends(spec) {
  135. for (let path, kind in spec) {
  136. if (kind == 'directory') {
  137. if (!length(lsdir(path)))
  138. return false;
  139. }
  140. else if (kind == 'executable') {
  141. let fstat = stat(path);
  142. if (fstat?.type != 'file' || fstat?.user_exec == false)
  143. return false;
  144. }
  145. else if (kind == 'file') {
  146. let fstat = stat(path);
  147. if (fstat?.type != 'file')
  148. return false;
  149. }
  150. else if (kind == 'absent') {
  151. if (stat(path) != null)
  152. return false;
  153. }
  154. }
  155. return true;
  156. }
  157. function check_uci_depends_options(conf, s, opts) {
  158. if (type(opts) == 'string') {
  159. return (s['.type'] == opts);
  160. }
  161. else if (opts === true) {
  162. for (let option, value in s)
  163. if (ord(option) != 46)
  164. return true;
  165. }
  166. else if (type(opts) == 'object') {
  167. for (let option, value in opts) {
  168. let sval = s[option];
  169. if (type(sval) == 'array') {
  170. if (!(value in sval))
  171. return false;
  172. }
  173. else if (value === true) {
  174. if (sval == null)
  175. return false;
  176. }
  177. else {
  178. if (sval != value)
  179. return false;
  180. }
  181. }
  182. }
  183. return true;
  184. }
  185. function check_uci_depends_section(conf, sect) {
  186. for (let section, options in sect) {
  187. let stype = match(section, /^@([A-Za-z0-9_-]+)$/);
  188. if (stype) {
  189. let found = false;
  190. uci.load(conf);
  191. uci.foreach(conf, stype[1], (s) => {
  192. if (check_uci_depends_options(conf, s, options)) {
  193. found = true;
  194. return false;
  195. }
  196. });
  197. if (!found)
  198. return false;
  199. }
  200. else {
  201. let s = uci.get_all(conf, section);
  202. if (!s || !check_uci_depends_options(conf, s, options))
  203. return false;
  204. }
  205. }
  206. return true;
  207. }
  208. function check_uci_depends(conf) {
  209. for (let config, values in conf) {
  210. if (values == true) {
  211. let found = false;
  212. uci.load(config);
  213. uci.foreach(config, null, () => { found = true });
  214. if (!found)
  215. return false;
  216. }
  217. else if (type(values) == 'object') {
  218. if (!check_uci_depends_section(config, values))
  219. return false;
  220. }
  221. }
  222. return true;
  223. }
  224. function check_depends(spec) {
  225. if (type(spec?.depends?.fs) in ['array', 'object']) {
  226. let satisfied = false;
  227. let alternatives = (type(spec.depends.fs) == 'array') ? spec.depends.fs : [ spec.depends.fs ];
  228. for (let alternative in alternatives) {
  229. if (check_fs_depends(alternative)) {
  230. satisfied = true;
  231. break;
  232. }
  233. }
  234. if (!satisfied)
  235. return false;
  236. }
  237. if (type(spec?.depends?.uci) in ['array', 'object']) {
  238. let satisfied = false;
  239. let alternatives = (type(spec.depends.uci) == 'array') ? spec.depends.uci : [ spec.depends.uci ];
  240. for (let alternative in alternatives) {
  241. if (check_uci_depends(alternative)) {
  242. satisfied = true;
  243. break;
  244. }
  245. }
  246. if (!satisfied)
  247. return false;
  248. }
  249. return true;
  250. }
  251. function check_acl_depends(require_groups, groups) {
  252. if (length(require_groups)) {
  253. let writable = false;
  254. for (let group in require_groups) {
  255. let read = ('read' in groups?.[group]);
  256. let write = ('write' in groups?.[group]);
  257. if (!read && !write)
  258. return null;
  259. if (write)
  260. writable = true;
  261. }
  262. return writable;
  263. }
  264. return true;
  265. }
  266. function hash_filelist(files) {
  267. let hashval = 0x1b756362;
  268. for (let file in files) {
  269. let st = stat(file);
  270. if (st)
  271. hashval = hash(sprintf("%x|%x|%x", st.ino, st.mtime, st.size), hashval);
  272. }
  273. return hashval;
  274. }
  275. function build_pagetree() {
  276. let tree = { action: { type: 'firstchild' } };
  277. let schema = {
  278. action: 'object',
  279. auth: 'object',
  280. cors: 'bool',
  281. depends: 'object',
  282. order: 'int',
  283. setgroup: 'string',
  284. setuser: 'string',
  285. title: 'string',
  286. wildcard: 'bool',
  287. firstchild_ineligible: 'bool'
  288. };
  289. let files = glob('/usr/share/luci/menu.d/*.json', '/usr/lib/lua/luci/controller/*.lua', '/usr/lib/lua/luci/controller/*/*.lua');
  290. let cachefile;
  291. if (indexcache) {
  292. cachefile = sprintf('%s.%08x.json', indexcache, hash_filelist(files));
  293. let res = read_cachefile(cachefile, read_jsonfile);
  294. if (res)
  295. return res;
  296. for (let path in glob(indexcache + '.*.json'))
  297. unlink(path);
  298. }
  299. for (let file in files) {
  300. let data;
  301. if (substr(file, -5) == '.json')
  302. data = read_jsonfile(file);
  303. else if (load_luabridge(true))
  304. data = runtime.call('luci.dispatcher', 'process_lua_controller', file);
  305. else
  306. warn(`Lua controller ${file} present but no Lua runtime installed.\n`);
  307. if (type(data) == 'object') {
  308. for (let path, spec in data) {
  309. if (type(spec) == 'object') {
  310. let node = tree;
  311. for (let s in match(path, /[^\/]+/g)) {
  312. if (s[0] == '*') {
  313. node.wildcard = true;
  314. break;
  315. }
  316. node.children ??= {};
  317. node.children[s[0]] ??= { satisfied: true };
  318. node = node.children[s[0]];
  319. }
  320. if (node !== tree) {
  321. for (let k, t in schema)
  322. if (type(spec[k]) == t)
  323. node[k] = spec[k];
  324. node.satisfied = check_depends(spec);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. if (cachefile) {
  331. let fd = open(cachefile, 'w', 0600);
  332. if (fd) {
  333. fd.write(tree);
  334. fd.close();
  335. }
  336. }
  337. return tree;
  338. }
  339. function apply_tree_acls(node, acl) {
  340. for (let name, spec in node?.children)
  341. apply_tree_acls(spec, acl);
  342. if (node?.depends?.acl) {
  343. switch (check_acl_depends(node.depends.acl, acl["access-group"])) {
  344. case null: node.satisfied = false; break;
  345. case false: node.readonly = true; break;
  346. }
  347. }
  348. }
  349. function menu_json(acl) {
  350. tree ??= build_pagetree();
  351. if (acl)
  352. apply_tree_acls(tree, acl);
  353. return tree;
  354. }
  355. function ctx_append(ctx, name, node) {
  356. ctx.path ??= [];
  357. push(ctx.path, name);
  358. ctx.acls ??= [];
  359. push(ctx.acls, ...(node?.depends?.acl || []));
  360. ctx.auth = node.auth || ctx.auth;
  361. ctx.cors = node.cors || ctx.cors;
  362. ctx.suid = node.setuser || ctx.suid;
  363. ctx.sgid = node.setgroup || ctx.sgid;
  364. return ctx;
  365. }
  366. function session_retrieve(sid, allowed_users) {
  367. let sdat = ubus.call("session", "get", { ubus_rpc_session: sid });
  368. let sacl = ubus.call("session", "access", { ubus_rpc_session: sid });
  369. if (type(sdat?.values?.token) == 'string' &&
  370. (!length(allowed_users) || sdat?.values?.username in allowed_users)) {
  371. // uci:set_session_id(sid)
  372. return {
  373. sid,
  374. data: sdat.values,
  375. acls: length(sacl) ? sacl : {}
  376. };
  377. }
  378. return null;
  379. }
  380. function randomid(num_bytes) {
  381. let bytes = [];
  382. while (num_bytes-- > 0)
  383. push(bytes, sprintf('%02x', rand() % 256));
  384. return join('', bytes);
  385. }
  386. function syslog(prio, msg) {
  387. warn(sprintf("[%s] %s\n", prio, msg));
  388. }
  389. function session_setup(user, pass, path) {
  390. let timeout = uci.get('luci', 'sauth', 'sessiontime');
  391. let login = ubus.call("session", "login", {
  392. username: user,
  393. password: pass,
  394. timeout: timeout ? +timeout : null
  395. });
  396. if (type(login?.ubus_rpc_session) == 'string') {
  397. ubus.call("session", "set", {
  398. ubus_rpc_session: login.ubus_rpc_session,
  399. values: { token: randomid(16) }
  400. });
  401. syslog("info", sprintf("luci: accepted login on /%s for %s from %s",
  402. join('/', path), user || "?", http.getenv("REMOTE_ADDR") || "?"));
  403. return session_retrieve(login.ubus_rpc_session);
  404. }
  405. syslog("info", sprintf("luci: failed login on /%s for %s from %s",
  406. join('/', path), user || "?", http.getenv("REMOTE_ADDR") || "?"));
  407. }
  408. function check_authentication(method) {
  409. let m = match(method, /^([[:alpha:]]+):(.+)$/);
  410. let sid;
  411. switch (m?.[1]) {
  412. case 'cookie':
  413. sid = http.getcookie(m[2]);
  414. break;
  415. case 'param':
  416. sid = http.formvalue(m[2]);
  417. break;
  418. case 'query':
  419. sid = http.formvalue(m[2], true);
  420. break;
  421. }
  422. return sid ? session_retrieve(sid) : null;
  423. }
  424. function is_authenticated(auth) {
  425. for (let method in auth?.methods) {
  426. let session = check_authentication(method);
  427. if (session)
  428. return session;
  429. }
  430. return null;
  431. }
  432. function node_weight(node) {
  433. let weight = min(node.order ?? 9999, 9999);
  434. if (node.auth?.login)
  435. weight += 10000;
  436. return weight;
  437. }
  438. function clone(src) {
  439. switch (type(src)) {
  440. case 'array':
  441. return map(src, clone);
  442. case 'object':
  443. let dest = {};
  444. for (let k, v in src)
  445. dest[k] = clone(v);
  446. return dest;
  447. default:
  448. return src;
  449. }
  450. }
  451. function resolve_firstchild(node, session, login_allowed, ctx) {
  452. let candidate, candidate_ctx;
  453. for (let name, child in node.children) {
  454. if (!child.satisfied)
  455. continue;
  456. if (!session)
  457. session = is_authenticated(node.auth);
  458. let cacl = child.depends?.acl;
  459. let login = login_allowed || child.auth?.login;
  460. if (login || check_acl_depends(cacl, session?.acls?.["access-group"]) != null) {
  461. if (child.title && type(child.action) == "object") {
  462. let child_ctx = ctx_append(clone(ctx), name, child);
  463. if (child.action.type == "firstchild") {
  464. if (!candidate || node_weight(candidate) > node_weight(child)) {
  465. let have_grandchild = resolve_firstchild(child, session, login, child_ctx);
  466. if (have_grandchild) {
  467. candidate = child;
  468. candidate_ctx = child_ctx;
  469. }
  470. }
  471. }
  472. else if (!child.firstchild_ineligible) {
  473. if (!candidate || node_weight(candidate) > node_weight(child)) {
  474. candidate = child;
  475. candidate_ctx = child_ctx;
  476. }
  477. }
  478. }
  479. }
  480. }
  481. if (!candidate)
  482. return false;
  483. for (let k, v in candidate_ctx)
  484. ctx[k] = v;
  485. return true;
  486. }
  487. function resolve_page(tree, request_path) {
  488. let node = tree;
  489. let login = false;
  490. let session = null;
  491. let ctx = {};
  492. for (let i, s in request_path) {
  493. node = node.children?.[s];
  494. if (!node?.satisfied)
  495. break;
  496. ctx_append(ctx, s, node);
  497. if (!session)
  498. session = is_authenticated(node.auth);
  499. if (!login && node.auth?.login)
  500. login = true;
  501. if (node.wildcard) {
  502. ctx.request_args = [];
  503. ctx.request_path = ctx.path ? [ ...ctx.path ] : [];
  504. while (++i < length(request_path)) {
  505. push(ctx.request_path, request_path[i]);
  506. push(ctx.request_args, request_path[i]);
  507. }
  508. break;
  509. }
  510. }
  511. if (node?.action?.type == 'firstchild')
  512. resolve_firstchild(node, session, login, ctx);
  513. ctx.acls ??= {};
  514. ctx.path ??= [];
  515. ctx.request_args ??= [];
  516. ctx.request_path ??= request_path ? [ ...request_path ] : [];
  517. ctx.authsession = session?.sid;
  518. ctx.authtoken = session?.data?.token;
  519. ctx.authuser = session?.data?.username;
  520. ctx.authacl = session?.acls;
  521. node = tree;
  522. for (let s in ctx.path) {
  523. node = node.children[s];
  524. assert(node, "Internal node resolve error");
  525. }
  526. return { node, ctx, session };
  527. }
  528. function require_post_security(target, args) {
  529. if (target?.type == 'arcombine')
  530. return require_post_security(length(args) ? target?.targets?.[1] : target?.targets?.[0], args);
  531. if (type(target?.post) == 'object') {
  532. for (let param_name, required_val in target.post) {
  533. let request_val = http.formvalue(param_name);
  534. if ((type(required_val) == 'string' && request_val != required_val) ||
  535. (required_val == true && request_val == null))
  536. return false;
  537. }
  538. return true;
  539. }
  540. return (target?.post == true);
  541. }
  542. function test_post_security(authtoken) {
  543. if (http.getenv("REQUEST_METHOD") != "POST") {
  544. http.status(405, "Method Not Allowed");
  545. http.header("Allow", "POST");
  546. return false;
  547. }
  548. if (http.formvalue("token") != authtoken) {
  549. http.status(403, "Forbidden");
  550. runtime.render("csrftoken");
  551. return false;
  552. }
  553. return true;
  554. }
  555. function build_url(...path) {
  556. let url = [ http.getenv('SCRIPT_NAME') ?? '' ];
  557. for (let p in path)
  558. if (match(p, /^[A-Za-z0-9_%.\/,;-]+$/))
  559. push(url, '/', p);
  560. if (length(url) == 1)
  561. push(url, '/');
  562. return join('', url);
  563. }
  564. function lookup(...segments) {
  565. let node = menu_json();
  566. let path = [];
  567. for (let segment in segments)
  568. for (let name in split(segment, '/'))
  569. push(path, name);
  570. for (let name in path) {
  571. node = node.children[name];
  572. if (!node)
  573. return null;
  574. if (node.leaf)
  575. break;
  576. }
  577. return { node, url: build_url(...path) };
  578. }
  579. function rollback_pending() {
  580. const now = time();
  581. const rv = ubus.call('session', 'get', {
  582. ubus_rpc_session: '00000000000000000000000000000000',
  583. keys: [ 'rollback' ]
  584. });
  585. if (type(rv?.values?.rollback?.token) != 'string' ||
  586. type(rv?.values?.rollback?.session) != 'string' ||
  587. type(rv?.values?.rollback?.timeout) != 'int' ||
  588. rv.values.rollback.timeout <= now)
  589. return false;
  590. return {
  591. remaining: rv.values.rollback.timeout - now,
  592. session: rv.values.rollback.session,
  593. token: rv.values.rollback.token
  594. };
  595. }
  596. let dispatch;
  597. function render_action(fn) {
  598. const data = render(fn);
  599. http.write_headers();
  600. http.output(data);
  601. }
  602. function run_action(request_path, lang, tree, resolved, action) {
  603. switch ((type(action) == 'object') ? action.type : 'none') {
  604. case 'template':
  605. if (runtime.is_ucode_template(action.path))
  606. runtime.render(action.path, {});
  607. else
  608. render_action(() => {
  609. runtime.call('luci.dispatcher', 'render_lua_template', action.path);
  610. });
  611. break;
  612. case 'view':
  613. runtime.render('view', { view: action.path });
  614. break;
  615. case 'call':
  616. render_action(() => {
  617. runtime.call(action.module, action.function,
  618. ...(action.parameters ?? []),
  619. ...resolved.ctx.request_args
  620. );
  621. });
  622. break;
  623. case 'function':
  624. const mod = require(action.module);
  625. assert(type(mod[action.function]) == 'function',
  626. `Module '${action.module}' does not export function '${action.function}'`);
  627. render_action(() => {
  628. call(mod[action.function], mod, runtime.env,
  629. ...(action.parameters ?? []),
  630. ...resolved.ctx.request_args
  631. );
  632. });
  633. break;
  634. case 'cbi':
  635. render_action(() => {
  636. runtime.call('luci.dispatcher', 'invoke_cbi_action',
  637. action.path, null,
  638. ...resolved.ctx.request_args
  639. );
  640. });
  641. break;
  642. case 'form':
  643. render_action(() => {
  644. runtime.call('luci.dispatcher', 'invoke_form_action',
  645. action.path,
  646. ...resolved.ctx.request_args
  647. );
  648. });
  649. break;
  650. case 'alias':
  651. dispatch(http, [ ...split(action.path, '/'), ...resolved.ctx.request_args ]);
  652. break;
  653. case 'rewrite':
  654. dispatch(http, [
  655. ...splice([ ...request_path ], 0, action.remove),
  656. ...split(action.path, '/'),
  657. ...resolved.ctx.request_args
  658. ]);
  659. break;
  660. case 'firstchild':
  661. if (!length(tree.children)) {
  662. error404("No root node was registered, this usually happens if no module was installed.\n" +
  663. "Install luci-mod-admin-full and retry. " +
  664. "If the module is already installed, try removing the /tmp/luci-indexcache file.");
  665. break;
  666. }
  667. /* fall through */
  668. case 'none':
  669. error404(`No page is registered at '/${entityencode(join("/", resolved.ctx.request_path))}'.\n` +
  670. "If this url belongs to an extension, make sure it is properly installed.\n" +
  671. "If the extension was recently installed, try removing the /tmp/luci-indexcache file.");
  672. break;
  673. default:
  674. error500(`Unhandled action type ${action?.type ?? '?'}`);
  675. }
  676. }
  677. dispatch = function(_http, path) {
  678. http = _http;
  679. let version = determine_version();
  680. let lang = determine_request_language();
  681. runtime = runtime || LuCIRuntime({
  682. http,
  683. ubus,
  684. uci,
  685. ctx: {},
  686. version,
  687. config: {
  688. main: uci.get_all('luci', 'main') ?? {},
  689. apply: uci.get_all('luci', 'apply') ?? {}
  690. },
  691. dispatcher: {
  692. rollback_pending,
  693. is_authenticated,
  694. load_luabridge,
  695. lookup,
  696. menu_json,
  697. build_url,
  698. randomid,
  699. error404,
  700. error500,
  701. lang
  702. },
  703. striptags,
  704. entityencode,
  705. _: (...args) => translate(...args) ?? args[0],
  706. N_: (...args) => ntranslate(...args) ?? (args[0] == 1 ? args[1] : args[2]),
  707. });
  708. try {
  709. let menu = menu_json();
  710. path ??= map(match(http.getenv('PATH_INFO'), /[^\/]+/g), m => urldecode(m[0]));
  711. let resolved = resolve_page(menu, path);
  712. runtime.env.ctx = resolved.ctx;
  713. runtime.env.dispatched = resolved.node;
  714. runtime.env.requested ??= resolved.node;
  715. if (length(resolved.ctx.auth)) {
  716. let session = is_authenticated(resolved.ctx.auth);
  717. if (!session && resolved.ctx.auth.login) {
  718. let user = http.getenv('HTTP_AUTH_USER');
  719. let pass = http.getenv('HTTP_AUTH_PASS');
  720. if (user == null && pass == null) {
  721. user = http.formvalue('luci_username');
  722. pass = http.formvalue('luci_password');
  723. }
  724. if (user != null && pass != null)
  725. session = session_setup(user, pass, resolved.ctx.request_path);
  726. if (!session) {
  727. resolved.ctx.path = [];
  728. http.status(403, 'Forbidden');
  729. http.header('X-LuCI-Login-Required', 'yes');
  730. let scope = { duser: 'root', fuser: user };
  731. let theme_sysauth = `themes/${basename(runtime.env.media)}/sysauth`;
  732. if (runtime.is_ucode_template(theme_sysauth) || runtime.is_lua_template(theme_sysauth)) {
  733. try {
  734. return runtime.render(theme_sysauth, scope);
  735. }
  736. catch (e) {
  737. runtime.env.media_error = `${e}`;
  738. }
  739. }
  740. return runtime.render('sysauth', scope);
  741. }
  742. let cookie_name = (http.getenv('HTTPS') == 'on') ? 'sysauth_https' : 'sysauth_http',
  743. cookie_secure = (http.getenv('HTTPS') == 'on') ? '; secure' : '';
  744. http.header('Set-Cookie', `${cookie_name}=${session.sid}; path=${build_url()}; SameSite=strict; HttpOnly${cookie_secure}`);
  745. http.redirect(build_url(...resolved.ctx.request_path));
  746. return;
  747. }
  748. if (!session) {
  749. http.status(403, 'Forbidden');
  750. http.header('X-LuCI-Login-Required', 'yes');
  751. return;
  752. }
  753. resolved.ctx.authsession ??= session.sid;
  754. resolved.ctx.authtoken ??= session.data?.token;
  755. resolved.ctx.authuser ??= session.data?.username;
  756. resolved.ctx.authacl ??= session.acls;
  757. /* In case the Lua runtime was already initialized, e.g. by probing legacy
  758. * theme header templates, make sure to update the session ID of the uci
  759. * module. */
  760. if (runtime.L) {
  761. runtime.L.invoke('require', 'luci.model.uci');
  762. runtime.L.get('luci', 'model', 'uci').invoke('set_session_id', session.sid);
  763. }
  764. }
  765. if (length(resolved.ctx.acls)) {
  766. let perm = check_acl_depends(resolved.ctx.acls, resolved.ctx.authacl?.['access-group']);
  767. if (perm == null) {
  768. http.status(403, 'Forbidden');
  769. return;
  770. }
  771. if (resolved.node)
  772. resolved.node.readonly = !perm;
  773. }
  774. let action = resolved.node.action;
  775. if (action?.type == 'arcombine')
  776. action = length(resolved.ctx.request_args) ? action.targets?.[1] : action.targets?.[0];
  777. if (resolved.ctx.cors && http.getenv('REQUEST_METHOD') == 'OPTIONS') {
  778. http.status(200, 'OK');
  779. http.header('Access-Control-Allow-Origin', http.getenv('HTTP_ORIGIN') ?? '*');
  780. http.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  781. return;
  782. }
  783. if (require_post_security(action) && !test_post_security(resolved.ctx.authtoken))
  784. return;
  785. run_action(path, lang, menu, resolved, action);
  786. }
  787. catch (ex) {
  788. error500('Unhandled exception during request dispatching', ex);
  789. }
  790. };
  791. export default dispatch;