moonbridge

view moonbridge_http.lua @ 36:b841dc424baf

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

Impressum / About Us