Debian Codegraph @

texk/web2c/luatexdir/luasocket/src/http.lua

raw symbols SCIP
1 -----------------------------------------------------------------------------
2 -- HTTP/1.1 client support for the Lua language.
3 -- LuaSocket toolkit.
4 -- Author: Diego Nehab
5 -----------------------------------------------------------------------------
6
7 -----------------------------------------------------------------------------
8 -- Declare module and import dependencies
9 -------------------------------------------------------------------------------
10 local socket = socket or require("socket")
11 local url = socket.url or require("socket.url")
12 local ltn12 = ltn12 or require("ltn12")
13 local mime = mime or require("mime")
14 local string = require("string")
15 local headers = socket.headers or require("socket.headers")
16 local base = _G
17 local table = require("table")
18 socket.http = {}
19 local _M = socket.http
20 module("socket.http")
21
22 -----------------------------------------------------------------------------
23 -- Program constants
24 -----------------------------------------------------------------------------
25 -- connection timeout in seconds
26 _M.TIMEOUT = 60
27 -- user agent field sent in request
28 _M.USERAGENT = socket._VERSION
29
30 -- supported schemes
31 local SCHEMES = { ["http"] = true }
32 -- default port for document retrieval
33 local PORT = 80
34
35 -----------------------------------------------------------------------------
36 -- Reads MIME headers from a connection, unfolding where needed
37 -----------------------------------------------------------------------------
38 local function receiveheaders(sock, headers)
39 local line, name, value, err
40 headers = headers or {}
41 -- get first line
42 line, err = sock:receive()
43 if err then return nil, err end
44 -- headers go until a blank line is found
45 while line ~= "" do
46 -- get field-name and value
47 name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)"))
48 if not (name and value) then return nil, "malformed reponse headers" end
49 name = string.lower(name)
50 -- get next line (value might be folded)
51 line, err = sock:receive()
52 if err then return nil, err end
53 -- unfold any folded values
54 while string.find(line, "^%s") do
55 value = value .. line
56 line = sock:receive()
57 if err then return nil, err end
58 end
59 -- save pair in table
60 if headers[name] then headers[name] = headers[name] .. ", " .. value
61 else headers[name] = value end
62 end
63 return headers
64 end
65
66 -----------------------------------------------------------------------------
67 -- Extra sources and sinks
68 -----------------------------------------------------------------------------
69 socket.sourcet["http-chunked"] = function(sock, headers)
70 return base.setmetatable({
71 getfd = function() return sock:getfd() end,
72 dirty = function() return sock:dirty() end
73 }, {
74 __call = function()
75 -- get chunk size, skip extention
76 local line, err = sock:receive()
77 if err then return nil, err end
78 local size = base.tonumber(string.gsub(line, ";.*", ""), 16)
79 if not size then return nil, "invalid chunk size" end
80 -- was it the last chunk?
81 if size > 0 then
82 -- if not, get chunk and skip terminating CRLF
83 local chunk, err, part = sock:receive(size)
84 if chunk then sock:receive() end
85 return chunk, err
86 else
87 -- if it was, read trailers into headers table
88 headers, err = receiveheaders(sock, headers)
89 if not headers then return nil, err end
90 end
91 end
92 })
93 end
94
95 socket.sinkt["http-chunked"] = function(sock)
96 return base.setmetatable({
97 getfd = function() return sock:getfd() end,
98 dirty = function() return sock:dirty() end
99 }, {
100 __call = function(self, chunk, err)
101 if not chunk then return sock:send("0\r\n\r\n") end
102 local size = string.format("%X\r\n", string.len(chunk))
103 return sock:send(size .. chunk .. "\r\n")
104 end
105 })
106 end
107
108 -----------------------------------------------------------------------------
109 -- Low level HTTP API
110 -----------------------------------------------------------------------------
111 local metat = { __index = {} }
112
113 function _M.open(host, port, create)
114 -- create socket with user connect function, or with default
115 local c = socket.try((create or socket.tcp)())
116 local h = base.setmetatable({ c = c }, metat)
117 -- create finalized try
118 h.try = socket.newtry(function() h:close() end)
119 -- set timeout before connecting
120 h.try(c:settimeout(_M.TIMEOUT))
121 h.try(c:connect(host, port or PORT))
122 -- here everything worked
123 return h
124 end
125
126 function metat.__index:sendrequestline(method, uri)
127 local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri)
128 return self.try(self.c:send(reqline))
129 end
130
131 function metat.__index:sendheaders(tosend)
132 local canonic = headers.canonic
133 local h = "\r\n"
134 for f, v in base.pairs(tosend) do
135 h = (canonic[f] or f) .. ": " .. v .. "\r\n" .. h
136 end
137 self.try(self.c:send(h))
138 return 1
139 end
140
141 function metat.__index:sendbody(headers, source, step)
142 source = source or ltn12.source.empty()
143 step = step or ltn12.pump.step
144 -- if we don't know the size in advance, send chunked and hope for the best
145 local mode = "http-chunked"
146 if headers["content-length"] then mode = "keep-open" end
147 return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step))
148 end
149
150 function metat.__index:receivestatusline()
151 local status = self.try(self.c:receive(5))
152 -- identify HTTP/0.9 responses, which do not contain a status line
153 -- this is just a heuristic, but is what the RFC recommends
154 if status ~= "HTTP/" then return nil, status end
155 -- otherwise proceed reading a status line
156 status = self.try(self.c:receive("*l", status))
157 local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)"))
158 return self.try(base.tonumber(code), status)
159 end
160
161 function metat.__index:receiveheaders()
162 return self.try(receiveheaders(self.c))
163 end
164
165 function metat.__index:receivebody(headers, sink, step)
166 sink = sink or ltn12.sink.null()
167 step = step or ltn12.pump.step
168 local length = base.tonumber(headers["content-length"])
169 local t = headers["transfer-encoding"] -- shortcut
170 local mode = "default" -- connection close
171 if t and t ~= "identity" then mode = "http-chunked"
172 elseif base.tonumber(headers["content-length"]) then mode = "by-length" end
173 return self.try(ltn12.pump.all(socket.source(mode, self.c, length),
174 sink, step))
175 end
176
177 function metat.__index:receive09body(status, sink, step)
178 local source = ltn12.source.rewind(socket.source("until-closed", self.c))
179 source(status)
180 return self.try(ltn12.pump.all(source, sink, step))
181 end
182
183 function metat.__index:close()
184 return self.c:close()
185 end
186
187 -----------------------------------------------------------------------------
188 -- High level HTTP API
189 -----------------------------------------------------------------------------
190 local function adjusturi(reqt)
191 local u = reqt
192 -- if there is a proxy, we need the full url. otherwise, just a part.
193 if not reqt.proxy and not _M.PROXY then
194 u = {
195 path = socket.try(reqt.path, "invalid path 'nil'"),
196 params = reqt.params,
197 query = reqt.query,
198 fragment = reqt.fragment
199 }
200 end
201 return url.build(u)
202 end
203
204 local function adjustproxy(reqt)
205 local proxy = reqt.proxy or _M.PROXY
206 if proxy then
207 proxy = url.parse(proxy)
208 return proxy.host, proxy.port or 3128
209 else
210 return reqt.host, reqt.port
211 end
212 end
213
214 local function adjustheaders(reqt)
215 -- default headers
216 local host = string.gsub(reqt.authority, "^.-@", "")
217 local lower = {
218 ["user-agent"] = _M.USERAGENT,
219 ["host"] = host,
220 ["connection"] = "close, TE",
221 ["te"] = "trailers"
222 }
223 -- if we have authentication information, pass it along
224 if reqt.user and reqt.password then
225 lower["authorization"] =
226 "Basic " .. (mime.b64(reqt.user .. ":" ..
227 url.unescape(reqt.password)))
228 end
229 -- if we have proxy authentication information, pass it along
230 local proxy = reqt.proxy or _M.PROXY
231 if proxy then
232 proxy = url.parse(proxy)
233 if proxy.user and proxy.password then
234 lower["proxy-authorization"] =
235 "Basic " .. (mime.b64(proxy.user .. ":" .. proxy.password))
236 end
237 end
238 -- override with user headers
239 for i,v in base.pairs(reqt.headers or lower) do
240 lower[string.lower(i)] = v
241 end
242 return lower
243 end
244
245 -- default url parts
246 local default = {
247 host = "",
248 port = PORT,
249 path ="/",
250 scheme = "http"
251 }
252
253 local function adjustrequest(reqt)
254 -- parse url if provided
255 local nreqt = reqt.url and url.parse(reqt.url, default) or {}
256 -- explicit components override url
257 for i,v in base.pairs(reqt) do nreqt[i] = v end
258 if nreqt.port == "" then nreqt.port = PORT end
259 if not (nreqt.host and nreqt.host ~= "") then
260 socket.try(nil, "invalid host '" .. base.tostring(nreqt.host) .. "'")
261 end
262 -- compute uri if user hasn't overriden
263 nreqt.uri = reqt.uri or adjusturi(nreqt)
264 -- adjust headers in request
265 nreqt.headers = adjustheaders(nreqt)
266 -- ajust host and port if there is a proxy
267 nreqt.host, nreqt.port = adjustproxy(nreqt)
268 return nreqt
269 end
270
271 local function shouldredirect(reqt, code, headers)
272 local location = headers.location
273 if not location then return false end
274 location = string.gsub(location, "%s", "")
275 if location == "" then return false end
276 local scheme = string.match(location, "^([%w][%w%+%-%.]*)%:")
277 if scheme and not SCHEMES[scheme] then return false end
278 return (reqt.redirect ~= false) and
279 (code == 301 or code == 302 or code == 303 or code == 307) and
280 (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD")
281 and (not reqt.nredirects or reqt.nredirects < 5)
282 end
283
284 local function shouldreceivebody(reqt, code)
285 if reqt.method == "HEAD" then return nil end
286 if code == 204 or code == 304 then return nil end
287 if code >= 100 and code < 200 then return nil end
288 return 1
289 end
290
291 -- forward declarations
292 local trequest, tredirect
293
294 --[[local]] function tredirect(reqt, location)
295 local result, code, headers, status = trequest {
296 -- the RFC says the redirect URL has to be absolute, but some
297 -- servers do not respect that
298 url = url.absolute(reqt.url, location),
299 source = reqt.source,
300 sink = reqt.sink,
301 headers = reqt.headers,
302 proxy = reqt.proxy,
303 nredirects = (reqt.nredirects or 0) + 1,
304 create = reqt.create
305 }
306 -- pass location header back as a hint we redirected
307 headers = headers or {}
308 headers.location = headers.location or location
309 return result, code, headers, status
310 end
311
312 --[[local]] function trequest(reqt)
313 -- we loop until we get what we want, or
314 -- until we are sure there is no way to get it
315 local nreqt = adjustrequest(reqt)
316 local h = _M.open(nreqt.host, nreqt.port, nreqt.create)
317 -- send request line and headers
318 h:sendrequestline(nreqt.method, nreqt.uri)
319 h:sendheaders(nreqt.headers)
320 -- if there is a body, send it
321 if nreqt.source then
322 h:sendbody(nreqt.headers, nreqt.source, nreqt.step)
323 end
324 local code, status = h:receivestatusline()
325 -- if it is an HTTP/0.9 server, simply get the body and we are done
326 if not code then
327 h:receive09body(status, nreqt.sink, nreqt.step)
328 return 1, 200
329 end
330 local headers
331 -- ignore any 100-continue messages
332 while code == 100 do
333 headers = h:receiveheaders()
334 code, status = h:receivestatusline()
335 end
336 headers = h:receiveheaders()
337 -- at this point we should have a honest reply from the server
338 -- we can't redirect if we already used the source, so we report the error
339 if shouldredirect(nreqt, code, headers) and not nreqt.source then
340 h:close()
341 return tredirect(reqt, headers.location)
342 end
343 -- here we are finally done
344 if shouldreceivebody(nreqt, code) then
345 h:receivebody(headers, nreqt.sink, nreqt.step)
346 end
347 h:close()
348 return 1, code, headers, status
349 end
350
351 -- turns an url and a body into a generic request
352 local function genericform(u, b)
353 local t = {}
354 local reqt = {
355 url = u,
356 sink = ltn12.sink.table(t),
357 target = t
358 }
359 if b then
360 reqt.source = ltn12.source.string(b)
361 reqt.headers = {
362 ["content-length"] = string.len(b),
363 ["content-type"] = "application/x-www-form-urlencoded"
364 }
365 reqt.method = "POST"
366 end
367 return reqt
368 end
369
370 _M.genericform = genericform
371
372 local function srequest(u, b)
373 local reqt = genericform(u, b)
374 local _, code, headers, status = trequest(reqt)
375 return table.concat(reqt.target), code, headers, status
376 end
377
378 _M.request = socket.protect(function(reqt, body)
379 if base.type(reqt) == "string" then return srequest(reqt, body)
380 else return trequest(reqt) end
381 end)
382
383 socket.http = _M
384 return _M