1 -- Copyright 2009 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
5 local nixio = require "nixio"
7 local ltn12 = require "luci.ltn12"
8 local util = require "luci.util"
9 local table = require "table"
10 local http = require "luci.http.protocol"
11 local date = require "luci.http.protocol.date"
13 local type, pairs, ipairs, tonumber = type, pairs, ipairs, tonumber
16 module "luci.httpclient"
18 function chunksource(sock, buffer)
22 local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
23 while not count and #buffer <= 1024 do
24 local newblock, code = sock:recv(1024 - #buffer)
28 buffer = buffer .. newblock
29 _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
31 count = tonumber(count, 16)
33 return nil, -1, "invalid encoding"
34 elseif count == 0 then
36 elseif count + 2 <= #buffer - endp then
37 output = buffer:sub(endp+1, endp+count)
38 buffer = buffer:sub(endp+count+3)
41 output = buffer:sub(endp+1, endp+count)
43 if count - #output > 0 then
44 local remain, code = sock:recvall(count-#output)
48 output = output .. remain
49 count, code = sock:recvall(2)
51 count, code = sock:recvall(count+2-#buffer+endp)
62 function request_to_buffer(uri, options)
63 local source, code, msg = request_to_source(uri, options)
70 source, code = ltn12.pump.all(source, (ltn12.sink.table(output)))
76 return table.concat(output)
79 function request_to_source(uri, options)
80 local status, response, buffer, sock = request_raw(uri, options)
82 return status, response, buffer
83 elseif status ~= 200 and status ~= 206 then
84 return nil, status, buffer
87 if response.headers["Transfer-Encoding"] == "chunked" then
88 return chunksource(sock, buffer)
90 return ltn12.source.cat(ltn12.source.string(buffer), sock:blocksource())
97 function request_raw(uri, options)
98 options = options or {}
99 local pr, auth, host, port, path
101 if uri:find("%[") then
102 if uri:find("@") then
103 pr, auth, host, port, path = uri:match("(%w+)://(.+)@(%b[]):?([0-9]*)(.*)")
104 host = host:sub(2,-2)
106 pr, host, port, path = uri:match("(%w+)://(%b[]):?([0-9]*)(.*)")
107 host = host:sub(2,-2)
110 if uri:find("@") then
111 pr, auth, host, port, path =
112 uri:match("(%w+)://(.+)@([%w-.]+):?([0-9]*)(.*)")
114 pr, host, port, path = uri:match("(%w+)://([%w-.]+):?([0-9]*)(.*)")
119 return nil, -1, "unable to parse URI"
122 if pr ~= "http" and pr ~= "https" then
123 return nil, -2, "protocol not supported"
126 port = #port > 0 and port or (pr == "https" and 443 or 80)
127 path = #path > 0 and path or "/"
129 options.depth = options.depth or 10
130 local headers = options.headers or {}
131 local protocol = options.protocol or "HTTP/1.1"
132 headers["User-Agent"] = headers["User-Agent"] or "LuCI httpclient 0.1"
134 if headers.Connection == nil then
135 headers.Connection = "close"
138 if auth and not headers.Authorization then
139 headers.Authorization = "Basic " .. nixio.bin.b64encode(auth)
142 local sock, code, msg = nixio.connect(host, port)
144 return nil, code, msg
147 sock:setsockopt("socket", "sndtimeo", options.sndtimeo or 15)
148 sock:setsockopt("socket", "rcvtimeo", options.rcvtimeo or 15)
150 if pr == "https" then
151 local tls = options.tls_context or nixio.tls()
152 sock = tls:create(sock)
153 local stat, code, error = sock:connect()
155 return stat, code, error
159 -- Pre assemble fixes
160 if protocol == "HTTP/1.1" then
161 headers.Host = headers.Host or host
164 if type(options.body) == "table" then
165 options.body = http.urlencode_params(options.body)
168 if type(options.body) == "string" then
169 headers["Content-Length"] = headers["Content-Length"] or #options.body
170 headers["Content-Type"] = headers["Content-Type"] or
171 "application/x-www-form-urlencoded"
172 options.method = options.method or "POST"
175 if type(options.body) == "function" then
176 options.method = options.method or "POST"
180 local message = {(options.method or "GET") .. " " .. path .. " " .. protocol}
182 for k, v in pairs(headers) do
183 if type(v) == "string" or type(v) == "number" then
184 message[#message+1] = k .. ": " .. v
185 elseif type(v) == "table" then
186 for i, j in ipairs(v) do
187 message[#message+1] = k .. ": " .. j
192 if options.cookies then
193 for _, c in ipairs(options.cookies) do
194 local cdo = c.flags.domain
195 local cpa = c.flags.path
196 if (cdo == host or cdo == "."..host or host:sub(-#cdo) == cdo)
197 and (cpa == path or cpa == "/" or cpa .. "/" == path:sub(#cpa+1))
198 and (not c.flags.secure or pr == "https")
200 message[#message+1] = "Cookie: " .. c.key .. "=" .. c.value
205 message[#message+1] = ""
206 message[#message+1] = ""
209 sock:sendall(table.concat(message, "\r\n"))
211 if type(options.body) == "string" then
212 sock:sendall(options.body)
213 elseif type(options.body) == "function" then
214 local res = {options.body(sock)}
221 -- Create source and fetch response
222 local linesrc = sock:linesource()
223 local line, code, error = linesrc()
227 return nil, code, error
230 local protocol, status, msg = line:match("^([%w./]+) ([0-9]+) (.*)")
234 return nil, -3, "invalid response magic: " .. line
238 status = line, headers = {}, code = 0, cookies = {}, uri = uri
242 while line and line ~= "" do
243 local key, val = line:match("^([%w-]+)%s?:%s?(.*)")
244 if key and key ~= "Status" then
245 if type(response.headers[key]) == "string" then
246 response.headers[key] = {response.headers[key], val}
247 elseif type(response.headers[key]) == "table" then
248 response.headers[key][#response.headers[key]+1] = val
250 response.headers[key] = val
258 return nil, -4, "protocol error"
262 if response.headers["Set-Cookie"] then
263 local cookies = response.headers["Set-Cookie"]
264 for _, c in ipairs(type(cookies) == "table" and cookies or {cookies}) do
265 local cobj = cookie_parse(c)
266 cobj.flags.path = cobj.flags.path or path:match("(/.*)/?[^/]*")
267 if not cobj.flags.domain or cobj.flags.domain == "" then
268 cobj.flags.domain = host
269 response.cookies[#response.cookies+1] = cobj
271 local hprt, cprt = {}, {}
273 -- Split hostnames and save them in reverse order
274 for part in host:gmatch("[^.]*") do
275 table.insert(hprt, 1, part)
277 for part in cobj.flags.domain:gmatch("[^.]*") do
278 table.insert(cprt, 1, part)
282 for i, part in ipairs(cprt) do
283 -- If parts are different and no wildcard
284 if hprt[i] ~= part and #part ~= 0 then
287 -- Wildcard on invalid position
288 elseif hprt[i] ~= part and #part == 0 then
289 if i ~= #cprt or (#hprt ~= i and #hprt+1 ~= i) then
296 if valid and #cprt > 1 and #cprt[2] > 0 then
297 response.cookies[#response.cookies+1] = cobj
304 response.code = tonumber(status)
305 if response.code and options.depth > 0 then
306 if (response.code == 301 or response.code == 302 or response.code == 307)
307 and response.headers.Location then
308 local nuri = response.headers.Location or response.headers.location
310 return nil, -5, "invalid reference"
312 if not nuri:find("https?://") then
313 nuri = pr .. "://" .. host .. ":" .. port .. nuri
316 options.depth = options.depth - 1
317 if options.headers then
318 options.headers.Host = nil
322 return request_raw(nuri, options)
326 return response.code, response, linesrc(true)..sock:readall(), sock
329 function cookie_parse(cookiestr)
330 local key, val, flags = cookiestr:match("%s?([^=;]+)=?([^;]*)(.*)")
335 local cookie = {key = key, value = val, flags = {}}
336 for fkey, fval in flags:gmatch(";%s?([^=;]+)=?([^;]*)") do
338 if fkey == "expires" then
339 fval = date.to_unix(fval:gsub("%-", " "))
341 cookie.flags[fkey] = fval
347 function cookie_create(cookie)
348 local cookiedata = {cookie.key .. "=" .. cookie.value}
350 for k, v in pairs(cookie.flags) do
351 if k == "expires" then
352 v = date.to_http(v):gsub(", (%w+) (%w+) (%w+) ", ", %1-%2-%3 ")
354 cookiedata[#cookiedata+1] = k .. ((#v > 0) and ("=" .. v) or "")
357 return table.concat(cookiedata, "; ")