moonbridge

annotate moonbridge_http.lua @ 196:281f1ac41fc6

Do not read whole request body unless necessary in HTTP module (extra yield)
author jbe
date Sat Jun 20 00:14:18 2015 +0200 (2015-06-20)
parents ab12ecb399f1
children efd1b4cfd2e9
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@176 505 local limit = body_size_limit
jbe@168 506 while true do
jbe@176 507 local line = read(32 + limit, "\n")
jbe@168 508 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
jbe@168 509 local chunkext
jbe@168 510 if lenstr then
jbe@168 511 chunkext = ""
jbe@168 512 else
jbe@168 513 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
jbe@168 514 end
jbe@168 515 if not lenstr or #lenstr > 13 then
jbe@168 516 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 517 end
jbe@168 518 local len = tonumber("0x" .. lenstr)
jbe@176 519 limit = limit - (#zeros + #chunkext + len)
jbe@176 520 if limit < 0 then
jbe@168 521 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
jbe@168 522 end
jbe@168 523 if len == 0 then break end
jbe@168 524 read_body_bytes(len)
jbe@170 525 local term = read(2, "\n")
jbe@168 526 if term ~= "\r\n" and term ~= "\n" then
jbe@168 527 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 528 end
jbe@168 529 end
jbe@168 530 while true do
jbe@176 531 local line = read(2 + limit, "\n")
jbe@168 532 if line == "\r\n" or line == "\n" then break end
jbe@176 533 limit = limit - #line
jbe@176 534 if limit < 0 then
jbe@168 535 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
jbe@168 536 end
jbe@168 537 end
jbe@168 538 elseif request_body_content_length then
jbe@168 539 read_body_bytes(request_body_content_length)
jbe@168 540 end
jbe@191 541 if process_body_chunk then
jbe@191 542 process_body_chunk(nil) -- signal EOF
jbe@191 543 end
jbe@189 544 consume = nil -- avoid further resumes
jbe@168 545 end
jbe@172 546 -- function to setup default request body handling:
jbe@172 547 local function default_request_body_handling()
jbe@172 548 local post_params_list, post_params = new_params_list()
jbe@172 549 local content_type = request.headers_value["Content-Type"]
jbe@172 550 if content_type then
jbe@172 551 if
jbe@172 552 content_type == "application/x-www-form-urlencoded" or
jbe@172 553 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
jbe@172 554 then
jbe@172 555 read_urlencoded_form(post_params_list, request.body)
jbe@172 556 request.post_params_list, request.post_params = post_params_list, post_params
jbe@172 557 else
jbe@172 558 local boundary = string.match(
jbe@172 559 content_type,
jbe@172 560 '^multipart/form%-data[ \t]*[;,][ \t]*boundary="([^"]+)"$'
jbe@172 561 ) or string.match(
jbe@172 562 content_type,
jbe@172 563 '^multipart/form%-data[ \t]*[;,][ \t]*boundary=([^"; \t]+)$'
jbe@172 564 )
jbe@172 565 if boundary then
jbe@172 566 local post_metadata_list, post_metadata = new_params_list()
jbe@172 567 boundary = "--" .. boundary
jbe@172 568 local headerdata = ""
jbe@172 569 local streamer
jbe@172 570 local field_name
jbe@172 571 local metadata = {}
jbe@172 572 local value_parts
jbe@172 573 local function default_streamer(chunk)
jbe@172 574 value_parts[#value_parts+1] = chunk
jbe@172 575 end
jbe@172 576 local function stream_part_finish()
jbe@172 577 if streamer == default_streamer then
jbe@172 578 local value = table.concat(value_parts)
jbe@172 579 value_parts = nil
jbe@172 580 if field_name then
jbe@172 581 local values = post_params_list[field_name]
jbe@172 582 values[#values+1] = value
jbe@172 583 local metadata_entries = post_metadata_list[field_name]
jbe@172 584 metadata_entries[#metadata_entries+1] = metadata
jbe@172 585 end
jbe@172 586 else
jbe@172 587 streamer()
jbe@172 588 end
jbe@172 589 headerdata = ""
jbe@172 590 streamer = nil
jbe@172 591 field_name = nil
jbe@172 592 metadata = {}
jbe@172 593 end
jbe@172 594 local function stream_part_chunk(chunk)
jbe@172 595 if streamer then
jbe@172 596 streamer(chunk)
jbe@172 597 else
jbe@172 598 headerdata = headerdata .. chunk
jbe@172 599 while true do
jbe@172 600 local line, remaining = string.match(headerdata, "^(.-)\r?\n(.*)$")
jbe@172 601 if not line then
jbe@172 602 break
jbe@172 603 end
jbe@172 604 if line == "" then
jbe@172 605 streamer = streamed_post_params[field_name]
jbe@172 606 if not streamer then
jbe@172 607 for i, rule in ipairs(streamed_post_param_patterns) do
jbe@172 608 if string.match(field_name, rule[1]) then
jbe@172 609 streamer = rule[2]
jbe@172 610 break
jbe@172 611 end
jbe@172 612 end
jbe@172 613 end
jbe@172 614 if not streamer then
jbe@172 615 value_parts = {}
jbe@172 616 streamer = default_streamer
jbe@172 617 end
jbe@172 618 streamer(remaining, field_name, metadata)
jbe@172 619 return
jbe@172 620 end
jbe@172 621 headerdata = remaining
jbe@172 622 local header_key, header_value = string.match(line, "^([^:]*):[ \t]*(.-)[ \t]*$")
jbe@172 623 if not header_key then
jbe@172 624 request_error(true, "400 Bad Request", "Invalid header in multipart/form-data part")
jbe@172 625 end
jbe@172 626 header_key = string.lower(header_key)
jbe@172 627 if header_key == "content-disposition" then
jbe@172 628 local escaped_header_value = string.gsub(header_value, '"[^"]*"', function(str)
jbe@172 629 return string.gsub(str, "=", "==")
jbe@172 630 end)
jbe@172 631 field_name = string.match(escaped_header_value, ';[ \t]*name="([^"]*)"')
jbe@172 632 if field_name then
jbe@172 633 field_name = string.gsub(field_name, "==", "=")
jbe@172 634 else
jbe@172 635 field_name = string.match(header_value, ';[ \t]*name=([^"; \t]+)')
jbe@172 636 end
jbe@172 637 metadata.file_name = string.match(escaped_header_value, ';[ \t]*filename="([^"]*)"')
jbe@172 638 if metadata.file_name then
jbe@172 639 metadata.file_name = string.gsub(metadata.file_name, "==", "=")
jbe@172 640 else
jbe@172 641 string.match(header_value, ';[ \t]*filename=([^"; \t]+)')
jbe@172 642 end
jbe@172 643 elseif header_key == "content-type" then
jbe@172 644 metadata.content_type = header_value
jbe@172 645 elseif header_key == "content-transfer-encoding" then
jbe@172 646 request_error(true, "400 Bad Request", "Content-transfer-encoding not supported by multipart/form-data parser")
jbe@172 647 end
jbe@172 648 end
jbe@172 649 end
jbe@172 650 end
jbe@172 651 local skippart = true -- ignore data until first boundary
jbe@172 652 local afterbound = false -- interpret 2 bytes after boundary ("\r\n" or "--")
jbe@172 653 local terminated = false -- final boundary read
jbe@172 654 local bigchunk = ""
jbe@184 655 request:stream_request_body(function(chunk)
jbe@172 656 if chunk == nil then
jbe@172 657 if not terminated then
jbe@172 658 request_error(true, "400 Bad Request", "Premature end of multipart/form-data request body")
jbe@172 659 end
jbe@183 660 request.post_params_list, request.post_params = post_params_list, post_params
jbe@172 661 request.post_metadata_list, request.post_metadata = post_metadata_list, post_metadata
jbe@172 662 end
jbe@172 663 if terminated then
jbe@172 664 return
jbe@172 665 end
jbe@172 666 bigchunk = bigchunk .. chunk
jbe@172 667 while true do
jbe@172 668 if afterbound then
jbe@172 669 if #bigchunk <= 2 then
jbe@172 670 return
jbe@172 671 end
jbe@172 672 local terminator = string.sub(bigchunk, 1, 2)
jbe@172 673 if terminator == "\r\n" then
jbe@172 674 afterbound = false
jbe@172 675 bigchunk = string.sub(bigchunk, 3)
jbe@172 676 elseif terminator == "--" then
jbe@172 677 terminated = true
jbe@172 678 bigchunk = nil
jbe@172 679 return
jbe@172 680 else
jbe@172 681 request_error(true, "400 Bad Request", "Error while parsing multipart body (expected CRLF or double minus)")
jbe@172 682 end
jbe@172 683 end
jbe@172 684 local pos1, pos2 = string.find(bigchunk, boundary, 1, true)
jbe@172 685 if not pos1 then
jbe@172 686 if not skippart then
jbe@172 687 local safe = #bigchunk-#boundary
jbe@172 688 if safe > 0 then
jbe@172 689 stream_part_chunk(string.sub(bigchunk, 1, safe))
jbe@172 690 bigchunk = string.sub(bigchunk, safe+1)
jbe@172 691 end
jbe@172 692 end
jbe@172 693 return
jbe@172 694 end
jbe@172 695 if not skippart then
jbe@172 696 stream_part_chunk(string.sub(bigchunk, 1, pos1 - 1))
jbe@172 697 stream_part_finish()
jbe@172 698 else
jbe@172 699 boundary = "\r\n" .. boundary
jbe@172 700 skippart = false
jbe@172 701 end
jbe@172 702 bigchunk = string.sub(bigchunk, pos2 + 1)
jbe@172 703 afterbound = true
jbe@172 704 end
jbe@172 705 end)
jbe@172 706 else
jbe@172 707 request_error(true, "415 Unsupported Media Type", "Unknown Content-Type of request body")
jbe@172 708 end
jbe@172 709 end
jbe@172 710 end
jbe@172 711 end
jbe@172 712 -- function to prepare body processing:
jbe@162 713 local function prepare()
jbe@164 714 assert_not_faulty()
jbe@183 715 if state ~= "init" then
jbe@183 716 return
jbe@183 717 end
jbe@172 718 if process_body_chunk == nil then
jbe@172 719 default_request_body_handling()
jbe@172 720 end
jbe@183 721 if state ~= "init" then -- re-check if state is still "init"
jbe@162 722 return
jbe@162 723 end
jbe@171 724 consume = coroutine.wrap(read_body)
jbe@162 725 state = "no_status_sent"
jbe@171 726 if request.headers_flags["Expect"]["100-continue"] then
jbe@171 727 request:send_status("100 Continue")
jbe@171 728 request:finish_headers()
jbe@171 729 end
jbe@162 730 end
jbe@163 731 -- method to ignore input and close connection after response:
jbe@163 732 function request:monologue()
jbe@164 733 assert_not_faulty()
jbe@163 734 if
jbe@163 735 state == "headers_sent" or
jbe@163 736 state == "finished"
jbe@163 737 then
jbe@163 738 error("All HTTP headers have already been sent")
jbe@163 739 end
jbe@187 740 local old_state = state; state = "faulty"
jbe@183 741 enable_drain()
jbe@163 742 close_requested = true
jbe@171 743 if old_state == "init" then
jbe@163 744 state = "no_status_sent"
jbe@164 745 else
jbe@164 746 state = old_state
jbe@162 747 end
jbe@162 748 end
jbe@162 749 -- method to send a HTTP response status (e.g. "200 OK"):
jbe@162 750 function request:send_status(status)
jbe@162 751 prepare()
jbe@187 752 local old_state = state; state = "faulty"
jbe@164 753 if old_state == "info_status_sent" then
jbe@162 754 send_flush("\r\n")
jbe@164 755 elseif old_state ~= "no_status_sent" then
jbe@183 756 state = old_state
jbe@162 757 error("HTTP status has already been sent")
jbe@162 758 end
jbe@162 759 local status1 = string.sub(status, 1, 1)
jbe@162 760 local status3 = string.sub(status, 1, 3)
jbe@162 761 send("HTTP/1.1 ", status, "\r\n", preamble)
jbe@162 762 local wrb = status_without_response_body[status3]
jbe@162 763 if wrb then
jbe@162 764 state = "bodyless_status_sent"
jbe@162 765 if wrb == "zero_content_length" then
jbe@162 766 request:send_header("Content-Length", 0)
jbe@162 767 end
jbe@162 768 elseif status1 == "1" then
jbe@162 769 state = "info_status_sent"
jbe@162 770 else
jbe@162 771 state = "status_sent"
jbe@162 772 end
jbe@162 773 end
jbe@162 774 -- method to send a HTTP response header:
jbe@162 775 -- (key and value must be provided as separate args)
jbe@162 776 function request:send_header(key, value)
jbe@164 777 assert_not_faulty()
jbe@171 778 if state == "init" or state == "no_status_sent" then
jbe@162 779 error("HTTP status has not been sent yet")
jbe@162 780 elseif
jbe@164 781 state == "headers_sent" or
jbe@164 782 state == "finished"
jbe@162 783 then
jbe@162 784 error("All HTTP headers have already been sent")
jbe@162 785 end
jbe@187 786 local old_state = state; state = "faulty"
jbe@162 787 local key_lower = string.lower(key)
jbe@162 788 if key_lower == "content-length" then
jbe@183 789 if old_state == "info_status_sent" then
jbe@183 790 state = old_state
jbe@162 791 error("Cannot set Content-Length for informational status response")
jbe@162 792 end
jbe@162 793 local cl = assert(tonumber(value), "Invalid content-length")
jbe@162 794 if content_length == nil then
jbe@162 795 content_length = cl
jbe@162 796 elseif content_length == cl then
jbe@162 797 return
jbe@162 798 else
jbe@162 799 error("Content-Length has been set multiple times with different values")
jbe@162 800 end
jbe@162 801 elseif key_lower == "connection" then
jbe@162 802 for entry in string.gmatch(string.lower(value), "[^,]+") do
jbe@162 803 if string.match(entry, "^[ \t]*close[ \t]*$") then
jbe@183 804 if old_state == "info_status_sent" then
jbe@183 805 state = old_state
jbe@162 806 error("Cannot set \"Connection: close\" for informational status response")
jbe@162 807 end
jbe@162 808 close_responded = true
jbe@162 809 break
jbe@162 810 end
jbe@162 811 end
jbe@162 812 end
jbe@188 813 send(key, ": ", value, "\r\n")
jbe@183 814 state = old_state
jbe@162 815 end
jbe@184 816 -- method to announce (and enforce) connection close after sending the
jbe@184 817 -- response:
jbe@184 818 function request:close_after_finish()
jbe@184 819 assert_not_faulty()
jbe@184 820 if state == "headers_sent" or state == "finished" then
jbe@184 821 error("All HTTP headers have already been sent")
jbe@184 822 end
jbe@184 823 close_requested = true
jbe@184 824 end
jbe@162 825 -- function to terminate header section in response, optionally flushing:
jbe@162 826 -- (may be called multiple times unless response is finished)
jbe@162 827 local function finish_headers(with_flush)
jbe@162 828 if state == "finished" then
jbe@162 829 error("Response has already been finished")
jbe@162 830 elseif state == "info_status_sent" then
jbe@183 831 state = "faulty"
jbe@162 832 send_flush("\r\n")
jbe@162 833 state = "no_status_sent"
jbe@162 834 elseif state == "bodyless_status_sent" then
jbe@162 835 if close_requested and not close_responded then
jbe@162 836 request:send_header("Connection", "close")
jbe@162 837 end
jbe@181 838 state = "faulty"
jbe@162 839 send("\r\n")
jbe@163 840 finish()
jbe@162 841 state = "finished"
jbe@162 842 elseif state == "status_sent" then
jbe@162 843 if not content_length then
jbe@162 844 request:send_header("Transfer-Encoding", "chunked")
jbe@162 845 end
jbe@162 846 if close_requested and not close_responded then
jbe@162 847 request:send_header("Connection", "close")
jbe@162 848 end
jbe@181 849 state = "faulty"
jbe@162 850 send("\r\n")
jbe@162 851 if request.method == "HEAD" then
jbe@163 852 finish()
jbe@162 853 elseif with_flush then
jbe@162 854 send_flush()
jbe@162 855 end
jbe@162 856 state = "headers_sent"
jbe@162 857 elseif state ~= "headers_sent" then
jbe@162 858 error("HTTP status has not been sent yet")
jbe@162 859 end
jbe@162 860 end
jbe@162 861 -- method to finish and flush headers:
jbe@162 862 function request:finish_headers()
jbe@164 863 assert_not_faulty()
jbe@162 864 finish_headers(true)
jbe@162 865 end
jbe@164 866 -- method to send body data:
jbe@164 867 function request:send_data(...)
jbe@164 868 assert_not_faulty()
jbe@183 869 if state == "info_status_sent" then
jbe@164 870 error("No (non-informational) HTTP status has been sent yet")
jbe@183 871 elseif state == "bodyless_status_sent" then
jbe@164 872 error("Cannot send response data for body-less status message")
jbe@164 873 end
jbe@164 874 finish_headers(false)
jbe@183 875 if state ~= "headers_sent" then
jbe@164 876 error("Unexpected internal status in HTTP engine")
jbe@164 877 end
jbe@164 878 if request.method == "HEAD" then
jbe@164 879 return
jbe@164 880 end
jbe@183 881 state = "faulty"
jbe@164 882 for i = 1, select("#", ...) do
jbe@164 883 local str = tostring(select(i, ...))
jbe@164 884 if #str > 0 then
jbe@164 885 if content_length then
jbe@164 886 local bytes_to_send = #str
jbe@164 887 if bytes_sent + bytes_to_send > content_length then
jbe@164 888 error("Content length exceeded")
jbe@164 889 else
jbe@164 890 send(str)
jbe@164 891 bytes_sent = bytes_sent + bytes_to_send
jbe@164 892 end
jbe@164 893 else
jbe@164 894 chunk_bytes = chunk_bytes + #str
jbe@164 895 chunk_parts[#chunk_parts+1] = str
jbe@164 896 end
jbe@164 897 end
jbe@164 898 end
jbe@164 899 if chunk_bytes >= output_chunk_size then
jbe@164 900 send_chunk()
jbe@164 901 end
jbe@183 902 state = "headers_sent"
jbe@164 903 end
jbe@165 904 -- method to flush output buffer:
jbe@165 905 function request:flush()
jbe@165 906 assert_not_faulty()
jbe@165 907 send_chunk()
jbe@165 908 send_flush()
jbe@165 909 end
jbe@165 910 -- method to finish response:
jbe@165 911 function request:finish()
jbe@165 912 assert_not_faulty()
jbe@165 913 if state == "finished" then
jbe@165 914 return
jbe@165 915 elseif state == "info_status_sent" then
jbe@165 916 error("Informational HTTP response can be finished with :finish_headers() method")
jbe@165 917 end
jbe@165 918 finish_headers(false)
jbe@165 919 if state == "headers_sent" then
jbe@165 920 if request.method ~= "HEAD" then
jbe@165 921 state = "faulty"
jbe@165 922 if content_length then
jbe@165 923 if bytes_sent ~= content_length then
jbe@165 924 error("Content length not used")
jbe@165 925 end
jbe@165 926 else
jbe@165 927 send_chunk()
jbe@165 928 send("0\r\n\r\n")
jbe@165 929 end
jbe@165 930 finish()
jbe@165 931 end
jbe@165 932 state = "finished"
jbe@165 933 elseif state ~= "finished" then
jbe@165 934 error("Unexpected internal status in HTTP engine")
jbe@165 935 end
jbe@165 936 end
jbe@172 937 -- method to register POST param stream handler for a single field name:
jbe@172 938 function request:stream_post_param(field_name, callback)
jbe@172 939 if state ~= "init" then
jbe@183 940 error("Cannot setup request body streamer at this stage anymore")
jbe@172 941 end
jbe@172 942 streamed_post_params[field_name] = callback
jbe@172 943 end
jbe@172 944 -- method to register POST param stream handler for a field name pattern:
jbe@172 945 function request:stream_post_params(pattern, callback)
jbe@172 946 if state ~= "init" then
jbe@183 947 error("Cannot setup request body streamer at this stage anymore")
jbe@172 948 end
jbe@172 949 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
jbe@172 950 end
jbe@172 951 -- method to register request body stream handler
jbe@184 952 function request:stream_request_body(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 local inprogress = false
jbe@191 957 local eof = false
jbe@172 958 local buffer = {}
jbe@172 959 process_body_chunk = function(chunk)
jbe@172 960 if inprogress then
jbe@191 961 if chunk == nil then
jbe@191 962 eof = true
jbe@191 963 else
jbe@191 964 buffer[#buffer+1] = chunk
jbe@191 965 end
jbe@172 966 else
jbe@172 967 inprogress = true
jbe@172 968 callback(chunk)
jbe@172 969 while #buffer > 0 do
jbe@172 970 chunk = table.concat(buffer)
jbe@172 971 buffer = {}
jbe@172 972 callback(chunk)
jbe@172 973 end
jbe@191 974 if eof then
jbe@191 975 callback() -- signal EOF
jbe@191 976 end
jbe@172 977 inprogress = false
jbe@172 978 end
jbe@172 979 end
jbe@172 980 end
jbe@172 981 -- method to start reading request body
jbe@172 982 function request:consume_input()
jbe@172 983 prepare()
jbe@172 984 consume_all()
jbe@172 985 end
jbe@172 986 -- method to stream request body
jbe@184 987 function request:stream_request_body_now(callback)
jbe@184 988 request:stream_request_body(function(chunk)
jbe@172 989 if chunk ~= nil then
jbe@172 990 callback(chunk)
jbe@172 991 end
jbe@172 992 end)
jbe@172 993 request:consume_input()
jbe@172 994 end
jbe@172 995 -- metamethod to read special attibutes of request object:
jbe@172 996 function request_mt:__index(key, value)
jbe@184 997 if key == "faulty" then
jbe@184 998 return state == "faulty"
jbe@184 999 elseif key == "fresh" then
jbe@184 1000 return state == "init" and process_body_chunk == nil
jbe@184 1001 elseif key == "body" then
jbe@172 1002 local chunks = {}
jbe@184 1003 request:stream_request_body_now(function(chunk)
jbe@172 1004 chunks[#chunks+1] = chunk
jbe@172 1005 end)
jbe@172 1006 self.body = table.concat(chunks)
jbe@172 1007 return self.body
jbe@172 1008 elseif
jbe@172 1009 key == "post_params_list" or key == "post_params" or
jbe@172 1010 key == "post_metadata_list" or key == "post_metadata"
jbe@172 1011 then
jbe@172 1012 prepare()
jbe@172 1013 consume_all()
jbe@190 1014 return rawget(self, key)
jbe@172 1015 end
jbe@172 1016 end
jbe@186 1017 -- variable to store request target
jbe@186 1018 local target
jbe@173 1019 -- coroutine for reading headers:
jbe@173 1020 local function read_headers()
jbe@176 1021 -- initialize limit:
jbe@176 1022 local limit = header_size_limit
jbe@173 1023 -- read and parse request line:
jbe@176 1024 local line = read_eof(limit, "\n")
jbe@173 1025 if not line then
jbe@173 1026 return false, survive
jbe@173 1027 end
jbe@176 1028 limit = limit - #line
jbe@176 1029 if limit == 0 then
jbe@173 1030 return false, request_error(false, "414 Request-URI Too Long")
jbe@173 1031 end
jbe@186 1032 local proto
jbe@173 1033 request.method, target, proto =
jbe@173 1034 line:match("^([^ \t\r]+)[ \t]+([^ \t\r]+)[ \t]*([^ \t\r]*)[ \t]*\r?\n$")
jbe@173 1035 if not request.method then
jbe@173 1036 return false, request_error(false, "400 Bad Request")
jbe@173 1037 elseif proto ~= "HTTP/1.1" then
jbe@173 1038 return false, request_error(false, "505 HTTP Version Not Supported")
jbe@173 1039 end
jbe@173 1040 -- read and parse headers:
jbe@173 1041 while true do
jbe@176 1042 local line = read(limit, "\n");
jbe@176 1043 limit = limit - #line
jbe@173 1044 if line == "\r\n" or line == "\n" then
jbe@173 1045 break
jbe@173 1046 end
jbe@176 1047 if limit == 0 then
jbe@173 1048 return false, request_error(false, "431 Request Header Fields Too Large")
jbe@173 1049 end
jbe@173 1050 local key, value = string.match(line, "^([^ \t\r]+):[ \t]*(.-)[ \t]*\r?\n$")
jbe@173 1051 if not key then
jbe@173 1052 return false, request_error(false, "400 Bad Request")
jbe@173 1053 end
jbe@173 1054 local values = request.headers[key]
jbe@173 1055 values[#values+1] = value
jbe@173 1056 end
jbe@173 1057 return true -- success
jbe@173 1058 end
jbe@160 1059 -- wait for input:
jbe@160 1060 if not poll(socket_set, nil, request_idle_timeout) then
jbe@163 1061 return request_error(false, "408 Request Timeout", "Idle connection timed out")
jbe@38 1062 end
jbe@173 1063 -- read headers (with timeout):
jbe@173 1064 do
jbe@173 1065 local coro = coroutine.wrap(read_headers)
jbe@173 1066 local starttime = request_header_timeout and moonbridge_io.timeref()
jbe@173 1067 while true do
jbe@173 1068 local status, retval = coro()
jbe@173 1069 if status == nil then
jbe@173 1070 local remaining
jbe@173 1071 if request_header_timeout then
jbe@173 1072 remaining = request_header_timeout - moonbridge_io.timeref(starttime)
jbe@173 1073 end
jbe@173 1074 if not poll(socket_set, nil, remaining) then
jbe@173 1075 return request_error(false, "408 Request Timeout", "Timeout while receiving headers")
jbe@173 1076 end
jbe@173 1077 elseif status == false then
jbe@173 1078 return retval
jbe@173 1079 elseif status == true then
jbe@173 1080 break
jbe@173 1081 else
jbe@173 1082 error("Unexpected yield value")
jbe@173 1083 end
jbe@173 1084 end
jbe@173 1085 end
jbe@173 1086 -- process "Connection: close" header if existent:
jbe@173 1087 connection_close_requested = request.headers_flags["Connection"]["close"]
jbe@173 1088 -- process "Content-Length" header if existent:
jbe@173 1089 do
jbe@173 1090 local values = request.headers_csv_table["Content-Length"]
jbe@173 1091 if #values > 0 then
jbe@173 1092 request_body_content_length = tonumber(values[1])
jbe@173 1093 local proper_value = tostring(request_body_content_length)
jbe@173 1094 for i, value in ipairs(values) do
jbe@173 1095 value = string.match(value, "^0*(.*)")
jbe@173 1096 if value ~= proper_value then
jbe@173 1097 return request_error(false, "400 Bad Request", "Content-Length header(s) invalid")
jbe@173 1098 end
jbe@173 1099 end
jbe@176 1100 if request_body_content_length > body_size_limit then
jbe@173 1101 return request_error(false, "413 Request Entity Too Large", "Announced request body size is too big")
jbe@173 1102 end
jbe@173 1103 end
jbe@173 1104 end
jbe@173 1105 -- process "Transfer-Encoding" header if existent:
jbe@173 1106 do
jbe@173 1107 local flag = request.headers_flags["Transfer-Encoding"]["chunked"]
jbe@173 1108 local list = request.headers_csv_table["Transfer-Encoding"]
jbe@173 1109 if (flag and #list ~= 1) or (not flag and #list ~= 0) then
jbe@173 1110 return request_error(false, "400 Bad Request", "Unexpected Transfer-Encoding")
jbe@173 1111 end
jbe@173 1112 end
jbe@173 1113 -- process "Expect" header if existent:
jbe@173 1114 for i, value in ipairs(request.headers_csv_table["Expect"]) do
jbe@173 1115 if string.lower(value) ~= "100-continue" then
jbe@173 1116 return request_error(false, "417 Expectation Failed", "Unexpected Expect header")
jbe@173 1117 end
jbe@173 1118 end
jbe@173 1119 -- get mandatory Host header according to RFC 7230:
jbe@173 1120 request.host = request.headers_value["Host"]
jbe@173 1121 if not request.host then
jbe@173 1122 return request_error(false, "400 Bad Request", "No valid host header")
jbe@173 1123 end
jbe@173 1124 -- parse request target:
jbe@173 1125 request.path, request.query = string.match(target, "^/([^?]*)(.*)$")
jbe@173 1126 if not request.path then
jbe@173 1127 local host2
jbe@173 1128 host2, request.path, request.query = string.match(target, "^[Hh][Tt][Tt][Pp]://([^/?]+)/?([^?]*)(.*)$")
jbe@173 1129 if host2 then
jbe@173 1130 if request.host ~= host2 then
jbe@173 1131 return request_error(false, "400 Bad Request", "No valid host header")
jbe@173 1132 end
jbe@173 1133 elseif not (target == "*" and request.method == "OPTIONS") then
jbe@173 1134 return request_error(false, "400 Bad Request", "Invalid request target")
jbe@173 1135 end
jbe@173 1136 end
jbe@173 1137 -- parse GET params:
jbe@173 1138 if request.query then
jbe@173 1139 read_urlencoded_form(request.get_params_list, request.query)
jbe@173 1140 end
jbe@173 1141 -- parse cookies:
jbe@173 1142 for i, line in ipairs(request.headers["Cookie"]) do
jbe@173 1143 for rawkey, rawvalue in
jbe@173 1144 string.gmatch(line, "([^=; ]*)=([^=; ]*)")
jbe@173 1145 do
jbe@173 1146 request.cookies[decode_uri(rawkey)] = decode_uri(rawvalue)
jbe@173 1147 end
jbe@173 1148 end
jbe@173 1149 -- (re)set timeout for handler:
jbe@173 1150 timeout(response_timeout or 0)
jbe@173 1151 -- call underlying handler and remember boolean result:
jbe@173 1152 if handler(request) ~= true then survive = false end
jbe@173 1153 -- finish request (unless already done by underlying handler):
jbe@173 1154 request:finish()
jbe@173 1155 -- stop timeout timer:
jbe@173 1156 timeout(0)
jbe@162 1157 until close_responded
jbe@0 1158 return survive
jbe@0 1159 end
jbe@0 1160 end
jbe@0 1161
jbe@0 1162 return _M
jbe@0 1163

Impressum / About Us