af79695244088c9e457b89768f92a943613fb609
[project/luci.git] / libs / luci-lib-httpclient / luasrc / httpclient.lua
1 -- Copyright 2009 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 require "nixio.util"
5 local nixio = require "nixio"
6
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"
12
13 local type, pairs, ipairs, tonumber = type, pairs, ipairs, tonumber
14 local unpack = unpack
15
16 module "luci.httpclient"
17
18 function chunksource(sock, buffer)
19         buffer = buffer or ""
20         return function()
21                 local output
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)
25                         if not newblock then
26                                 return nil, code
27                         end
28                         buffer = buffer .. newblock  
29                         _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
30                 end
31                 count = tonumber(count, 16)
32                 if not count then
33                         return nil, -1, "invalid encoding"
34                 elseif count == 0 then
35                         return nil
36                 elseif count + 2 <= #buffer - endp then
37                         output = buffer:sub(endp+1, endp+count)
38                         buffer = buffer:sub(endp+count+3)
39                         return output
40                 else
41                         output = buffer:sub(endp+1, endp+count)
42                         buffer = ""
43                         if count - #output > 0 then
44                                 local remain, code = sock:recvall(count-#output)
45                                 if not remain then
46                                         return nil, code
47                                 end
48                                 output = output .. remain
49                                 count, code = sock:recvall(2)
50                         else
51                                 count, code = sock:recvall(count+2-#buffer+endp)
52                         end
53                         if not count then
54                                 return nil, code
55                         end
56                         return output
57                 end
58         end
59 end
60
61
62 function request_to_buffer(uri, options)
63         local source, code, msg = request_to_source(uri, options)
64         local output = {}
65         
66         if not source then
67                 return nil, code, msg
68         end
69         
70         source, code = ltn12.pump.all(source, (ltn12.sink.table(output)))
71         
72         if not source then
73                 return nil, code
74         end
75         
76         return table.concat(output)
77 end
78
79 function request_to_source(uri, options)
80         local status, response, buffer, sock = request_raw(uri, options)
81         if not status then
82                 return status, response, buffer
83         elseif status ~= 200 and status ~= 206 then
84                 return nil, status, buffer
85         end
86         
87         if response.headers["Transfer-Encoding"] == "chunked" then
88                 return chunksource(sock, buffer)
89         else
90                 return ltn12.source.cat(ltn12.source.string(buffer), sock:blocksource())
91         end
92 end
93
94 --
95 -- GET HTTP-resource
96 --
97 function request_raw(uri, options)
98         options = options or {}
99         local pr, auth, host, port, path
100         
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)
105                 else
106                         pr, host, port, path = uri:match("(%w+)://(%b[]):?([0-9]*)(.*)")
107                         host = host:sub(2,-2)
108                 end
109         else
110                 if uri:find("@") then
111                         pr, auth, host, port, path =
112                                 uri:match("(%w+)://(.+)@([%w-.]+):?([0-9]*)(.*)")
113                 else
114                         pr, host, port, path = uri:match("(%w+)://([%w-.]+):?([0-9]*)(.*)")
115                 end
116         end
117
118         if not host then
119                 return nil, -1, "unable to parse URI"
120         end
121         
122         if pr ~= "http" and pr ~= "https" then
123                 return nil, -2, "protocol not supported"
124         end
125         
126         port = #port > 0 and port or (pr == "https" and 443 or 80)
127         path = #path > 0 and path or "/"
128         
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"
133         
134         if headers.Connection == nil then
135                 headers.Connection = "close"
136         end
137         
138         if auth and not headers.Authorization then
139                 headers.Authorization = "Basic " .. nixio.bin.b64encode(auth)
140         end
141
142         local sock, code, msg = nixio.connect(host, port)
143         if not sock then
144                 return nil, code, msg
145         end
146         
147         sock:setsockopt("socket", "sndtimeo", options.sndtimeo or 15)
148         sock:setsockopt("socket", "rcvtimeo", options.rcvtimeo or 15)
149         
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()
154                 if not stat then
155                         return stat, code, error
156                 end
157         end
158
159         -- Pre assemble fixes   
160         if protocol == "HTTP/1.1" then
161                 headers.Host = headers.Host or host
162         end
163         
164         if type(options.body) == "table" then
165                 options.body = http.urlencode_params(options.body)
166         end
167
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"
173         end
174         
175         if type(options.body) == "function" then
176                 options.method = options.method or "POST"
177         end
178
179         if options.cookies then
180                 local cookiedata = {}
181                 for _, c in ipairs(options.cookies) do
182                         local cdo = c.flags.domain
183                         local cpa = c.flags.path
184                         if   (cdo == host or cdo == "."..host or host:sub(-#cdo) == cdo) 
185                          and (cpa == path or cpa == "/" or cpa .. "/" == path:sub(#cpa+1))
186                          and (not c.flags.secure or pr == "https")
187                         then
188                                 cookiedata[#cookiedata+1] = c.key .. "=" .. c.value
189                         end 
190                 end
191                 if headers["Cookie"] then
192                         headers["Cookie"] = headers["Cookie"] .. "; " .. table.concat(cookiedata, "; ")
193                 else
194                         headers["Cookie"] = table.concat(cookiedata, "; ")
195                 end
196         end
197
198         -- Assemble message
199         local message = {(options.method or "GET") .. " " .. path .. " " .. protocol}
200         
201         for k, v in pairs(headers) do
202                 if type(v) == "string" or type(v) == "number" then
203                         message[#message+1] = k .. ": " .. v
204                 elseif type(v) == "table" then
205                         for i, j in ipairs(v) do
206                                 message[#message+1] = k .. ": " .. j
207                         end
208                 end
209         end
210
211         message[#message+1] = ""
212         message[#message+1] = ""
213         
214         -- Send request
215         sock:sendall(table.concat(message, "\r\n"))
216         
217         if type(options.body) == "string" then
218                 sock:sendall(options.body)
219         elseif type(options.body) == "function" then
220                 local res = {options.body(sock)}
221                 if not res[1] then
222                         sock:close()
223                         return unpack(res)
224                 end
225         end
226         
227         -- Create source and fetch response
228         local linesrc = sock:linesource()
229         local line, code, error = linesrc()
230         
231         if not line then
232                 sock:close()
233                 return nil, code, error
234         end
235         
236         local protocol, status, msg = line:match("^([%w./]+) ([0-9]+) (.*)")
237         
238         if not protocol then
239                 sock:close()
240                 return nil, -3, "invalid response magic: " .. line
241         end
242         
243         local response = {
244                 status = line, headers = {}, code = 0, cookies = {}, uri = uri
245         }
246         
247         line = linesrc()
248         while line and line ~= "" do
249                 local key, val = line:match("^([%w-]+)%s?:%s?(.*)")
250                 if key and key ~= "Status" then
251                         if type(response.headers[key]) == "string" then
252                                 response.headers[key] = {response.headers[key], val}
253                         elseif type(response.headers[key]) == "table" then
254                                 response.headers[key][#response.headers[key]+1] = val
255                         else
256                                 response.headers[key] = val
257                         end
258                 end
259                 line = linesrc()
260         end
261         
262         if not line then
263                 sock:close()
264                 return nil, -4, "protocol error"
265         end
266         
267         -- Parse cookies
268         if response.headers["Set-Cookie"] then
269                 local cookies = response.headers["Set-Cookie"]
270                 for _, c in ipairs(type(cookies) == "table" and cookies or {cookies}) do
271                         local cobj = cookie_parse(c)
272                         cobj.flags.path = cobj.flags.path or path:match("(/.*)/?[^/]*")
273                         if not cobj.flags.domain or cobj.flags.domain == "" then
274                                 cobj.flags.domain = host
275                                 response.cookies[#response.cookies+1] = cobj
276                         else
277                                 local hprt, cprt = {}, {}
278                                 
279                                 -- Split hostnames and save them in reverse order
280                                 for part in host:gmatch("[^.]*") do
281                                         table.insert(hprt, 1, part)
282                                 end
283                                 for part in cobj.flags.domain:gmatch("[^.]*") do
284                                         table.insert(cprt, 1, part)
285                                 end
286                                 
287                                 local valid = true
288                                 for i, part in ipairs(cprt) do
289                                         -- If parts are different and no wildcard
290                                         if hprt[i] ~= part and #part ~= 0 then
291                                                 valid = false
292                                                 break
293                                         -- Wildcard on invalid position
294                                         elseif hprt[i] ~= part and #part == 0 then
295                                                 if i ~= #cprt or (#hprt ~= i and #hprt+1 ~= i) then
296                                                         valid = false
297                                                         break
298                                                 end
299                                         end
300                                 end
301                                 -- No TLD cookies
302                                 if valid and #cprt > 1 and #cprt[2] > 0 then
303                                         response.cookies[#response.cookies+1] = cobj
304                                 end
305                         end
306                 end
307         end
308         
309         -- Follow 
310         response.code = tonumber(status)
311         if response.code and options.depth > 0 then
312                 if (response.code == 301 or response.code == 302 or response.code == 307)
313                  and response.headers.Location then
314                         local nuri = response.headers.Location or response.headers.location
315                         if not nuri then
316                                 return nil, -5, "invalid reference"
317                         end
318                         if not nuri:find("https?://") then
319                                 nuri = pr .. "://" .. host .. ":" .. port .. nuri
320                         end
321                         
322                         options.depth = options.depth - 1
323                         if options.headers then
324                                 options.headers.Host = nil
325                         end
326                         sock:close()
327                         
328                         return request_raw(nuri, options)
329                 end
330         end
331         
332         return response.code, response, linesrc(true)..sock:readall(), sock
333 end
334
335 function cookie_parse(cookiestr)
336         local key, val, flags = cookiestr:match("%s?([^=;]+)=?([^;]*)(.*)")
337         if not key then
338                 return nil
339         end
340
341         local cookie = {key = key, value = val, flags = {}}
342         for fkey, fval in flags:gmatch(";%s?([^=;]+)=?([^;]*)") do
343                 fkey = fkey:lower()
344                 if fkey == "expires" then
345                         fval = date.to_unix(fval:gsub("%-", " "))
346                 end
347                 cookie.flags[fkey] = fval
348         end
349
350         return cookie
351 end
352
353 function cookie_create(cookie)
354         local cookiedata = {cookie.key .. "=" .. cookie.value}
355
356         for k, v in pairs(cookie.flags) do
357                 if k == "expires" then
358                         v = date.to_http(v):gsub(", (%w+) (%w+) (%w+) ", ", %1-%2-%3 ")
359                 end
360                 cookiedata[#cookiedata+1] = k .. ((#v > 0) and ("=" .. v) or "")
361         end
362
363         return table.concat(cookiedata, "; ")
364 end