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