webmcp
view framework/env/request/handler.lua @ 351:b1748c6c3c89
extos.stat(...) returns false (instead of nil) if file does not exist; Added extos.lstat(...) and extos.fstat(...)
| author | jbe | 
|---|---|
| date | Thu Mar 26 16:38:30 2015 +0100 (2015-03-26) | 
| parents | 8cf6d927d074 | 
| children | 2b5bdf9028fb | 
 line source
     1 --[[--
     2 success =         -- false if an error occurred, true otherwise
     3 request.handler(
     4   http_request    -- HTTP request object
     5 )
     7 Called by mcp.lua to process an HTTP request. Calls request.router(), and handles the request. Note: request initializers will have to be (automatically) executed before this function is invoked by mcp.lua.
     9 --]]--
    11 local function file_exists(filename)
    12   local file = io.open(filename, "r")
    13   if file then
    14     io.close(file)
    15     return true
    16   else
    17     return false
    18   end
    19 end
    21 function request.handler(http_request)
    22   request._http_request = http_request
    23   local path = http_request.path
    24   if path then
    25     local relative_baseurl_elements = {}
    26     for match in string.gmatch(path, "/") do
    27       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    28     end
    29     if #relative_baseurl_elements > 0 then
    30       request._relative_baseurl = table.concat(relative_baseurl_elements)
    31     else
    32       request._relative_baseurl = "./"
    33     end
    34   else
    35     request._relative_baseurl = nil
    36   end
    37   request._route = request.router()
    38   do
    39     local post_id = http_request.post_params["_webmcp_id"]
    40     if post_id then
    41       request._route.id = post_id
    42     end
    43   end
    45   local success, error_info = xpcall(
    46     function()
    48       if not request._route then
    49         request._route = {}
    50         if request.get_404_route() then
    51           request.set_status("404 Not Found")
    52           request.forward(request.get_404_route())
    53         else
    54           error("Could not route request URL")
    55         end
    56       end
    58       if request._route.static then
    59         local filename = WEBMCP_BASE_PATH .. "static/" .. request._route.static
    60         -- TODO: move sanitizer from request.default_router(...) to request.handler(...)
    61         local fstat, f, errmsg
    62         fstat, errmsg = extos.stat(filename)
    63         if fstat then
    64           if fstat.isdir then
    65             errmsg = "Is a directory"
    66           elseif not fstat.isreg then
    67             errmsg = "Not a regular file"
    68           else
    69             f, errmsg = io.open(filename, "r")
    70           end
    71         end
    72         if not f then
    73           request.set_status("404 Not Found")
    74           if request.get_404_route() then
    75             request.set_status("404 Not Found")
    76             request.forward(request.get_404_route())
    77           else
    78             error('Could not open static file "' .. request._route.static .. '": ' .. errmsg)
    79           end
    80         else
    81           local d = assert(f:read("*a"))
    82           f:close()
    83           slot.put_into("data", d)
    84           local filename_extension = string.match(request._route.static, "%.([^.]+)$")
    85           slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
    86           request.allow_caching()
    87           return
    88         end
    89       end
    91       -- restore slots if coming from http redirect
    92       do
    93         local tempstore_value = http_request.get_params["_tempstore"]
    94         if tempstore_value then
    95           trace.restore_slots{}
    96           local blob = tempstore.pop(tempstore_value)
    97           if blob then slot.restore_all(blob) end
    98         end
    99       end
   101       if request.get_action() then
   102         trace.request{
   103           module = request.get_module(),
   104           action = request.get_action()
   105         }
   106         if
   107           request.get_404_route() and
   108           not file_exists(
   109             encode.action_file_path{
   110               module = request.get_module(),
   111               action = request.get_action()
   112             }
   113           )
   114         then
   115           request.set_status("404 Not Found")
   116           request.forward(request.get_404_route())
   117         else
   118           if http_request.method ~= "POST" then
   119             request.set_status("405 Method Not Allowed")
   120             request.add_header("Allow", "POST")
   121             error("Tried to invoke an action with a GET request.")
   122           end
   123           local action_status = execute.filtered_action{
   124             module = request.get_module(),
   125             action = request.get_action(),
   126           }
   127           if not request.is_rerouted() then
   128             local routing_mode, routing_module, routing_view, routing_anchor
   129             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   130             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   131             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   132             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   133             if not (routing_mode or routing_module or routing_view) then
   134               action_status = "default"
   135               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   136               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   137               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   138               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   139             end
   140             assert(routing_module, "Routing information has no module.")
   141             assert(routing_view,   "Routing information has no view.")
   142             if routing_mode == "redirect" then
   143               local routing_params = {}
   144               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   145                 local status, stripped_key = string.match(
   146                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   147                 )
   148                 if status == action_status then
   149                   routing_params[stripped_key] = value
   150                 end
   151               end
   152               request.redirect{
   153                 module = routing_module,
   154                 view   = routing_view,
   155                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   156                 params = routing_params,
   157                 anchor = routing_anchor
   158               }
   159             elseif routing_mode == "forward" then
   160               request.forward{ module = routing_module, view = routing_view }
   161             else
   162               error("Missing or unknown routing mode in request parameters.")
   163             end
   164           end
   165         end
   166       else
   167         -- no action
   168         trace.request{
   169           module = request.get_module(),
   170           view   = request.get_view()
   171         }
   172         if
   173           request.get_404_route() and
   174           not file_exists(
   175             encode.view_file_path{
   176               module = request.get_module(),
   177               view   = request.get_view()
   178             }
   179           )
   180         then
   181           request.set_status("404 Not Found")
   182           request.forward(request.get_404_route())
   183         end
   184       end
   186       if not request.get_redirect_data() then
   187         request.process_forward()
   188         local view = request.get_view()
   189         if string.find(view, "^_") then
   190           error("Tried to call a private view (prefixed with underscore).")
   191         end
   192         execute.filtered_view{
   193           module = request.get_module(),
   194           view   = view,
   195         }
   196       end
   198     end,
   200     function(errobj)
   201       return {
   202         errobj = errobj,
   203         stacktrace = string.gsub(
   204           debug.traceback('', 2),
   205           "^\r?\n?stack traceback:\r?\n?", ""
   206         )
   207       }
   208     end
   209   )
   211   if not success then trace.error{} end
   213   -- TODO: extend trace system to generally monitor execution time
   214   -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   216   slot.select('trace', trace.render)  -- render trace information
   218   local redirect_data = request.get_redirect_data()
   220   -- log error and switch to error layout, unless success
   221   if not success then
   222     local errobj     = error_info.errobj
   223     local stacktrace = error_info.stacktrace
   224     if not request._status then
   225       request._status = "500 Internal Server Error"
   226     end
   227     http_request:close_after_finish()
   228     slot.set_layout('system_error')
   229     slot.select('system_error', function()
   230       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   231         slot.put(
   232           "<p>Database error of class <b>",
   233           encode.html(errobj.code),
   234           "</b> occured:<br/><b>",
   235           encode.html(errobj.message),
   236           "</b></p>"
   237         )
   238       else
   239         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   240       end
   241       slot.put("<p>Stack trace follows:<br/>")
   242       slot.put(encode.html_newlines(encode.html(stacktrace)))
   243       slot.put("</p>")
   244     end)
   245   elseif redirect_data then
   246     redirect_data = table.new(redirect_data)
   247     redirect_data.params = table.new(redirect_data.params)
   248     local slot_dump = slot.dump_all()
   249     if slot_dump ~= "" then
   250       redirect_data.params._tempstore = tempstore.save(slot_dump)
   251     end
   252     http_request:send_status("303 See Other")
   253     for i, header in ipairs(request._response_headers) do
   254       http_request:send_header(header[1], header[2])
   255     end
   256     http_request:send_header("Location", encode.url(redirect_data))
   257     http_request:finish()
   258   end
   260   if not success or not redirect_data then
   262     http_request:send_status(request._status or "200 OK")
   263     for i, header in ipairs(request._response_headers) do
   264       http_request:send_header(header[1], header[2])
   265     end
   266     if not request._cache_manual then
   267       local cache_time = request._cache_time
   268       if request._cache and cache_time and cache_time > 0 then
   269         http_request:send_header("Cache-Control", "max-age=" .. cache_time)
   270       else
   271         http_request:send_header("Cache-Control", "no-cache")
   272       end
   273     end
   274     http_request:send_header("Content-Type", slot.get_content_type())
   275     http_request:send_data(slot.render_layout())
   276     http_request:finish()
   277   end
   279   return success
   281 end
