1 -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
2 -- Licensed to the public under the Apache License 2.0.
4 -- This class contains several functions useful for http message- and content
5 -- decoding and to retrive form data from raw http messages.
6 module("luci.http.protocol", package.seeall)
8 local ltn12 = require("luci.ltn12")
10 HTTP_MAX_CONTENT = 1024*8 -- 8 kB maximum content size
12 -- the "+" sign to " " - and return the decoded string.
13 function urldecode( str, no_plus )
15 local function __chrdec( hex )
16 return string.char( tonumber( hex, 16 ) )
19 if type(str) == "string" then
21 str = str:gsub( "+", " " )
24 str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec )
30 -- from given url or string. Returns a table with urldecoded values.
31 -- Simple parameters are stored as string values associated with the parameter
32 -- name within the table. Parameters with multiple values are stored as array
33 -- containing the corresponding values.
34 function urldecode_params( url, tbl )
36 local params = tbl or { }
39 url = url:gsub( "^.+%?([^?]+)", "%1" )
42 for pair in url:gmatch( "[^&;]+" ) do
45 local key = urldecode( pair:match("^([^=]+)") )
46 local val = urldecode( pair:match("^[^=]+=(.+)$") )
49 if type(key) == "string" and key:len() > 0 then
50 if type(val) ~= "string" then val = "" end
52 if not params[key] then
54 elseif type(params[key]) ~= "table" then
55 params[key] = { params[key], val }
57 table.insert( params[key], val )
65 function urlencode( str )
67 local function __chrenc( chr )
69 "%%%02x", string.byte( chr )
73 if type(str) == "string" then
75 "([^a-zA-Z0-9$_%-%.!*'(),])",
83 -- separated by "&". Tables are encoded as parameters with multiple values by
84 -- repeating the parameter name with each value.
85 function urlencode_params( tbl )
88 for k, v in pairs(tbl) do
89 if type(v) == "table" then
90 for i, v2 in ipairs(v) do
91 enc = enc .. ( #enc > 0 and "&" or "" ) ..
92 urlencode(k) .. "=" .. urlencode(v2)
95 enc = enc .. ( #enc > 0 and "&" or "" ) ..
96 urlencode(k) .. "=" .. urlencode(v)
103 -- (Internal function)
104 -- Initialize given parameter and coerce string into table when the parameter
106 local function __initval( tbl, key )
107 if tbl[key] == nil then
109 elseif type(tbl[key]) == "string" then
110 tbl[key] = { tbl[key], "" }
112 table.insert( tbl[key], "" )
116 -- (Internal function)
117 -- Append given data to given parameter, either by extending the string value
118 -- or by appending it to the last string in the parameter's value table.
119 local function __appendval( tbl, key, chunk )
120 if type(tbl[key]) == "table" then
121 tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk
123 tbl[key] = tbl[key] .. chunk
127 -- (Internal function)
128 -- Finish the value of given parameter, either by transforming the string value
129 -- or - in the case of multi value parameters - the last element in the
130 -- associated values table.
131 local function __finishval( tbl, key, handler )
133 if type(tbl[key]) == "table" then
134 tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] )
136 tbl[key] = handler( tbl[key] )
142 -- Table of our process states
143 local process_states = { }
145 -- Extract "magic", the first line of a http message.
146 -- Extracts the message type ("get", "post" or "response"), the requested uri
147 -- or the status code if the line descripes a http response.
148 process_states['magic'] = function( msg, chunk, err )
151 -- ignore empty lines before request
157 local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$")
163 msg.request_method = method:lower()
164 msg.request_uri = uri
165 msg.http_version = tonumber( http_ver )
168 -- We're done, next state is header parsing
169 return true, function( chunk )
170 return process_states['headers']( msg, chunk )
176 local http_ver, code, message = chunk:match("^HTTP/([01]%.[019]) ([0-9]+) ([^\r\n]+)$")
181 msg.type = "response"
182 msg.status_code = code
183 msg.status_message = message
184 msg.http_version = tonumber( http_ver )
187 -- We're done, next state is header parsing
188 return true, function( chunk )
189 return process_states['headers']( msg, chunk )
196 return nil, "Invalid HTTP message magic"
200 -- Extract headers from given string.
201 process_states['headers'] = function( msg, chunk )
205 -- Look for a valid header format
206 local hdr, val = chunk:match( "^([A-Za-z][A-Za-z0-9%-_]+): +(.+)$" )
208 if type(hdr) == "string" and hdr:len() > 0 and
209 type(val) == "string" and val:len() > 0
211 msg.headers[hdr] = val
213 -- Valid header line, proceed
216 elseif #chunk == 0 then
217 -- Empty line, we won't accept data anymore
221 return nil, "Invalid HTTP header received"
224 return nil, "Unexpected EOF"
229 -- data line by line with the trailing \r\n stripped of.
230 function header_source( sock )
231 return ltn12.source.simplify( function()
233 local chunk, err, part = sock:receive("*l")
237 if err ~= "timeout" then
239 and "Line exceeds maximum allowed length"
246 elseif chunk ~= nil then
249 chunk = chunk:gsub("\r$","")
256 -- Content-Type. Stores all extracted data associated with its parameter name
257 -- in the params table withing the given message object. Multiple parameter
258 -- values are stored as tables, ordinary ones as strings.
259 -- If an optional file callback function is given then it is feeded with the
260 -- file contents chunk by chunk and only the extracted file name is stored
261 -- within the params table. The callback function will be called subsequently
262 -- with three arguments:
263 -- o Table containing decoded (name, file) and raw (headers) mime header data
264 -- o String value containing a chunk of the file data
265 -- o Boolean which indicates wheather the current chunk is the last one (eof)
266 function mimedecode_message_body( src, msg, filecb )
268 if msg and msg.env.CONTENT_TYPE then
269 msg.mime_boundary = msg.env.CONTENT_TYPE:match("^multipart/form%-data; boundary=(.+)$")
272 if not msg.mime_boundary then
273 return nil, "Invalid Content-Type found"
283 local function parse_headers( chunk, field )
287 chunk, stat = chunk:gsub(
288 "^([A-Z][A-Za-z0-9%-_]+): +([^\r\n]+)\r\n",
296 chunk, stat = chunk:gsub("^\r\n","")
300 if field.headers["Content-Disposition"] then
301 if field.headers["Content-Disposition"]:match("^form%-data; ") then
302 field.name = field.headers["Content-Disposition"]:match('name="(.-)"')
303 field.file = field.headers["Content-Disposition"]:match('filename="(.+)"$')
307 if not field.headers["Content-Type"] then
308 field.headers["Content-Type"] = "text/plain"
311 if field.name and field.file and filecb then
312 __initval( msg.params, field.name )
313 __appendval( msg.params, field.name, field.file )
316 elseif field.name then
317 __initval( msg.params, field.name )
319 store = function( hdr, buf, eof )
320 __appendval( msg.params, field.name, buf )
332 local function snk( chunk )
334 tlen = tlen + ( chunk and #chunk or 0 )
336 if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then
337 return nil, "Message body size exceeds Content-Length"
340 if chunk and not lchunk then
341 lchunk = "\r\n" .. chunk
344 local data = lchunk .. ( chunk or "" )
345 local spos, epos, found
348 spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "\r\n", 1, true )
351 spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "--\r\n", 1, true )
356 local predata = data:sub( 1, spos - 1 )
359 predata, eof = parse_headers( predata, field )
362 return nil, "Invalid MIME section header"
363 elseif not field.name then
364 return nil, "Invalid Content-Disposition header"
369 store( field, predata, true )
373 field = { headers = { } }
374 found = found or true
376 data, eof = parse_headers( data:sub( epos + 1, #data ), field )
382 -- We found at least some boundary. Save
383 -- the unparsed remaining data for the
385 lchunk, data = data, nil
387 -- There was a complete chunk without a boundary. Parse it as headers or
388 -- append it as data, depending on our current state.
390 lchunk, eof = parse_headers( data, field )
393 -- We're inside data, so append the data. Note that we only append
394 -- lchunk, not all of data, since there is a chance that chunk
395 -- contains half a boundary. Assuming that each chunk is at least the
396 -- boundary in size, this should prevent problems
397 store( field, lchunk, false )
398 lchunk, chunk = chunk, nil
406 return ltn12.pump.all( src, snk )
409 -- Content-Type. Stores all extracted data associated with its parameter name
410 -- in the params table withing the given message object. Multiple parameter
411 -- values are stored as tables, ordinary ones as strings.
412 function urldecode_message_body( src, msg )
417 local function snk( chunk )
419 tlen = tlen + ( chunk and #chunk or 0 )
421 if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then
422 return nil, "Message body size exceeds Content-Length"
423 elseif tlen > HTTP_MAX_CONTENT then
424 return nil, "Message body size exceeds maximum allowed length"
427 if not lchunk and chunk then
431 local data = lchunk .. ( chunk or "&" )
435 spos, epos = data:find("^.-[;&]")
438 local pair = data:sub( spos, epos - 1 )
439 local key = pair:match("^(.-)=")
440 local val = pair:match("=([^%s]*)%s*$")
442 if key and #key > 0 then
443 __initval( msg.params, key )
444 __appendval( msg.params, key, val )
445 __finishval( msg.params, key, urldecode )
448 data = data:sub( epos + 1, #data )
458 return ltn12.pump.all( src, snk )
461 -- version, message headers and resulting CGI environment variables from the
462 -- given ltn12 source.
463 function parse_message_header( src )
468 local sink = ltn12.sink.simplify(
470 return process_states['magic']( msg, chunk )
474 -- Pump input data...
478 ok, err = ltn12.pump.step( src, sink )
481 if not ok and err then
487 -- Process get parameters
488 if ( msg.request_method == "get" or msg.request_method == "post" ) and
489 msg.request_uri:match("?")
491 msg.params = urldecode_params( msg.request_uri )
496 -- Populate common environment variables
498 CONTENT_LENGTH = msg.headers['Content-Length'];
499 CONTENT_TYPE = msg.headers['Content-Type'] or msg.headers['Content-type'];
500 REQUEST_METHOD = msg.request_method:upper();
501 REQUEST_URI = msg.request_uri;
502 SCRIPT_NAME = msg.request_uri:gsub("?.+$","");
503 SCRIPT_FILENAME = ""; -- XXX implement me
504 SERVER_PROTOCOL = "HTTP/" .. string.format("%.1f", msg.http_version);
505 QUERY_STRING = msg.request_uri:match("?")
506 and msg.request_uri:gsub("^.+?","") or ""
509 -- Populate HTTP_* environment variables
510 for i, hdr in ipairs( {
521 local var = 'HTTP_' .. hdr:upper():gsub("%-","_")
522 local val = msg.headers[hdr]
532 -- This function will examine the Content-Type within the given message object
533 -- to select the appropriate content decoder.
534 -- Currently the application/x-www-urlencoded and application/form-data
535 -- mime types are supported. If the encountered content encoding can't be
536 -- handled then the whole message body will be stored unaltered as "content"
537 -- property within the given message object.
538 function parse_message_body( src, msg, filecb )
539 -- Is it multipart/mime ?
540 if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and
541 msg.env.CONTENT_TYPE:match("^multipart/form%-data")
544 return mimedecode_message_body( src, msg, filecb )
546 -- Is it application/x-www-form-urlencoded ?
547 elseif msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and
548 msg.env.CONTENT_TYPE:match("^application/x%-www%-form%-urlencoded")
550 return urldecode_message_body( src, msg, filecb )
553 -- Unhandled encoding
554 -- If a file callback is given then feed it chunk by chunk, else
555 -- store whole buffer in message.content
560 -- If we have a file callback then feed it
561 if type(filecb) == "function" then
564 -- ... else append to .content
567 msg.content_length = 0
569 sink = function( chunk, err )
571 if ( msg.content_length + #chunk ) <= HTTP_MAX_CONTENT then
572 msg.content = msg.content .. chunk
573 msg.content_length = msg.content_length + #chunk
576 return nil, "POST data exceeds maximum allowed length"
585 local ok, err = ltn12.pump.step( src, sink )
587 if not ok and err then
589 elseif not ok then -- eof
600 [206] = "Partial Content",
601 [301] = "Moved Permanently",
603 [304] = "Not Modified",
604 [400] = "Bad Request",
607 [405] = "Method Not Allowed",
608 [408] = "Request Time-out",
609 [411] = "Length Required",
610 [412] = "Precondition Failed",
611 [416] = "Requested range not satisfiable",
612 [500] = "Internal Server Error",
613 [503] = "Server Unavailable",