moonbridge

annotate moonbridge_http.lua @ 199:198b85b736fc

Initialize request.get_params correctly in HTTP module
author jbe
date Sat Jun 20 01:11:30 2015 +0200 (2015-06-20)
parents 6927f8897f71
children 40a7bd08e304
rev   line source
jbe@0 1 #!/usr/bin/env lua
jbe@0 2
jbe@0 3 -- module preamble
jbe@0 4 local _G, _M = _ENV, {}
jbe@0 5 _ENV = setmetatable({}, {
jbe@0 6 __index = function(self, key)
jbe@0 7 local value = _M[key]; if value ~= nil then return value end
jbe@0 8 return _G[key]
jbe@0 9 end,
jbe@63 10 __newindex = _M
jbe@0 11 })
jbe@0 12
jbe@0 13 -- function that encodes certain HTML entities:
jbe@0 14 -- (not used by the library itself)
jbe@0 15 function encode_html(text)
jbe@0 16 return (
jbe@0 17 string.gsub(
jbe@0 18 text, '[<>&"]',
jbe@0 19 function(char)
jbe@0 20 if char == '<' then
jbe@0 21 return "&lt;"
jbe@0 22 elseif char == '>' then
jbe@0 23 return "&gt;"
jbe@0 24 elseif char == '&' then
jbe@0 25 return "&amp;"
jbe@0 26 elseif char == '"' then
jbe@0 27 return "&quot;"
jbe@0 28 end
jbe@0 29 end
jbe@0 30 )
jbe@0 31 )
jbe@0 32
jbe@0 33 end
jbe@0 34
jbe@0 35 -- function that encodes special characters for URIs:
jbe@0 36 -- (not used by the library itself)
jbe@0 37 function encode_uri(text)
jbe@0 38 return (
jbe@0 39 string.gsub(text, "[^0-9A-Za-z_%.~-]",
jbe@0 40 function (char)
jbe@0 41 return string.format("%%%02x", string.byte(char))
jbe@0 42 end
jbe@0 43 )
jbe@0 44 )
jbe@0 45 end
jbe@0 46
jbe@0 47 -- function undoing URL encoding:
jbe@0 48 do
jbe@0 49 local b0 = string.byte("0")
jbe@0 50 local b9 = string.byte("9")
jbe@0 51 local bA = string.byte("A")
jbe@0 52 local bF = string.byte("F")
jbe@0 53 local ba = string.byte("a")
jbe@0 54 local bf = string.byte("f")
jbe@0 55 function decode_uri(str)
jbe@0 56 return (
jbe@0 57 string.gsub(
jbe@0 58 string.gsub(str, "%+", " "),
jbe@0 59 "%%([0-9A-Fa-f][0-9A-Fa-f])",
jbe@0 60 function(hex)
jbe@0 61 local n1, n2 = string.byte(hex, 1, 2)
jbe@0 62 if n1 >= b0 and n1 <= b9 then n1 = n1 - b0
jbe@0 63 elseif n1 >= bA and n1 <= bF then n1 = n1 - bA + 10
jbe@0 64 elseif n1 >= ba and n1 <= bf then n1 = n1 - ba + 10
jbe@0 65 else error("Assertion failed") end
jbe@0 66 if n2 >= b0 and n2 <= b9 then n2 = n2 - b0
jbe@0 67 elseif n2 >= bA and n2 <= bF then n2 = n2 - bA + 10
jbe@0 68 elseif n2 >= ba and n2 <= bf then n2 = n2 - ba + 10
jbe@0 69 else error("Assertion failed") end
jbe@0 70 return string.char(n1 * 16 + n2)
jbe@0 71 end
jbe@0 72 )
jbe@0 73 )
jbe@0 74 end
jbe@0 75 end
jbe@0 76
jbe@0 77 -- status codes that carry no response body (in addition to 1xx):
jbe@0 78 -- (set to "zero_content_length" if Content-Length header is required)
jbe@0 79 status_without_response_body = {
jbe@5 80 ["101"] = true, -- list 101 to allow protocol switch
jbe@0 81 ["204"] = true,
jbe@0 82 ["205"] = "zero_content_length",
jbe@0 83 ["304"] = true
jbe@0 84 }
jbe@0 85
jbe@167 86 -- handling of GET/POST param tables:
jbe@167 87 local new_params_list -- defined later
jbe@167 88 do
jbe@167 89 local params_list_mapping = setmetatable({}, {__mode="k"})
jbe@167 90 local function nextnonempty(tbl, key)
jbe@167 91 while true do
jbe@167 92 key = next(tbl, key)
jbe@167 93 if key == nil then
jbe@167 94 return nil
jbe@167 95 end
jbe@167 96 local value = tbl[key]
jbe@167 97 if #value > 0 then
jbe@167 98 return key, value
jbe@167 99 end
jbe@35 100 end
jbe@35 101 end
jbe@167 102 local function nextvalue(tbl, key)
jbe@174 103 while true do
jbe@174 104 key = next(tbl, key)
jbe@174 105 if key == nil then
jbe@174 106 return nil
jbe@174 107 end
jbe@174 108 local value = tbl[key][1]
jbe@174 109 if value ~= nil then
jbe@174 110 return key, value
jbe@174 111 end
jbe@167 112 end
jbe@167 113 end
jbe@167 114 local params_list_metatable = {
jbe@167 115 __index = function(self, key)
jbe@167 116 local tbl = {}
jbe@167 117 self[key] = tbl
jbe@167 118 return tbl
jbe@167 119 end,
jbe@167 120 __pairs = function(self)
jbe@167 121 return nextnonempty, self, nil
jbe@167 122 end
jbe@167 123 }
jbe@167 124 local params_metatable = {
jbe@167 125 __index = function(self, key)
jbe@167 126 return params_list_mapping[self][key][1]
jbe@167 127 end,
jbe@167 128 __newindex = function(self, key, value)
jbe@167 129 params_list_mapping[self][key] = {value}
jbe@167 130 end,
jbe@167 131 __pairs = function(self)
jbe@167 132 return nextvalue, params_list_mapping[self], nil
jbe@167 133 end
jbe@167 134 }
jbe@175 135 -- function that returns a table to store key value-list pairs,
jbe@167 136 -- and a second table automatically mapping keys to the first value
jbe@167 137 -- using the key value-list pairs in the first table:
jbe@167 138 new_params_list = function()
jbe@167 139 local params_list = setmetatable({}, params_list_metatable)
jbe@167 140 local params = setmetatable({}, params_metatable)
jbe@167 141 params_list_mapping[params] = params_list
jbe@167 142 return params_list, params
jbe@167 143 end
jbe@167 144 end
jbe@167 145
jbe@175 146 -- function parsing URL encoded form data and storing it in
jbe@167 147 -- a key value-list pairs structure that has to be
jbe@167 148 -- previously obtained by calling by new_params_list():
jbe@167 149 local function read_urlencoded_form(tbl, data)
jbe@167 150 for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do
jbe@167 151 local subtbl = tbl[decode_uri(rawkey)]
jbe@167 152 subtbl[#subtbl+1] = decode_uri(rawvalue)
jbe@167 153 end
jbe@0 154 end
jbe@0 155
jbe@175 156 -- function to convert a HTTP request handler to a socket handler:
jbe@0 157 function generate_handler(handler, options)
jbe@0 158 -- swap arguments if necessary (for convenience):
jbe@0 159 if type(handler) ~= "function" and type(options) == "function" then
jbe@0 160 handler, options = options, handler
jbe@0 161 end
jbe@160 162 -- helper function to process options:
jbe@160 163 local function default(name, default_value)
jbe@160 164 local value = options[name]
jbe@160 165 if value == nil then
jbe@160 166 return default_value
jbe@160 167 else
jbe@160 168 return value or nil
jbe@159 169 end
jbe@160 170 end
jbe@0 171 -- process options:
jbe@0 172 options = options or {}
jbe@0 173 local preamble = "" -- preamble sent with every(!) HTTP response
jbe@0 174 do
jbe@0 175 -- named arg "static_headers" is used to create the preamble:
jbe@0 176 local s = options.static_headers
jbe@0 177 local t = {}
jbe@0 178 if s then
jbe@0 179 if type(s) == "string" then
jbe@0 180 for line in string.gmatch(s, "[^\r\n]+") do
jbe@0 181 t[#t+1] = line
jbe@0 182 end
jbe@0 183 else
jbe@175 184 for i, kv in ipairs(s) do
jbe@0 185 if type(kv) == "string" then
jbe@0 186 t[#t+1] = kv
jbe@0 187 else
jbe@0 188 t[#t+1] = kv[1] .. ": " .. kv[2]
jbe@0 189 end
jbe@0 190 end
jbe@0 191 end
jbe@0 192 end
jbe@0 193 t[#t+1] = ""
jbe@0 194 preamble = table.concat(t, "\r\n")
jbe@0 195 end
jbe@160 196 local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384
jbe@44 197 local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024
jbe@160 198 local header_size_limit = options.header_size_limit or 1024*1024
jbe@160 199 local body_size_limit = options.body_size_limit or 64*1024*1024
jbe@175 200 local request_idle_timeout = default("request_idle_timeout", 65)
jbe@173 201 local request_header_timeout = default("request_header_timeout", 30)
jbe@175 202 local request_body_timeout = default("request_body_timeout", 300)
jbe@173 203 local response_timeout = default("response_timeout", 1800)
jbe@160 204 local poll = options.poll_function or moonbridge_io.poll
jbe@160 205 -- return socket handler:
jbe@0 206 return function(socket)
jbe@160 207 local socket_set = {[socket] = true} -- used for poll function
jbe@0 208 local survive = true -- set to false if process shall be terminated later
jbe@176 209 local consume -- can be set to function that reads some input if possible
jbe@176 210 -- function that may be used as "consume" function
jbe@176 211 -- and which drains some input if possible:
jbe@160 212 local function drain()
jbe@163 213 local bytes, status = socket:drain_nb(input_chunk_size)
jbe@163 214 if not bytes or status == "eof" then
jbe@160 215 consume = nil
jbe@50 216 end
jbe@159 217 end
jbe@163 218 -- function trying to unblock socket by reading:
jbe@160 219 local function unblock()
jbe@160 220 if consume then
jbe@160 221 poll(socket_set, socket_set)
jbe@160 222 consume()
jbe@160 223 else
jbe@160 224 poll(nil, socket_set)
jbe@0 225 end
jbe@154 226 end
jbe@163 227 -- function that enforces consumption of all input:
jbe@162 228 local function consume_all()
jbe@162 229 while consume do
jbe@163 230 poll(socket_set, nil)
jbe@162 231 consume()
jbe@162 232 end
jbe@162 233 end
jbe@163 234 -- handle requests in a loop:
jbe@160 235 repeat
jbe@166 236 -- table for caching nil values:
jbe@166 237 local headers_value_nil = {}
jbe@177 238 -- create a new request object (methods are added later):
jbe@166 239 local request -- allow references to local variable
jbe@166 240 request = {
jbe@165 241 -- allow access to underlying socket:
jbe@0 242 socket = socket,
jbe@165 243 -- cookies are simply stored in a table:
jbe@165 244 cookies = {},
jbe@165 245 -- table mapping header field names to value-lists
jbe@165 246 -- (raw access, but case-insensitive):
jbe@165 247 headers = setmetatable({}, {
jbe@165 248 __index = function(self, key)
jbe@180 249 assert(type(key) == "string", "Attempted to index headers table with a non-string key")
jbe@179 250 local lowerkey = string.lower(key)
jbe@179 251 local result = rawget(self, lowerkey)
jbe@179 252 if result == nil then
jbe@179 253 result = {}
jbe@179 254 rawset(self, lowerkey, result)
jbe@179 255 end
jbe@179 256 rawset(self, key, result)
jbe@179 257 return result
jbe@165 258 end
jbe@165 259 }),
jbe@165 260 -- table mapping header field names to value-lists
jbe@165 261 -- (for headers with comma separated values):
jbe@165 262 headers_csv_table = setmetatable({}, {
jbe@165 263 __index = function(self, key)
jbe@165 264 local result = {}
jbe@165 265 for i, line in ipairs(request.headers[key]) do
jbe@165 266 for entry in string.gmatch(line, "[^,]+") do
jbe@165 267 local value = string.match(entry, "^[ \t]*(..-)[ \t]*$")
jbe@165 268 if value then
jbe@165 269 result[#result+1] = value
jbe@165 270 end
jbe@165 271 end
jbe@165 272 end
jbe@165 273 self[key] = result
jbe@165 274 return result
jbe@165 275 end
jbe@165 276 }),
jbe@165 277 -- table mapping header field names to a comma separated string
jbe@165 278 -- (for headers with comma separated values):
jbe@165 279 headers_csv_string = setmetatable({}, {
jbe@165 280 __index = function(self, key)
jbe@165 281 local result = {}
jbe@165 282 for i, line in ipairs(request.headers[key]) do
jbe@165 283 result[#result+1] = line
jbe@165 284 end
jbe@172 285 result = table.concat(result, ", ")
jbe@165 286 self[key] = result
jbe@165 287 return result
jbe@165 288 end
jbe@165 289 }),
jbe@165 290 -- table mapping header field names to a single string value
jbe@165 291 -- (or false if header has been sent multiple times):
jbe@165 292 headers_value = setmetatable({}, {
jbe@165 293 __index = function(self, key)
jbe@165 294 if headers_value_nil[key] then
jbe@165 295 return nil
jbe@165 296 end
jbe@165 297 local values = request.headers_csv_table[key]
jbe@165 298 if #values == 0 then
jbe@165 299 headers_value_nil[key] = true
jbe@165 300 else
jbe@180 301 local result
jbe@180 302 if #values == 1 then
jbe@180 303 result = values[1]
jbe@180 304 else
jbe@180 305 result = false
jbe@180 306 end
jbe@180 307 self[key] = result
jbe@180 308 return result
jbe@165 309 end
jbe@165 310 end
jbe@165 311 }),
jbe@165 312 -- table mapping header field names to a flag table,
jbe@165 313 -- indicating if the comma separated value contains certain entries:
jbe@165 314 headers_flags = setmetatable({}, {
jbe@165 315 __index = function(self, key)
jbe@165 316 local result = setmetatable({}, {
jbe@165 317 __index = function(self, key)
jbe@180 318 assert(type(key) == "string", "Attempted to index header flag table with a non-string key")
jbe@165 319 local lowerkey = string.lower(key)
jbe@165 320 local result = rawget(self, lowerkey) or false
jbe@165 321 self[lowerkey] = result
jbe@165 322 self[key] = result
jbe@165 323 return result
jbe@165 324 end
jbe@165 325 })
jbe@165 326 for i, value in ipairs(request.headers_csv_table[key]) do
jbe@165 327 result[string.lower(value)] = true
jbe@165 328 end
jbe@165 329 self[key] = result
jbe@165 330 return result
jbe@165 331 end
jbe@165 332 })
jbe@0 333 }
jbe@172 334 -- create metatable for request object:
jbe@172 335 local request_mt = {}
jbe@172 336 setmetatable(request, request_mt)
jbe@172 337 -- callback for request body streaming:
jbe@172 338 local process_body_chunk
jbe@183 339 -- function to enable draining:
jbe@183 340 local function enable_drain()
jbe@183 341 consume = drain
jbe@183 342 process_body_chunk = nil -- allow for early garbage collection
jbe@183 343 end
jbe@162 344 -- local variables to track the state:
jbe@162 345 local state = "init" -- one of:
jbe@162 346 -- "init" (initial state)
jbe@180 347 -- "no_status_sent" (request body streaming config complete)
jbe@162 348 -- "info_status_sent" (1xx status code has been sent)
jbe@162 349 -- "bodyless_status_sent" (204/304 status code has been sent)
jbe@162 350 -- "status_sent" (regular status code has been sent)
jbe@162 351 -- "headers_sent" (headers have been terminated)
jbe@162 352 -- "finished" (request has been answered completely)
jbe@163 353 -- "faulty" (I/O or protocaol error)
jbe@180 354 local request_body_content_length -- Content-Length of request body
jbe@162 355 local close_requested = false -- "Connection: close" requested
jbe@162 356 local close_responded = false -- "Connection: close" sent
jbe@180 357 local content_length = nil -- value of Content-Length header sent
jbe@183 358 local bytes_sent = 0 -- number of bytes sent if Content-Length is set
jbe@180 359 local chunk_parts = {} -- list of chunks to send
jbe@180 360 local chunk_bytes = 0 -- sum of lengths of chunks to send
jbe@172 361 local streamed_post_params = {} -- mapping from POST field name to stream function
jbe@172 362 local streamed_post_param_patterns = {} -- list of POST field pattern and stream function pairs
jbe@164 363 -- function to assert non-faulty handle:
jbe@164 364 local function assert_not_faulty()
jbe@164 365 assert(state ~= "faulty", "Tried to use faulty request handle")
jbe@164 366 end
jbe@162 367 -- functions to send data to the browser:
jbe@160 368 local function send(...)
jbe@187 369 local old_state = state; state = "faulty"
jbe@181 370 if not socket:write_call(unblock, ...) then
jbe@181 371 socket:reset()
jbe@181 372 error("Could not send data to client: " .. errmsg)
jbe@181 373 end
jbe@181 374 state = old_state
jbe@38 375 end
jbe@162 376 local function send_flush(...)
jbe@187 377 local old_state = state; state = "faulty"
jbe@181 378 if not socket:flush_call(unblock, ...) then
jbe@181 379 socket:reset()
jbe@181 380 error("Could not send data to client: " .. errmsg)
jbe@181 381 end
jbe@181 382 state = old_state
jbe@181 383 end
jbe@181 384 -- function to assert proper finish/close/reset:
jbe@181 385 local function assert_close(retval, errmsg)
jbe@181 386 if not retval then
jbe@181 387 error("Could not finish sending data to client: " .. errmsg)
jbe@181 388 end
jbe@162 389 end
jbe@163 390 -- function to finish request:
jbe@163 391 local function finish()
jbe@163 392 if close_responded then
jbe@163 393 -- discard any input:
jbe@183 394 enable_drain()
jbe@163 395 -- close output stream:
jbe@163 396 send_flush()
jbe@163 397 assert_close(socket:finish())
jbe@181 398 -- wait for EOF from peer to avoid immediate TCP RST condition:
jbe@163 399 consume_all()
jbe@163 400 -- fully close socket:
jbe@163 401 assert_close(socket:close())
jbe@163 402 else
jbe@181 403 -- flush outgoing data:
jbe@163 404 send_flush()
jbe@181 405 -- consume incoming data:
jbe@163 406 consume_all()
jbe@163 407 end
jbe@163 408 end
jbe@164 409 -- function that writes out buffered chunks (without flushing the socket):
jbe@164 410 function send_chunk()
jbe@164 411 if chunk_bytes > 0 then
jbe@187 412 local old_state = state; state = "faulty"
jbe@181 413 send(string.format("%x\r\n", chunk_bytes))
jbe@181 414 for i = 1, #chunk_parts do
jbe@164 415 send(chunk_parts[i])
jbe@164 416 chunk_parts[i] = nil
jbe@164 417 end
jbe@164 418 chunk_bytes = 0
jbe@164 419 send("\r\n")
jbe@181 420 state = old_state
jbe@164 421 end
jbe@164 422 end
jbe@168 423 -- function to report an error:
jbe@168 424 local function request_error(throw_error, status, text)
jbe@168 425 if
jbe@168 426 state == "init" or
jbe@168 427 state == "no_status_sent" or
jbe@168 428 state == "info_status_sent"
jbe@168 429 then
jbe@182 430 local error_response_status, errmsg = pcall(function()
jbe@168 431 request:monologue()
jbe@168 432 request:send_status(status)
jbe@168 433 request:send_header("Content-Type", "text/plain")
jbe@168 434 request:send_data(status, "\n")
jbe@168 435 if text then
jbe@168 436 request:send_data("\n", text, "\n")
jbe@168 437 end
jbe@168 438 request:finish()
jbe@168 439 end)
jbe@168 440 if not error_response_status then
jbe@181 441 if text then
jbe@182 442 error("Error while sending error response (" .. status .. " / " .. text .. "): " .. errmsg)
jbe@181 443 else
jbe@182 444 error("Error while sending error response (" .. status .. "): " .. errmsg)
jbe@181 445 end
jbe@168 446 end
jbe@168 447 end
jbe@168 448 if throw_error then
jbe@182 449 local errmsg = "Error while reading request from client. Error response: " .. status
jbe@182 450 if text then
jbe@182 451 errmsg = errmsg .. " (" .. text .. ")"
jbe@182 452 end
jbe@168 453 error(errmsg)
jbe@168 454 else
jbe@168 455 return survive
jbe@168 456 end
jbe@168 457 end
jbe@173 458 -- read functions
jbe@170 459 local function read(...)
jbe@170 460 local data, status = socket:read_yield(...)
jbe@170 461 if data == nil then
jbe@170 462 request_error(true, "400 Bad Request", "Read error")
jbe@170 463 end
jbe@170 464 if status == "eof" then
jbe@170 465 request_error(true, "400 Bad Request", "Unexpected EOF")
jbe@170 466 end
jbe@170 467 return data
jbe@170 468 end
jbe@173 469 local function read_eof(...)
jbe@173 470 local data, status = socket:read_yield(...)
jbe@173 471 if data == nil then
jbe@173 472 request_error(true, "400 Bad Request", "Read error")
jbe@173 473 end
jbe@173 474 if status == "eof" then
jbe@173 475 if data == "" then
jbe@173 476 return nil
jbe@173 477 else
jbe@173 478 request_error(true, "400 Bad Request", "Unexpected EOF")
jbe@173 479 end
jbe@173 480 end
jbe@173 481 return data
jbe@173 482 end
jbe@168 483 -- reads a number of bytes from the socket,
jbe@182 484 -- optionally feeding these bytes chunk-wise into
jbe@182 485 -- the "process_body_chunk" callback function:
jbe@168 486 local function read_body_bytes(remaining)
jbe@168 487 while remaining > 0 do
jbe@182 488 local chunklen
jbe@168 489 if remaining > input_chunk_size then
jbe@182 490 chunklen = input_chunk_size
jbe@168 491 else
jbe@182 492 chunklen = remaining
jbe@168 493 end
jbe@182 494 local chunk = read(chunklen)
jbe@182 495 remaining = remaining - chunklen
jbe@168 496 if process_body_chunk then
jbe@168 497 process_body_chunk(chunk)
jbe@168 498 end
jbe@196 499 coroutine.yield() -- do not read more than necessary
jbe@168 500 end
jbe@168 501 end
jbe@168 502 -- coroutine for request body processing:
jbe@168 503 local function read_body()
jbe@168 504 if request.headers_flags["Transfer-Encoding"]["chunked"] then
jbe@198 505 coroutine.yield() -- do not read on first invocation
jbe@176 506 local limit = body_size_limit
jbe@168 507 while true do
jbe@176 508 local line = read(32 + limit, "\n")
jbe@168 509 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
jbe@168 510 local chunkext
jbe@168 511 if lenstr then
jbe@168 512 chunkext = ""
jbe@168 513 else
jbe@168 514 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
jbe@168 515 end
jbe@168 516 if not lenstr or #lenstr > 13 then
jbe@168 517 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 518 end
jbe@168 519 local len = tonumber("0x" .. lenstr)
jbe@176 520 limit = limit - (#zeros + #chunkext + len)
jbe@176 521 if limit < 0 then
jbe@168 522 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
jbe@168 523 end
jbe@168 524 if len == 0 then break end
jbe@168 525 read_body_bytes(len)
jbe@170 526 local term = read(2, "\n")
jbe@168 527 if term ~= "\r\n" and term ~= "\n" then
jbe@168 528 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 529 end
jbe@168 530 end
jbe@168 531 while true do
jbe@176 532 local line = read(2 + limit, "\n")
jbe@168 533 if line == "\r\n" or line == "\n" then break end
jbe@176 534 limit = limit - #line
jbe@176 535 if limit < 0 then
jbe@168 536 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
jbe@168 537 end
jbe@168 538 end
jbe@168 539 elseif request_body_content_length then
jbe@198 540 coroutine.yield() -- do not read on first invocation
jbe@168 541 read_body_bytes(request_body_content_length)
jbe@168 542 end
jbe@191 543 if process_body_chunk then
jbe@191 544 process_body_chunk(nil) -- signal EOF
jbe@191 545 end
jbe@189 546 consume = nil -- avoid further resumes
jbe@168 547 end
jbe@172 548 -- function to setup default request body handling:
jbe@172 549 local function default_request_body_handling()
jbe@172 550 local post_params_list, post_params = new_params_list()
jbe@172 551 local content_type = request.headers_value["Content-Type"]
jbe@172 552 if content_type then
jbe@172 553 if
jbe@172 554 content_type == "application/x-www-form-urlencoded" or
jbe@172 555 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
jbe@172 556 then
jbe@172 557 read_urlencoded_form(post_params_list, request.body)
jbe@172 558 else
jbe@172 559 local boundary = string.match(
jbe@172 560 content_type,
jbe@172 561 '^multipart/form%-data[ \t]*[;,][ \t]*boundary="([^"]+)"$'
jbe@172 562 ) or string.match(
jbe@172 563 content_type,
jbe@172 564 '^multipart/form%-data[ \t]*[;,][ \t]*boundary=([^"; \t]+)$'
jbe@172 565 )
jbe@172 566 if boundary then
jbe@172 567 local post_metadata_list, post_metadata = new_params_list()
jbe@172 568 boundary = "--" .. boundary
jbe@172 569 local headerdata = ""
jbe@172 570 local streamer
jbe@172 571 local field_name
jbe@172 572 local metadata = {}
jbe@172 573 local value_parts
jbe@172 574 local function default_streamer(chunk)
jbe@172 575 value_parts[#value_parts+1] = chunk
jbe@172 576 end
jbe@172 577 local function stream_part_finish()
jbe@172 578 if streamer == default_streamer then
jbe@172 579 local value = table.concat(value_parts)
jbe@172 580 value_parts = nil
jbe@172 581 if field_name then
jbe@172 582 local values = post_params_list[field_name]
jbe@172 583 values[#values+1] = value
jbe@172 584 local metadata_entries = post_metadata_list[field_name]
jbe@172 585 metadata_entries[#metadata_entries+1] = metadata
jbe@172 586 end
jbe@172 587 else
jbe@172 588 streamer()
jbe@172 589 end
jbe@172 590 headerdata = ""
jbe@172 591 streamer = nil
jbe@172 592 field_name = nil
jbe@172 593 metadata = {}
jbe@172 594 end
jbe@172 595 local function stream_part_chunk(chunk)
jbe@172 596 if streamer then
jbe@172 597 streamer(chunk)
jbe@172 598 else
jbe@172 599 headerdata = headerdata .. chunk
jbe@172 600 while true do
jbe@172 601 local line, remaining = string.match(headerdata, "^(.-)\r?\n(.*)$")
jbe@172 602 if not line then
jbe@172 603 break
jbe@172 604 end
jbe@172 605 if line == "" then
jbe@172 606 streamer = streamed_post_params[field_name]
jbe@172 607 if not streamer then
jbe@172 608 for i, rule in ipairs(streamed_post_param_patterns) do
jbe@172 609 if string.match(field_name, rule[1]) then
jbe@172 610 streamer = rule[2]
jbe@172 611 break
jbe@172 612 end
jbe@172 613 end
jbe@172 614 end
jbe@172 615 if not streamer then
jbe@172 616 value_parts = {}
jbe@172 617 streamer = default_streamer
jbe@172 618 end
jbe@172 619 streamer(remaining, field_name, metadata)
jbe@172 620 return
jbe@172 621 end
jbe@172 622 headerdata = remaining
jbe@172 623 local header_key, header_value = string.match(line, "^([^:]*):[ \t]*(.-)[ \t]*$")
jbe@172 624 if not header_key then
jbe@172 625 request_error(true, "400 Bad Request", "Invalid header in multipart/form-data part")
jbe@172 626 end
jbe@172 627 header_key = string.lower(header_key)
jbe@172 628 if header_key == "content-disposition" then
jbe@172 629 local escaped_header_value = string.gsub(header_value, '"[^"]*"', function(str)
jbe@172 630 return string.gsub(str, "=", "==")
jbe@172 631 end)
jbe@172 632 field_name = string.match(escaped_header_value, ';[ \t]*name="([^"]*)"')
jbe@172 633 if field_name then
jbe@172 634 field_name = string.gsub(field_name, "==", "=")
jbe@172 635 else
jbe@172 636 field_name = string.match(header_value, ';[ \t]*name=([^"; \t]+)')
jbe@172 637 end
jbe@172 638 metadata.file_name = string.match(escaped_header_value, ';[ \t]*filename="([^"]*)"')
jbe@172 639 if metadata.file_name then
jbe@172 640 metadata.file_name = string.gsub(metadata.file_name, "==", "=")
jbe@172 641 else
jbe@172 642 string.match(header_value, ';[ \t]*filename=([^"; \t]+)')
jbe@172 643 end
jbe@172 644 elseif header_key == "content-type" then
jbe@172 645 metadata.content_type = header_value
jbe@172 646 elseif header_key == "content-transfer-encoding" then
jbe@172 647 request_error(true, "400 Bad Request", "Content-transfer-encoding not supported by multipart/form-data parser")
jbe@172 648 end
jbe@172 649 end
jbe@172 650 end
jbe@172 651 end
jbe@172 652 local skippart = true -- ignore data until first boundary
jbe@172 653 local afterbound = false -- interpret 2 bytes after boundary ("\r\n" or "--")
jbe@172 654 local terminated = false -- final boundary read
jbe@172 655 local bigchunk = ""
jbe@184 656 request:stream_request_body(function(chunk)
jbe@172 657 if chunk == nil then
jbe@172 658 if not terminated then
jbe@172 659 request_error(true, "400 Bad Request", "Premature end of multipart/form-data request body")
jbe@172 660 end
jbe@183 661 request.post_params_list, request.post_params = post_params_list, post_params
jbe@172 662 request.post_metadata_list, request.post_metadata = post_metadata_list, post_metadata
jbe@172 663 end
jbe@172 664 if terminated then
jbe@172 665 return
jbe@172 666 end
jbe@172 667 bigchunk = bigchunk .. chunk
jbe@172 668 while true do
jbe@172 669 if afterbound then
jbe@172 670 if #bigchunk <= 2 then
jbe@172 671 return
jbe@172 672 end
jbe@172 673 local terminator = string.sub(bigchunk, 1, 2)
jbe@172 674 if terminator == "\r\n" then
jbe@172 675 afterbound = false
jbe@172 676 bigchunk = string.sub(bigchunk, 3)
jbe@172 677 elseif terminator == "--" then
jbe@172 678 terminated = true
jbe@172 679 bigchunk = nil
jbe@172 680 return
jbe@172 681 else
jbe@172 682 request_error(true, "400 Bad Request", "Error while parsing multipart body (expected CRLF or double minus)")
jbe@172 683 end
jbe@172 684 end
jbe@172 685 local pos1, pos2 = string.find(bigchunk, boundary, 1, true)
jbe@172 686 if not pos1 then
jbe@172 687 if not skippart then
jbe@172 688 local safe = #bigchunk-#boundary
jbe@172 689 if safe > 0 then
jbe@172 690 stream_part_chunk(string.sub(bigchunk, 1, safe))
jbe@172 691 bigchunk = string.sub(bigchunk, safe+1)
jbe@172 692 end
jbe@172 693 end
jbe@172 694 return
jbe@172 695 end
jbe@172 696 if not skippart then
jbe@172 697 stream_part_chunk(string.sub(bigchunk, 1, pos1 - 1))
jbe@172 698 stream_part_finish()
jbe@172 699 else
jbe@172 700 boundary = "\r\n" .. boundary
jbe@172 701 skippart = false
jbe@172 702 end
jbe@172 703 bigchunk = string.sub(bigchunk, pos2 + 1)
jbe@172 704 afterbound = true
jbe@172 705 end
jbe@172 706 end)
jbe@197 707 return -- finalization is executed in stream handler
jbe@172 708 else
jbe@172 709 request_error(true, "415 Unsupported Media Type", "Unknown Content-Type of request body")
jbe@172 710 end
jbe@172 711 end
jbe@172 712 end
jbe@197 713 request.post_params_list, request.post_params = post_params_list, post_params
jbe@172 714 end
jbe@172 715 -- function to prepare body processing:
jbe@162 716 local function prepare()
jbe@164 717 assert_not_faulty()
jbe@183 718 if state ~= "init" then
jbe@183 719 return
jbe@183 720 end
jbe@172 721 if process_body_chunk == nil then
jbe@172 722 default_request_body_handling()
jbe@172 723 end
jbe@183 724 if state ~= "init" then -- re-check if state is still "init"
jbe@162 725 return
jbe@162 726 end
jbe@171 727 consume = coroutine.wrap(read_body)
jbe@198 728 consume() -- call coroutine once to avoid hangup on empty body
jbe@162 729 state = "no_status_sent"
jbe@171 730 if request.headers_flags["Expect"]["100-continue"] then
jbe@171 731 request:send_status("100 Continue")
jbe@171 732 request:finish_headers()
jbe@171 733 end
jbe@162 734 end
jbe@163 735 -- method to ignore input and close connection after response:
jbe@163 736 function request:monologue()
jbe@164 737 assert_not_faulty()
jbe@163 738 if
jbe@163 739 state == "headers_sent" or
jbe@163 740 state == "finished"
jbe@163 741 then
jbe@163 742 error("All HTTP headers have already been sent")
jbe@163 743 end
jbe@187 744 local old_state = state; state = "faulty"
jbe@183 745 enable_drain()
jbe@163 746 close_requested = true
jbe@171 747 if old_state == "init" then
jbe@163 748 state = "no_status_sent"
jbe@164 749 else
jbe@164 750 state = old_state
jbe@162 751 end
jbe@162 752 end
jbe@162 753 -- method to send a HTTP response status (e.g. "200 OK"):
jbe@162 754 function request:send_status(status)
jbe@162 755 prepare()
jbe@187 756 local old_state = state; state = "faulty"
jbe@164 757 if old_state == "info_status_sent" then
jbe@162 758 send_flush("\r\n")
jbe@164 759 elseif old_state ~= "no_status_sent" then
jbe@183 760 state = old_state
jbe@162 761 error("HTTP status has already been sent")
jbe@162 762 end
jbe@162 763 local status1 = string.sub(status, 1, 1)
jbe@162 764 local status3 = string.sub(status, 1, 3)
jbe@162 765 send("HTTP/1.1 ", status, "\r\n", preamble)
jbe@162 766 local wrb = status_without_response_body[status3]
jbe@162 767 if wrb then
jbe@162 768 state = "bodyless_status_sent"
jbe@162 769 if wrb == "zero_content_length" then
jbe@162 770 request:send_header("Content-Length", 0)
jbe@162 771 end
jbe@162 772 elseif status1 == "1" then
jbe@162 773 state = "info_status_sent"
jbe@162 774 else
jbe@162 775 state = "status_sent"
jbe@162 776 end
jbe@162 777 end
jbe@162 778 -- method to send a HTTP response header:
jbe@162 779 -- (key and value must be provided as separate args)
jbe@162 780 function request:send_header(key, value)
jbe@164 781 assert_not_faulty()
jbe@171 782 if state == "init" or state == "no_status_sent" then
jbe@162 783 error("HTTP status has not been sent yet")
jbe@162 784 elseif
jbe@164 785 state == "headers_sent" or
jbe@164 786 state == "finished"
jbe@162 787 then
jbe@162 788 error("All HTTP headers have already been sent")
jbe@162 789 end
jbe@187 790 local old_state = state; state = "faulty"
jbe@162 791 local key_lower = string.lower(key)
jbe@162 792 if key_lower == "content-length" then
jbe@183 793 if old_state == "info_status_sent" then
jbe@183 794 state = old_state
jbe@162 795 error("Cannot set Content-Length for informational status response")
jbe@162 796 end
jbe@162 797 local cl = assert(tonumber(value), "Invalid content-length")
jbe@162 798 if content_length == nil then
jbe@162 799 content_length = cl
jbe@162 800 elseif content_length == cl then
jbe@162 801 return
jbe@162 802 else
jbe@162 803 error("Content-Length has been set multiple times with different values")
jbe@162 804 end
jbe@162 805 elseif key_lower == "connection" then
jbe@162 806 for entry in string.gmatch(string.lower(value), "[^,]+") do
jbe@162 807 if string.match(entry, "^[ \t]*close[ \t]*$") then
jbe@183 808 if old_state == "info_status_sent" then
jbe@183 809 state = old_state
jbe@162 810 error("Cannot set \"Connection: close\" for informational status response")
jbe@162 811 end
jbe@162 812 close_responded = true
jbe@162 813 break
jbe@162 814 end
jbe@162 815 end
jbe@162 816 end
jbe@188 817 send(key, ": ", value, "\r\n")
jbe@183 818 state = old_state
jbe@162 819 end
jbe@184 820 -- method to announce (and enforce) connection close after sending the
jbe@184 821 -- response:
jbe@184 822 function request:close_after_finish()
jbe@184 823 assert_not_faulty()
jbe@184 824 if state == "headers_sent" or state == "finished" then
jbe@184 825 error("All HTTP headers have already been sent")
jbe@184 826 end
jbe@184 827 close_requested = true
jbe@184 828 end
jbe@162 829 -- function to terminate header section in response, optionally flushing:
jbe@162 830 -- (may be called multiple times unless response is finished)
jbe@162 831 local function finish_headers(with_flush)
jbe@162 832 if state == "finished" then
jbe@162 833 error("Response has already been finished")
jbe@162 834 elseif state == "info_status_sent" then
jbe@183 835 state = "faulty"
jbe@162 836 send_flush("\r\n")
jbe@162 837 state = "no_status_sent"
jbe@162 838 elseif state == "bodyless_status_sent" then
jbe@162 839 if close_requested and not close_responded then
jbe@162 840 request:send_header("Connection", "close")
jbe@162 841 end
jbe@181 842 state = "faulty"
jbe@162 843 send("\r\n")
jbe@163 844 finish()
jbe@162 845 state = "finished"
jbe@162 846 elseif state == "status_sent" then
jbe@162 847 if not content_length then
jbe@162 848 request:send_header("Transfer-Encoding", "chunked")
jbe@162 849 end
jbe@162 850 if close_requested and not close_responded then
jbe@162 851 request:send_header("Connection", "close")
jbe@162 852 end
jbe@181 853 state = "faulty"
jbe@162 854 send("\r\n")
jbe@162 855 if request.method == "HEAD" then
jbe@163 856 finish()
jbe@162 857 elseif with_flush then
jbe@162 858 send_flush()
jbe@162 859 end
jbe@162 860 state = "headers_sent"
jbe@162 861 elseif state ~= "headers_sent" then
jbe@162 862 error("HTTP status has not been sent yet")
jbe@162 863 end
jbe@162 864 end
jbe@162 865 -- method to finish and flush headers:
jbe@162 866 function request:finish_headers()
jbe@164 867 assert_not_faulty()
jbe@162 868 finish_headers(true)
jbe@162 869 end
jbe@164 870 -- method to send body data:
jbe@164 871 function request:send_data(...)
jbe@164 872 assert_not_faulty()
jbe@183 873 if state == "info_status_sent" then
jbe@164 874 error("No (non-informational) HTTP status has been sent yet")
jbe@183 875 elseif state == "bodyless_status_sent" then
jbe@164 876 error("Cannot send response data for body-less status message")
jbe@164 877 end
jbe@164 878 finish_headers(false)
jbe@183 879 if state ~= "headers_sent" then
jbe@164 880 error("Unexpected internal status in HTTP engine")
jbe@164 881 end
jbe@164 882 if request.method == "HEAD" then
jbe@164 883 return
jbe@164 884 end
jbe@183 885 state = "faulty"
jbe@164 886 for i = 1, select("#", ...) do
jbe@164 887 local str = tostring(select(i, ...))
jbe@164 888 if #str > 0 then
jbe@164 889 if content_length then
jbe@164 890 local bytes_to_send = #str
jbe@164 891 if bytes_sent + bytes_to_send > content_length then
jbe@164 892 error("Content length exceeded")
jbe@164 893 else
jbe@164 894 send(str)
jbe@164 895 bytes_sent = bytes_sent + bytes_to_send
jbe@164 896 end
jbe@164 897 else
jbe@164 898 chunk_bytes = chunk_bytes + #str
jbe@164 899 chunk_parts[#chunk_parts+1] = str
jbe@164 900 end
jbe@164 901 end
jbe@164 902 end
jbe@164 903 if chunk_bytes >= output_chunk_size then
jbe@164 904 send_chunk()
jbe@164 905 end
jbe@183 906 state = "headers_sent"
jbe@164 907 end
jbe@165 908 -- method to flush output buffer:
jbe@165 909 function request:flush()
jbe@165 910 assert_not_faulty()
jbe@165 911 send_chunk()
jbe@165 912 send_flush()
jbe@165 913 end
jbe@165 914 -- method to finish response:
jbe@165 915 function request:finish()
jbe@165 916 assert_not_faulty()
jbe@165 917 if state == "finished" then
jbe@165 918 return
jbe@165 919 elseif state == "info_status_sent" then
jbe@165 920 error("Informational HTTP response can be finished with :finish_headers() method")
jbe@165 921 end
jbe@165 922 finish_headers(false)
jbe@165 923 if state == "headers_sent" then
jbe@165 924 if request.method ~= "HEAD" then
jbe@165 925 state = "faulty"
jbe@165 926 if content_length then
jbe@165 927 if bytes_sent ~= content_length then
jbe@165 928 error("Content length not used")
jbe@165 929 end
jbe@165 930 else
jbe@165 931 send_chunk()
jbe@165 932 send("0\r\n\r\n")
jbe@165 933 end
jbe@165 934 finish()
jbe@165 935 end
jbe@165 936 state = "finished"
jbe@165 937 elseif state ~= "finished" then
jbe@165 938 error("Unexpected internal status in HTTP engine")
jbe@165 939 end
jbe@165 940 end
jbe@172 941 -- method to register POST param stream handler for a single field name:
jbe@172 942 function request:stream_post_param(field_name, callback)
jbe@172 943 if state ~= "init" then
jbe@183 944 error("Cannot setup request body streamer at this stage anymore")
jbe@172 945 end
jbe@172 946 streamed_post_params[field_name] = callback
jbe@172 947 end
jbe@172 948 -- method to register POST param stream handler for a field name pattern:
jbe@172 949 function request:stream_post_params(pattern, callback)
jbe@172 950 if state ~= "init" then
jbe@183 951 error("Cannot setup request body streamer at this stage anymore")
jbe@172 952 end
jbe@172 953 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
jbe@172 954 end
jbe@172 955 -- method to register request body stream handler
jbe@184 956 function request:stream_request_body(callback)
jbe@172 957 if state ~= "init" then
jbe@183 958 error("Cannot setup request body streamer at this stage anymore")
jbe@172 959 end
jbe@172 960 local inprogress = false
jbe@191 961 local eof = false
jbe@172 962 local buffer = {}
jbe@172 963 process_body_chunk = function(chunk)
jbe@172 964 if inprogress then
jbe@191 965 if chunk == nil then
jbe@191 966 eof = true
jbe@191 967 else
jbe@191 968 buffer[#buffer+1] = chunk
jbe@191 969 end
jbe@172 970 else
jbe@172 971 inprogress = true
jbe@172 972 callback(chunk)
jbe@172 973 while #buffer > 0 do
jbe@172 974 chunk = table.concat(buffer)
jbe@172 975 buffer = {}
jbe@172 976 callback(chunk)
jbe@172 977 end
jbe@191 978 if eof then
jbe@191 979 callback() -- signal EOF
jbe@191 980 end
jbe@172 981 inprogress = false
jbe@172 982 end
jbe@172 983 end
jbe@172 984 end
jbe@172 985 -- method to start reading request body
jbe@172 986 function request:consume_input()
jbe@172 987 prepare()
jbe@172 988 consume_all()
jbe@172 989 end
jbe@172 990 -- method to stream request body
jbe@184 991 function request:stream_request_body_now(callback)
jbe@184 992 request:stream_request_body(function(chunk)
jbe@172 993 if chunk ~= nil then
jbe@172 994 callback(chunk)
jbe@172 995 end
jbe@172 996 end)
jbe@172 997 request:consume_input()
jbe@172 998 end
jbe@172 999 -- metamethod to read special attibutes of request object:
jbe@172 1000 function request_mt:__index(key, value)
jbe@184 1001 if key == "faulty" then
jbe@184 1002 return state == "faulty"
jbe@184 1003 elseif key == "fresh" then
jbe@184 1004 return state == "init" and process_body_chunk == nil
jbe@184 1005 elseif key == "body" then
jbe@172 1006 local chunks = {}
jbe@184 1007 request:stream_request_body_now(function(chunk)
jbe@172 1008 chunks[#chunks+1] = chunk
jbe@172 1009 end)
jbe@172 1010 self.body = table.concat(chunks)
jbe@172 1011 return self.body
jbe@172 1012 elseif
jbe@172 1013 key == "post_params_list" or key == "post_params" or
jbe@172 1014 key == "post_metadata_list" or key == "post_metadata"
jbe@172 1015 then
jbe@172 1016 prepare()
jbe@172 1017 consume_all()
jbe@190 1018 return rawget(self, key)
jbe@172 1019 end
jbe@172 1020 end
jbe@186 1021 -- variable to store request target
jbe@186 1022 local target
jbe@173 1023 -- coroutine for reading headers:
jbe@173 1024 local function read_headers()
jbe@176 1025 -- initialize limit:
jbe@176 1026 local limit = header_size_limit
jbe@173 1027 -- read and parse request line:
jbe@176 1028 local line = read_eof(limit, "\n")
jbe@173 1029 if not line then
jbe@173 1030 return false, survive
jbe@173 1031 end
jbe@176 1032 limit = limit - #line
jbe@176 1033 if limit == 0 then
jbe@173 1034 return false, request_error(false, "414 Request-URI Too Long")
jbe@173 1035 end
jbe@186 1036 local proto
jbe@173 1037 request.method, target, proto =
jbe@173 1038 line:match("^([^ \t\r]+)[ \t]+([^ \t\r]+)[ \t]*([^ \t\r]*)[ \t]*\r?\n$")
jbe@173 1039 if not request.method then
jbe@173 1040 return false, request_error(false, "400 Bad Request")
jbe@173 1041 elseif proto ~= "HTTP/1.1" then
jbe@173 1042 return false, request_error(false, "505 HTTP Version Not Supported")
jbe@173 1043 end
jbe@173 1044 -- read and parse headers:
jbe@173 1045 while true do
jbe@176 1046 local line = read(limit, "\n");
jbe@176 1047 limit = limit - #line
jbe@173 1048 if line == "\r\n" or line == "\n" then
jbe@173 1049 break
jbe@173 1050 end
jbe@176 1051 if limit == 0 then
jbe@173 1052 return false, request_error(false, "431 Request Header Fields Too Large")
jbe@173 1053 end
jbe@173 1054 local key, value = string.match(line, "^([^ \t\r]+):[ \t]*(.-)[ \t]*\r?\n$")
jbe@173 1055 if not key then
jbe@173 1056 return false, request_error(false, "400 Bad Request")
jbe@173 1057 end
jbe@173 1058 local values = request.headers[key]
jbe@173 1059 values[#values+1] = value
jbe@173 1060 end
jbe@173 1061 return true -- success
jbe@173 1062 end
jbe@160 1063 -- wait for input:
jbe@160 1064 if not poll(socket_set, nil, request_idle_timeout) then
jbe@163 1065 return request_error(false, "408 Request Timeout", "Idle connection timed out")
jbe@38 1066 end
jbe@173 1067 -- read headers (with timeout):
jbe@173 1068 do
jbe@173 1069 local coro = coroutine.wrap(read_headers)
jbe@173 1070 local starttime = request_header_timeout and moonbridge_io.timeref()
jbe@173 1071 while true do
jbe@173 1072 local status, retval = coro()
jbe@173 1073 if status == nil then
jbe@173 1074 local remaining
jbe@173 1075 if request_header_timeout then
jbe@173 1076 remaining = request_header_timeout - moonbridge_io.timeref(starttime)
jbe@173 1077 end
jbe@173 1078 if not poll(socket_set, nil, remaining) then
jbe@173 1079 return request_error(false, "408 Request Timeout", "Timeout while receiving headers")
jbe@173 1080 end
jbe@173 1081 elseif status == false then
jbe@173 1082 return retval
jbe@173 1083 elseif status == true then
jbe@173 1084 break
jbe@173 1085 else
jbe@173 1086 error("Unexpected yield value")
jbe@173 1087 end
jbe@173 1088 end
jbe@173 1089 end
jbe@173 1090 -- process "Connection: close" header if existent:
jbe@173 1091 connection_close_requested = request.headers_flags["Connection"]["close"]
jbe@173 1092 -- process "Content-Length" header if existent:
jbe@173 1093 do
jbe@173 1094 local values = request.headers_csv_table["Content-Length"]
jbe@173 1095 if #values > 0 then
jbe@173 1096 request_body_content_length = tonumber(values[1])
jbe@173 1097 local proper_value = tostring(request_body_content_length)
jbe@173 1098 for i, value in ipairs(values) do
jbe@173 1099 value = string.match(value, "^0*(.*)")
jbe@173 1100 if value ~= proper_value then
jbe@173 1101 return request_error(false, "400 Bad Request", "Content-Length header(s) invalid")
jbe@173 1102 end
jbe@173 1103 end
jbe@176 1104 if request_body_content_length > body_size_limit then
jbe@173 1105 return request_error(false, "413 Request Entity Too Large", "Announced request body size is too big")
jbe@173 1106 end
jbe@173 1107 end
jbe@173 1108 end
jbe@173 1109 -- process "Transfer-Encoding" header if existent:
jbe@173 1110 do
jbe@173 1111 local flag = request.headers_flags["Transfer-Encoding"]["chunked"]
jbe@173 1112 local list = request.headers_csv_table["Transfer-Encoding"]
jbe@173 1113 if (flag and #list ~= 1) or (not flag and #list ~= 0) then
jbe@173 1114 return request_error(false, "400 Bad Request", "Unexpected Transfer-Encoding")
jbe@173 1115 end
jbe@173 1116 end
jbe@173 1117 -- process "Expect" header if existent:
jbe@173 1118 for i, value in ipairs(request.headers_csv_table["Expect"]) do
jbe@173 1119 if string.lower(value) ~= "100-continue" then
jbe@173 1120 return request_error(false, "417 Expectation Failed", "Unexpected Expect header")
jbe@173 1121 end
jbe@173 1122 end
jbe@173 1123 -- get mandatory Host header according to RFC 7230:
jbe@173 1124 request.host = request.headers_value["Host"]
jbe@173 1125 if not request.host then
jbe@173 1126 return request_error(false, "400 Bad Request", "No valid host header")
jbe@173 1127 end
jbe@173 1128 -- parse request target:
jbe@173 1129 request.path, request.query = string.match(target, "^/([^?]*)(.*)$")
jbe@173 1130 if not request.path then
jbe@173 1131 local host2
jbe@173 1132 host2, request.path, request.query = string.match(target, "^[Hh][Tt][Tt][Pp]://([^/?]+)/?([^?]*)(.*)$")
jbe@173 1133 if host2 then
jbe@173 1134 if request.host ~= host2 then
jbe@173 1135 return request_error(false, "400 Bad Request", "No valid host header")
jbe@173 1136 end
jbe@173 1137 elseif not (target == "*" and request.method == "OPTIONS") then
jbe@173 1138 return request_error(false, "400 Bad Request", "Invalid request target")
jbe@173 1139 end
jbe@173 1140 end
jbe@173 1141 -- parse GET params:
jbe@199 1142 request.get_params_list, request.get_params = new_params_list()
jbe@173 1143 if request.query then
jbe@173 1144 read_urlencoded_form(request.get_params_list, request.query)
jbe@173 1145 end
jbe@173 1146 -- parse cookies:
jbe@173 1147 for i, line in ipairs(request.headers["Cookie"]) do
jbe@173 1148 for rawkey, rawvalue in
jbe@173 1149 string.gmatch(line, "([^=; ]*)=([^=; ]*)")
jbe@173 1150 do
jbe@173 1151 request.cookies[decode_uri(rawkey)] = decode_uri(rawvalue)
jbe@173 1152 end
jbe@173 1153 end
jbe@173 1154 -- (re)set timeout for handler:
jbe@173 1155 timeout(response_timeout or 0)
jbe@173 1156 -- call underlying handler and remember boolean result:
jbe@173 1157 if handler(request) ~= true then survive = false end
jbe@173 1158 -- finish request (unless already done by underlying handler):
jbe@173 1159 request:finish()
jbe@173 1160 -- stop timeout timer:
jbe@173 1161 timeout(0)
jbe@162 1162 until close_responded
jbe@0 1163 return survive
jbe@0 1164 end
jbe@0 1165 end
jbe@0 1166
jbe@0 1167 return _M
jbe@0 1168

Impressum / About Us