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