5 The request dispatcher and module dispatcher generators
11 Copyright 2008 Steven Barth <steven@midlink.org>
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
17 http://www.apache.org/licenses/LICENSE-2.0
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
27 --- LuCI web dispatcher.
28 local fs = require "nixio.fs"
29 local sys = require "luci.sys"
30 local init = require "luci.init"
31 local util = require "luci.util"
32 local http = require "luci.http"
33 local nixio = require "nixio", require "nixio.util"
35 module("luci.dispatcher", package.seeall)
36 context = util.threadlocal()
47 --- Build the URL relative to the server webroot from given virtual path.
48 -- @param ... Virtual path
49 -- @return Relative URL
50 function build_url(...)
52 local sn = http.getenv("SCRIPT_NAME") or ""
53 for k, v in pairs(context.urltoken) do
54 sn = sn .. "/;" .. k .. "=" .. http.urlencode(v)
56 return sn .. ((#path > 0) and "/" .. table.concat(path, "/") or "")
59 --- Send a 404 error code and render the "error404" template if available.
60 -- @param message Custom error message (optional)
62 function error404(message)
63 luci.http.status(404, "Not Found")
64 message = message or "Not Found"
66 require("luci.template")
67 if not luci.util.copcall(luci.template.render, "error404") then
68 luci.http.prepare_content("text/plain")
69 luci.http.write(message)
74 --- Send a 500 error code and render the "error500" template if available.
75 -- @param message Custom error message (optional)#
77 function error500(message)
78 luci.util.perror(message)
79 if not context.template_header_sent then
80 luci.http.status(500, "Internal Server Error")
81 luci.http.prepare_content("text/plain")
82 luci.http.write(message)
84 require("luci.template")
85 if not luci.util.copcall(luci.template.render, "error500", {message=message}) then
86 luci.http.prepare_content("text/plain")
87 luci.http.write(message)
93 function authenticator.htmlauth(validator, accs, default)
94 local user = luci.http.formvalue("username")
95 local pass = luci.http.formvalue("password")
97 if user and validator(user, pass) then
102 require("luci.template")
104 luci.template.render("sysauth", {duser=default, fuser=user})
109 --- Dispatch an HTTP request.
110 -- @param request LuCI HTTP Request object
111 function httpdispatch(request, prefix)
112 luci.http.context.request = request
116 local pathinfo = http.urldecode(request:getenv("PATH_INFO") or "", true)
119 for _, node in ipairs(prefix) do
124 for node in pathinfo:gmatch("[^/]+") do
128 local stat, err = util.coxpcall(function()
129 dispatch(context.request)
134 --context._disable_memtrace()
137 --- Dispatches a LuCI virtual path.
138 -- @param request Virtual path
139 function dispatch(request)
140 --context._disable_memtrace = require "luci.debug".trap_memtrace("l")
143 ctx.urltoken = ctx.urltoken or {}
145 local conf = require "luci.config"
147 "/etc/config/luci seems to be corrupt, unable to find section 'main'")
149 local lang = conf.main.lang
150 if lang == "auto" then
151 local aclang = http.getenv("HTTP_ACCEPT_LANGUAGE") or ""
152 for lpat in aclang:gmatch("[%w-]+") do
153 lpat = lpat and lpat:gsub("-", "_")
154 if conf.languages[lpat] then
160 require "luci.i18n".setlanguage(lang)
171 ctx.requestargs = ctx.requestargs or args
174 local token = ctx.urltoken
178 for i, s in ipairs(request) do
181 tkey, tval = s:match(";(%w+)=(.*)")
196 util.update(track, c)
205 for j=n+1, #request do
206 args[#args+1] = request[j]
207 freq[#freq+1] = request[j]
211 ctx.requestpath = freq
215 require("luci.i18n").loadc(track.i18n)
218 -- Init template engine
219 if (c and c.index) or not track.notemplate then
220 local tpl = require("luci.template")
221 local media = track.mediaurlbase or luci.config.main.mediaurlbase
222 if not pcall(tpl.Template, "themes/%s/header" % fs.basename(media)) then
224 for name, theme in pairs(luci.config.themes) do
225 if name:sub(1,1) ~= "." and pcall(tpl.Template,
226 "themes/%s/header" % fs.basename(theme)) then
230 assert(media, "No valid theme found")
233 tpl.context.viewns = setmetatable({
234 write = luci.http.write;
235 include = function(name) tpl.Template(name):render(getfenv(2)) end;
236 translate = function(...) return require("luci.i18n").translate(...) end;
237 striptags = util.striptags;
239 theme = fs.basename(media);
240 resource = luci.config.main.resourcebase
241 }, {__index=function(table, key)
242 if key == "controller" then
244 elseif key == "REQUEST_URI" then
245 return build_url(unpack(ctx.requestpath))
247 return rawget(table, key) or _G[key]
252 track.dependent = (track.dependent ~= false)
253 assert(not track.dependent or not track.auto, "Access Violation")
255 if track.sysauth then
256 local sauth = require "luci.sauth"
258 local authen = type(track.sysauth_authenticator) == "function"
259 and track.sysauth_authenticator
260 or authenticator[track.sysauth_authenticator]
262 local def = (type(track.sysauth) == "string") and track.sysauth
263 local accs = def and {track.sysauth} or track.sysauth
264 local sess = ctx.authsession
265 local verifytoken = false
267 sess = luci.http.getcookie("sysauth")
268 sess = sess and sess:match("^[a-f0-9]*$")
272 local sdat = sauth.read(sess)
276 sdat = loadstring(sdat)
279 if not verifytoken or ctx.urltoken.stok == sdat.token then
283 local eu = http.getenv("HTTP_AUTH_USER")
284 local ep = http.getenv("HTTP_AUTH_PASS")
285 if eu and ep and luci.sys.user.checkpasswd(eu, ep) then
286 authen = function() return eu end
290 if not util.contains(accs, user) then
292 ctx.urltoken.stok = nil
293 local user, sess = authen(luci.sys.user.checkpasswd, accs, def)
294 if not user or not util.contains(accs, user) then
297 local sid = sess or luci.sys.uniqueid(16)
299 local token = luci.sys.uniqueid(16)
300 sauth.write(sid, util.get_bytecode({
303 secret=luci.sys.uniqueid(16)
305 ctx.urltoken.stok = token
307 luci.http.header("Set-Cookie", "sysauth=" .. sid.."; path="..build_url())
308 ctx.authsession = sid
311 luci.http.status(403, "Forbidden")
315 ctx.authsession = sess
319 if track.setgroup then
320 luci.sys.process.setgroup(track.setgroup)
323 if track.setuser then
324 luci.sys.process.setuser(track.setuser)
329 if type(c.target) == "function" then
331 elseif type(c.target) == "table" then
332 target = c.target.target
336 if c and (c.index or type(target) == "function") then
338 ctx.requested = ctx.requested or ctx.dispatched
341 if c and c.index then
342 local tpl = require "luci.template"
344 if util.copcall(tpl.render, "indexer", {}) then
349 if type(target) == "function" then
350 util.copcall(function()
351 local oldenv = getfenv(target)
352 local module = require(c.module)
353 local env = setmetatable({}, {__index=
356 return rawget(tbl, key) or module[key] or oldenv[key]
362 if type(c.target) == "table" then
363 target(c.target, unpack(args))
372 --- Generate the dispatching index using the best possible strategy.
373 function createindex()
374 local path = luci.util.libpath() .. "/controller/"
375 local suff = { ".lua", ".lua.gz" }
377 if luci.util.copcall(require, "luci.fastindex") then
378 createindex_fastindex(path, suff)
380 createindex_plain(path, suff)
384 --- Generate the dispatching index using the fastindex C-indexer.
385 -- @param path Controller base directory
386 -- @param suffixes Controller file suffixes
387 function createindex_fastindex(path, suffixes)
391 fi = luci.fastindex.new("index")
392 for _, suffix in ipairs(suffixes) do
393 fi.add(path .. "*" .. suffix)
394 fi.add(path .. "*/*" .. suffix)
399 for k, v in pairs(fi.indexes) do
404 --- Generate the dispatching index using the native file-cache based strategy.
405 -- @param path Controller base directory
406 -- @param suffixes Controller file suffixes
407 function createindex_plain(path, suffixes)
408 local controllers = { }
409 for _, suffix in ipairs(suffixes) do
410 nixio.util.consume((fs.glob(path .. "*" .. suffix)), controllers)
411 nixio.util.consume((fs.glob(path .. "*/*" .. suffix)), controllers)
415 local cachedate = fs.stat(indexcache, "mtime")
418 for _, obj in ipairs(controllers) do
419 local omtime = fs.stat(path .. "/" .. obj, "mtime")
420 realdate = (omtime and omtime > realdate) and omtime or realdate
423 if cachedate > realdate then
425 sys.process.info("uid") == fs.stat(indexcache, "uid")
426 and fs.stat(indexcache, "modestr") == "rw-------",
427 "Fatal: Indexcache is not sane!"
430 index = loadfile(indexcache)()
438 for i,c in ipairs(controllers) do
439 local module = "luci.controller." .. c:sub(#path+1, #c):gsub("/", ".")
440 for _, suffix in ipairs(suffixes) do
441 module = module:gsub(suffix.."$", "")
444 local mod = require(module)
445 local idx = mod.index
447 if type(idx) == "function" then
453 local f = nixio.open(indexcache, "w", 600)
454 f:writeall(util.get_bytecode(index))
459 --- Create the dispatching tree from the index.
460 -- Build the index before if it does not exist yet.
461 function createtree()
467 local tree = {nodes={}}
470 ctx.treecache = setmetatable({}, {__mode="v"})
474 -- Load default translation
475 require "luci.i18n".loadc("default")
477 local scope = setmetatable({}, {__index = luci.dispatcher})
479 for k, v in pairs(index) do
485 local function modisort(a,b)
486 return modi[a].order < modi[b].order
489 for _, v in util.spairs(modi, modisort) do
490 scope._NAME = v.module
491 setfenv(v.func, scope)
498 --- Register a tree modifier.
499 -- @param func Modifier function
500 -- @param order Modifier order value (optional)
501 function modifier(func, order)
502 context.modifiers[#context.modifiers+1] = {
510 --- Clone a node of the dispatching tree to another position.
511 -- @param path Virtual path destination
512 -- @param clone Virtual path source
513 -- @param title Destination node title (optional)
514 -- @param order Destination node order value (optional)
515 -- @return Dispatching tree node
516 function assign(path, clone, title, order)
517 local obj = node(unpack(path))
524 setmetatable(obj, {__index = _create_node(clone)})
529 --- Create a new dispatching node and define common parameters.
530 -- @param path Virtual path
531 -- @param target Target function to call when dispatched.
532 -- @param title Destination node title
533 -- @param order Destination node order value (optional)
534 -- @return Dispatching tree node
535 function entry(path, target, title, order)
536 local c = node(unpack(path))
541 c.module = getfenv(2)._NAME
546 --- Fetch or create a dispatching node without setting the target module or
547 -- enabling the node.
548 -- @param ... Virtual path
549 -- @return Dispatching tree node
551 return _create_node({...})
554 --- Fetch or create a new dispatching node.
555 -- @param ... Virtual path
556 -- @return Dispatching tree node
558 local c = _create_node({...})
560 c.module = getfenv(2)._NAME
566 function _create_node(path, cache)
571 cache = cache or context.treecache
572 local name = table.concat(path, ".")
573 local c = cache[name]
576 local new = {nodes={}, auto=true, path=util.clone(path)}
577 local last = table.remove(path)
579 c = _create_node(path, cache)
592 --- Create a redirect to another dispatching node.
593 -- @param ... Virtual path destination
597 for _, r in ipairs({...}) do
605 --- Rewrite the first x path values of the request.
606 -- @param n Number of path values to replace
607 -- @param ... Virtual path to replace removed path values with
608 function rewrite(n, ...)
611 local dispatched = util.clone(context.dispatched)
614 table.remove(dispatched, 1)
617 for i, r in ipairs(req) do
618 table.insert(dispatched, i, r)
621 for _, r in ipairs({...}) do
622 dispatched[#dispatched+1] = r
630 local function _call(self, ...)
631 if #self.argv > 0 then
632 return getfenv()[self.name](unpack(self.argv), ...)
634 return getfenv()[self.name](...)
638 --- Create a function-call dispatching target.
639 -- @param name Target function of local controller
640 -- @param ... Additional parameters passed to the function
641 function call(name, ...)
642 return {type = "call", argv = {...}, name = name, target = _call}
646 local _template = function(self, ...)
647 require "luci.template".render(self.view)
650 --- Create a template render dispatching target.
651 -- @param name Template to be rendered
652 function template(name)
653 return {type = "template", view = name, target = _template}
657 local function _cbi(self, ...)
658 local cbi = require "luci.cbi"
659 local tpl = require "luci.template"
660 local http = require "luci.http"
662 local config = self.config or {}
663 local maps = cbi.load(self.model, ...)
667 for i, res in ipairs(maps) do
669 local cstate = res:parse()
670 if cstate and (not state or cstate < state) then
675 local function _resolve_path(path)
676 return type(path) == "table" and build_url(unpack(path)) or path
679 if config.on_valid_to and state and state > 0 and state < 2 then
680 http.redirect(_resolve_path(config.on_valid_to))
684 if config.on_changed_to and state and state > 1 then
685 http.redirect(_resolve_path(config.on_changed_to))
689 if config.on_success_to and state and state > 0 then
690 http.redirect(_resolve_path(config.on_success_to))
694 if config.state_handler then
695 if not config.state_handler(state, maps) then
700 local pageaction = true
701 http.header("X-CBI-State", state or 0)
702 if not config.noheader then
703 tpl.render("cbi/header", {state = state})
705 for i, res in ipairs(maps) do
707 if res.pageaction == false then
711 if not config.nofooter then
712 tpl.render("cbi/footer", {flow = config, pageaction=pageaction, state = state, autoapply = config.autoapply})
716 --- Create a CBI model dispatching target.
717 -- @param model CBI model to be rendered
718 function cbi(model, config)
719 return {type = "cbi", config = config, model = model, target = _cbi}
723 local function _arcombine(self, ...)
725 local target = #argv > 0 and self.targets[2] or self.targets[1]
726 setfenv(target.target, self.env)
727 target:target(unpack(argv))
730 --- Create a combined dispatching target for non argv and argv requests.
731 -- @param trg1 Overview Target
732 -- @param trg2 Detail Target
733 function arcombine(trg1, trg2)
734 return {type = "arcombine", env = getfenv(), target = _arcombine, targets = {trg1, trg2}}
738 local function _form(self, ...)
739 local cbi = require "luci.cbi"
740 local tpl = require "luci.template"
741 local http = require "luci.http"
743 local maps = luci.cbi.load(self.model, ...)
746 for i, res in ipairs(maps) do
747 local cstate = res:parse()
748 if cstate and (not state or cstate < state) then
753 http.header("X-CBI-State", state or 0)
755 for i, res in ipairs(maps) do
761 --- Create a CBI form model dispatching target.
762 -- @param model CBI form model tpo be rendered
764 return {type = "cbi", model = model, target = _form}