moonbridge

view moonbridge_http.lua @ 164:27dc025e76cc

Work on new HTTP module implementation
author jbe
date Sat Jun 13 00:55:01 2015 +0200 (2015-06-13)
parents 80266ee1593f
children 00f01d945e13
line source
1 #!/usr/bin/env lua
3 -- module preamble
4 local _G, _M = _ENV, {}
5 _ENV = setmetatable({}, {
6 __index = function(self, key)
7 local value = _M[key]; if value ~= nil then return value end
8 return _G[key]
9 end,
10 __newindex = _M
11 })
13 -- function that encodes certain HTML entities:
14 -- (not used by the library itself)
15 function encode_html(text)
16 return (
17 string.gsub(
18 text, '[<>&"]',
19 function(char)
20 if char == '<' then
21 return "&lt;"
22 elseif char == '>' then
23 return "&gt;"
24 elseif char == '&' then
25 return "&amp;"
26 elseif char == '"' then
27 return "&quot;"
28 end
29 end
30 )
31 )
33 end
35 -- function that encodes special characters for URIs:
36 -- (not used by the library itself)
37 function encode_uri(text)
38 return (
39 string.gsub(text, "[^0-9A-Za-z_%.~-]",
40 function (char)
41 return string.format("%%%02x", string.byte(char))
42 end
43 )
44 )
45 end
47 -- function undoing URL encoding:
48 do
49 local b0 = string.byte("0")
50 local b9 = string.byte("9")
51 local bA = string.byte("A")
52 local bF = string.byte("F")
53 local ba = string.byte("a")
54 local bf = string.byte("f")
55 function decode_uri(str)
56 return (
57 string.gsub(
58 string.gsub(str, "%+", " "),
59 "%%([0-9A-Fa-f][0-9A-Fa-f])",
60 function(hex)
61 local n1, n2 = string.byte(hex, 1, 2)
62 if n1 >= b0 and n1 <= b9 then n1 = n1 - b0
63 elseif n1 >= bA and n1 <= bF then n1 = n1 - bA + 10
64 elseif n1 >= ba and n1 <= bf then n1 = n1 - ba + 10
65 else error("Assertion failed") end
66 if n2 >= b0 and n2 <= b9 then n2 = n2 - b0
67 elseif n2 >= bA and n2 <= bF then n2 = n2 - bA + 10
68 elseif n2 >= ba and n2 <= bf then n2 = n2 - ba + 10
69 else error("Assertion failed") end
70 return string.char(n1 * 16 + n2)
71 end
72 )
73 )
74 end
75 end
77 -- status codes that carry no response body (in addition to 1xx):
78 -- (set to "zero_content_length" if Content-Length header is required)
79 status_without_response_body = {
80 ["101"] = true, -- list 101 to allow protocol switch
81 ["204"] = true,
82 ["205"] = "zero_content_length",
83 ["304"] = true
84 }
86 -- parses URL encoded form data:
87 local function read_urlencoded_form(data)
88 local tbl = {}
89 for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do
90 local key = decode_uri(rawkey)
91 local value = decode_uri(rawvalue)
92 local subtbl = tbl[key]
93 if subtbl then
94 subtbl[#subtbl+1] = value
95 else
96 tbl[key] = {value}
97 end
98 end
99 return tbl
100 end
102 -- extracts first value from each subtable:
103 local function get_first_values(tbl)
104 local newtbl = {}
105 for key, subtbl in pairs(tbl) do
106 newtbl[key] = subtbl[1]
107 end
108 return newtbl
109 end
111 function generate_handler(handler, options)
112 -- swap arguments if necessary (for convenience):
113 if type(handler) ~= "function" and type(options) == "function" then
114 handler, options = options, handler
115 end
116 -- helper function to process options:
117 local function default(name, default_value)
118 local value = options[name]
119 if value == nil then
120 return default_value
121 else
122 return value or nil
123 end
124 end
125 -- process options:
126 options = options or {}
127 local preamble = "" -- preamble sent with every(!) HTTP response
128 do
129 -- named arg "static_headers" is used to create the preamble:
130 local s = options.static_headers
131 local t = {}
132 if s then
133 if type(s) == "string" then
134 for line in string.gmatch(s, "[^\r\n]+") do
135 t[#t+1] = line
136 end
137 else
138 for i, kv in ipairs(options.static_headers) do
139 if type(kv) == "string" then
140 t[#t+1] = kv
141 else
142 t[#t+1] = kv[1] .. ": " .. kv[2]
143 end
144 end
145 end
146 end
147 t[#t+1] = ""
148 preamble = table.concat(t, "\r\n")
149 end
150 local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384
151 local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024
152 local header_size_limit = options.header_size_limit or 1024*1024
153 local body_size_limit = options.body_size_limit or 64*1024*1024
154 local request_idle_timeout = default("request_idle_timeout", 330)
155 local request_header_timeout = default("request_header_timeout", 30)
156 local request_body_timeout = default("request_body_timeout", 60)
157 local request_response_timeout = default("request_response_timeout", 1800)
158 local poll = options.poll_function or moonbridge_io.poll
159 -- return socket handler:
160 return function(socket)
161 local socket_set = {[socket] = true} -- used for poll function
162 local survive = true -- set to false if process shall be terminated later
163 local consume -- function that reads some input if possible
164 -- function that drains some input if possible:
165 local function drain()
166 local bytes, status = socket:drain_nb(input_chunk_size)
167 if not bytes or status == "eof" then
168 consume = nil
169 end
170 end
171 -- function trying to unblock socket by reading:
172 local function unblock()
173 if consume then
174 poll(socket_set, socket_set)
175 consume()
176 else
177 poll(nil, socket_set)
178 end
179 end
180 -- function that enforces consumption of all input:
181 local function consume_all()
182 while consume do
183 poll(socket_set, nil)
184 consume()
185 end
186 end
187 -- handle requests in a loop:
188 repeat
189 -- create a new request object:
190 local request = {
191 socket = socket,
192 cookies = {}
193 }
194 -- local variables to track the state:
195 local state = "init" -- one of:
196 -- "init" (initial state)
197 -- "prepare" (configureation in preparation)
198 -- "no_status_sent" (configuration complete)
199 -- "info_status_sent" (1xx status code has been sent)
200 -- "bodyless_status_sent" (204/304 status code has been sent)
201 -- "status_sent" (regular status code has been sent)
202 -- "headers_sent" (headers have been terminated)
203 -- "finished" (request has been answered completely)
204 -- "faulty" (I/O or protocaol error)
205 local close_requested = false -- "Connection: close" requested
206 local close_responded = false -- "Connection: close" sent
207 local content_length = nil -- value of Content-Length header sent
208 local chunk_parts = {} -- list of chunks to send
209 local chunk_bytes = 0 -- sum of lengths of chunks to send
210 -- functions to assert proper output/closing:
211 local function assert_output(...)
212 local retval, errmsg = ...
213 if retval then return ... end
214 state = "faulty"
215 socket:reset()
216 error("Could not send data to client: " .. errmsg)
217 end
218 local function assert_close(...)
219 local retval, errmsg = ...
220 if retval then return ... end
221 state = "faulty"
222 error("Could not finish sending data to client: " .. errmsg)
223 end
224 -- function to assert non-faulty handle:
225 local function assert_not_faulty()
226 assert(state ~= "faulty", "Tried to use faulty request handle")
227 end
228 -- functions to send data to the browser:
229 local function send(...)
230 assert_output(socket:write_call(unblock, ...))
231 end
232 local function send_flush(...)
233 assert_output(socket:flush_call(unblock, ...))
234 end
235 -- function to finish request:
236 local function finish()
237 if close_responded then
238 -- discard any input:
239 consume = drain
240 -- close output stream:
241 send_flush()
242 assert_close(socket:finish())
243 -- wait for EOF of peer to avoid immediate TCP RST condition:
244 consume_all()
245 -- fully close socket:
246 assert_close(socket:close())
247 else
248 send_flush()
249 consume_all()
250 end
251 end
252 -- function that writes out buffered chunks (without flushing the socket):
253 function send_chunk()
254 if chunk_bytes > 0 then
255 assert_output(socket:write(string.format("%x\r\n", chunk_bytes)))
256 for i = 1, #chunk_parts do -- TODO: evaluated only once?
257 send(chunk_parts[i])
258 chunk_parts[i] = nil
259 end
260 chunk_bytes = 0
261 send("\r\n")
262 end
263 end
264 -- function to prepare (or skip) body processing:
265 local function prepare()
266 assert_not_faulty()
267 if state == "prepare" then
268 error("Unexpected internal status in HTTP engine (recursive prepare)")
269 elseif state ~= "init" then
270 return
271 end
272 state = "prepare"
273 -- TODO
274 state = "no_status_sent"
275 end
276 -- method to ignore input and close connection after response:
277 function request:monologue()
278 assert_not_faulty()
279 if
280 state == "headers_sent" or
281 state == "finished"
282 then
283 error("All HTTP headers have already been sent")
284 end
285 local old_state = state
286 state = "faulty"
287 consume = drain
288 close_requested = true
289 if old_state == "init" or old_state == "prepare" then -- TODO: ok?
290 state = "no_status_sent"
291 else
292 state = old_state
293 end
294 end
295 --
296 -- method to send a HTTP response status (e.g. "200 OK"):
297 function request:send_status(status)
298 prepare()
299 local old_state = state
300 state = "faulty"
301 if old_state == "info_status_sent" then
302 send_flush("\r\n")
303 elseif old_state ~= "no_status_sent" then
304 error("HTTP status has already been sent")
305 end
306 local status1 = string.sub(status, 1, 1)
307 local status3 = string.sub(status, 1, 3)
308 send("HTTP/1.1 ", status, "\r\n", preamble)
309 local wrb = status_without_response_body[status3]
310 if wrb then
311 state = "bodyless_status_sent"
312 if wrb == "zero_content_length" then
313 request:send_header("Content-Length", 0)
314 end
315 elseif status1 == "1" then
316 state = "info_status_sent"
317 else
318 state = "status_sent"
319 end
320 end
321 -- method to send a HTTP response header:
322 -- (key and value must be provided as separate args)
323 function request:send_header(key, value)
324 assert_not_faulty()
325 if
326 state == "init" or
327 state == "prepare" or
328 state == "no_status_sent"
329 then
330 error("HTTP status has not been sent yet")
331 elseif
332 state == "headers_sent" or
333 state == "finished"
334 then
335 error("All HTTP headers have already been sent")
336 end
337 local key_lower = string.lower(key)
338 if key_lower == "content-length" then
339 if state == "info_status_sent" then
340 error("Cannot set Content-Length for informational status response")
341 end
342 local cl = assert(tonumber(value), "Invalid content-length")
343 if content_length == nil then
344 content_length = cl
345 elseif content_length == cl then
346 return
347 else
348 error("Content-Length has been set multiple times with different values")
349 end
350 elseif key_lower == "connection" then
351 for entry in string.gmatch(string.lower(value), "[^,]+") do
352 if string.match(entry, "^[ \t]*close[ \t]*$") then
353 if state == "info_status_sent" then
354 error("Cannot set \"Connection: close\" for informational status response")
355 end
356 close_responded = true
357 break
358 end
359 end
360 end
361 assert_output(socket:write(key, ": ", value, "\r\n"))
362 end
363 -- function to terminate header section in response, optionally flushing:
364 -- (may be called multiple times unless response is finished)
365 local function finish_headers(with_flush)
366 if state == "finished" then
367 error("Response has already been finished")
368 elseif state == "info_status_sent" then
369 send_flush("\r\n")
370 state = "no_status_sent"
371 elseif state == "bodyless_status_sent" then
372 if close_requested and not close_responded then
373 request:send_header("Connection", "close")
374 end
375 send("\r\n")
376 finish()
377 state = "finished"
378 elseif state == "status_sent" then
379 if not content_length then
380 request:send_header("Transfer-Encoding", "chunked")
381 end
382 if close_requested and not close_responded then
383 request:send_header("Connection", "close")
384 end
385 send("\r\n")
386 if request.method == "HEAD" then
387 finish()
388 elseif with_flush then
389 send_flush()
390 end
391 state = "headers_sent"
392 elseif state ~= "headers_sent" then
393 error("HTTP status has not been sent yet")
394 end
395 end
396 -- method to finish and flush headers:
397 function request:finish_headers()
398 assert_not_faulty()
399 finish_headers(true)
400 end
401 -- method to send body data:
402 function request:send_data(...)
403 assert_not_faulty()
404 if output_state == "info_status_sent" then
405 error("No (non-informational) HTTP status has been sent yet")
406 elseif output_state == "bodyless_status_sent" then
407 error("Cannot send response data for body-less status message")
408 end
409 finish_headers(false)
410 if output_state ~= "headers_sent" then
411 error("Unexpected internal status in HTTP engine")
412 end
413 if request.method == "HEAD" then
414 return
415 end
416 for i = 1, select("#", ...) do
417 local str = tostring(select(i, ...))
418 if #str > 0 then
419 if content_length then
420 local bytes_to_send = #str
421 if bytes_sent + bytes_to_send > content_length then
422 error("Content length exceeded")
423 else
424 send(str)
425 bytes_sent = bytes_sent + bytes_to_send
426 end
427 else
428 chunk_bytes = chunk_bytes + #str
429 chunk_parts[#chunk_parts+1] = str
430 end
431 end
432 end
433 if chunk_bytes >= output_chunk_size then
434 send_chunk()
435 end
436 end
437 -- function to report an error:
438 local function request_error(throw_error, status, text)
439 local errmsg = "Error while reading request from client. Error response: " .. status
440 if text then
441 errmsg = errmsg .. " (" .. text .. ")"
442 end
443 if
444 state == "init" or
445 state == "prepare" or
446 state == "no_status_sent" or
447 state == "info_status_sent"
448 then
449 local error_response_status, errmsg2 = pcall(function()
450 request:monologue()
451 request:send_status(status)
452 request:send_header("Content-Type", "text/plain")
453 request:send_data(status, "\n")
454 if text then
455 request:send_data("\n", text, "\n")
456 end
457 request:finish()
458 end)
459 if not error_response_status then
460 error("Unexpected error while sending error response: " .. errmsg2)
461 end
462 elseif state ~= "faulty" then
463 assert_close(socket:reset())
464 end
465 if throw_error then
466 error(errmsg)
467 else
468 return survive
469 end
470 end
471 -- wait for input:
472 if not poll(socket_set, nil, request_idle_timeout) then
473 return request_error(false, "408 Request Timeout", "Idle connection timed out")
474 end
475 until close_responded
476 return survive
477 end
478 end
480 return _M

Impressum / About Us