webmcp
view framework/env/request/handler.lua @ 459:dc6d3719f2e7
Support of HTTP OPTIONS requests; Error handling in router
| author | jbe | 
|---|---|
| date | Tue Jul 26 15:35:37 2016 +0200 (2016-07-26) | 
| parents | e2389cc82214 | 
| children | ffdfd54ba881 | 
 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 (see request.initialize()) are to be executed by mcp.lua before this function is invoked by mcp.lua.
     9 --]]--
    11 function request.handler(http_request)
    13   request._http_request = http_request
    14   local path = http_request.path
    15   if path then
    16     local relative_baseurl_elements = {}
    17     for match in string.gmatch(path, "/") do
    18       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    19     end
    20     if #relative_baseurl_elements > 0 then
    21       request._relative_baseurl = table.concat(relative_baseurl_elements)
    22     else
    23       request._relative_baseurl = "./"
    24     end
    25   else
    26     request._relative_baseurl = nil
    27   end
    29   local success, error_info = xpcall(
    30     function()
    32       local function require_method(errmsg, ...)
    33         for i = 2, select("#", ...) do
    34           if http_request.method == select(i, ...) then return end
    35         end
    36         request.set_status("405 Method Not Allowed")
    37         request.add_header("Allow", table.concat({...}, ", "))
    38         error(errmsg)
    39       end
    41       request._route = request.router()
    42       do
    43         local post_id = http_request.post_params["_webmcp_id"]
    44         if post_id then
    45           request._route.id = post_id
    46         end
    47       end
    48       local options_handler = loadcached(encode.file_path(
    49         WEBMCP_BASE_PATH, 'app', WEBMCP_APP_NAME, 'http_options.lua'
    50       ))
    51       if options_handler then
    52         options_handler()
    53       end
    54       if http_request.method == "OPTIONS" then
    55         return
    56       end
    58       if not request._route then
    59         request._route = {}
    60         if request.get_404_route() then
    61           request.set_status("404 Not Found")
    62           request.forward(request.get_404_route())
    63         else
    64           error("Could not route request URL")
    65         end
    66       end
    68       if request._route.static then
    69         local subpath = request._route.static
    70         for element in string.gmatch(subpath, "[^/]+") do
    71           if element == "." or element == ".." then
    72             subpath = nil
    73             break
    74           end
    75         end
    76         local fstat, f, errmsg
    77         if subpath then
    78           local filename = WEBMCP_BASE_PATH .. "static/" .. subpath
    79           fstat, errmsg = extos.stat(filename)
    80           if fstat then
    81             if fstat.isdir then
    82               errmsg = "Is a directory"
    83             elseif not fstat.isreg then
    84               errmsg = "Not a regular file"
    85             else
    86               f, errmsg = io.open(filename, "r")
    87             end
    88           end
    89         end
    90         if not f then
    91           if request.get_404_route() then
    92             request.set_status("404 Not Found")
    93             request.forward(request.get_404_route())
    94           else
    95             error('Could not open static file "' .. subpath .. '": ' .. errmsg)
    96           end
    97         else
    98           require_method(
    99             "Invalid HTTP method for static file",
   100             "HEAD", "GET", "POST"
   101           )
   102           local d = assert(f:read("*a"))
   103           f:close()
   104           slot.put_into("data", d)
   105           local filename_extension = string.match(subpath, "%.([^.]+)$")
   106           slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
   107           request.allow_caching()
   108           return
   109         end
   110       end
   112       -- restore slots if coming from http redirect
   113       do
   114         local tempstore_value = http_request.get_params["_tempstore"]
   115         if tempstore_value then
   116           trace.restore_slots{}
   117           local blob = tempstore.pop(tempstore_value)
   118           if blob then slot.restore_all(blob) end
   119         end
   120       end
   122       if request.get_action() then
   123         trace.request{
   124           module = request.get_module(),
   125           action = request.get_action()
   126         }
   127         if
   128           not execute.action{
   129             module = request.get_module(),
   130             action = request.get_action(),
   131             test_existence = true
   132           } and
   133           request.get_404_route()
   134         then
   135           request.set_status("404 Not Found")
   136           request.forward(request.get_404_route())
   137         else
   138           require_method(
   139             "Invalid HTTP method for action (POST request required)",
   140             "POST"
   141           )
   142           local action_status = execute.filtered_action{
   143             module = request.get_module(),
   144             action = request.get_action(),
   145           }
   146           if not request.is_rerouted() then
   147             local routing_mode, routing_module, routing_view, routing_anchor
   148             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   149             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   150             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   151             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   152             if not (routing_mode or routing_module or routing_view) then
   153               action_status = "default"
   154               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   155               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   156               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   157               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   158             end
   159             assert(routing_module, "Routing information has no module.")
   160             assert(routing_view,   "Routing information has no view.")
   161             if routing_mode == "redirect" then
   162               local routing_params = {}
   163               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   164                 local status, stripped_key = string.match(
   165                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   166                 )
   167                 if status == action_status then
   168                   routing_params[stripped_key] = value
   169                 end
   170               end
   171               request.redirect{
   172                 module = routing_module,
   173                 view   = routing_view,
   174                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   175                 params = routing_params,
   176                 anchor = routing_anchor
   177               }
   178             elseif routing_mode == "forward" then
   179               request.forward{ module = routing_module, view = routing_view }
   180             else
   181               error("Missing or unknown routing mode in request parameters.")
   182             end
   183           end
   184         end
   185       else
   186         -- no action
   187         trace.request{
   188           module = request.get_module(),
   189           view   = request.get_view()
   190         }
   191         if
   192           not execute.view{
   193             module = request.get_module(),
   194             view   = request.get_view(),
   195             test_existence = true
   196           } and request.get_404_route()
   197         then
   198           request.set_status("404 Not Found")
   199           request.forward(request.get_404_route())
   200         end
   201       end
   203       if not request.get_redirect_data() then
   204         request.process_forward()
   205         local view = request.get_view()
   206         if string.find(view, "^_") then
   207           error("Tried to call a private view (prefixed with underscore).")
   208         end
   209         require_method(
   210           "Invalid HTTP method",
   211           "HEAD", "GET", "POST"
   212         )
   213         execute.filtered_view{
   214           module = request.get_module(),
   215           view   = view,
   216         }
   217       end
   219     end,
   221     function(errobj)
   222       return {
   223         errobj = errobj,
   224         stacktrace = string.gsub(
   225           debug.traceback('', 2),
   226           "^\r?\n?stack traceback:\r?\n?", ""
   227         )
   228       }
   229     end
   230   )
   232   if not success then trace.error{} end
   234   slot.select('trace', trace.render)  -- render trace information
   236   local redirect_data = request.get_redirect_data()
   238   -- log error and switch to error layout, unless success
   239   if not success then
   240     local errobj     = error_info.errobj
   241     local stacktrace = error_info.stacktrace
   242     if not request._status then
   243       request._status = "500 Internal Server Error"
   244     end
   245     http_request:close_after_finish()
   246     slot.set_layout('system_error')
   247     slot.select('system_error', function()
   248       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   249         slot.put(
   250           "<p>Database error of class <b>",
   251           encode.html(errobj.code),
   252           "</b> occured:<br/><b>",
   253           encode.html(errobj.message),
   254           "</b></p>"
   255         )
   256       else
   257         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   258       end
   259       slot.put("<p>Stack trace follows:<br/>")
   260       slot.put(encode.html_newlines(encode.html(stacktrace)))
   261       slot.put("</p>")
   262     end)
   263   elseif redirect_data then
   264     if
   265       redirect_data.include_tempstore == true or (
   266         redirect_data.include_tempstore ~= false and
   267         not redirect_data.external
   268       )
   269     then
   270       redirect_data = table.new(redirect_data)
   271       redirect_data.params = table.new(redirect_data.params)
   272       local slot_dump = slot.dump_all()
   273       if slot_dump ~= "" then
   274         redirect_data.params._tempstore = tempstore.save(slot_dump)
   275       end
   276     end
   277     http_request:send_status("303 See Other")
   278     for i, header in ipairs(request._response_headers) do
   279       http_request:send_header(header[1], header[2])
   280     end
   281     http_request:send_header("Location", encode.url(redirect_data))
   282     http_request:finish()
   283   end
   285   if not success or not redirect_data then
   287     http_request:send_status(request._status or "200 OK")
   288     for i, header in ipairs(request._response_headers) do
   289       http_request:send_header(header[1], header[2])
   290     end
   291     if not request._cache_manual then
   292       local cache_time = request._cache_time
   293       if request._cache and cache_time and cache_time > 0 then
   294         http_request:send_header("Cache-Control", "max-age=" .. cache_time)
   295       else
   296         http_request:send_header("Cache-Control", "no-cache")
   297       end
   298     end
   299     http_request:send_header("Content-Type", slot.get_content_type())
   300     http_request:send_data(slot.render_layout())
   301     http_request:finish()
   302   end
   304   return success
   306 end
