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 module("luci.dispatcher", package.seeall)
35 context = luci.util.threadlocal()
46 --- Build the URL relative to the server webroot from given virtual path.
47 -- @param ... Virtual path
48 -- @return Relative URL
49 function build_url(...)
50 return luci.http.getenv("SCRIPT_NAME") .. "/" .. table.concat(arg, "/")
53 --- Send a 404 error code and render the "error404" template if available.
54 -- @param message Custom error message (optional)
56 function error404(message)
57 luci.http.status(404, "Not Found")
58 message = message or "Not Found"
60 require("luci.template")
61 if not luci.util.copcall(luci.template.render, "error404") then
62 luci.http.prepare_content("text/plain")
63 luci.http.write(message)
68 --- Send a 500 error code and render the "error500" template if available.
69 -- @param message Custom error message (optional)#
71 function error500(message)
72 luci.http.status(500, "Internal Server Error")
74 require("luci.template")
75 if not luci.util.copcall(luci.template.render, "error500", {message=message}) then
76 luci.http.prepare_content("text/plain")
77 luci.http.write(message)
82 function authenticator.htmlauth(validator, default)
83 local user = luci.http.formvalue("username")
84 local pass = luci.http.formvalue("password")
86 if user and validator(user, pass) then
91 require("luci.template")
93 luci.template.render("sysauth", {duser=default, fuser=user})
98 --- Dispatch an HTTP request.
99 -- @param request LuCI HTTP Request object
100 function httpdispatch(request)
101 luci.http.context.request = request
103 local pathinfo = request:getenv("PATH_INFO") or ""
105 for node in pathinfo:gmatch("[^/]+") do
106 table.insert(context.request, node)
109 dispatch(context.request)
113 --- Dispatches a LuCI virtual path.
114 -- @param request Virtual path
115 function dispatch(request)
116 context.path = request
119 luci.i18n.setlanguage(require("luci.config").main.lang)
121 if not context.tree then
125 local c = context.tree
128 context.args = context.path
131 for i, s in ipairs(request) do
138 for k, v in pairs(c) do
148 for j=n+1, #request do
149 table.insert(args, request[j])
154 require("luci.i18n").loadc(track.i18n)
157 -- Init template engine
158 local tpl = require("luci.template")
160 tpl.context.viewns = viewns
161 viewns.write = luci.http.write
162 viewns.translate = function(...) return require("luci.i18n").translate(...) end
163 viewns.striptags = luci.util.striptags
164 viewns.controller = luci.http.getenv("SCRIPT_NAME")
165 viewns.media = luci.config.main.mediaurlbase
166 viewns.resource = luci.config.main.resourcebase
167 viewns.REQUEST_URI = luci.http.getenv("SCRIPT_NAME") .. (luci.http.getenv("PATH_INFO") or "")
169 if track.dependent then
170 local stat, err = pcall(assert, not track.auto)
177 if track.sysauth then
178 require("luci.sauth")
179 local authen = type(track.sysauth_authenticator) == "function"
180 and track.sysauth_authenticator
181 or authenticator[track.sysauth_authenticator]
182 local def = (type(track.sysauth) == "string") and track.sysauth
183 local accs = def and {track.sysauth} or track.sysauth
184 local sess = luci.http.getcookie("sysauth")
185 sess = sess and sess:match("^[A-F0-9]+$")
186 local user = luci.sauth.read(sess)
188 if not luci.util.contains(accs, user) then
190 local user = authen(luci.sys.user.checkpasswd, def)
191 if not user or not luci.util.contains(accs, user) then
194 local sid = luci.sys.uniqueid(16)
195 luci.http.header("Set-Cookie", "sysauth=" .. sid.."; path=/")
196 luci.sauth.write(sid, user)
199 luci.http.status(403, "Forbidden")
205 if track.setgroup then
206 luci.sys.process.setgroup(track.setgroup)
209 if track.setuser then
210 luci.sys.process.setuser(track.setuser)
213 if c and type(c.target) == "function" then
214 context.dispatched = c
215 stat, mod = luci.util.copcall(require, c.module)
217 luci.util.updfenv(c.target, mod)
220 stat, err = luci.util.copcall(c.target, unpack(args))
229 --- Generate the dispatching index using the best possible strategy.
230 function createindex()
231 local path = luci.util.libpath() .. "/controller/"
234 if luci.util.copcall(require, "luci.fastindex") then
235 createindex_fastindex(path, suff)
237 createindex_plain(path, suff)
241 --- Generate the dispatching index using the fastindex C-indexer.
242 -- @param path Controller base directory
243 -- @param suffix Controller file suffix
244 function createindex_fastindex(path, suffix)
248 fi = luci.fastindex.new("index")
249 fi.add(path .. "*" .. suffix)
250 fi.add(path .. "*/*" .. suffix)
254 for k, v in pairs(fi.indexes) do
259 --- Generate the dispatching index using the native file-cache based strategy.
260 -- @param path Controller base directory
261 -- @param suffix Controller file suffix
262 function createindex_plain(path, suffix)
267 local controllers = luci.util.combine(
268 luci.fs.glob(path .. "*" .. suffix) or {},
269 luci.fs.glob(path .. "*/*" .. suffix) or {}
273 cache = luci.fs.mtime(indexcache)
276 luci.fs.mkdir(indexcache)
277 luci.fs.chmod(indexcache, "a=,u=rwx")
278 cache = luci.fs.mtime(indexcache)
282 for i,c in ipairs(controllers) do
283 local module = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
289 cachefile = indexcache .. "/" .. module
290 stime = luci.fs.mtime(c) or 0
291 ctime = luci.fs.mtime(cachefile) or 0
294 if not cache or stime > ctime then
295 stat, mod = luci.util.copcall(require, module)
297 if stat and mod and type(mod.index) == "function" then
298 index[module] = mod.index
301 luci.fs.writefile(cachefile, luci.util.get_bytecode(mod.index))
305 index[module] = loadfile(cachefile)
310 --- Create the dispatching tree from the index.
311 -- Build the index before if it does not exist yet.
312 function createtree()
317 context.tree = {nodes={}}
320 -- Load default translation
321 luci.i18n.loadc("default")
323 local scope = luci.util.clone(_G)
324 for k,v in pairs(luci.dispatcher) do
325 if type(v) == "function" then
330 for k, v in pairs(index) do
334 local stat, err = luci.util.copcall(v)
336 error500("createtree failed: " .. k .. ": " .. err)
343 --- Clone a node of the dispatching tree to another position.
344 -- @param path Virtual path destination
345 -- @param clone Virtual path source
346 -- @param title Destination node title (optional)
347 -- @param order Destination node order value (optional)
348 -- @return Dispatching tree node
349 function assign(path, clone, title, order)
350 local obj = node(unpack(path))
357 local c = context.tree
358 for k, v in ipairs(clone) do
359 if not c.nodes[v] then
360 c.nodes[v] = {nodes={}}
366 setmetatable(obj, {__index = c})
371 --- Create a new dispatching node and define common parameters.
372 -- @param path Virtual path
373 -- @param target Target function to call when dispatched.
374 -- @param title Destination node title
375 -- @param order Destination node order value (optional)
376 -- @return Dispatching tree node
377 function entry(path, target, title, order)
378 local c = node(unpack(path))
383 c.module = getfenv(2)._NAME
388 --- Fetch or create a new dispatching node.
389 -- @param ... Virtual path
390 -- @return Dispatching tree node
392 local c = context.tree
395 for k,v in ipairs(arg) do
396 if not c.nodes[v] then
397 c.nodes[v] = {nodes={}, auto=true}
403 c.module = getfenv(2)._NAME
412 --- Create a redirect to another dispatching node.
413 -- @param ... Virtual path destination
421 --- Rewrite the first x path values of the request.
422 -- @param n Number of path values to replace
423 -- @param ... Virtual path to replace removed path values with
424 function rewrite(n, ...)
428 table.remove(context.path, 1)
431 for i,r in ipairs(req) do
432 table.insert(context.path, i, r)
439 --- Create a function-call dispatching target.
440 -- @param name Target function of local controller
441 -- @param ... Additional parameters passed to the function
442 function call(name, ...)
444 return function() return getfenv()[name](unpack(argv)) end
447 --- Create a template render dispatching target.
448 -- @param name Template to be rendered
449 function template(name)
450 require("luci.template")
451 return function() luci.template.render(name) end
454 --- Create a CBI model dispatching target.
455 -- @param model CBI model tpo be rendered
458 require("luci.template")
461 local stat, maps = luci.util.copcall(luci.cbi.load, model, ...)
467 for i, res in ipairs(maps) do
468 local stat, err = luci.util.copcall(res.parse, res)
475 luci.template.render("cbi/header")
476 for i, res in ipairs(maps) do
479 luci.template.render("cbi/footer")
483 --- Create a CBI form model dispatching target.
484 -- @param model CBI form model tpo be rendered
487 require("luci.template")
490 local stat, maps = luci.util.copcall(luci.cbi.load, model, ...)
496 for i, res in ipairs(maps) do
497 local stat, err = luci.util.copcall(res.parse, res)
504 luci.template.render("header")
505 for i, res in ipairs(maps) do
508 luci.template.render("footer")