moonbridge

annotate moonbridge_http.lua @ 171:32d7423a6753

Removed "prepare" state and added 100-Continue header in local prepare() function in HTTP module
author jbe
date Tue Jun 16 02:49:34 2015 +0200 (2015-06-16)
parents 4d5cf5cacc68
children fb54c76e1484
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@167 103 key = next(tbl, key)
jbe@167 104 if key == nil then
jbe@167 105 return nil
jbe@167 106 end
jbe@167 107 return key, tbl[key][1]
jbe@167 108 end
jbe@167 109 local params_list_metatable = {
jbe@167 110 __index = function(self, key)
jbe@167 111 local tbl = {}
jbe@167 112 self[key] = tbl
jbe@167 113 return tbl
jbe@167 114 end,
jbe@167 115 __pairs = function(self)
jbe@167 116 return nextnonempty, self, nil
jbe@167 117 end
jbe@167 118 }
jbe@167 119 local params_metatable = {
jbe@167 120 __index = function(self, key)
jbe@167 121 return params_list_mapping[self][key][1]
jbe@167 122 end,
jbe@167 123 __newindex = function(self, key, value)
jbe@167 124 params_list_mapping[self][key] = {value}
jbe@167 125 end,
jbe@167 126 __pairs = function(self)
jbe@167 127 return nextvalue, params_list_mapping[self], nil
jbe@167 128 end
jbe@167 129 }
jbe@167 130 -- returns a table to store key value-list pairs (i.e. multiple values),
jbe@167 131 -- and a second table automatically mapping keys to the first value
jbe@167 132 -- using the key value-list pairs in the first table:
jbe@167 133 new_params_list = function()
jbe@167 134 local params_list = setmetatable({}, params_list_metatable)
jbe@167 135 local params = setmetatable({}, params_metatable)
jbe@167 136 params_list_mapping[params] = params_list
jbe@167 137 return params_list, params
jbe@167 138 end
jbe@167 139 end
jbe@167 140
jbe@167 141 -- parses URL encoded form data and stores it in
jbe@167 142 -- a key value-list pairs structure that has to be
jbe@167 143 -- previously obtained by calling by new_params_list():
jbe@167 144 local function read_urlencoded_form(tbl, data)
jbe@167 145 for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do
jbe@167 146 local subtbl = tbl[decode_uri(rawkey)]
jbe@167 147 subtbl[#subtbl+1] = decode_uri(rawvalue)
jbe@167 148 end
jbe@0 149 end
jbe@0 150
jbe@154 151 -- extracts first value from each subtable:
jbe@154 152 local function get_first_values(tbl)
jbe@154 153 local newtbl = {}
jbe@154 154 for key, subtbl in pairs(tbl) do
jbe@154 155 newtbl[key] = subtbl[1]
jbe@0 156 end
jbe@154 157 return newtbl
jbe@154 158 end
jbe@154 159
jbe@0 160 function generate_handler(handler, options)
jbe@0 161 -- swap arguments if necessary (for convenience):
jbe@0 162 if type(handler) ~= "function" and type(options) == "function" then
jbe@0 163 handler, options = options, handler
jbe@0 164 end
jbe@160 165 -- helper function to process options:
jbe@160 166 local function default(name, default_value)
jbe@160 167 local value = options[name]
jbe@160 168 if value == nil then
jbe@160 169 return default_value
jbe@160 170 else
jbe@160 171 return value or nil
jbe@159 172 end
jbe@160 173 end
jbe@0 174 -- process options:
jbe@0 175 options = options or {}
jbe@0 176 local preamble = "" -- preamble sent with every(!) HTTP response
jbe@0 177 do
jbe@0 178 -- named arg "static_headers" is used to create the preamble:
jbe@0 179 local s = options.static_headers
jbe@0 180 local t = {}
jbe@0 181 if s then
jbe@0 182 if type(s) == "string" then
jbe@0 183 for line in string.gmatch(s, "[^\r\n]+") do
jbe@0 184 t[#t+1] = line
jbe@0 185 end
jbe@0 186 else
jbe@0 187 for i, kv in ipairs(options.static_headers) do
jbe@0 188 if type(kv) == "string" then
jbe@0 189 t[#t+1] = kv
jbe@0 190 else
jbe@0 191 t[#t+1] = kv[1] .. ": " .. kv[2]
jbe@0 192 end
jbe@0 193 end
jbe@0 194 end
jbe@0 195 end
jbe@0 196 t[#t+1] = ""
jbe@0 197 preamble = table.concat(t, "\r\n")
jbe@0 198 end
jbe@160 199 local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384
jbe@44 200 local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024
jbe@160 201 local header_size_limit = options.header_size_limit or 1024*1024
jbe@160 202 local body_size_limit = options.body_size_limit or 64*1024*1024
jbe@160 203 local request_idle_timeout = default("request_idle_timeout", 330)
jbe@160 204 local request_header_timeout = default("request_header_timeout", 30)
jbe@160 205 local request_body_timeout = default("request_body_timeout", 60)
jbe@160 206 local request_response_timeout = default("request_response_timeout", 1800)
jbe@160 207 local poll = options.poll_function or moonbridge_io.poll
jbe@160 208 -- return socket handler:
jbe@0 209 return function(socket)
jbe@160 210 local socket_set = {[socket] = true} -- used for poll function
jbe@0 211 local survive = true -- set to false if process shall be terminated later
jbe@160 212 local consume -- function that reads some input if possible
jbe@160 213 -- function that drains some input if possible:
jbe@160 214 local function drain()
jbe@163 215 local bytes, status = socket:drain_nb(input_chunk_size)
jbe@163 216 if not bytes or status == "eof" then
jbe@160 217 consume = nil
jbe@50 218 end
jbe@159 219 end
jbe@163 220 -- function trying to unblock socket by reading:
jbe@160 221 local function unblock()
jbe@160 222 if consume then
jbe@160 223 poll(socket_set, socket_set)
jbe@160 224 consume()
jbe@160 225 else
jbe@160 226 poll(nil, socket_set)
jbe@0 227 end
jbe@154 228 end
jbe@163 229 -- function that enforces consumption of all input:
jbe@162 230 local function consume_all()
jbe@162 231 while consume do
jbe@163 232 poll(socket_set, nil)
jbe@162 233 consume()
jbe@162 234 end
jbe@162 235 end
jbe@163 236 -- handle requests in a loop:
jbe@160 237 repeat
jbe@168 238 -- copy limits:
jbe@168 239 local remaining_header_size_limit = header_size_limit
jbe@168 240 local remaining_body_size_limit = body_size_limit
jbe@166 241 -- table for caching nil values:
jbe@166 242 local headers_value_nil = {}
jbe@162 243 -- create a new request object:
jbe@166 244 local request -- allow references to local variable
jbe@166 245 request = {
jbe@165 246 -- allow access to underlying socket:
jbe@0 247 socket = socket,
jbe@165 248 -- cookies are simply stored in a table:
jbe@165 249 cookies = {},
jbe@165 250 -- table mapping header field names to value-lists
jbe@165 251 -- (raw access, but case-insensitive):
jbe@165 252 headers = setmetatable({}, {
jbe@165 253 __index = function(self, key)
jbe@165 254 local lowerkey = string.lower(key)
jbe@165 255 if lowerkey == key then
jbe@165 256 return
jbe@165 257 end
jbe@165 258 local result = rawget(self, lowerkey)
jbe@165 259 if result == nil then
jbe@165 260 result = {}
jbe@165 261 end
jbe@165 262 self[lowerkey] = result
jbe@165 263 self[key] = result
jbe@165 264 return result
jbe@165 265 end
jbe@165 266 }),
jbe@165 267 -- table mapping header field names to value-lists
jbe@165 268 -- (for headers with comma separated values):
jbe@165 269 headers_csv_table = setmetatable({}, {
jbe@165 270 __index = function(self, key)
jbe@165 271 local result = {}
jbe@165 272 for i, line in ipairs(request.headers[key]) do
jbe@165 273 for entry in string.gmatch(line, "[^,]+") do
jbe@165 274 local value = string.match(entry, "^[ \t]*(..-)[ \t]*$")
jbe@165 275 if value then
jbe@165 276 result[#result+1] = value
jbe@165 277 end
jbe@165 278 end
jbe@165 279 end
jbe@165 280 self[key] = result
jbe@165 281 return result
jbe@165 282 end
jbe@165 283 }),
jbe@165 284 -- table mapping header field names to a comma separated string
jbe@165 285 -- (for headers with comma separated values):
jbe@165 286 headers_csv_string = setmetatable({}, {
jbe@165 287 __index = function(self, key)
jbe@165 288 local result = {}
jbe@165 289 for i, line in ipairs(request.headers[key]) do
jbe@165 290 result[#result+1] = line
jbe@165 291 end
jbe@165 292 result = string.concat(result, ", ")
jbe@165 293 self[key] = result
jbe@165 294 return result
jbe@165 295 end
jbe@165 296 }),
jbe@165 297 -- table mapping header field names to a single string value
jbe@165 298 -- (or false if header has been sent multiple times):
jbe@165 299 headers_value = setmetatable({}, {
jbe@165 300 __index = function(self, key)
jbe@165 301 if headers_value_nil[key] then
jbe@165 302 return nil
jbe@165 303 end
jbe@165 304 local result = nil
jbe@165 305 local values = request.headers_csv_table[key]
jbe@165 306 if #values == 0 then
jbe@165 307 headers_value_nil[key] = true
jbe@165 308 elseif #values == 1 then
jbe@165 309 result = values[1]
jbe@165 310 else
jbe@165 311 result = false
jbe@165 312 end
jbe@165 313 self[key] = result
jbe@165 314 return result
jbe@165 315 end
jbe@165 316 }),
jbe@165 317 -- table mapping header field names to a flag table,
jbe@165 318 -- indicating if the comma separated value contains certain entries:
jbe@165 319 headers_flags = setmetatable({}, {
jbe@165 320 __index = function(self, key)
jbe@165 321 local result = setmetatable({}, {
jbe@165 322 __index = function(self, key)
jbe@165 323 local lowerkey = string.lower(key)
jbe@165 324 local result = rawget(self, lowerkey) or false
jbe@165 325 self[lowerkey] = result
jbe@165 326 self[key] = result
jbe@165 327 return result
jbe@165 328 end
jbe@165 329 })
jbe@165 330 for i, value in ipairs(request.headers_csv_table[key]) do
jbe@165 331 result[string.lower(value)] = true
jbe@165 332 end
jbe@165 333 self[key] = result
jbe@165 334 return result
jbe@165 335 end
jbe@165 336 })
jbe@0 337 }
jbe@162 338 -- local variables to track the state:
jbe@162 339 local state = "init" -- one of:
jbe@162 340 -- "init" (initial state)
jbe@162 341 -- "no_status_sent" (configuration complete)
jbe@162 342 -- "info_status_sent" (1xx status code has been sent)
jbe@162 343 -- "bodyless_status_sent" (204/304 status code has been sent)
jbe@162 344 -- "status_sent" (regular status code has been sent)
jbe@162 345 -- "headers_sent" (headers have been terminated)
jbe@162 346 -- "finished" (request has been answered completely)
jbe@163 347 -- "faulty" (I/O or protocaol error)
jbe@162 348 local close_requested = false -- "Connection: close" requested
jbe@162 349 local close_responded = false -- "Connection: close" sent
jbe@162 350 local content_length = nil -- value of Content-Length header sent
jbe@164 351 local chunk_parts = {} -- list of chunks to send
jbe@164 352 local chunk_bytes = 0 -- sum of lengths of chunks to send
jbe@163 353 -- functions to assert proper output/closing:
jbe@163 354 local function assert_output(...)
jbe@163 355 local retval, errmsg = ...
jbe@163 356 if retval then return ... end
jbe@163 357 state = "faulty"
jbe@163 358 socket:reset()
jbe@163 359 error("Could not send data to client: " .. errmsg)
jbe@163 360 end
jbe@163 361 local function assert_close(...)
jbe@163 362 local retval, errmsg = ...
jbe@163 363 if retval then return ... end
jbe@163 364 state = "faulty"
jbe@163 365 error("Could not finish sending data to client: " .. errmsg)
jbe@163 366 end
jbe@164 367 -- function to assert non-faulty handle:
jbe@164 368 local function assert_not_faulty()
jbe@164 369 assert(state ~= "faulty", "Tried to use faulty request handle")
jbe@164 370 end
jbe@162 371 -- functions to send data to the browser:
jbe@160 372 local function send(...)
jbe@163 373 assert_output(socket:write_call(unblock, ...))
jbe@38 374 end
jbe@162 375 local function send_flush(...)
jbe@163 376 assert_output(socket:flush_call(unblock, ...))
jbe@162 377 end
jbe@163 378 -- function to finish request:
jbe@163 379 local function finish()
jbe@163 380 if close_responded then
jbe@163 381 -- discard any input:
jbe@163 382 consume = drain
jbe@163 383 -- close output stream:
jbe@163 384 send_flush()
jbe@163 385 assert_close(socket:finish())
jbe@163 386 -- wait for EOF of peer to avoid immediate TCP RST condition:
jbe@163 387 consume_all()
jbe@163 388 -- fully close socket:
jbe@163 389 assert_close(socket:close())
jbe@163 390 else
jbe@163 391 send_flush()
jbe@163 392 consume_all()
jbe@163 393 end
jbe@163 394 end
jbe@164 395 -- function that writes out buffered chunks (without flushing the socket):
jbe@164 396 function send_chunk()
jbe@164 397 if chunk_bytes > 0 then
jbe@164 398 assert_output(socket:write(string.format("%x\r\n", chunk_bytes)))
jbe@164 399 for i = 1, #chunk_parts do -- TODO: evaluated only once?
jbe@164 400 send(chunk_parts[i])
jbe@164 401 chunk_parts[i] = nil
jbe@164 402 end
jbe@164 403 chunk_bytes = 0
jbe@164 404 send("\r\n")
jbe@164 405 end
jbe@164 406 end
jbe@168 407 -- function to report an error:
jbe@168 408 local function request_error(throw_error, status, text)
jbe@168 409 local errmsg = "Error while reading request from client. Error response: " .. status
jbe@168 410 if text then
jbe@168 411 errmsg = errmsg .. " (" .. text .. ")"
jbe@168 412 end
jbe@168 413 if
jbe@168 414 state == "init" or
jbe@168 415 state == "no_status_sent" or
jbe@168 416 state == "info_status_sent"
jbe@168 417 then
jbe@168 418 local error_response_status, errmsg2 = pcall(function()
jbe@168 419 request:monologue()
jbe@168 420 request:send_status(status)
jbe@168 421 request:send_header("Content-Type", "text/plain")
jbe@168 422 request:send_data(status, "\n")
jbe@168 423 if text then
jbe@168 424 request:send_data("\n", text, "\n")
jbe@168 425 end
jbe@168 426 request:finish()
jbe@168 427 end)
jbe@168 428 if not error_response_status then
jbe@168 429 error("Unexpected error while sending error response: " .. errmsg2)
jbe@168 430 end
jbe@168 431 elseif state ~= "faulty" then
jbe@169 432 state = "faulty"
jbe@168 433 assert_close(socket:reset())
jbe@168 434 end
jbe@168 435 if throw_error then
jbe@168 436 error(errmsg)
jbe@168 437 else
jbe@168 438 return survive
jbe@168 439 end
jbe@168 440 end
jbe@170 441 -- read function
jbe@170 442 local function read(...)
jbe@170 443 local data, status = socket:read_yield(...)
jbe@170 444 if data == nil then
jbe@170 445 request_error(true, "400 Bad Request", "Read error")
jbe@170 446 end
jbe@170 447 if status == "eof" then
jbe@170 448 request_error(true, "400 Bad Request", "Unexpected EOF")
jbe@170 449 end
jbe@170 450 return data
jbe@170 451 end
jbe@168 452 -- callback for request body streaming:
jbe@168 453 local process_body_chunk
jbe@168 454 -- reads a number of bytes from the socket,
jbe@168 455 -- optionally feeding these bytes chunk-wise
jbe@168 456 -- into a callback function:
jbe@168 457 local function read_body_bytes(remaining)
jbe@168 458 while remaining > 0 do
jbe@168 459 local limit
jbe@168 460 if remaining > input_chunk_size then
jbe@168 461 limit = input_chunk_size
jbe@168 462 else
jbe@168 463 limit = remaining
jbe@168 464 end
jbe@170 465 local chunk = read(limit)
jbe@168 466 remaining = remaining - limit
jbe@168 467 if process_body_chunk then
jbe@168 468 process_body_chunk(chunk)
jbe@168 469 end
jbe@168 470 end
jbe@168 471 end
jbe@168 472 -- coroutine for request body processing:
jbe@168 473 local function read_body()
jbe@168 474 if request.headers_flags["Transfer-Encoding"]["chunked"] then
jbe@168 475 while true do
jbe@170 476 local line = read(32 + remaining_body_size_limit, "\n")
jbe@168 477 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
jbe@168 478 local chunkext
jbe@168 479 if lenstr then
jbe@168 480 chunkext = ""
jbe@168 481 else
jbe@168 482 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
jbe@168 483 end
jbe@168 484 if not lenstr or #lenstr > 13 then
jbe@168 485 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 486 end
jbe@168 487 local len = tonumber("0x" .. lenstr)
jbe@168 488 remaining_body_size_limit = remaining_body_size_limit - (#zeros + #chunkext + len)
jbe@168 489 if remaining_body_size_limit < 0 then
jbe@168 490 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
jbe@168 491 end
jbe@168 492 if len == 0 then break end
jbe@168 493 read_body_bytes(len)
jbe@170 494 local term = read(2, "\n")
jbe@168 495 if term ~= "\r\n" and term ~= "\n" then
jbe@168 496 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
jbe@168 497 end
jbe@168 498 end
jbe@168 499 while true do
jbe@170 500 local line = read(2 + remaining_body_size_limit, "\n")
jbe@168 501 if line == "\r\n" or line == "\n" then break end
jbe@168 502 remaining_body_size_limit = remaining_body_size_limit - #line
jbe@168 503 if remaining_body_size_limit < 0 then
jbe@168 504 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
jbe@168 505 end
jbe@168 506 end
jbe@168 507 elseif request_body_content_length then
jbe@168 508 read_body_bytes(request_body_content_length)
jbe@168 509 end
jbe@168 510 end
jbe@164 511 -- function to prepare (or skip) body processing:
jbe@162 512 local function prepare()
jbe@164 513 assert_not_faulty()
jbe@171 514 if state ~= "init" then
jbe@162 515 return
jbe@162 516 end
jbe@171 517 consume = coroutine.wrap(read_body)
jbe@162 518 state = "no_status_sent"
jbe@171 519 if request.headers_flags["Expect"]["100-continue"] then
jbe@171 520 request:send_status("100 Continue")
jbe@171 521 request:finish_headers()
jbe@171 522 end
jbe@162 523 end
jbe@163 524 -- method to ignore input and close connection after response:
jbe@163 525 function request:monologue()
jbe@164 526 assert_not_faulty()
jbe@163 527 if
jbe@163 528 state == "headers_sent" or
jbe@163 529 state == "finished"
jbe@163 530 then
jbe@163 531 error("All HTTP headers have already been sent")
jbe@163 532 end
jbe@164 533 local old_state = state
jbe@164 534 state = "faulty"
jbe@163 535 consume = drain
jbe@163 536 close_requested = true
jbe@171 537 if old_state == "init" then
jbe@163 538 state = "no_status_sent"
jbe@164 539 else
jbe@164 540 state = old_state
jbe@162 541 end
jbe@162 542 end
jbe@163 543 --
jbe@162 544 -- method to send a HTTP response status (e.g. "200 OK"):
jbe@162 545 function request:send_status(status)
jbe@162 546 prepare()
jbe@164 547 local old_state = state
jbe@164 548 state = "faulty"
jbe@164 549 if old_state == "info_status_sent" then
jbe@162 550 send_flush("\r\n")
jbe@164 551 elseif old_state ~= "no_status_sent" then
jbe@162 552 error("HTTP status has already been sent")
jbe@162 553 end
jbe@162 554 local status1 = string.sub(status, 1, 1)
jbe@162 555 local status3 = string.sub(status, 1, 3)
jbe@162 556 send("HTTP/1.1 ", status, "\r\n", preamble)
jbe@162 557 local wrb = status_without_response_body[status3]
jbe@162 558 if wrb then
jbe@162 559 state = "bodyless_status_sent"
jbe@162 560 if wrb == "zero_content_length" then
jbe@162 561 request:send_header("Content-Length", 0)
jbe@162 562 end
jbe@162 563 elseif status1 == "1" then
jbe@162 564 state = "info_status_sent"
jbe@162 565 else
jbe@162 566 state = "status_sent"
jbe@162 567 end
jbe@162 568 end
jbe@162 569 -- method to send a HTTP response header:
jbe@162 570 -- (key and value must be provided as separate args)
jbe@162 571 function request:send_header(key, value)
jbe@164 572 assert_not_faulty()
jbe@171 573 if state == "init" or state == "no_status_sent" then
jbe@162 574 error("HTTP status has not been sent yet")
jbe@162 575 elseif
jbe@164 576 state == "headers_sent" or
jbe@164 577 state == "finished"
jbe@162 578 then
jbe@162 579 error("All HTTP headers have already been sent")
jbe@162 580 end
jbe@162 581 local key_lower = string.lower(key)
jbe@162 582 if key_lower == "content-length" then
jbe@162 583 if state == "info_status_sent" then
jbe@162 584 error("Cannot set Content-Length for informational status response")
jbe@162 585 end
jbe@162 586 local cl = assert(tonumber(value), "Invalid content-length")
jbe@162 587 if content_length == nil then
jbe@162 588 content_length = cl
jbe@162 589 elseif content_length == cl then
jbe@162 590 return
jbe@162 591 else
jbe@162 592 error("Content-Length has been set multiple times with different values")
jbe@162 593 end
jbe@162 594 elseif key_lower == "connection" then
jbe@162 595 for entry in string.gmatch(string.lower(value), "[^,]+") do
jbe@162 596 if string.match(entry, "^[ \t]*close[ \t]*$") then
jbe@162 597 if state == "info_status_sent" then
jbe@162 598 error("Cannot set \"Connection: close\" for informational status response")
jbe@162 599 end
jbe@162 600 close_responded = true
jbe@162 601 break
jbe@162 602 end
jbe@162 603 end
jbe@162 604 end
jbe@162 605 assert_output(socket:write(key, ": ", value, "\r\n"))
jbe@162 606 end
jbe@162 607 -- function to terminate header section in response, optionally flushing:
jbe@162 608 -- (may be called multiple times unless response is finished)
jbe@162 609 local function finish_headers(with_flush)
jbe@162 610 if state == "finished" then
jbe@162 611 error("Response has already been finished")
jbe@162 612 elseif state == "info_status_sent" then
jbe@162 613 send_flush("\r\n")
jbe@162 614 state = "no_status_sent"
jbe@162 615 elseif state == "bodyless_status_sent" then
jbe@162 616 if close_requested and not close_responded then
jbe@162 617 request:send_header("Connection", "close")
jbe@162 618 end
jbe@162 619 send("\r\n")
jbe@163 620 finish()
jbe@162 621 state = "finished"
jbe@162 622 elseif state == "status_sent" then
jbe@162 623 if not content_length then
jbe@162 624 request:send_header("Transfer-Encoding", "chunked")
jbe@162 625 end
jbe@162 626 if close_requested and not close_responded then
jbe@162 627 request:send_header("Connection", "close")
jbe@162 628 end
jbe@162 629 send("\r\n")
jbe@162 630 if request.method == "HEAD" then
jbe@163 631 finish()
jbe@162 632 elseif with_flush then
jbe@162 633 send_flush()
jbe@162 634 end
jbe@162 635 state = "headers_sent"
jbe@162 636 elseif state ~= "headers_sent" then
jbe@162 637 error("HTTP status has not been sent yet")
jbe@162 638 end
jbe@162 639 end
jbe@162 640 -- method to finish and flush headers:
jbe@162 641 function request:finish_headers()
jbe@164 642 assert_not_faulty()
jbe@162 643 finish_headers(true)
jbe@162 644 end
jbe@164 645 -- method to send body data:
jbe@164 646 function request:send_data(...)
jbe@164 647 assert_not_faulty()
jbe@164 648 if output_state == "info_status_sent" then
jbe@164 649 error("No (non-informational) HTTP status has been sent yet")
jbe@164 650 elseif output_state == "bodyless_status_sent" then
jbe@164 651 error("Cannot send response data for body-less status message")
jbe@164 652 end
jbe@164 653 finish_headers(false)
jbe@164 654 if output_state ~= "headers_sent" then
jbe@164 655 error("Unexpected internal status in HTTP engine")
jbe@164 656 end
jbe@164 657 if request.method == "HEAD" then
jbe@164 658 return
jbe@164 659 end
jbe@164 660 for i = 1, select("#", ...) do
jbe@164 661 local str = tostring(select(i, ...))
jbe@164 662 if #str > 0 then
jbe@164 663 if content_length then
jbe@164 664 local bytes_to_send = #str
jbe@164 665 if bytes_sent + bytes_to_send > content_length then
jbe@164 666 error("Content length exceeded")
jbe@164 667 else
jbe@164 668 send(str)
jbe@164 669 bytes_sent = bytes_sent + bytes_to_send
jbe@164 670 end
jbe@164 671 else
jbe@164 672 chunk_bytes = chunk_bytes + #str
jbe@164 673 chunk_parts[#chunk_parts+1] = str
jbe@164 674 end
jbe@164 675 end
jbe@164 676 end
jbe@164 677 if chunk_bytes >= output_chunk_size then
jbe@164 678 send_chunk()
jbe@164 679 end
jbe@164 680 end
jbe@165 681 -- method to flush output buffer:
jbe@165 682 function request:flush()
jbe@165 683 assert_not_faulty()
jbe@165 684 send_chunk()
jbe@165 685 send_flush()
jbe@165 686 end
jbe@165 687 -- method to finish response:
jbe@165 688 function request:finish()
jbe@165 689 assert_not_faulty()
jbe@165 690 if state == "finished" then
jbe@165 691 return
jbe@165 692 elseif state == "info_status_sent" then
jbe@165 693 error("Informational HTTP response can be finished with :finish_headers() method")
jbe@165 694 end
jbe@165 695 finish_headers(false)
jbe@165 696 if state == "headers_sent" then
jbe@165 697 if request.method ~= "HEAD" then
jbe@165 698 state = "faulty"
jbe@165 699 if content_length then
jbe@165 700 if bytes_sent ~= content_length then
jbe@165 701 error("Content length not used")
jbe@165 702 end
jbe@165 703 else
jbe@165 704 send_chunk()
jbe@165 705 send("0\r\n\r\n")
jbe@165 706 end
jbe@165 707 finish()
jbe@165 708 end
jbe@165 709 state = "finished"
jbe@165 710 elseif state ~= "finished" then
jbe@165 711 error("Unexpected internal status in HTTP engine")
jbe@165 712 end
jbe@165 713 end
jbe@160 714 -- wait for input:
jbe@160 715 if not poll(socket_set, nil, request_idle_timeout) then
jbe@163 716 return request_error(false, "408 Request Timeout", "Idle connection timed out")
jbe@38 717 end
jbe@162 718 until close_responded
jbe@0 719 return survive
jbe@0 720 end
jbe@0 721 end
jbe@0 722
jbe@0 723 return _M
jbe@0 724

Impressum / About Us