moonbridge

view moonbridge_http.lua @ 170:4d5cf5cacc68

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

Impressum / About Us