moonbridge

annotate moonbridge_http.lua @ 35:2d7e3028d993

Support iteration using pairs(...) on request.get_params, request.get_params_list, request.post_params, and request.post_params_list
author jbe
date Fri Feb 27 00:53:40 2015 +0100 (2015-02-27)
parents 59f485dc48ea
children b841dc424baf
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@0 10 __newindex = function(self, key, value) _M[key] = value end
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@0 86 -- handling of GET/POST param tables:
jbe@0 87 local new_params_list -- defined later
jbe@0 88 do
jbe@0 89 local params_list_mapping = setmetatable({}, {__mode="k"})
jbe@35 90 local function nextnonempty(tbl, key)
jbe@35 91 while true do
jbe@35 92 key = next(tbl, key)
jbe@35 93 if key == nil then
jbe@35 94 return nil
jbe@35 95 end
jbe@35 96 local value = tbl[key]
jbe@35 97 if #value > 0 then
jbe@35 98 return key, value
jbe@35 99 end
jbe@35 100 end
jbe@35 101 end
jbe@35 102 local function nextvalue(tbl, key)
jbe@35 103 key = next(tbl, key)
jbe@35 104 if key == nil then
jbe@35 105 return nil
jbe@35 106 end
jbe@35 107 return key, tbl[key][1]
jbe@35 108 end
jbe@0 109 local params_list_metatable = {
jbe@0 110 __index = function(self, key)
jbe@0 111 local tbl = {}
jbe@0 112 self[key] = tbl
jbe@0 113 return tbl
jbe@35 114 end,
jbe@35 115 __pairs = function(self)
jbe@35 116 return nextnonempty, self, nil
jbe@0 117 end
jbe@0 118 }
jbe@0 119 local params_metatable = {
jbe@0 120 __index = function(self, key)
jbe@0 121 local value = params_list_mapping[self][key][1]
jbe@0 122 self[key] = value
jbe@0 123 return value
jbe@35 124 end,
jbe@35 125 __pairs = function(self)
jbe@35 126 return nextvalue, params_list_mapping[self], nil
jbe@0 127 end
jbe@0 128 }
jbe@0 129 -- returns a table to store key value-list pairs (i.e. multiple values),
jbe@0 130 -- and a second table automatically mapping keys to the first value
jbe@0 131 -- using the key value-list pairs in the first table:
jbe@0 132 new_params_list = function()
jbe@0 133 local params_list = setmetatable({}, params_list_metatable)
jbe@0 134 local params = setmetatable({}, params_metatable)
jbe@0 135 params_list_mapping[params] = params_list
jbe@0 136 return params_list, params
jbe@0 137 end
jbe@0 138 end
jbe@0 139 -- parses URL encoded form data and stores it in
jbe@0 140 -- a key value-list pairs structure that has to be
jbe@0 141 -- previously obtained by calling by new_params_list():
jbe@0 142 local function read_urlencoded_form(tbl, data)
jbe@12 143 for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do
jbe@0 144 local subtbl = tbl[decode_uri(rawkey)]
jbe@0 145 subtbl[#subtbl+1] = decode_uri(rawvalue)
jbe@0 146 end
jbe@0 147 end
jbe@0 148
jbe@0 149 -- function creating a HTTP handler:
jbe@0 150 function generate_handler(handler, options)
jbe@0 151 -- swap arguments if necessary (for convenience):
jbe@0 152 if type(handler) ~= "function" and type(options) == "function" then
jbe@0 153 handler, options = options, handler
jbe@0 154 end
jbe@0 155 -- process options:
jbe@0 156 options = options or {}
jbe@0 157 local preamble = "" -- preamble sent with every(!) HTTP response
jbe@0 158 do
jbe@0 159 -- named arg "static_headers" is used to create the preamble:
jbe@0 160 local s = options.static_headers
jbe@0 161 local t = {}
jbe@0 162 if s then
jbe@0 163 if type(s) == "string" then
jbe@0 164 for line in string.gmatch(s, "[^\r\n]+") do
jbe@0 165 t[#t+1] = line
jbe@0 166 end
jbe@0 167 else
jbe@0 168 for i, kv in ipairs(options.static_headers) do
jbe@0 169 if type(kv) == "string" then
jbe@0 170 t[#t+1] = kv
jbe@0 171 else
jbe@0 172 t[#t+1] = kv[1] .. ": " .. kv[2]
jbe@0 173 end
jbe@0 174 end
jbe@0 175 end
jbe@0 176 end
jbe@0 177 t[#t+1] = ""
jbe@0 178 preamble = table.concat(t, "\r\n")
jbe@0 179 end
jbe@0 180 -- return connect handler:
jbe@0 181 return function(socket)
jbe@0 182 local survive = true -- set to false if process shall be terminated later
jbe@31 183 repeat
jbe@0 184 -- desired chunk sizes:
jbe@0 185 local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384
jbe@0 186 local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024
jbe@0 187 -- process named arguments "request_header_size_limit" and "request_body_size_limit":
jbe@0 188 local remaining_header_size_limit = options.request_header_size_limit or 1024*1024
jbe@0 189 local remaining_body_size_limit = options.request_body_size_limit or 64*1024*1024
jbe@0 190 -- state variables for request handling:
jbe@0 191 local output_state = "no_status_sent" -- one of:
jbe@0 192 -- "no_status_sent" (initial state)
jbe@0 193 -- "info_status_sent" (1xx status code has been sent)
jbe@0 194 -- "bodyless_status_sent" (204/304 status code has been sent)
jbe@0 195 -- "status_sent" (regular status code has been sent)
jbe@0 196 -- "headers_sent" (headers have been terminated)
jbe@0 197 -- "finished" (request has been answered completely)
jbe@0 198 local content_length -- value of Content-Length header sent
jbe@0 199 local bytes_sent = 0 -- number of bytes sent if Content-Length is set
jbe@0 200 local chunk_parts = {} -- list of chunks to send
jbe@0 201 local chunk_bytes = 0 -- sum of lengths of chunks to send
jbe@0 202 local connection_close_requested = false
jbe@0 203 local connection_close_responded = false
jbe@0 204 local headers_value_nil = {} -- header values that are nil
jbe@0 205 local request_body_content_length -- Content-Length of request body
jbe@0 206 local input_state = "pending" -- one of:
jbe@0 207 -- "pending" (request body has not been processed yet)
jbe@0 208 -- "deferred" (request body processing is deferred)
jbe@0 209 -- "reading" (request body is currently being read)
jbe@0 210 -- "finished" (request body has been read)
jbe@0 211 local streamed_post_params = {} -- mapping from POST field name to stream function
jbe@0 212 local streamed_post_param_patterns = {} -- list of POST field pattern and stream function pairs
jbe@0 213 -- object passed to handler (with methods, GET/POST params, etc.):
jbe@0 214 local request
jbe@0 215 -- reads a number of bytes from the socket,
jbe@0 216 -- optionally feeding these bytes chunk-wise
jbe@0 217 -- into a callback function:
jbe@0 218 local function read_body_bytes(remaining, callback)
jbe@0 219 while remaining > 0 do
jbe@0 220 local limit
jbe@0 221 if remaining > input_chunk_size then
jbe@0 222 limit = input_chunk_size
jbe@0 223 else
jbe@0 224 limit = remaining
jbe@0 225 end
jbe@0 226 local chunk = socket:read(limit)
jbe@0 227 if not chunk or #chunk ~= limit then
jbe@0 228 error("Unexpected EOF while reading chunk of request body")
jbe@0 229 end
jbe@0 230 remaining = remaining - limit
jbe@0 231 if callback then
jbe@0 232 callback(chunk)
jbe@0 233 end
jbe@0 234 end
jbe@0 235 end
jbe@0 236 -- flushes or closes the socket (depending on
jbe@0 237 -- whether "Connection: close" header was sent):
jbe@0 238 local function finish_response()
jbe@0 239 if connection_close_responded then
jbe@0 240 -- close output stream:
jbe@0 241 socket.output:close()
jbe@0 242 -- wait for EOF of peer to avoid immediate TCP RST condition:
jbe@0 243 timeout(2, function()
jbe@0 244 while socket.input:read(input_chunk_size) do end
jbe@0 245 end)
jbe@0 246 -- fully close socket:
jbe@0 247 socket:close()
jbe@0 248 else
jbe@0 249 socket:flush()
jbe@0 250 request:stream_request_body()
jbe@0 251 end
jbe@0 252 end
jbe@0 253 -- writes out buffered chunks (without flushing the socket):
jbe@0 254 local function send_chunk()
jbe@0 255 if chunk_bytes > 0 then
jbe@0 256 socket:write(string.format("%x\r\n", chunk_bytes))
jbe@0 257 for i = 1, #chunk_parts do
jbe@0 258 socket:write(chunk_parts[i])
jbe@0 259 end
jbe@0 260 chunk_parts = {}
jbe@0 261 chunk_bytes = 0
jbe@0 262 socket:write("\r\n")
jbe@0 263 end
jbe@0 264 end
jbe@0 265 -- terminate header section in response, optionally flushing:
jbe@0 266 -- (may be called multiple times unless response is finished)
jbe@0 267 local function finish_headers(flush)
jbe@0 268 if output_state == "no_status_sent" then
jbe@0 269 error("HTTP status has not been sent yet")
jbe@0 270 elseif output_state == "finished" then
jbe@0 271 error("Response has already been finished")
jbe@0 272 elseif output_state == "info_status_sent" then
jbe@0 273 socket:write("\r\n")
jbe@0 274 socket:flush()
jbe@0 275 output_state = "no_status_sent"
jbe@0 276 elseif output_state == "bodyless_status_sent" then
jbe@0 277 if connection_close_requested and not connection_close_responded then
jbe@0 278 request:send_header("Connection", "close")
jbe@0 279 end
jbe@0 280 socket:write("\r\n")
jbe@0 281 finish_response()
jbe@0 282 output_state = "finished"
jbe@0 283 elseif output_state == "status_sent" then
jbe@0 284 if not content_length then
jbe@0 285 socket:write("Transfer-Encoding: chunked\r\n")
jbe@0 286 end
jbe@0 287 if connection_close_requested and not connection_close_responded then
jbe@0 288 request:send_header("Connection", "close")
jbe@0 289 end
jbe@0 290 socket:write("\r\n")
jbe@0 291 if request.method == "HEAD" then
jbe@0 292 finish_response()
jbe@0 293 elseif flush then
jbe@0 294 socket:flush()
jbe@0 295 end
jbe@0 296 output_state = "headers_sent"
jbe@0 297 elseif output_state ~= "headers_sent" then
jbe@0 298 error("Unexpected internal status in HTTP engine")
jbe@0 299 end
jbe@0 300 end
jbe@0 301 -- create request object and set several functions and values:
jbe@0 302 request = {
jbe@0 303 -- allow raw socket access:
jbe@0 304 socket = socket,
jbe@0 305 -- parsed cookies:
jbe@0 306 cookies = {},
jbe@0 307 -- send a HTTP response status (e.g. "200 OK"):
jbe@0 308 send_status = function(self, value)
jbe@0 309 if input_state == "pending" then
jbe@0 310 request:process_request_body()
jbe@0 311 end
jbe@0 312 if output_state == "info_status_sent" then
jbe@0 313 socket:write("\r\n")
jbe@0 314 socket:flush()
jbe@0 315 elseif output_state ~= "no_status_sent" then
jbe@0 316 error("HTTP status has already been sent")
jbe@0 317 end
jbe@0 318 local status1 = string.sub(value, 1, 1)
jbe@0 319 local status3 = string.sub(value, 1, 3)
jbe@0 320 socket:write("HTTP/1.1 ", value, "\r\n", preamble)
jbe@0 321 local without_response_body = status_without_response_body[status3]
jbe@0 322 if without_response_body then
jbe@0 323 output_state = "bodyless_status_sent"
jbe@0 324 if without_response_body == "zero_content_length" then
jbe@0 325 request:send_header("Content-Length", 0)
jbe@0 326 end
jbe@0 327 elseif status1 == "1" then
jbe@0 328 output_state = "info_status_sent"
jbe@0 329 else
jbe@0 330 output_state = "status_sent"
jbe@0 331 end
jbe@0 332 end,
jbe@0 333 -- send a HTTP response header
jbe@0 334 -- (key and value as separate args):
jbe@0 335 send_header = function(self, key, value)
jbe@0 336 if output_state == "no_status_sent" then
jbe@0 337 error("HTTP status has not been sent yet")
jbe@0 338 elseif
jbe@0 339 output_state ~= "info_status_sent" and
jbe@0 340 output_state ~= "bodyless_status_sent" and
jbe@0 341 output_state ~= "status_sent"
jbe@0 342 then
jbe@0 343 error("All HTTP headers have already been sent")
jbe@0 344 end
jbe@0 345 local key_lower = string.lower(key)
jbe@0 346 if key_lower == "content-length" then
jbe@0 347 if output_state == "info_status_sent" then
jbe@0 348 error("Cannot set Content-Length for informational status response")
jbe@0 349 end
jbe@0 350 local new_content_length = assert(tonumber(value), "Invalid content-length")
jbe@0 351 if content_length == nil then
jbe@0 352 content_length = new_content_length
jbe@0 353 elseif content_length == new_content_length then
jbe@0 354 return
jbe@0 355 else
jbe@0 356 error("Content-Length has been set multiple times with different values")
jbe@0 357 end
jbe@0 358 elseif key_lower == "connection" then
jbe@0 359 for entry in string.gmatch(string.lower(value), "[^,]+") do
jbe@0 360 if string.match(entry, "^[ \t]*close[ \t]*$") then
jbe@0 361 if output_state == "info_status_sent" then
jbe@0 362 error("Cannot set \"Connection: close\" for informational status response")
jbe@0 363 end
jbe@0 364 if connection_close_responded then
jbe@0 365 return
jbe@0 366 else
jbe@0 367 connection_close_responded = true
jbe@0 368 break
jbe@0 369 end
jbe@0 370 end
jbe@0 371 end
jbe@0 372 end
jbe@0 373 socket:write(key, ": ", value, "\r\n")
jbe@0 374 end,
jbe@0 375 -- method to finish and flush headers:
jbe@0 376 finish_headers = function()
jbe@0 377 finish_headers(true)
jbe@0 378 end,
jbe@0 379 -- send data for response body:
jbe@0 380 send_data = function(self, ...)
jbe@0 381 if output_state == "info_status_sent" then
jbe@0 382 error("No (non-informational) HTTP status has been sent yet")
jbe@0 383 elseif output_state == "bodyless_status_sent" then
jbe@0 384 error("Cannot send response data for body-less status message")
jbe@0 385 end
jbe@0 386 finish_headers(false)
jbe@0 387 if output_state ~= "headers_sent" then
jbe@0 388 error("Unexpected internal status in HTTP engine")
jbe@0 389 end
jbe@0 390 if request.method == "HEAD" then
jbe@0 391 return
jbe@0 392 end
jbe@0 393 for i = 1, select("#", ...) do
jbe@0 394 local str = tostring(select(i, ...))
jbe@0 395 if #str > 0 then
jbe@0 396 if content_length then
jbe@0 397 local bytes_to_send = #str
jbe@0 398 if bytes_sent + bytes_to_send > content_length then
jbe@0 399 socket:write(string.sub(str, 1, content_length - bytes_sent))
jbe@0 400 bytes_sent = content_length
jbe@0 401 error("Content length exceeded")
jbe@0 402 else
jbe@0 403 socket:write(str)
jbe@0 404 bytes_sent = bytes_sent + bytes_to_send
jbe@0 405 end
jbe@0 406 else
jbe@0 407 chunk_bytes = chunk_bytes + #str
jbe@0 408 chunk_parts[#chunk_parts+1] = str
jbe@0 409 end
jbe@0 410 end
jbe@0 411 end
jbe@0 412 if chunk_bytes >= output_chunk_size then
jbe@0 413 send_chunk()
jbe@0 414 end
jbe@0 415 end,
jbe@0 416 -- flush output buffer:
jbe@0 417 flush = function(self)
jbe@0 418 send_chunk()
jbe@0 419 socket:flush()
jbe@0 420 end,
jbe@0 421 -- finish response:
jbe@0 422 finish = function(self)
jbe@0 423 if output_state == "finished" then
jbe@0 424 return
jbe@0 425 elseif output_state == "info_status_sent" then
jbe@0 426 error("Informational HTTP response can be finished with :finish_headers() method")
jbe@0 427 end
jbe@0 428 finish_headers(false)
jbe@0 429 if output_state == "headers_sent" then
jbe@0 430 if request.method ~= "HEAD" then
jbe@0 431 if content_length then
jbe@0 432 if bytes_sent ~= content_length then
jbe@0 433 error("Content length not used")
jbe@0 434 end
jbe@0 435 else
jbe@0 436 send_chunk()
jbe@0 437 socket:write("0\r\n\r\n")
jbe@0 438 end
jbe@0 439 finish_response()
jbe@0 440 end
jbe@0 441 output_state = "finished"
jbe@28 442 elseif output_state ~= "finished" then
jbe@0 443 error("Unexpected internal status in HTTP engine")
jbe@0 444 end
jbe@0 445 end,
jbe@0 446 -- table mapping header field names to value-lists
jbe@0 447 -- (raw access):
jbe@0 448 headers = setmetatable({}, {
jbe@0 449 __index = function(self, key)
jbe@0 450 local lowerkey = string.lower(key)
jbe@0 451 if lowerkey == key then
jbe@0 452 return
jbe@0 453 end
jbe@0 454 local result = rawget(self, lowerkey)
jbe@0 455 if result == nil then
jbe@0 456 result = {}
jbe@0 457 end
jbe@0 458 self[lowerkey] = result
jbe@0 459 self[key] = result
jbe@0 460 return result
jbe@0 461 end
jbe@0 462 }),
jbe@0 463 -- table mapping header field names to value-lists
jbe@0 464 -- (for headers with comma separated values):
jbe@0 465 headers_csv_table = setmetatable({}, {
jbe@0 466 __index = function(self, key)
jbe@0 467 local result = {}
jbe@0 468 for i, line in ipairs(request.headers[key]) do
jbe@0 469 for entry in string.gmatch(line, "[^,]+") do
jbe@0 470 local value = string.match(entry, "^[ \t]*(..-)[ \t]*$")
jbe@0 471 if value then
jbe@0 472 result[#result+1] = value
jbe@0 473 end
jbe@0 474 end
jbe@0 475 end
jbe@0 476 self[key] = result
jbe@0 477 return result
jbe@0 478 end
jbe@0 479 }),
jbe@0 480 -- table mapping header field names to a comma separated string
jbe@0 481 -- (for headers with comma separated values):
jbe@0 482 headers_csv_string = setmetatable({}, {
jbe@0 483 __index = function(self, key)
jbe@0 484 local result = {}
jbe@0 485 for i, line in ipairs(request.headers[key]) do
jbe@0 486 result[#result+1] = line
jbe@0 487 end
jbe@0 488 result = string.concat(result, ", ")
jbe@0 489 self[key] = result
jbe@0 490 return result
jbe@0 491 end
jbe@0 492 }),
jbe@0 493 -- table mapping header field names to a single string value
jbe@0 494 -- (or false if header has been sent multiple times):
jbe@0 495 headers_value = setmetatable({}, {
jbe@0 496 __index = function(self, key)
jbe@0 497 if headers_value_nil[key] then
jbe@0 498 return nil
jbe@0 499 end
jbe@0 500 local result = nil
jbe@0 501 local values = request.headers_csv_table[key]
jbe@0 502 if #values == 0 then
jbe@0 503 headers_value_nil[key] = true
jbe@0 504 elseif #values == 1 then
jbe@0 505 result = values[1]
jbe@0 506 else
jbe@0 507 result = false
jbe@0 508 end
jbe@0 509 self[key] = result
jbe@0 510 return result
jbe@0 511 end
jbe@0 512 }),
jbe@0 513 -- table mapping header field names to a flag table,
jbe@0 514 -- indicating if the comma separated value contains certain entries:
jbe@0 515 headers_flags = setmetatable({}, {
jbe@0 516 __index = function(self, key)
jbe@0 517 local result = setmetatable({}, {
jbe@0 518 __index = function(self, key)
jbe@0 519 local lowerkey = string.lower(key)
jbe@0 520 local result = rawget(self, lowerkey) or false
jbe@0 521 self[lowerkey] = result
jbe@0 522 self[key] = result
jbe@0 523 return result
jbe@0 524 end
jbe@0 525 })
jbe@0 526 for i, value in ipairs(request.headers_csv_table[key]) do
jbe@0 527 result[string.lower(value)] = true
jbe@0 528 end
jbe@0 529 self[key] = result
jbe@0 530 return result
jbe@0 531 end
jbe@0 532 }),
jbe@0 533 -- register POST param stream handler for a single field name:
jbe@0 534 stream_post_param = function(self, field_name, callback)
jbe@0 535 if input_state == "inprogress" or input_state == "finished" then
jbe@0 536 error("Cannot register POST param streaming function if request body is already processed")
jbe@0 537 end
jbe@0 538 streamed_post_params[field_name] = callback
jbe@0 539 end,
jbe@0 540 -- register POST param stream handler for a field name pattern:
jbe@0 541 stream_post_params = function(self, pattern, callback)
jbe@0 542 if input_state == "inprogress" or input_state == "finished" then
jbe@0 543 error("Cannot register POST param streaming function if request body is already processed")
jbe@0 544 end
jbe@0 545 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
jbe@0 546 end,
jbe@0 547 -- disables automatic request body processing on write
jbe@0 548 -- (use with caution):
jbe@0 549 defer_reading = function(self)
jbe@0 550 if input_state == "pending" then
jbe@0 551 input_state = "deferred"
jbe@0 552 end
jbe@0 553 end,
jbe@0 554 -- processes the request body and sets the request.post_params,
jbe@0 555 -- request.post_params_list, request.meta_post_params, and
jbe@0 556 -- request.meta_post_params_list values (can be called manually or
jbe@0 557 -- automatically if post_params are accessed or data is written out)
jbe@0 558 process_request_body = function(self)
jbe@0 559 if input_state == "finished" then
jbe@0 560 return
jbe@0 561 end
jbe@0 562 local post_params_list, post_params = new_params_list()
jbe@0 563 local content_type = request.headers_value["Content-Type"]
jbe@0 564 if content_type then
jbe@0 565 if
jbe@0 566 content_type == "application/x-www-form-urlencoded" or
jbe@0 567 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
jbe@0 568 then
jbe@0 569 read_urlencoded_form(post_params_list, request.body)
jbe@0 570 else
jbe@0 571 local boundary = string.match(
jbe@0 572 content_type,
jbe@0 573 '^multipart/form%-data[ \t]*[;,][ \t]*boundary="([^"]+)"$'
jbe@0 574 ) or string.match(
jbe@0 575 content_type,
jbe@0 576 '^multipart/form%-data[ \t]*[;,][ \t]*boundary=([^"; \t]+)$'
jbe@0 577 )
jbe@0 578 if boundary then
jbe@0 579 local post_metadata_list, post_metadata = new_params_list()
jbe@0 580 boundary = "--" .. boundary
jbe@0 581 local headerdata = ""
jbe@0 582 local streamer
jbe@0 583 local field_name
jbe@0 584 local metadata = {}
jbe@0 585 local value_parts
jbe@0 586 local function default_streamer(chunk)
jbe@0 587 value_parts[#value_parts+1] = chunk
jbe@0 588 end
jbe@0 589 local function stream_part_finish()
jbe@0 590 if streamer == default_streamer then
jbe@0 591 local value = table.concat(value_parts)
jbe@0 592 value_parts = nil
jbe@0 593 if field_name then
jbe@0 594 local values = post_params_list[field_name]
jbe@0 595 values[#values+1] = value
jbe@0 596 local metadata_entries = post_metadata_list[field_name]
jbe@0 597 metadata_entries[#metadata_entries+1] = metadata
jbe@0 598 end
jbe@0 599 else
jbe@0 600 streamer()
jbe@0 601 end
jbe@0 602 headerdata = ""
jbe@0 603 streamer = nil
jbe@0 604 field_name = nil
jbe@0 605 metadata = {}
jbe@0 606 end
jbe@0 607 local function stream_part_chunk(chunk)
jbe@0 608 if streamer then
jbe@0 609 streamer(chunk)
jbe@0 610 else
jbe@0 611 headerdata = headerdata .. chunk
jbe@0 612 while true do
jbe@0 613 local line, remaining = string.match(headerdata, "^(.-)\r?\n(.*)$")
jbe@0 614 if not line then
jbe@0 615 break
jbe@0 616 end
jbe@0 617 if line == "" then
jbe@0 618 streamer = streamed_post_params[field_name]
jbe@0 619 if not streamer then
jbe@0 620 for i, rule in ipairs(streamed_post_param_patterns) do
jbe@0 621 if string.match(field_name, rule[1]) then
jbe@0 622 streamer = rule[2]
jbe@0 623 break
jbe@0 624 end
jbe@0 625 end
jbe@0 626 end
jbe@0 627 if not streamer then
jbe@0 628 value_parts = {}
jbe@0 629 streamer = default_streamer
jbe@0 630 end
jbe@0 631 streamer(remaining, field_name, metadata)
jbe@0 632 return
jbe@0 633 end
jbe@0 634 headerdata = remaining
jbe@0 635 local header_key, header_value = string.match(line, "^([^:]*):[ \t]*(.-)[ \t]*$")
jbe@0 636 if not header_key then
jbe@0 637 error("Invalid header in multipart/form-data part")
jbe@0 638 end
jbe@0 639 header_key = string.lower(header_key)
jbe@0 640 if header_key == "content-disposition" then
jbe@0 641 local escaped_header_value = string.gsub(header_value, '"[^"]*"', function(str)
jbe@0 642 return string.gsub(str, "=", "==")
jbe@0 643 end)
jbe@0 644 field_name = string.match(escaped_header_value, ';[ \t]*name="([^"]*)"')
jbe@0 645 if field_name then
jbe@0 646 field_name = string.gsub(field_name, "==", "=")
jbe@0 647 else
jbe@0 648 field_name = string.match(header_value, ';[ \t]*name=([^"; \t]+)')
jbe@0 649 end
jbe@0 650 metadata.file_name = string.match(escaped_header_value, ';[ \t]*filename="([^"]*)"')
jbe@0 651 if metadata.file_name then
jbe@0 652 metadata.file_name = string.gsub(metadata.file_name, "==", "=")
jbe@0 653 else
jbe@0 654 string.match(header_value, ';[ \t]*filename=([^"; \t]+)')
jbe@0 655 end
jbe@0 656 elseif header_key == "content-type" then
jbe@0 657 metadata.content_type = header_value
jbe@0 658 elseif header_key == "content-transfer-encoding" then
jbe@0 659 error("Content-transfer-encoding not supported by multipart/form-data parser")
jbe@0 660 end
jbe@0 661 end
jbe@0 662 end
jbe@0 663 end
jbe@0 664 local skippart = true -- ignore data until first boundary
jbe@0 665 local afterbound = false -- interpret 2 bytes after boundary ("\r\n" or "--")
jbe@0 666 local terminated = false -- final boundary read
jbe@0 667 local bigchunk = ""
jbe@0 668 request:stream_request_body(function(chunk)
jbe@0 669 if terminated then
jbe@0 670 return
jbe@0 671 end
jbe@0 672 bigchunk = bigchunk .. chunk
jbe@0 673 while true do
jbe@0 674 if afterbound then
jbe@0 675 if #bigchunk <= 2 then
jbe@0 676 return
jbe@0 677 end
jbe@0 678 local terminator = string.sub(bigchunk, 1, 2)
jbe@0 679 if terminator == "\r\n" then
jbe@0 680 afterbound = false
jbe@0 681 bigchunk = string.sub(bigchunk, 3)
jbe@0 682 elseif terminator == "--" then
jbe@0 683 terminated = true
jbe@0 684 bigchunk = nil
jbe@0 685 return
jbe@0 686 else
jbe@0 687 error("Error while parsing multipart body (expected CRLF or double minus)")
jbe@0 688 end
jbe@0 689 end
jbe@0 690 local pos1, pos2 = string.find(bigchunk, boundary, 1, true)
jbe@0 691 if not pos1 then
jbe@0 692 if not skippart then
jbe@0 693 local safe = #bigchunk-#boundary
jbe@0 694 if safe > 0 then
jbe@0 695 stream_part_chunk(string.sub(bigchunk, 1, safe))
jbe@0 696 bigchunk = string.sub(bigchunk, safe+1)
jbe@0 697 end
jbe@0 698 end
jbe@0 699 return
jbe@0 700 end
jbe@0 701 if not skippart then
jbe@0 702 stream_part_chunk(string.sub(bigchunk, 1, pos1 - 1))
jbe@0 703 stream_part_finish()
jbe@0 704 else
jbe@0 705 boundary = "\r\n" .. boundary
jbe@0 706 skippart = false
jbe@0 707 end
jbe@0 708 bigchunk = string.sub(bigchunk, pos2 + 1)
jbe@0 709 afterbound = true
jbe@0 710 end
jbe@0 711 end)
jbe@0 712 if not terminated then
jbe@0 713 error("Premature end of multipart/form-data request body")
jbe@0 714 end
jbe@0 715 request.post_metadata_list, request.post_metadata = post_metadata_list, post_metadata
jbe@0 716 else
jbe@0 717 error("Unknown Content-Type of request body")
jbe@0 718 end
jbe@0 719 end
jbe@0 720 end
jbe@0 721 request.post_params_list, request.post_params = post_params_list, post_params
jbe@0 722 end,
jbe@0 723 -- stream request body to an (optional) callback function
jbe@0 724 -- without processing it otherwise:
jbe@0 725 stream_request_body = function(self, callback)
jbe@0 726 if input_state ~= "pending" and input_state ~= "deferred" then
jbe@0 727 if callback then
jbe@0 728 if input_state == "inprogress" then
jbe@0 729 error("Request body is already being processed")
jbe@0 730 else
jbe@0 731 error("Request body has already been processed")
jbe@0 732 end
jbe@0 733 end
jbe@0 734 return
jbe@0 735 end
jbe@0 736 input_state = "inprogress"
jbe@0 737 if request.headers_flags["Expect"]["100-continue"] then
jbe@0 738 request:send_status("100 Continue")
jbe@0 739 request:finish_headers()
jbe@0 740 end
jbe@0 741 if request.headers_flags["Transfer-Encoding"]["chunked"] then
jbe@0 742 while true do
jbe@0 743 local line = socket:readuntil("\n", 32 + remaining_body_size_limit)
jbe@0 744 if not line then
jbe@0 745 error("Unexpected EOF while reading next chunk of request body")
jbe@0 746 end
jbe@0 747 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
jbe@0 748 local chunkext
jbe@0 749 if lenstr then
jbe@0 750 chunkext = ""
jbe@0 751 else
jbe@0 752 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
jbe@0 753 end
jbe@0 754 if not lenstr or #lenstr > 13 then
jbe@0 755 error("Encoding error or unexpected EOF while reading chunk of request body")
jbe@0 756 end
jbe@0 757 local len = tonumber("0x" .. lenstr)
jbe@0 758 remaining_body_size_limit = remaining_body_size_limit - (#zeros + #chunkext + len)
jbe@0 759 if remaining_body_size_limit < 0 then
jbe@0 760 error("Request body size limit exceeded")
jbe@0 761 end
jbe@0 762 if len == 0 then break end
jbe@0 763 read_body_bytes(len, callback)
jbe@0 764 local term = socket:readuntil("\n", 2)
jbe@0 765 if term ~= "\r\n" and term ~= "\n" then
jbe@0 766 error("Encoding error while reading chunk of request body")
jbe@0 767 end
jbe@0 768 end
jbe@0 769 while true do
jbe@0 770 local line = socket:readuntil("\n", 2 + remaining_body_size_limit)
jbe@0 771 if line == "\r\n" or line == "\n" then break end
jbe@0 772 remaining_body_size_limit = remaining_body_size_limit - #line
jbe@0 773 if remaining_body_size_limit < 0 then
jbe@0 774 error("Request body size limit exceeded while reading trailer section of chunked request body")
jbe@0 775 end
jbe@0 776 end
jbe@0 777 elseif request_body_content_length then
jbe@0 778 read_body_bytes(request_body_content_length, callback)
jbe@0 779 end
jbe@0 780 input_state = "finished"
jbe@0 781 end
jbe@0 782 }
jbe@0 783 -- initialize tables for GET params in request object:
jbe@0 784 request.get_params_list, request.get_params = new_params_list()
jbe@0 785 -- add meta table to request object to allow access to "body" and POST params:
jbe@0 786 setmetatable(request, {
jbe@0 787 __index = function(self, key)
jbe@0 788 if key == "body" then
jbe@0 789 local chunks = {}
jbe@0 790 request:stream_request_body(function(chunk)
jbe@0 791 chunks[#chunks+1] = chunk
jbe@0 792 end)
jbe@0 793 self.body = table.concat(chunks)
jbe@0 794 return self.body
jbe@0 795 elseif
jbe@0 796 key == "post_params_list" or key == "post_params" or
jbe@0 797 key == "post_metadata_list" or key == "post_metadata"
jbe@0 798 then
jbe@0 799 request:process_request_body()
jbe@0 800 return request[key]
jbe@0 801 end
jbe@0 802 end
jbe@0 803 })
jbe@33 804 -- sends a minimalistic error response and enforces closing of the
jbe@33 805 -- connection and returns the boolean value "survive"
jbe@7 806 local function error_response(...)
jbe@32 807 request:send_status(status)
jbe@32 808 request:send_header("Content-Type", "text/plain")
jbe@32 809 request:send_header("Connection", "close")
jbe@32 810 request:send_data(status, "\n")
jbe@32 811 if text then
jbe@32 812 request:send_data("\n", text, "\n")
jbe@32 813 end
jbe@32 814 request:finish()
jbe@0 815 return survive
jbe@0 816 end
jbe@0 817 -- read and parse request line:
jbe@0 818 local line = socket:readuntil("\n", remaining_header_size_limit)
jbe@0 819 if not line then return survive end
jbe@0 820 remaining_header_size_limit = remaining_header_size_limit - #line
jbe@0 821 if remaining_header_size_limit == 0 then
jbe@0 822 return error_response("413 Request Entity Too Large", "Request line too long")
jbe@0 823 end
jbe@10 824 local target, proto
jbe@10 825 request.method, target, proto =
jbe@0 826 line:match("^([^ \t\r]+)[ \t]+([^ \t\r]+)[ \t]*([^ \t\r]*)[ \t]*\r?\n$")
jbe@0 827 if not request.method then
jbe@0 828 return error_response("400 Bad Request")
jbe@0 829 elseif proto ~= "HTTP/1.1" then
jbe@0 830 return error_response("505 HTTP Version Not Supported")
jbe@0 831 else
jbe@0 832 -- read and parse headers:
jbe@0 833 while true do
jbe@0 834 local line = socket:readuntil("\n", remaining_header_size_limit);
jbe@0 835 remaining_header_size_limit = remaining_header_size_limit - #line
jbe@0 836 if not line then
jbe@0 837 return error_response("400 Bad Request")
jbe@0 838 end
jbe@0 839 if line == "\r\n" or line == "\n" then
jbe@0 840 break
jbe@0 841 end
jbe@0 842 if remaining_header_size_limit == 0 then
jbe@0 843 return error_response("413 Request Entity Too Large", "Headers too long")
jbe@0 844 end
jbe@0 845 local key, value = string.match(line, "^([^ \t\r]+):[ \t]*(.-)[ \t]*\r?\n$")
jbe@0 846 if not key then
jbe@0 847 return error_response("400 Bad Request")
jbe@0 848 end
jbe@0 849 local values = request.headers[key]
jbe@0 850 values[#values+1] = value
jbe@0 851 end
jbe@0 852 -- process "Connection: close" header if existent:
jbe@0 853 connection_close_requested = request.headers_flags["Connection"]["close"]
jbe@0 854 -- process "Content-Length" header if existent:
jbe@0 855 do
jbe@0 856 local values = request.headers_csv_table["Content-Length"]
jbe@0 857 if #values > 0 then
jbe@0 858 request_body_content_length = tonumber(values[1])
jbe@0 859 local proper_value = tostring(request_body_content_length)
jbe@0 860 for i, value in ipairs(values) do
jbe@0 861 value = string.match(value, "^0*(.*)")
jbe@0 862 if value ~= proper_value then
jbe@0 863 return error_response("400 Bad Request", "Content-Length header(s) invalid")
jbe@0 864 end
jbe@0 865 end
jbe@0 866 if request_body_content_length > remaining_body_size_limit then
jbe@0 867 return error_response("413 Request Entity Too Large", "Request body too big")
jbe@0 868 end
jbe@0 869 end
jbe@0 870 end
jbe@0 871 -- process "Transfer-Encoding" header if existent:
jbe@0 872 do
jbe@0 873 local flag = request.headers_flags["Transfer-Encoding"]["chunked"]
jbe@0 874 local list = request.headers_csv_table["Transfer-Encoding"]
jbe@0 875 if (flag and #list ~= 1) or (not flag and #list ~= 0) then
jbe@0 876 return error_response("400 Bad Request", "Unexpected Transfer-Encoding")
jbe@0 877 end
jbe@0 878 end
jbe@0 879 -- process "Expect" header if existent:
jbe@0 880 for i, value in ipairs(request.headers_csv_table["Expect"]) do
jbe@0 881 if string.lower(value) ~= "100-continue" then
jbe@0 882 return error_response("417 Expectation Failed", "Unexpected Expect header")
jbe@0 883 end
jbe@0 884 end
jbe@10 885 -- get mandatory Host header according to RFC 7230:
jbe@10 886 request.host = request.headers_value["Host"]
jbe@10 887 if not request.host then
jbe@10 888 return error_response("400 Bad Request", "No valid host header")
jbe@10 889 end
jbe@5 890 -- parse request target:
jbe@12 891 request.path, request.query = string.match(target, "^/([^?]*)(.*)$")
jbe@10 892 if not request.path then
jbe@10 893 local host2
jbe@12 894 host2, request.path, request.query = string.match(target, "^[Hh][Tt][Tt][Pp]://([^/?]+)/?([^?]*)(.*)$")
jbe@10 895 if host2 then
jbe@10 896 if request.host ~= host2 then
jbe@5 897 return error_response("400 Bad Request", "No valid host header")
jbe@5 898 end
jbe@10 899 elseif not (target == "*" and request.method == "OPTIONS") then
jbe@10 900 return error_response("400 Bad Request", "Invalid request target")
jbe@5 901 end
jbe@5 902 end
jbe@0 903 -- parse GET params:
jbe@5 904 if request.query then
jbe@5 905 read_urlencoded_form(request.get_params_list, request.query)
jbe@5 906 end
jbe@0 907 -- parse cookies:
jbe@0 908 for i, line in ipairs(request.headers["Cookie"]) do
jbe@0 909 for rawkey, rawvalue in
jbe@0 910 string.gmatch(line, "([^=; ]*)=([^=; ]*)")
jbe@0 911 do
jbe@0 912 request.cookies[decode_uri(rawkey)] = decode_uri(rawvalue)
jbe@0 913 end
jbe@0 914 end
jbe@0 915 -- call underlying handler and remember boolean result:
jbe@0 916 if handler(request) ~= true then survive = false end
jbe@0 917 -- finish request (unless already done by underlying handler):
jbe@0 918 request:finish()
jbe@0 919 end
jbe@31 920 until connection_close_responded
jbe@0 921 return survive
jbe@0 922 end
jbe@0 923 end
jbe@0 924
jbe@0 925 return _M
jbe@0 926

Impressum / About Us