moonbridge

view moonbridge_http.lua @ 163:80266ee1593f

Work on new HTTP module implementation
author jbe
date Fri Jun 12 01:55:50 2015 +0200 (2015-06-12)
parents 6c1561547f79
children 27dc025e76cc
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 -- functions to assert proper output/closing:
209 local function assert_output(...)
210 local retval, errmsg = ...
211 if retval then return ... end
212 state = "faulty"
213 socket:reset()
214 error("Could not send data to client: " .. errmsg)
215 end
216 local function assert_close(...)
217 local retval, errmsg = ...
218 if retval then return ... end
219 state = "faulty"
220 error("Could not finish sending data to client: " .. errmsg)
221 end
222 -- functions to send data to the browser:
223 local function send(...)
224 assert_output(socket:write_call(unblock, ...))
225 end
226 local function send_flush(...)
227 assert_output(socket:flush_call(unblock, ...))
228 end
229 -- function to finish request:
230 local function finish()
231 if close_responded then
232 -- discard any input:
233 consume = drain
234 -- close output stream:
235 send_flush()
236 assert_close(socket:finish())
237 -- wait for EOF of peer to avoid immediate TCP RST condition:
238 consume_all()
239 -- fully close socket:
240 assert_close(socket:close())
241 else
242 send_flush()
243 consume_all()
244 end
245 end
246 -- function to prepare body processing:
247 local function prepare()
248 if state == "prepare" then
249 error("Unexpected internal status in HTTP engine")
250 elseif state ~= "init" then
251 return
252 end
253 state = "prepare"
254 -- TODO
255 state = "no_status_sent"
256 end
257 -- method to ignore input and close connection after response:
258 function request:monologue()
259 prepare()
260 if
261 state == "headers_sent" or
262 state == "finished"
263 then
264 error("All HTTP headers have already been sent")
265 end
266 consume = drain
267 close_requested = true
268 if state == "init" or state == "prepare" then -- TODO: ok?
269 state = "no_status_sent"
270 end
271 end
272 --
273 -- method to send a HTTP response status (e.g. "200 OK"):
274 function request:send_status(status)
275 prepare()
276 if state == "info_status_sent" then
277 send_flush("\r\n")
278 elseif state ~= "no_status_sent" then
279 error("HTTP status has already been sent")
280 end
281 local status1 = string.sub(status, 1, 1)
282 local status3 = string.sub(status, 1, 3)
283 send("HTTP/1.1 ", status, "\r\n", preamble)
284 local wrb = status_without_response_body[status3]
285 if wrb then
286 state = "bodyless_status_sent"
287 if wrb == "zero_content_length" then
288 request:send_header("Content-Length", 0)
289 end
290 elseif status1 == "1" then
291 state = "info_status_sent"
292 else
293 state = "status_sent"
294 end
295 end
296 -- method to send a HTTP response header:
297 -- (key and value must be provided as separate args)
298 function request:send_header(key, value)
299 prepare()
300 if state == "no_status_sent" then
301 error("HTTP status has not been sent yet")
302 elseif
303 state ~= "info_status_sent" and
304 state ~= "bodyless_status_sent" and
305 state ~= "status_sent"
306 then
307 error("All HTTP headers have already been sent")
308 end
309 local key_lower = string.lower(key)
310 if key_lower == "content-length" then
311 if state == "info_status_sent" then
312 error("Cannot set Content-Length for informational status response")
313 end
314 local cl = assert(tonumber(value), "Invalid content-length")
315 if content_length == nil then
316 content_length = cl
317 elseif content_length == cl then
318 return
319 else
320 error("Content-Length has been set multiple times with different values")
321 end
322 elseif key_lower == "connection" then
323 for entry in string.gmatch(string.lower(value), "[^,]+") do
324 if string.match(entry, "^[ \t]*close[ \t]*$") then
325 if state == "info_status_sent" then
326 error("Cannot set \"Connection: close\" for informational status response")
327 end
328 close_responded = true
329 break
330 end
331 end
332 end
333 assert_output(socket:write(key, ": ", value, "\r\n"))
334 end
335 -- function to terminate header section in response, optionally flushing:
336 -- (may be called multiple times unless response is finished)
337 local function finish_headers(with_flush)
338 if state == "finished" then
339 error("Response has already been finished")
340 elseif state == "info_status_sent" then
341 send_flush("\r\n")
342 state = "no_status_sent"
343 elseif state == "bodyless_status_sent" then
344 if close_requested and not close_responded then
345 request:send_header("Connection", "close")
346 end
347 send("\r\n")
348 finish()
349 state = "finished"
350 elseif state == "status_sent" then
351 if not content_length then
352 request:send_header("Transfer-Encoding", "chunked")
353 end
354 if close_requested and not close_responded then
355 request:send_header("Connection", "close")
356 end
357 send("\r\n")
358 if request.method == "HEAD" then
359 finish()
360 elseif with_flush then
361 send_flush()
362 end
363 state = "headers_sent"
364 elseif state ~= "headers_sent" then
365 error("HTTP status has not been sent yet")
366 end
367 end
368 -- method to finish and flush headers:
369 function request:finish_headers()
370 prepare()
371 finish_headers(true)
372 end
373 -- function to report an error:
374 local function request_error(throw_error, status, text)
375 local errmsg = "Error while reading request from client. Error response: " .. status
376 if text then
377 errmsg = errmsg .. " (" .. text .. ")"
378 end
379 if
380 state == "init" or
381 state == "prepare" or
382 state == "no_status_sent" or
383 state == "info_status_sent"
384 then
385 local error_response_status, errmsg2 = pcall(function()
386 request:monologue()
387 request:send_status(status)
388 request:send_header("Content-Type", "text/plain")
389 request:send_data(status, "\n")
390 if text then
391 request:send_data("\n", text, "\n")
392 end
393 request:finish()
394 end)
395 if not error_response_status then
396 error("Unexpected error while sending error response: " .. errmsg2)
397 end
398 elseif state ~= "faulty" then
399 assert_close(socket:reset())
400 end
401 if throw_error then
402 error(errmsg)
403 else
404 return survive
405 end
406 end
407 -- wait for input:
408 if not poll(socket_set, nil, request_idle_timeout) then
409 return request_error(false, "408 Request Timeout", "Idle connection timed out")
410 end
411 until close_responded
412 return survive
413 end
414 end
416 return _M

Impressum / About Us