moonbridge

annotate moonbridge_http.lua @ 201:4e72725118d0

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

Impressum / About Us