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