moonbridge

annotate moonbridge_http.lua @ 326:4379766473ec

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

Impressum / About Us