* luci/libs/http: remove left over field initialisation
[project/luci.git] / libs / http / luasrc / http / protocol.lua
index 08e8ba2..cb5f786 100644 (file)
@@ -15,9 +15,7 @@ $Id$
 
 module("luci.http.protocol", package.seeall)
 
-require("ltn12")
-require("luci.util")
-require("luci.http.protocol.filter")
+local ltn12 = require("luci.ltn12")
 
 HTTP_MAX_CONTENT      = 1024*4         -- 4 kB maximum content size
 HTTP_URLENC_MAXKEYLEN = 1024           -- maximum allowd size of urlencoded parameter names
@@ -25,14 +23,18 @@ HTTP_URLENC_MAXKEYLEN = 1024                -- maximum allowd size of urlencoded parameter nam
 
 -- Decode an urlencoded string.
 -- Returns the decoded value.
-function urldecode( str )
+function urldecode( str, no_plus )
 
        local function __chrdec( hex )
                return string.char( tonumber( hex, 16 ) )
        end
 
        if type(str) == "string" then
-               str = str:gsub( "+", " " ):gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec )
+               if not no_plus then
+                       str = str:gsub( "+", " " )
+               end
+
+               str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec )
        end
 
        return str
@@ -49,7 +51,7 @@ function urldecode_params( url, tbl )
                url = url:gsub( "^.+%?([^?]+)", "%1" )
        end
 
-       for i, pair in ipairs(luci.util.split( url, "[&;]+", nil, true )) do
+       for pair in url:gmatch( "[^&;]+" ) do
 
                -- find key and value
                local key = urldecode( pair:match("^([^=]+)")     )
@@ -85,7 +87,7 @@ function urlencode( str )
 
        if type(str) == "string" then
                str = str:gsub(
-                       "([^a-zA-Z0-9$_%-%.+!*'(),])",
+                       "([^a-zA-Z0-9$_%-%.%+!*'(),])",
                        __chrenc
                )
        end
@@ -109,15 +111,55 @@ function urlencode_params( tbl )
 end
 
 
+-- Parameter helper
+local function __initval( tbl, key )
+       local multival = ( key:sub( #key - 1, #key ) == "[]" )
+
+       if multival then
+               if type(tbl[key]) == "table" then
+                       table.insert( tbl[key], "" )
+               else
+                       tbl[key] = { "" }
+               end
+       else
+               tbl[key] = ""
+       end
+
+       return multival
+end
+
+local function __appendval( tbl, key, multival, chunk )
+       if multival then
+               tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk
+       else
+               tbl[key] = tbl[key] .. chunk
+       end
+end
+
+local function __finishval( tbl, key, multival, handler )
+       if handler then
+               if multival then
+                       tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] )
+               else
+                       tbl[key] = handler( tbl[key] )
+               end
+       end
+end
+
+
 -- Table of our process states
 local process_states = { }
 
 -- Extract "magic", the first line of a http message.
 -- Extracts the message type ("get", "post" or "response"), the requested uri
 -- or the status code if the line descripes a http response.
-process_states['magic'] = function( msg, chunk )
+process_states['magic'] = function( msg, chunk, err )
 
        if chunk ~= nil then
+               -- ignore empty lines before request
+               if #chunk == 0 then
+                       return true, nil
+               end
 
                -- Is it a request?
                local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$")
@@ -279,9 +321,9 @@ process_states['mime-headers'] = function( msg, chunk, filecb )
 
                                        -- Treat as form field
                                        else
-                                               msg.params[field] = ""
+                                               local mv = __initval( msg.params, field )
                                                msg._mimecallback = function(chunk,eof)
-                                                       msg.params[field] = msg.params[field] .. chunk
+                                                       __appendval( msg.params, field, mv, chunk )
                                                end
                                        end
 
@@ -424,7 +466,6 @@ process_states['urldecode-key'] = function( msg, chunk, filecb )
                                local key = urldecode( buffer:sub( 1, spos - 1 ) )
 
                                -- Prepare buffers
-                               msg.params[key]         = ""
                                msg._urldeclength   = msg._urldeclength + epos
                                msg._urldecbuffer   = buffer:sub( epos + 1, #buffer )
 
@@ -434,12 +475,13 @@ process_states['urldecode-key'] = function( msg, chunk, filecb )
                                                filecb( field, chunk, eof )
                                        end
                                else
+                                       local mv = __initval( msg.params, key )
                                        msg._urldeccallback = function( chunk, eof )
-                                               msg.params[key] = msg.params[key] .. chunk
+                                               __appendval( msg.params, key, mv, chunk )
 
                                                -- FIXME: Use a filter
                                                if eof then
-                                                       msg.params[key] = urldecode( msg.params[key] )
+                                                       __finishval( msg.params, key, mv, urldecode )
                                                end
                                        end
                                end
@@ -516,11 +558,41 @@ process_states['urldecode-value'] = function( msg, chunk, filecb )
                        return true
                end
        else
-               return nil, "Unexpected EOF"
+               -- Send EOF
+               msg._urldeccallback( "", true )
+               return false
        end
 end
 
 
+-- Creates a header source from a given socket
+function header_source( sock )
+       return ltn12.source.simplify( function()
+
+               local chunk, err, part = sock:receive("*l")
+
+               -- Line too long
+               if chunk == nil then
+                       if err ~= "timeout" then
+                               return nil, part
+                                       and "Line exceeds maximum allowed length"
+                                       or  "Unexpected EOF"
+                       else
+                               return nil, err
+                       end
+
+               -- Line ok
+               elseif chunk ~= nil then
+
+                       -- Strip trailing CR
+                       chunk = chunk:gsub("\r$","")
+
+                       return chunk, nil
+               end
+       end )
+end
+
+
 -- Decode MIME encoded data.
 function mimedecode_message_body( source, msg, filecb )
 
@@ -616,20 +688,6 @@ function urldecode_message_body( source, msg )
 end
 
 
--- Parse a http message
-function parse_message( data, filecb )
-
-       local reader  = _linereader( data, HTTP_MAX_READBUF )
-       local message = parse_message_header( reader )
-
-       if message then
-               parse_message_body( reader, message, filecb )
-       end
-
-       return message
-end
-
-
 -- Parse a http message header
 function parse_message_header( source )
 
@@ -672,7 +730,7 @@ function parse_message_header( source )
                                REQUEST_URI       = msg.request_uri;
                                SCRIPT_NAME       = msg.request_uri:gsub("?.+$","");
                                SCRIPT_FILENAME   = "";         -- XXX implement me
-                               SERVER_PROTOCOL   = "HTTP/" .. msg.http_version
+                               SERVER_PROTOCOL   = "HTTP/" .. string.format("%.1f", msg.http_version)
                        }
 
                        -- Populate HTTP_* environment variables
@@ -701,19 +759,6 @@ end
 
 -- Parse a http message body
 function parse_message_body( source, msg, filecb )
-
-       -- Install an additional filter if we're operating on chunked transfer
-       -- coding and client is HTTP/1.1 capable
-       if msg.http_version == 1.1 and
-          msg.headers['Transfer-Encoding'] and
-          msg.headers['Transfer-Encoding']:find("chunked")
-       then
-               source = ltn12.source.chain(
-                       source, luci.http.protocol.filter.decode_chunked
-               )
-       end
-
-
        -- Is it multipart/mime ?
        if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and
           msg.env.CONTENT_TYPE:match("^multipart/form%-data")
@@ -729,7 +774,7 @@ function parse_message_body( source, msg, filecb )
 
 
        -- Unhandled encoding
-       -- If a file callback is given then feed it line by line, else
+       -- If a file callback is given then feed it chunk by chunk, else
        -- store whole buffer in message.content
        else
 
@@ -769,3 +814,18 @@ function parse_message_body( source, msg, filecb )
                end
        end
 end
+
+-- Status codes
+statusmsg = {
+       [200] = "OK",
+       [301] = "Moved Permanently",
+       [304] = "Not Modified",
+       [400] = "Bad Request",
+       [403] = "Forbidden",
+       [404] = "Not Found",
+       [405] = "Method Not Allowed",
+       [411] = "Length Required",
+       [412] = "Precondition Failed",
+       [500] = "Internal Server Error",
+       [503] = "Server Unavailable",
+}