webmcp
view framework/env/request/handler.lua @ 282:be8ede894624
Code cleanup: handle I/O errors while reading template file
| author | jbe | 
|---|---|
| date | Sun Mar 22 00:57:32 2015 +0100 (2015-03-22) | 
| parents | 5af7c66fbc08 | 
| children | 81711c529eb2 | 
 line source
     1 --[[--
     2 request.handler(
     3   http_request,   -- HTTP request object
     4   close           -- boolean indicating whether the server should announce to close the connection
     5 )
     7 Called by mcp.lua to process an HTTP request. Performs some initializations, calls request.router(), and handles the request.
     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, close)
    22   _G.app = {}  -- may be overwritten or modified by request initializers
    23   do
    24     request._in_progress = true  -- NOTE: must be set to true before initializer functions are called
    25     for i, func in ipairs(request._initializers) do
    26       func()
    27     end
    28   end
    30   request._http_request = http_request
    31   local path = http_request.path
    32   if path then
    33     local relative_baseurl_elements = {}
    34     for match in string.gmatch(path, "/") do
    35       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    36     end
    37     if #relative_baseurl_elements > 0 then
    38       request._relative_baseurl = table.concat(relative_baseurl_elements)
    39     else
    40       request._relative_baseurl = "./"
    41     end
    42   else
    43     request._relative_baseurl = nil
    44   end
    45   request._route = request.router() or {}
    46   do
    47     local post_id = http_request.post_params["_webmcp_id"]
    48     if post_id then
    49       request._route.id = post_id
    50     end
    51   end
    53   if close then
    54     request.add_header("Connection", "close")
    55   end
    57   local success, error_info = xpcall(
    58     function()
    60       if request._route.static then
    61         local f, errmsg = io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r")
    62         if not f then
    63           if request.get_404_route() then
    64             request.set_status("404 Not Found")
    65             request.forward(request.get_404_route())
    66             return
    67           else
    68             error('Could not open static file "' .. request._route.static .. '": ' .. errmsg)
    69           end
    70         end
    71         local d = assert(f:read("*a"))
    72         f:close()
    73         slot.put_into("data", d)
    74         local filename_extension = string.match(request._route.static, "%.([^.]+)$")
    75         slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
    76         return
    77       end
    79       -- restore slots if coming from http redirect
    80       local tempstore_value = http_request.get_params["_tempstore"]
    81       if tempstore_value then
    82         trace.restore_slots{}
    83         local blob = tempstore.pop(tempstore_value)
    84         if blob then slot.restore_all(blob) end
    85       end
    87       if request.get_action() then
    88         trace.request{
    89           module = request.get_module(),
    90           action = request.get_action()
    91         }
    92         if
    93           request.get_404_route() and
    94           not file_exists(
    95             encode.action_file_path{
    96               module = request.get_module(),
    97               action = request.get_action()
    98             }
    99           )
   100         then
   101           request.set_status("404 Not Found")
   102           request.forward(request.get_404_route())
   103         else
   104           if http_request.method ~= "POST" then
   105             request.set_status("405 Method Not Allowed")
   106             request.add_header("Allow", "POST")
   107             error("Tried to invoke an action with a GET request.")
   108           end
   109           local action_status = execute.filtered_action{
   110             module = request.get_module(),
   111             action = request.get_action(),
   112           }
   113           if not request.is_rerouted() then
   114             local routing_mode, routing_module, routing_view, routing_anchor
   115             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   116             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   117             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   118             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   119             if not (routing_mode or routing_module or routing_view) then
   120               action_status = "default"
   121               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   122               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   123               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   124               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   125             end
   126             assert(routing_module, "Routing information has no module.")
   127             assert(routing_view,   "Routing information has no view.")
   128             if routing_mode == "redirect" then
   129               local routing_params = {}
   130               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   131                 local status, stripped_key = string.match(
   132                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   133                 )
   134                 if status == action_status then
   135                   routing_params[stripped_key] = value
   136                 end
   137               end
   138               request.redirect{
   139                 module = routing_module,
   140                 view   = routing_view,
   141                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   142                 params = routing_params,
   143                 anchor = routing_anchor
   144               }
   145             elseif routing_mode == "forward" then
   146               request.forward{ module = routing_module, view = routing_view }
   147             else
   148               error("Missing or unknown routing mode in request parameters.")
   149             end
   150           end
   151         end
   152       else
   153         -- no action
   154         trace.request{
   155           module = request.get_module(),
   156           view   = request.get_view()
   157         }
   158         if
   159           request.get_404_route() and
   160           not file_exists(
   161             encode.view_file_path{
   162               module = request.get_module(),
   163               view   = request.get_view()
   164             }
   165           )
   166         then
   167           request.set_status("404 Not Found")
   168           request.forward(request.get_404_route())
   169         end
   170       end
   172       if not request.get_redirect_data() then
   173         request.process_forward()
   174         local view = request.get_view()
   175         if string.find(view, "^_") then
   176           error("Tried to call a private view (prefixed with underscore).")
   177         end
   178         execute.filtered_view{
   179           module = request.get_module(),
   180           view   = view,
   181         }
   182       end
   184       -- force error due to missing absolute base URL until its too late to display error message
   185       --if request.get_redirect_data() then
   186       --  request.get_absolute_baseurl()
   187       --end
   189     end,
   191     function(errobj)
   192       return {
   193         errobj = errobj,
   194         stacktrace = string.gsub(
   195           debug.traceback('', 2),
   196           "^\r?\n?stack traceback:\r?\n?", ""
   197         )
   198       }
   199     end
   200   )
   202   if not success then trace.error{} end
   204   -- TODO: extend trace system to generally monitor execution time
   205   -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   207   slot.select('trace', trace.render)  -- render trace information
   209   local redirect_data = request.get_redirect_data()
   211   -- log error and switch to error layout, unless success
   212   if not success then
   213     local errobj     = error_info.errobj
   214     local stacktrace = error_info.stacktrace
   215     if not request._status then
   216       request._status = "500 Internal Server Error"
   217     end
   218     slot.set_layout('system_error')
   219     slot.select('system_error', function()
   220       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   221         slot.put(
   222           "<p>Database error of class <b>",
   223           encode.html(errobj.code),
   224           "</b> occured:<br/><b>",
   225           encode.html(errobj.message),
   226           "</b></p>"
   227         )
   228       else
   229         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   230       end
   231       slot.put("<p>Stack trace follows:<br/>")
   232       slot.put(encode.html_newlines(encode.html(stacktrace)))
   233       slot.put("</p>")
   234     end)
   235   elseif redirect_data then
   236     redirect_data = table.new(redirect_data)
   237     if redirect_data.base == nil then
   238       redirect_data.base = request.get_absolute_baseurl()
   239     end
   240     redirect_data.params = table.new(redirect_data.params)
   241     local slot_dump = slot.dump_all()
   242     if slot_dump ~= "" then
   243       redirect_data.params.tempstore = tempstore.save(slot_dump)
   244     end
   245     http_request:send_status("303 See Other")
   246     for i, header in ipairs(request._response_headers) do
   247       http_request:send_header(header[1], header[2])
   248     end
   249     http_request:send_header("Location", encode.url(redirect_data))
   250     http_request:finish()
   251   end
   253   if not success or not redirect_data then
   255     http_request:send_status(request._status or "200 OK")
   256     for i, header in ipairs(request._response_headers) do
   257       http_request:send_header(header[1], header[2])
   258     end
   259     http_request:send_header("Content-Type", slot.get_content_type())
   260     http_request:send_data(slot.render_layout())
   261     http_request:finish()
   262   end
   264 end
   266 --//--
   268 --[[--
   269 app  -- table to store an application state
   271 'app' is a global table for storing any application state data. It will be reset for every request.
   272 --]]--
   274 -- Initialized in request.handler(...).
   276 --//--
