moonbridge

view moonbridge_http.lua @ 162:6c1561547f79

Work on new HTTP module implementation
author jbe
date Thu Jun 11 21:17:29 2015 +0200 (2015-06-11)
parents d5b8295d035e
children 80266ee1593f
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 = assert(socket:drain_nb(input_chunk_size))
167 if status == "eof" then
168 consume = nil
169 end
170 end
171 local function unblock()
172 if consume then
173 poll(socket_set, socket_set)
174 consume()
175 else
176 poll(nil, socket_set)
177 end
178 end
179 local function consume_all()
180 while consume do
181 consume()
182 end
183 end
184 repeat
185 -- create a new request object:
186 local request = {
187 socket = socket,
188 cookies = {}
189 }
190 -- local variables to track the state:
191 local state = "init" -- one of:
192 -- "init" (initial state)
193 -- "no_status_sent" (configuration complete)
194 -- "info_status_sent" (1xx status code has been sent)
195 -- "bodyless_status_sent" (204/304 status code has been sent)
196 -- "status_sent" (regular status code has been sent)
197 -- "headers_sent" (headers have been terminated)
198 -- "finished" (request has been answered completely)
199 local close_requested = false -- "Connection: close" requested
200 local close_responded = false -- "Connection: close" sent
201 local content_length = nil -- value of Content-Length header sent
202 -- functions to send data to the browser:
203 local function send(...)
204 assert(socket:write_call(unblock, ...))
205 end
206 local function send_flush(...)
207 assert(socket:flush_call(unblock, ...))
208 end
209 -- TODO:
210 local function prepare()
211 if state == "prepare" then
212 error("Unexpected internal status in HTTP engine")
213 elseif state ~= "init" then
214 return
215 end
216 state = "prepare"
217 -- TODO
218 state = "no_status_sent"
219 end
220 -- TODO:
221 local function finish_response()
222 if close_responded then
223 -- discard any input:
224 consume = drain
225 -- close output stream:
226 send_flush()
227 assert(socket:finish())
228 -- wait for EOF of peer to avoid immediate TCP RST condition:
229 consume_all()
230 -- fully close socket:
231 --socket_closed = true -- avoid double close on error -- TODO
232 assert(socket:close())
233 else
234 assert(socket:flush())
235 consume_all()
236 end
237 end
238 -- method to send a HTTP response status (e.g. "200 OK"):
239 function request:send_status(status)
240 prepare()
241 if state == "info_status_sent" then
242 send_flush("\r\n")
243 elseif state ~= "no_status_sent" then
244 error("HTTP status has already been sent")
245 end
246 local status1 = string.sub(status, 1, 1)
247 local status3 = string.sub(status, 1, 3)
248 send("HTTP/1.1 ", status, "\r\n", preamble)
249 local wrb = status_without_response_body[status3]
250 if wrb then
251 state = "bodyless_status_sent"
252 if wrb == "zero_content_length" then
253 request:send_header("Content-Length", 0)
254 end
255 elseif status1 == "1" then
256 state = "info_status_sent"
257 else
258 state = "status_sent"
259 end
260 end
261 -- method to send a HTTP response header:
262 -- (key and value must be provided as separate args)
263 function request:send_header(key, value)
264 prepare()
265 if state == "no_status_sent" then
266 error("HTTP status has not been sent yet")
267 elseif
268 state ~= "info_status_sent" and
269 state ~= "bodyless_status_sent" and
270 state ~= "status_sent"
271 then
272 error("All HTTP headers have already been sent")
273 end
274 local key_lower = string.lower(key)
275 if key_lower == "content-length" then
276 if state == "info_status_sent" then
277 error("Cannot set Content-Length for informational status response")
278 end
279 local cl = assert(tonumber(value), "Invalid content-length")
280 if content_length == nil then
281 content_length = cl
282 elseif content_length == cl then
283 return
284 else
285 error("Content-Length has been set multiple times with different values")
286 end
287 elseif key_lower == "connection" then
288 for entry in string.gmatch(string.lower(value), "[^,]+") do
289 if string.match(entry, "^[ \t]*close[ \t]*$") then
290 if state == "info_status_sent" then
291 error("Cannot set \"Connection: close\" for informational status response")
292 end
293 close_responded = true
294 break
295 end
296 end
297 end
298 assert_output(socket:write(key, ": ", value, "\r\n"))
299 end
300 -- method to close connection after sending the response:
301 function request:close_after_finish()
302 prepare()
303 if
304 state == "headers_sent" or
305 state == "finished"
306 then
307 error("All HTTP headers have already been sent")
308 end
309 close_requested = true
310 end
311 -- function to terminate header section in response, optionally flushing:
312 -- (may be called multiple times unless response is finished)
313 local function finish_headers(with_flush)
314 if state == "finished" then
315 error("Response has already been finished")
316 elseif state == "info_status_sent" then
317 send_flush("\r\n")
318 state = "no_status_sent"
319 elseif state == "bodyless_status_sent" then
320 if close_requested and not close_responded then
321 request:send_header("Connection", "close")
322 end
323 send("\r\n")
324 --finish_response() -- TODO
325 state = "finished"
326 elseif state == "status_sent" then
327 if not content_length then
328 request:send_header("Transfer-Encoding", "chunked")
329 end
330 if close_requested and not close_responded then
331 request:send_header("Connection", "close")
332 end
333 send("\r\n")
334 if request.method == "HEAD" then
335 --finish_response() -- TODO
336 elseif with_flush then
337 send_flush()
338 end
339 state = "headers_sent"
340 elseif state ~= "headers_sent" then
341 error("HTTP status has not been sent yet")
342 end
343 end
344 -- method to finish and flush headers:
345 function request:finish_headers()
346 prepare()
347 finish_headers(true)
348 end
349 -- wait for input:
350 if not poll(socket_set, nil, request_idle_timeout) then
351 -- TODO: send error
352 return survive
353 end
354 until close_responded
355 return survive
356 end
357 end
359 return _M

Impressum / About Us