moonbridge

annotate moonbridge_http.lua @ 200:40a7bd08e304

Bugfix in HTTP module regarding extra yield in read_body()
author jbe
date Sat Jun 20 01:26:30 2015 +0200 (2015-06-20)
parents 198b85b736fc
children 4e72725118d0
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@200 488 coroutine.yield() -- do not read more than necessary
jbe@182 489 local chunklen
jbe@168 490 if remaining > input_chunk_size then
jbe@182 491 chunklen = input_chunk_size
jbe@168 492 else
jbe@182 493 chunklen = remaining
jbe@168 494 end
jbe@182 495 local chunk = read(chunklen)
jbe@182 496 remaining = remaining - chunklen
jbe@168 497 if process_body_chunk then
jbe@168 498 process_body_chunk(chunk)
jbe@168 499 end
jbe@168 500 end
jbe@168 501 end
jbe@168 502 -- coroutine for request body processing:
jbe@168 503 local function read_body()
jbe@168 504 if request.headers_flags["Transfer-Encoding"]["chunked"] then
jbe@198 505 coroutine.yield() -- do not read on first invocation
jbe@176 506 local limit = body_size_limit
jbe@168 507 while true do
jbe@176 508 local line = read(32 + limit, "\n")
jbe@168 509 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
jbe@168 510 local chunkext
jbe@168 511 if lenstr then
jbe@168 512 chunkext = ""
jbe@168 513 else
jbe@168 514 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
jbe@168 515 end
jbe@168 516 if not lenstr or #lenstr > 13 then
jbe@168 517 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 518 end
jbe@168 519 local len = tonumber("0x" .. lenstr)
jbe@176 520 limit = limit - (#zeros + #chunkext + len)
jbe@176 521 if limit < 0 then
jbe@168 522 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
jbe@168 523 end
jbe@168 524 if len == 0 then break end
jbe@168 525 read_body_bytes(len)
jbe@170 526 local term = read(2, "\n")
jbe@168 527 if term ~= "\r\n" and term ~= "\n" then
jbe@168 528 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 529 end
jbe@168 530 end
jbe@168 531 while true do
jbe@176 532 local line = read(2 + limit, "\n")
jbe@168 533 if line == "\r\n" or line == "\n" then break end
jbe@176 534 limit = limit - #line
jbe@176 535 if limit < 0 then
jbe@168 536 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
jbe@168 537 end
jbe@168 538 end
jbe@168 539 elseif request_body_content_length then
jbe@168 540 read_body_bytes(request_body_content_length)
jbe@168 541 end
jbe@191 542 if process_body_chunk then
jbe@191 543 process_body_chunk(nil) -- signal EOF
jbe@191 544 end
jbe@189 545 consume = nil -- avoid further resumes
jbe@168 546 end
jbe@172 547 -- function to setup default request body handling:
jbe@172 548 local function default_request_body_handling()
jbe@172 549 local post_params_list, post_params = new_params_list()
jbe@172 550 local content_type = request.headers_value["Content-Type"]
jbe@172 551 if content_type then
jbe@172 552 if
jbe@172 553 content_type == "application/x-www-form-urlencoded" or
jbe@172 554 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
jbe@172 555 then
jbe@172 556 read_urlencoded_form(post_params_list, request.body)
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@197 706 return -- finalization is executed in stream handler
jbe@172 707 else
jbe@172 708 request_error(true, "415 Unsupported Media Type", "Unknown Content-Type of request body")
jbe@172 709 end
jbe@172 710 end
jbe@172 711 end
jbe@197 712 request.post_params_list, request.post_params = post_params_list, post_params
jbe@172 713 end
jbe@172 714 -- function to prepare body processing:
jbe@162 715 local function prepare()
jbe@164 716 assert_not_faulty()
jbe@183 717 if state ~= "init" then
jbe@183 718 return
jbe@183 719 end
jbe@172 720 if process_body_chunk == nil then
jbe@172 721 default_request_body_handling()
jbe@172 722 end
jbe@183 723 if state ~= "init" then -- re-check if state is still "init"
jbe@162 724 return
jbe@162 725 end
jbe@171 726 consume = coroutine.wrap(read_body)
jbe@198 727 consume() -- call coroutine once to avoid hangup on empty body
jbe@162 728 state = "no_status_sent"
jbe@171 729 if request.headers_flags["Expect"]["100-continue"] then
jbe@171 730 request:send_status("100 Continue")
jbe@171 731 request:finish_headers()
jbe@171 732 end
jbe@162 733 end
jbe@163 734 -- method to ignore input and close connection after response:
jbe@163 735 function request:monologue()
jbe@164 736 assert_not_faulty()
jbe@163 737 if
jbe@163 738 state == "headers_sent" or
jbe@163 739 state == "finished"
jbe@163 740 then
jbe@163 741 error("All HTTP headers have already been sent")
jbe@163 742 end
jbe@187 743 local old_state = state; state = "faulty"
jbe@183 744 enable_drain()
jbe@163 745 close_requested = true
jbe@171 746 if old_state == "init" then
jbe@163 747 state = "no_status_sent"
jbe@164 748 else
jbe@164 749 state = old_state
jbe@162 750 end
jbe@162 751 end
jbe@162 752 -- method to send a HTTP response status (e.g. "200 OK"):
jbe@162 753 function request:send_status(status)
jbe@162 754 prepare()
jbe@187 755 local old_state = state; state = "faulty"
jbe@164 756 if old_state == "info_status_sent" then
jbe@162 757 send_flush("\r\n")
jbe@164 758 elseif old_state ~= "no_status_sent" then
jbe@183 759 state = old_state
jbe@162 760 error("HTTP status has already been sent")
jbe@162 761 end
jbe@162 762 local status1 = string.sub(status, 1, 1)
jbe@162 763 local status3 = string.sub(status, 1, 3)
jbe@162 764 send("HTTP/1.1 ", status, "\r\n", preamble)
jbe@162 765 local wrb = status_without_response_body[status3]
jbe@162 766 if wrb then
jbe@162 767 state = "bodyless_status_sent"
jbe@162 768 if wrb == "zero_content_length" then
jbe@162 769 request:send_header("Content-Length", 0)
jbe@162 770 end
jbe@162 771 elseif status1 == "1" then
jbe@162 772 state = "info_status_sent"
jbe@162 773 else
jbe@162 774 state = "status_sent"
jbe@162 775 end
jbe@162 776 end
jbe@162 777 -- method to send a HTTP response header:
jbe@162 778 -- (key and value must be provided as separate args)
jbe@162 779 function request:send_header(key, value)
jbe@164 780 assert_not_faulty()
jbe@171 781 if state == "init" or state == "no_status_sent" then
jbe@162 782 error("HTTP status has not been sent yet")
jbe@162 783 elseif
jbe@164 784 state == "headers_sent" or
jbe@164 785 state == "finished"
jbe@162 786 then
jbe@162 787 error("All HTTP headers have already been sent")
jbe@162 788 end
jbe@187 789 local old_state = state; state = "faulty"
jbe@162 790 local key_lower = string.lower(key)
jbe@162 791 if key_lower == "content-length" then
jbe@183 792 if old_state == "info_status_sent" then
jbe@183 793 state = old_state
jbe@162 794 error("Cannot set Content-Length for informational status response")
jbe@162 795 end
jbe@162 796 local cl = assert(tonumber(value), "Invalid content-length")
jbe@162 797 if content_length == nil then
jbe@162 798 content_length = cl
jbe@162 799 elseif content_length == cl then
jbe@162 800 return
jbe@162 801 else
jbe@162 802 error("Content-Length has been set multiple times with different values")
jbe@162 803 end
jbe@162 804 elseif key_lower == "connection" then
jbe@162 805 for entry in string.gmatch(string.lower(value), "[^,]+") do
jbe@162 806 if string.match(entry, "^[ \t]*close[ \t]*$") then
jbe@183 807 if old_state == "info_status_sent" then
jbe@183 808 state = old_state
jbe@162 809 error("Cannot set \"Connection: close\" for informational status response")
jbe@162 810 end
jbe@162 811 close_responded = true
jbe@162 812 break
jbe@162 813 end
jbe@162 814 end
jbe@162 815 end
jbe@188 816 send(key, ": ", value, "\r\n")
jbe@183 817 state = old_state
jbe@162 818 end
jbe@184 819 -- method to announce (and enforce) connection close after sending the
jbe@184 820 -- response:
jbe@184 821 function request:close_after_finish()
jbe@184 822 assert_not_faulty()
jbe@184 823 if state == "headers_sent" or state == "finished" then
jbe@184 824 error("All HTTP headers have already been sent")
jbe@184 825 end
jbe@184 826 close_requested = true
jbe@184 827 end
jbe@162 828 -- function to terminate header section in response, optionally flushing:
jbe@162 829 -- (may be called multiple times unless response is finished)
jbe@162 830 local function finish_headers(with_flush)
jbe@162 831 if state == "finished" then
jbe@162 832 error("Response has already been finished")
jbe@162 833 elseif state == "info_status_sent" then
jbe@183 834 state = "faulty"
jbe@162 835 send_flush("\r\n")
jbe@162 836 state = "no_status_sent"
jbe@162 837 elseif state == "bodyless_status_sent" then
jbe@162 838 if close_requested and not close_responded then
jbe@162 839 request:send_header("Connection", "close")
jbe@162 840 end
jbe@181 841 state = "faulty"
jbe@162 842 send("\r\n")
jbe@163 843 finish()
jbe@162 844 state = "finished"
jbe@162 845 elseif state == "status_sent" then
jbe@162 846 if not content_length then
jbe@162 847 request:send_header("Transfer-Encoding", "chunked")
jbe@162 848 end
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@162 854 if request.method == "HEAD" then
jbe@163 855 finish()
jbe@162 856 elseif with_flush then
jbe@162 857 send_flush()
jbe@162 858 end
jbe@162 859 state = "headers_sent"
jbe@162 860 elseif state ~= "headers_sent" then
jbe@162 861 error("HTTP status has not been sent yet")
jbe@162 862 end
jbe@162 863 end
jbe@162 864 -- method to finish and flush headers:
jbe@162 865 function request:finish_headers()
jbe@164 866 assert_not_faulty()
jbe@162 867 finish_headers(true)
jbe@162 868 end
jbe@164 869 -- method to send body data:
jbe@164 870 function request:send_data(...)
jbe@164 871 assert_not_faulty()
jbe@183 872 if state == "info_status_sent" then
jbe@164 873 error("No (non-informational) HTTP status has been sent yet")
jbe@183 874 elseif state == "bodyless_status_sent" then
jbe@164 875 error("Cannot send response data for body-less status message")
jbe@164 876 end
jbe@164 877 finish_headers(false)
jbe@183 878 if state ~= "headers_sent" then
jbe@164 879 error("Unexpected internal status in HTTP engine")
jbe@164 880 end
jbe@164 881 if request.method == "HEAD" then
jbe@164 882 return
jbe@164 883 end
jbe@183 884 state = "faulty"
jbe@164 885 for i = 1, select("#", ...) do
jbe@164 886 local str = tostring(select(i, ...))
jbe@164 887 if #str > 0 then
jbe@164 888 if content_length then
jbe@164 889 local bytes_to_send = #str
jbe@164 890 if bytes_sent + bytes_to_send > content_length then
jbe@164 891 error("Content length exceeded")
jbe@164 892 else
jbe@164 893 send(str)
jbe@164 894 bytes_sent = bytes_sent + bytes_to_send
jbe@164 895 end
jbe@164 896 else
jbe@164 897 chunk_bytes = chunk_bytes + #str
jbe@164 898 chunk_parts[#chunk_parts+1] = str
jbe@164 899 end
jbe@164 900 end
jbe@164 901 end
jbe@164 902 if chunk_bytes >= output_chunk_size then
jbe@164 903 send_chunk()
jbe@164 904 end
jbe@183 905 state = "headers_sent"
jbe@164 906 end
jbe@165 907 -- method to flush output buffer:
jbe@165 908 function request:flush()
jbe@165 909 assert_not_faulty()
jbe@165 910 send_chunk()
jbe@165 911 send_flush()
jbe@165 912 end
jbe@165 913 -- method to finish response:
jbe@165 914 function request:finish()
jbe@165 915 assert_not_faulty()
jbe@165 916 if state == "finished" then
jbe@165 917 return
jbe@165 918 elseif state == "info_status_sent" then
jbe@165 919 error("Informational HTTP response can be finished with :finish_headers() method")
jbe@165 920 end
jbe@165 921 finish_headers(false)
jbe@165 922 if state == "headers_sent" then
jbe@165 923 if request.method ~= "HEAD" then
jbe@165 924 state = "faulty"
jbe@165 925 if content_length then
jbe@165 926 if bytes_sent ~= content_length then
jbe@165 927 error("Content length not used")
jbe@165 928 end
jbe@165 929 else
jbe@165 930 send_chunk()
jbe@165 931 send("0\r\n\r\n")
jbe@165 932 end
jbe@165 933 finish()
jbe@165 934 end
jbe@165 935 state = "finished"
jbe@165 936 elseif state ~= "finished" then
jbe@165 937 error("Unexpected internal status in HTTP engine")
jbe@165 938 end
jbe@165 939 end
jbe@172 940 -- method to register POST param stream handler for a single field name:
jbe@172 941 function request:stream_post_param(field_name, callback)
jbe@172 942 if state ~= "init" then
jbe@183 943 error("Cannot setup request body streamer at this stage anymore")
jbe@172 944 end
jbe@172 945 streamed_post_params[field_name] = callback
jbe@172 946 end
jbe@172 947 -- method to register POST param stream handler for a field name pattern:
jbe@172 948 function request:stream_post_params(pattern, callback)
jbe@172 949 if state ~= "init" then
jbe@183 950 error("Cannot setup request body streamer at this stage anymore")
jbe@172 951 end
jbe@172 952 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
jbe@172 953 end
jbe@172 954 -- method to register request body stream handler
jbe@184 955 function request:stream_request_body(callback)
jbe@172 956 if state ~= "init" then
jbe@183 957 error("Cannot setup request body streamer at this stage anymore")
jbe@172 958 end
jbe@172 959 local inprogress = false
jbe@191 960 local eof = false
jbe@172 961 local buffer = {}
jbe@172 962 process_body_chunk = function(chunk)
jbe@172 963 if inprogress then
jbe@191 964 if chunk == nil then
jbe@191 965 eof = true
jbe@191 966 else
jbe@191 967 buffer[#buffer+1] = chunk
jbe@191 968 end
jbe@172 969 else
jbe@172 970 inprogress = true
jbe@172 971 callback(chunk)
jbe@172 972 while #buffer > 0 do
jbe@172 973 chunk = table.concat(buffer)
jbe@172 974 buffer = {}
jbe@172 975 callback(chunk)
jbe@172 976 end
jbe@191 977 if eof then
jbe@191 978 callback() -- signal EOF
jbe@191 979 end
jbe@172 980 inprogress = false
jbe@172 981 end
jbe@172 982 end
jbe@172 983 end
jbe@172 984 -- method to start reading request body
jbe@172 985 function request:consume_input()
jbe@172 986 prepare()
jbe@172 987 consume_all()
jbe@172 988 end
jbe@172 989 -- method to stream request body
jbe@184 990 function request:stream_request_body_now(callback)
jbe@184 991 request:stream_request_body(function(chunk)
jbe@172 992 if chunk ~= nil then
jbe@172 993 callback(chunk)
jbe@172 994 end
jbe@172 995 end)
jbe@172 996 request:consume_input()
jbe@172 997 end
jbe@172 998 -- metamethod to read special attibutes of request object:
jbe@172 999 function request_mt:__index(key, value)
jbe@184 1000 if key == "faulty" then
jbe@184 1001 return state == "faulty"
jbe@184 1002 elseif key == "fresh" then
jbe@184 1003 return state == "init" and process_body_chunk == nil
jbe@184 1004 elseif key == "body" then
jbe@172 1005 local chunks = {}
jbe@184 1006 request:stream_request_body_now(function(chunk)
jbe@172 1007 chunks[#chunks+1] = chunk
jbe@172 1008 end)
jbe@172 1009 self.body = table.concat(chunks)
jbe@172 1010 return self.body
jbe@172 1011 elseif
jbe@172 1012 key == "post_params_list" or key == "post_params" or
jbe@172 1013 key == "post_metadata_list" or key == "post_metadata"
jbe@172 1014 then
jbe@172 1015 prepare()
jbe@172 1016 consume_all()
jbe@190 1017 return rawget(self, key)
jbe@172 1018 end
jbe@172 1019 end
jbe@186 1020 -- variable to store request target
jbe@186 1021 local target
jbe@173 1022 -- coroutine for reading headers:
jbe@173 1023 local function read_headers()
jbe@176 1024 -- initialize limit:
jbe@176 1025 local limit = header_size_limit
jbe@173 1026 -- read and parse request line:
jbe@176 1027 local line = read_eof(limit, "\n")
jbe@173 1028 if not line then
jbe@173 1029 return false, survive
jbe@173 1030 end
jbe@176 1031 limit = limit - #line
jbe@176 1032 if limit == 0 then
jbe@173 1033 return false, request_error(false, "414 Request-URI Too Long")
jbe@173 1034 end
jbe@186 1035 local proto
jbe@173 1036 request.method, target, proto =
jbe@173 1037 line:match("^([^ \t\r]+)[ \t]+([^ \t\r]+)[ \t]*([^ \t\r]*)[ \t]*\r?\n$")
jbe@173 1038 if not request.method then
jbe@173 1039 return false, request_error(false, "400 Bad Request")
jbe@173 1040 elseif proto ~= "HTTP/1.1" then
jbe@173 1041 return false, request_error(false, "505 HTTP Version Not Supported")
jbe@173 1042 end
jbe@173 1043 -- read and parse headers:
jbe@173 1044 while true do
jbe@176 1045 local line = read(limit, "\n");
jbe@176 1046 limit = limit - #line
jbe@173 1047 if line == "\r\n" or line == "\n" then
jbe@173 1048 break
jbe@173 1049 end
jbe@176 1050 if limit == 0 then
jbe@173 1051 return false, request_error(false, "431 Request Header Fields Too Large")
jbe@173 1052 end
jbe@173 1053 local key, value = string.match(line, "^([^ \t\r]+):[ \t]*(.-)[ \t]*\r?\n$")
jbe@173 1054 if not key then
jbe@173 1055 return false, request_error(false, "400 Bad Request")
jbe@173 1056 end
jbe@173 1057 local values = request.headers[key]
jbe@173 1058 values[#values+1] = value
jbe@173 1059 end
jbe@173 1060 return true -- success
jbe@173 1061 end
jbe@160 1062 -- wait for input:
jbe@160 1063 if not poll(socket_set, nil, request_idle_timeout) then
jbe@163 1064 return request_error(false, "408 Request Timeout", "Idle connection timed out")
jbe@38 1065 end
jbe@173 1066 -- read headers (with timeout):
jbe@173 1067 do
jbe@173 1068 local coro = coroutine.wrap(read_headers)
jbe@173 1069 local starttime = request_header_timeout and moonbridge_io.timeref()
jbe@173 1070 while true do
jbe@173 1071 local status, retval = coro()
jbe@173 1072 if status == nil then
jbe@173 1073 local remaining
jbe@173 1074 if request_header_timeout then
jbe@173 1075 remaining = request_header_timeout - moonbridge_io.timeref(starttime)
jbe@173 1076 end
jbe@173 1077 if not poll(socket_set, nil, remaining) then
jbe@173 1078 return request_error(false, "408 Request Timeout", "Timeout while receiving headers")
jbe@173 1079 end
jbe@173 1080 elseif status == false then
jbe@173 1081 return retval
jbe@173 1082 elseif status == true then
jbe@173 1083 break
jbe@173 1084 else
jbe@173 1085 error("Unexpected yield value")
jbe@173 1086 end
jbe@173 1087 end
jbe@173 1088 end
jbe@173 1089 -- process "Connection: close" header if existent:
jbe@173 1090 connection_close_requested = request.headers_flags["Connection"]["close"]
jbe@173 1091 -- process "Content-Length" header if existent:
jbe@173 1092 do
jbe@173 1093 local values = request.headers_csv_table["Content-Length"]
jbe@173 1094 if #values > 0 then
jbe@173 1095 request_body_content_length = tonumber(values[1])
jbe@173 1096 local proper_value = tostring(request_body_content_length)
jbe@173 1097 for i, value in ipairs(values) do
jbe@173 1098 value = string.match(value, "^0*(.*)")
jbe@173 1099 if value ~= proper_value then
jbe@173 1100 return request_error(false, "400 Bad Request", "Content-Length header(s) invalid")
jbe@173 1101 end
jbe@173 1102 end
jbe@176 1103 if request_body_content_length > body_size_limit then
jbe@173 1104 return request_error(false, "413 Request Entity Too Large", "Announced request body size is too big")
jbe@173 1105 end
jbe@173 1106 end
jbe@173 1107 end
jbe@173 1108 -- process "Transfer-Encoding" header if existent:
jbe@173 1109 do
jbe@173 1110 local flag = request.headers_flags["Transfer-Encoding"]["chunked"]
jbe@173 1111 local list = request.headers_csv_table["Transfer-Encoding"]
jbe@173 1112 if (flag and #list ~= 1) or (not flag and #list ~= 0) then
jbe@173 1113 return request_error(false, "400 Bad Request", "Unexpected Transfer-Encoding")
jbe@173 1114 end
jbe@173 1115 end
jbe@173 1116 -- process "Expect" header if existent:
jbe@173 1117 for i, value in ipairs(request.headers_csv_table["Expect"]) do
jbe@173 1118 if string.lower(value) ~= "100-continue" then
jbe@173 1119 return request_error(false, "417 Expectation Failed", "Unexpected Expect header")
jbe@173 1120 end
jbe@173 1121 end
jbe@173 1122 -- get mandatory Host header according to RFC 7230:
jbe@173 1123 request.host = request.headers_value["Host"]
jbe@173 1124 if not request.host then
jbe@173 1125 return request_error(false, "400 Bad Request", "No valid host header")
jbe@173 1126 end
jbe@173 1127 -- parse request target:
jbe@173 1128 request.path, request.query = string.match(target, "^/([^?]*)(.*)$")
jbe@173 1129 if not request.path then
jbe@173 1130 local host2
jbe@173 1131 host2, request.path, request.query = string.match(target, "^[Hh][Tt][Tt][Pp]://([^/?]+)/?([^?]*)(.*)$")
jbe@173 1132 if host2 then
jbe@173 1133 if request.host ~= host2 then
jbe@173 1134 return request_error(false, "400 Bad Request", "No valid host header")
jbe@173 1135 end
jbe@173 1136 elseif not (target == "*" and request.method == "OPTIONS") then
jbe@173 1137 return request_error(false, "400 Bad Request", "Invalid request target")
jbe@173 1138 end
jbe@173 1139 end
jbe@173 1140 -- parse GET params:
jbe@199 1141 request.get_params_list, request.get_params = new_params_list()
jbe@173 1142 if request.query then
jbe@173 1143 read_urlencoded_form(request.get_params_list, request.query)
jbe@173 1144 end
jbe@173 1145 -- parse cookies:
jbe@173 1146 for i, line in ipairs(request.headers["Cookie"]) do
jbe@173 1147 for rawkey, rawvalue in
jbe@173 1148 string.gmatch(line, "([^=; ]*)=([^=; ]*)")
jbe@173 1149 do
jbe@173 1150 request.cookies[decode_uri(rawkey)] = decode_uri(rawvalue)
jbe@173 1151 end
jbe@173 1152 end
jbe@173 1153 -- (re)set timeout for handler:
jbe@173 1154 timeout(response_timeout or 0)
jbe@173 1155 -- call underlying handler and remember boolean result:
jbe@173 1156 if handler(request) ~= true then survive = false end
jbe@173 1157 -- finish request (unless already done by underlying handler):
jbe@173 1158 request:finish()
jbe@173 1159 -- stop timeout timer:
jbe@173 1160 timeout(0)
jbe@162 1161 until close_responded
jbe@0 1162 return survive
jbe@0 1163 end
jbe@0 1164 end
jbe@0 1165
jbe@0 1166 return _M
jbe@0 1167

Impressum / About Us