blob: 0389f5e853c24f92360c867ce46c13dc83a6d290 [file] [log] [blame]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001"""An extensible library for opening URLs using a variety of protocols
2
3The simplest way to use this module is to call the urlopen function,
4which accepts a string containing a URL or a Request object (described
5below). It opens the URL and returns the results as file-like
6object; the returned object has some extra methods described below.
7
8The OpenerDirector manages a collection of Handler objects that do
9all the actual work. Each Handler implements a particular protocol or
10option. The OpenerDirector is a composite object that invokes the
11Handlers needed to open the requested URL. For example, the
12HTTPHandler performs HTTP GET and POST requests and deals with
13non-error returns. The HTTPRedirectHandler automatically deals with
14HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15deals with digest authentication.
16
17urlopen(url, data=None) -- Basic usage is the same as original
18urllib. pass the url and optionally data to post to an HTTP URL, and
19get a file-like object back. One difference is that you can also pass
20a Request instance instead of URL. Raises a URLError (subclass of
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020021OSError); for HTTP errors, raises an HTTPError, which can also be
Jeremy Hylton1afc1692008-06-18 20:49:58 +000022treated as a valid response.
23
24build_opener -- Function that creates a new OpenerDirector instance.
25Will install the default handlers. Accepts one or more Handlers as
26arguments, either instances or Handler classes that it will
27instantiate. If one of the argument is a subclass of the default
28handler, the argument will be installed instead of the default.
29
30install_opener -- Installs a new opener as the default opener.
31
32objects of interest:
Senthil Kumaran1107c5d2009-11-15 06:20:55 +000033
Senthil Kumaran47fff872009-12-20 07:10:31 +000034OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
35the Handler classes, while dealing with requests and responses.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000036
37Request -- An object that encapsulates the state of a request. The
38state can be as simple as the URL. It can also include extra HTTP
39headers, e.g. a User-Agent.
40
41BaseHandler --
42
43internals:
44BaseHandler and parent
45_call_chain conventions
46
47Example usage:
48
Georg Brandl029986a2008-06-23 11:44:14 +000049import urllib.request
Jeremy Hylton1afc1692008-06-18 20:49:58 +000050
51# set up authentication info
Georg Brandl029986a2008-06-23 11:44:14 +000052authinfo = urllib.request.HTTPBasicAuthHandler()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000053authinfo.add_password(realm='PDQ Application',
54 uri='https://mahler:8092/site-updates.py',
55 user='klem',
56 passwd='geheim$parole')
57
Georg Brandl029986a2008-06-23 11:44:14 +000058proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
Jeremy Hylton1afc1692008-06-18 20:49:58 +000059
60# build a new opener that adds authentication and caching FTP handlers
Georg Brandl029986a2008-06-23 11:44:14 +000061opener = urllib.request.build_opener(proxy_support, authinfo,
62 urllib.request.CacheFTPHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000063
64# install it
Georg Brandl029986a2008-06-23 11:44:14 +000065urllib.request.install_opener(opener)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066
Georg Brandl029986a2008-06-23 11:44:14 +000067f = urllib.request.urlopen('http://www.python.org/')
Jeremy Hylton1afc1692008-06-18 20:49:58 +000068"""
69
70# XXX issues:
71# If an authentication error handler that tries to perform
72# authentication for some reason but fails, how should the error be
73# signalled? The client needs to know the HTTP error code. But if
74# the handler knows that the problem was, e.g., that it didn't know
75# that hash algo that requested in the challenge, it would be good to
76# pass that information along to the client, too.
77# ftp errors aren't handled cleanly
78# check digest against correct (i.e. non-apache) implementation
79
80# Possible extensions:
81# complex proxies XXX not sure what exactly was meant by this
82# abstract factory for opener
83
84import base64
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +000085import bisect
Jeremy Hylton1afc1692008-06-18 20:49:58 +000086import email
87import hashlib
88import http.client
89import io
90import os
91import posixpath
Jeremy Hylton1afc1692008-06-18 20:49:58 +000092import re
93import socket
94import sys
95import time
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000096import collections
Senthil Kumarane24f96a2012-03-13 19:29:33 -070097import tempfile
98import contextlib
Senthil Kumaran38b968b92012-03-14 13:43:53 -070099import warnings
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700100
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000101
Georg Brandl13e89462008-07-01 19:56:00 +0000102from urllib.error import URLError, HTTPError, ContentTooShortError
103from urllib.parse import (
104 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
105 splittype, splithost, splitport, splituser, splitpasswd,
Antoine Pitroudf204be2012-11-24 17:59:08 +0100106 splitattr, splitquery, splitvalue, splittag, to_bytes,
107 unquote_to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000108from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000109
110# check for SSL
111try:
112 import ssl
Brett Cannoncd171c82013-07-04 17:43:24 -0400113except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000114 _have_ssl = False
115else:
116 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000117
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800118__all__ = [
119 # Classes
120 'Request', 'OpenerDirector', 'BaseHandler', 'HTTPDefaultErrorHandler',
121 'HTTPRedirectHandler', 'HTTPCookieProcessor', 'ProxyHandler',
122 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm',
123 'AbstractBasicAuthHandler', 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',
124 'AbstractDigestAuthHandler', 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',
Antoine Pitroudf204be2012-11-24 17:59:08 +0100125 'HTTPHandler', 'FileHandler', 'FTPHandler', 'CacheFTPHandler', 'DataHandler',
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800126 'UnknownHandler', 'HTTPErrorProcessor',
127 # Functions
128 'urlopen', 'install_opener', 'build_opener',
129 'pathname2url', 'url2pathname', 'getproxies',
130 # Legacy interface
131 'urlretrieve', 'urlcleanup', 'URLopener', 'FancyURLopener',
132]
133
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000134# used in User-Agent header sent
135__version__ = sys.version[:3]
136
137_opener = None
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000138def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
Antoine Pitroude9ac6c2012-05-16 21:40:01 +0200139 *, cafile=None, capath=None, cadefault=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000140 global _opener
Antoine Pitroude9ac6c2012-05-16 21:40:01 +0200141 if cafile or capath or cadefault:
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000142 if not _have_ssl:
143 raise ValueError('SSL support not available')
Christian Heimes67986f92013-11-23 22:43:47 +0100144 context = ssl._create_stdlib_context(cert_reqs=ssl.CERT_REQUIRED,
145 cafile=cafile,
146 capath=capath)
Antoine Pitrou9a8d6932013-04-01 18:55:35 +0200147 https_handler = HTTPSHandler(context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000148 opener = build_opener(https_handler)
149 elif _opener is None:
150 _opener = opener = build_opener()
151 else:
152 opener = _opener
153 return opener.open(url, data, timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000154
155def install_opener(opener):
156 global _opener
157 _opener = opener
158
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700159_url_tempfiles = []
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000160def urlretrieve(url, filename=None, reporthook=None, data=None):
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700161 """
162 Retrieve a URL into a temporary location on disk.
163
164 Requires a URL argument. If a filename is passed, it is used as
165 the temporary file location. The reporthook argument should be
166 a callable that accepts a block number, a read size, and the
167 total file size of the URL target. The data argument should be
168 valid URL encoded data.
169
170 If a filename is passed and the URL points to a local resource,
171 the result is a copy from local file to new file.
172
173 Returns a tuple containing the path to the newly created
174 data file as well as the resulting HTTPMessage object.
175 """
176 url_type, path = splittype(url)
177
178 with contextlib.closing(urlopen(url, data)) as fp:
179 headers = fp.info()
180
181 # Just return the local path and the "headers" for file://
182 # URLs. No sense in performing a copy unless requested.
183 if url_type == "file" and not filename:
184 return os.path.normpath(path), headers
185
186 # Handle temporary file setup.
187 if filename:
188 tfp = open(filename, 'wb')
189 else:
190 tfp = tempfile.NamedTemporaryFile(delete=False)
191 filename = tfp.name
192 _url_tempfiles.append(filename)
193
194 with tfp:
195 result = filename, headers
196 bs = 1024*8
197 size = -1
198 read = 0
199 blocknum = 0
200 if "content-length" in headers:
201 size = int(headers["Content-Length"])
202
203 if reporthook:
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800204 reporthook(blocknum, bs, size)
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700205
206 while True:
207 block = fp.read(bs)
208 if not block:
209 break
210 read += len(block)
211 tfp.write(block)
212 blocknum += 1
213 if reporthook:
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800214 reporthook(blocknum, bs, size)
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700215
216 if size >= 0 and read < size:
217 raise ContentTooShortError(
218 "retrieval incomplete: got only %i out of %i bytes"
219 % (read, size), result)
220
221 return result
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000222
223def urlcleanup():
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700224 for temp_file in _url_tempfiles:
225 try:
226 os.unlink(temp_file)
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200227 except OSError:
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700228 pass
229
230 del _url_tempfiles[:]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000231 global _opener
232 if _opener:
233 _opener = None
234
235# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000236_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000237def request_host(request):
238 """Return request-host, as defined by RFC 2965.
239
240 Variation from RFC: returned value is lowercased, for convenient
241 comparison.
242
243 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000244 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000245 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000246 if host == "":
247 host = request.get_header("Host", "")
248
249 # remove port, if present
250 host = _cut_port_re.sub("", host, 1)
251 return host.lower()
252
253class Request:
254
255 def __init__(self, url, data=None, headers={},
Senthil Kumarande49d642011-10-16 23:54:44 +0800256 origin_req_host=None, unverifiable=False,
257 method=None):
Senthil Kumaran52380922013-04-25 05:45:48 -0700258 self.full_url = url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000259 self.headers = {}
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200260 self.unredirected_hdrs = {}
261 self._data = None
262 self.data = data
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000263 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000264 for key, value in headers.items():
265 self.add_header(key, value)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000266 if origin_req_host is None:
267 origin_req_host = request_host(self)
268 self.origin_req_host = origin_req_host
269 self.unverifiable = unverifiable
Jason R. Coombs7dc4f4b2013-09-08 12:47:07 -0400270 if method:
271 self.method = method
Senthil Kumaran52380922013-04-25 05:45:48 -0700272
273 @property
274 def full_url(self):
Senthil Kumaran83070752013-05-24 09:14:12 -0700275 if self.fragment:
276 return '{}#{}'.format(self._full_url, self.fragment)
Senthil Kumaran52380922013-04-25 05:45:48 -0700277 return self._full_url
278
279 @full_url.setter
280 def full_url(self, url):
281 # unwrap('<URL:type://host/path>') --> 'type://host/path'
282 self._full_url = unwrap(url)
283 self._full_url, self.fragment = splittag(self._full_url)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000284 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000285
Senthil Kumaran52380922013-04-25 05:45:48 -0700286 @full_url.deleter
287 def full_url(self):
288 self._full_url = None
289 self.fragment = None
290 self.selector = ''
291
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200292 @property
293 def data(self):
294 return self._data
295
296 @data.setter
297 def data(self, data):
298 if data != self._data:
299 self._data = data
300 # issue 16464
301 # if we change data we need to remove content-length header
302 # (cause it's most probably calculated for previous value)
303 if self.has_header("Content-length"):
304 self.remove_header("Content-length")
305
306 @data.deleter
307 def data(self):
R David Murray9cc7d452013-03-20 00:10:51 -0400308 self.data = None
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200309
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000310 def _parse(self):
Senthil Kumaran52380922013-04-25 05:45:48 -0700311 self.type, rest = splittype(self._full_url)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000312 if self.type is None:
R David Murrayd8a46962013-04-03 06:58:34 -0400313 raise ValueError("unknown url type: %r" % self.full_url)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000314 self.host, self.selector = splithost(rest)
315 if self.host:
316 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000317
318 def get_method(self):
Senthil Kumarande49d642011-10-16 23:54:44 +0800319 """Return a string indicating the HTTP request method."""
Jason R. Coombsaae6a1d2013-09-08 12:54:33 -0400320 default_method = "POST" if self.data is not None else "GET"
321 return getattr(self, 'method', default_method)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000322
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000323 def get_full_url(self):
Senthil Kumaran52380922013-04-25 05:45:48 -0700324 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000325
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000326 def set_proxy(self, host, type):
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000327 if self.type == 'https' and not self._tunnel_host:
328 self._tunnel_host = self.host
329 else:
330 self.type= type
331 self.selector = self.full_url
332 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000333
334 def has_proxy(self):
335 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000336
337 def add_header(self, key, val):
338 # useful for something like authentication
339 self.headers[key.capitalize()] = val
340
341 def add_unredirected_header(self, key, val):
342 # will not be added to a redirected request
343 self.unredirected_hdrs[key.capitalize()] = val
344
345 def has_header(self, header_name):
346 return (header_name in self.headers or
347 header_name in self.unredirected_hdrs)
348
349 def get_header(self, header_name, default=None):
350 return self.headers.get(
351 header_name,
352 self.unredirected_hdrs.get(header_name, default))
353
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200354 def remove_header(self, header_name):
355 self.headers.pop(header_name, None)
356 self.unredirected_hdrs.pop(header_name, None)
357
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000358 def header_items(self):
359 hdrs = self.unredirected_hdrs.copy()
360 hdrs.update(self.headers)
361 return list(hdrs.items())
362
363class OpenerDirector:
364 def __init__(self):
365 client_version = "Python-urllib/%s" % __version__
366 self.addheaders = [('User-agent', client_version)]
R. David Murray25b8cca2010-12-23 19:44:49 +0000367 # self.handlers is retained only for backward compatibility
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000368 self.handlers = []
R. David Murray25b8cca2010-12-23 19:44:49 +0000369 # manage the individual handlers
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000370 self.handle_open = {}
371 self.handle_error = {}
372 self.process_response = {}
373 self.process_request = {}
374
375 def add_handler(self, handler):
376 if not hasattr(handler, "add_parent"):
377 raise TypeError("expected BaseHandler instance, got %r" %
378 type(handler))
379
380 added = False
381 for meth in dir(handler):
382 if meth in ["redirect_request", "do_open", "proxy_open"]:
383 # oops, coincidental match
384 continue
385
386 i = meth.find("_")
387 protocol = meth[:i]
388 condition = meth[i+1:]
389
390 if condition.startswith("error"):
391 j = condition.find("_") + i + 1
392 kind = meth[j+1:]
393 try:
394 kind = int(kind)
395 except ValueError:
396 pass
397 lookup = self.handle_error.get(protocol, {})
398 self.handle_error[protocol] = lookup
399 elif condition == "open":
400 kind = protocol
401 lookup = self.handle_open
402 elif condition == "response":
403 kind = protocol
404 lookup = self.process_response
405 elif condition == "request":
406 kind = protocol
407 lookup = self.process_request
408 else:
409 continue
410
411 handlers = lookup.setdefault(kind, [])
412 if handlers:
413 bisect.insort(handlers, handler)
414 else:
415 handlers.append(handler)
416 added = True
417
418 if added:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000419 bisect.insort(self.handlers, handler)
420 handler.add_parent(self)
421
422 def close(self):
423 # Only exists for backwards compatibility.
424 pass
425
426 def _call_chain(self, chain, kind, meth_name, *args):
427 # Handlers raise an exception if no one else should try to handle
428 # the request, or return None if they can't but another handler
429 # could. Otherwise, they return the response.
430 handlers = chain.get(kind, ())
431 for handler in handlers:
432 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000433 result = func(*args)
434 if result is not None:
435 return result
436
437 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
438 # accept a URL or a Request object
439 if isinstance(fullurl, str):
440 req = Request(fullurl, data)
441 else:
442 req = fullurl
443 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000444 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000445
446 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000447 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000448
449 # pre-process request
450 meth_name = protocol+"_request"
451 for processor in self.process_request.get(protocol, []):
452 meth = getattr(processor, meth_name)
453 req = meth(req)
454
455 response = self._open(req, data)
456
457 # post-process response
458 meth_name = protocol+"_response"
459 for processor in self.process_response.get(protocol, []):
460 meth = getattr(processor, meth_name)
461 response = meth(req, response)
462
463 return response
464
465 def _open(self, req, data=None):
466 result = self._call_chain(self.handle_open, 'default',
467 'default_open', req)
468 if result:
469 return result
470
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000471 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000472 result = self._call_chain(self.handle_open, protocol, protocol +
473 '_open', req)
474 if result:
475 return result
476
477 return self._call_chain(self.handle_open, 'unknown',
478 'unknown_open', req)
479
480 def error(self, proto, *args):
481 if proto in ('http', 'https'):
482 # XXX http[s] protocols are special-cased
483 dict = self.handle_error['http'] # https is not different than http
484 proto = args[2] # YUCK!
485 meth_name = 'http_error_%s' % proto
486 http_err = 1
487 orig_args = args
488 else:
489 dict = self.handle_error
490 meth_name = proto + '_error'
491 http_err = 0
492 args = (dict, proto, meth_name) + args
493 result = self._call_chain(*args)
494 if result:
495 return result
496
497 if http_err:
498 args = (dict, 'default', 'http_error_default') + orig_args
499 return self._call_chain(*args)
500
501# XXX probably also want an abstract factory that knows when it makes
502# sense to skip a superclass in favor of a subclass and when it might
503# make sense to include both
504
505def build_opener(*handlers):
506 """Create an opener object from a list of handlers.
507
508 The opener will use several default handlers, including support
Senthil Kumaran1107c5d2009-11-15 06:20:55 +0000509 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000510
511 If any of the handlers passed as arguments are subclasses of the
512 default handlers, the default handlers will not be used.
513 """
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000514 opener = OpenerDirector()
515 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
516 HTTPDefaultErrorHandler, HTTPRedirectHandler,
Antoine Pitroudf204be2012-11-24 17:59:08 +0100517 FTPHandler, FileHandler, HTTPErrorProcessor,
518 DataHandler]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000519 if hasattr(http.client, "HTTPSConnection"):
520 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000521 skip = set()
522 for klass in default_classes:
523 for check in handlers:
Benjamin Peterson78c85382014-04-01 16:27:30 -0400524 if isinstance(check, type):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000525 if issubclass(check, klass):
526 skip.add(klass)
527 elif isinstance(check, klass):
528 skip.add(klass)
529 for klass in skip:
530 default_classes.remove(klass)
531
532 for klass in default_classes:
533 opener.add_handler(klass())
534
535 for h in handlers:
Benjamin Peterson5dd3cae2014-04-01 14:20:56 -0400536 if isinstance(h, type):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000537 h = h()
538 opener.add_handler(h)
539 return opener
540
541class BaseHandler:
542 handler_order = 500
543
544 def add_parent(self, parent):
545 self.parent = parent
546
547 def close(self):
548 # Only exists for backwards compatibility
549 pass
550
551 def __lt__(self, other):
552 if not hasattr(other, "handler_order"):
553 # Try to preserve the old behavior of having custom classes
554 # inserted after default ones (works only for custom user
555 # classes which are not aware of handler_order).
556 return True
557 return self.handler_order < other.handler_order
558
559
560class HTTPErrorProcessor(BaseHandler):
561 """Process HTTP error responses."""
562 handler_order = 1000 # after all other processing
563
564 def http_response(self, request, response):
565 code, msg, hdrs = response.code, response.msg, response.info()
566
567 # According to RFC 2616, "2xx" code indicates that the client's
568 # request was successfully received, understood, and accepted.
569 if not (200 <= code < 300):
570 response = self.parent.error(
571 'http', request, response, code, msg, hdrs)
572
573 return response
574
575 https_response = http_response
576
577class HTTPDefaultErrorHandler(BaseHandler):
578 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000579 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000580
581class HTTPRedirectHandler(BaseHandler):
582 # maximum number of redirections to any single URL
583 # this is needed because of the state that cookies introduce
584 max_repeats = 4
585 # maximum total number of redirections (regardless of URL) before
586 # assuming we're in a loop
587 max_redirections = 10
588
589 def redirect_request(self, req, fp, code, msg, headers, newurl):
590 """Return a Request or None in response to a redirect.
591
592 This is called by the http_error_30x methods when a
593 redirection response is received. If a redirection should
594 take place, return a new Request to allow http_error_30x to
595 perform the redirect. Otherwise, raise HTTPError if no-one
596 else should try to handle this url. Return None if you can't
597 but another Handler might.
598 """
599 m = req.get_method()
600 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
601 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000602 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000603
604 # Strictly (according to RFC 2616), 301 or 302 in response to
605 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000606 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000607 # essentially all clients do redirect in this case, so we do
608 # the same.
609 # be conciliant with URIs containing a space
610 newurl = newurl.replace(' ', '%20')
611 CONTENT_HEADERS = ("content-length", "content-type")
612 newheaders = dict((k, v) for k, v in req.headers.items()
613 if k.lower() not in CONTENT_HEADERS)
614 return Request(newurl,
615 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000616 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000617 unverifiable=True)
618
619 # Implementation note: To avoid the server sending us into an
620 # infinite loop, the request object needs to track what URLs we
621 # have already seen. Do this by adding a handler-specific
622 # attribute to the Request object.
623 def http_error_302(self, req, fp, code, msg, headers):
624 # Some servers (incorrectly) return multiple Location headers
625 # (so probably same goes for URI). Use first header.
626 if "location" in headers:
627 newurl = headers["location"]
628 elif "uri" in headers:
629 newurl = headers["uri"]
630 else:
631 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000632
633 # fix a possible malformed URL
634 urlparts = urlparse(newurl)
guido@google.coma119df92011-03-29 11:41:02 -0700635
636 # For security reasons we don't allow redirection to anything other
637 # than http, https or ftp.
638
Senthil Kumaran6497aa32012-01-04 13:46:59 +0800639 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800640 raise HTTPError(
641 newurl, code,
642 "%s - Redirection to url '%s' is not allowed" % (msg, newurl),
643 headers, fp)
guido@google.coma119df92011-03-29 11:41:02 -0700644
Facundo Batistaf24802c2008-08-17 03:36:03 +0000645 if not urlparts.path:
646 urlparts = list(urlparts)
647 urlparts[2] = "/"
648 newurl = urlunparse(urlparts)
649
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000650 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000651
652 # XXX Probably want to forget about the state of the current
653 # request, although that might interact poorly with other
654 # handlers that also use handler-specific request attributes
655 new = self.redirect_request(req, fp, code, msg, headers, newurl)
656 if new is None:
657 return
658
659 # loop detection
660 # .redirect_dict has a key url if url was previously visited.
661 if hasattr(req, 'redirect_dict'):
662 visited = new.redirect_dict = req.redirect_dict
663 if (visited.get(newurl, 0) >= self.max_repeats or
664 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000665 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000666 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000667 else:
668 visited = new.redirect_dict = req.redirect_dict = {}
669 visited[newurl] = visited.get(newurl, 0) + 1
670
671 # Don't close the fp until we are sure that we won't use it
672 # with HTTPError.
673 fp.read()
674 fp.close()
675
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000676 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000677
678 http_error_301 = http_error_303 = http_error_307 = http_error_302
679
680 inf_msg = "The HTTP server returned a redirect error that would " \
681 "lead to an infinite loop.\n" \
682 "The last 30x error message was:\n"
683
684
685def _parse_proxy(proxy):
686 """Return (scheme, user, password, host/port) given a URL or an authority.
687
688 If a URL is supplied, it must have an authority (host:port) component.
689 According to RFC 3986, having an authority component means the URL must
Senthil Kumarand8e24f12014-04-14 16:32:20 -0400690 have two slashes after the scheme.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000691 """
Georg Brandl13e89462008-07-01 19:56:00 +0000692 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000693 if not r_scheme.startswith("/"):
694 # authority
695 scheme = None
696 authority = proxy
697 else:
698 # URL
699 if not r_scheme.startswith("//"):
700 raise ValueError("proxy URL with no authority: %r" % proxy)
701 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
702 # and 3.3.), path is empty or starts with '/'
703 end = r_scheme.find("/", 2)
704 if end == -1:
705 end = None
706 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000707 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000708 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000709 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000710 else:
711 user = password = None
712 return scheme, user, password, hostport
713
714class ProxyHandler(BaseHandler):
715 # Proxies must be in front
716 handler_order = 100
717
718 def __init__(self, proxies=None):
719 if proxies is None:
720 proxies = getproxies()
721 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
722 self.proxies = proxies
723 for type, url in proxies.items():
724 setattr(self, '%s_open' % type,
Georg Brandlfcbdbf22012-06-24 19:56:31 +0200725 lambda r, proxy=url, type=type, meth=self.proxy_open:
726 meth(r, proxy, type))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000727
728 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000729 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000730 proxy_type, user, password, hostport = _parse_proxy(proxy)
731 if proxy_type is None:
732 proxy_type = orig_type
Senthil Kumaran7bb04972009-10-11 04:58:55 +0000733
734 if req.host and proxy_bypass(req.host):
735 return None
736
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000737 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000738 user_pass = '%s:%s' % (unquote(user),
739 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000740 creds = base64.b64encode(user_pass.encode()).decode("ascii")
741 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000742 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000743 req.set_proxy(hostport, proxy_type)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000744 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000745 # let other handlers take care of it
746 return None
747 else:
748 # need to start over, because the other handlers don't
749 # grok the proxy's URL type
750 # e.g. if we have a constructor arg proxies like so:
751 # {'http': 'ftp://proxy.example.com'}, we may end up turning
752 # a request for http://acme.example.com/a into one for
753 # ftp://proxy.example.com/a
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000754 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000755
756class HTTPPasswordMgr:
757
758 def __init__(self):
759 self.passwd = {}
760
761 def add_password(self, realm, uri, user, passwd):
762 # uri could be a single URI or a sequence
763 if isinstance(uri, str):
764 uri = [uri]
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800765 if realm not in self.passwd:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000766 self.passwd[realm] = {}
767 for default_port in True, False:
768 reduced_uri = tuple(
769 [self.reduce_uri(u, default_port) for u in uri])
770 self.passwd[realm][reduced_uri] = (user, passwd)
771
772 def find_user_password(self, realm, authuri):
773 domains = self.passwd.get(realm, {})
774 for default_port in True, False:
775 reduced_authuri = self.reduce_uri(authuri, default_port)
776 for uris, authinfo in domains.items():
777 for uri in uris:
778 if self.is_suburi(uri, reduced_authuri):
779 return authinfo
780 return None, None
781
782 def reduce_uri(self, uri, default_port=True):
783 """Accept authority or URI and extract only the authority and path."""
784 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000785 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000786 if parts[1]:
787 # URI
788 scheme = parts[0]
789 authority = parts[1]
790 path = parts[2] or '/'
791 else:
792 # host or host:port
793 scheme = None
794 authority = uri
795 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000796 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000797 if default_port and port is None and scheme is not None:
798 dport = {"http": 80,
799 "https": 443,
800 }.get(scheme)
801 if dport is not None:
802 authority = "%s:%d" % (host, dport)
803 return authority, path
804
805 def is_suburi(self, base, test):
806 """Check if test is below base in a URI tree
807
808 Both args must be URIs in reduced form.
809 """
810 if base == test:
811 return True
812 if base[0] != test[0]:
813 return False
814 common = posixpath.commonprefix((base[1], test[1]))
815 if len(common) == len(base[1]):
816 return True
817 return False
818
819
820class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
821
822 def find_user_password(self, realm, authuri):
823 user, password = HTTPPasswordMgr.find_user_password(self, realm,
824 authuri)
825 if user is not None:
826 return user, password
827 return HTTPPasswordMgr.find_user_password(self, None, authuri)
828
829
830class AbstractBasicAuthHandler:
831
832 # XXX this allows for multiple auth-schemes, but will stupidly pick
833 # the last one with a realm specified.
834
835 # allow for double- and single-quoted realm values
836 # (single quotes are a violation of the RFC, but appear in the wild)
837 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +0800838 'realm=(["\']?)([^"\']*)\\2', re.I)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000839
840 # XXX could pre-emptively send auth info already accepted (RFC 2617,
841 # end of section 2, and section 1.2 immediately after "credentials"
842 # production).
843
844 def __init__(self, password_mgr=None):
845 if password_mgr is None:
846 password_mgr = HTTPPasswordMgr()
847 self.passwd = password_mgr
848 self.add_password = self.passwd.add_password
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000849 self.retried = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000850
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000851 def reset_retry_count(self):
852 self.retried = 0
853
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000854 def http_error_auth_reqed(self, authreq, host, req, headers):
855 # host may be an authority (without userinfo) or a URL with an
856 # authority
857 # XXX could be multiple headers
858 authreq = headers.get(authreq, None)
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000859
860 if self.retried > 5:
861 # retry sending the username:password 5 times before failing.
862 raise HTTPError(req.get_full_url(), 401, "basic auth failed",
863 headers, None)
864 else:
865 self.retried += 1
866
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000867 if authreq:
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800868 scheme = authreq.split()[0]
Senthil Kumaran1a129c82011-10-20 02:50:13 +0800869 if scheme.lower() != 'basic':
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800870 raise ValueError("AbstractBasicAuthHandler does not"
871 " support the following scheme: '%s'" %
872 scheme)
873 else:
874 mo = AbstractBasicAuthHandler.rx.search(authreq)
875 if mo:
876 scheme, quote, realm = mo.groups()
Senthil Kumaran92a5bf02012-05-16 00:03:29 +0800877 if quote not in ['"',"'"]:
878 warnings.warn("Basic Auth Realm was unquoted",
879 UserWarning, 2)
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800880 if scheme.lower() == 'basic':
881 response = self.retry_http_basic_auth(host, req, realm)
882 if response and response.code != 401:
883 self.retried = 0
884 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000885
886 def retry_http_basic_auth(self, host, req, realm):
887 user, pw = self.passwd.find_user_password(realm, host)
888 if pw is not None:
889 raw = "%s:%s" % (user, pw)
890 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
891 if req.headers.get(self.auth_header, None) == auth:
892 return None
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +0000893 req.add_unredirected_header(self.auth_header, auth)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000894 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000895 else:
896 return None
897
898
899class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
900
901 auth_header = 'Authorization'
902
903 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000904 url = req.full_url
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000905 response = self.http_error_auth_reqed('www-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000906 url, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000907 self.reset_retry_count()
908 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000909
910
911class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
912
913 auth_header = 'Proxy-authorization'
914
915 def http_error_407(self, req, fp, code, msg, headers):
916 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000917 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000918 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
919 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000920 authority = req.host
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000921 response = self.http_error_auth_reqed('proxy-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000922 authority, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000923 self.reset_retry_count()
924 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000925
926
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800927# Return n random bytes.
928_randombytes = os.urandom
929
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000930
931class AbstractDigestAuthHandler:
932 # Digest authentication is specified in RFC 2617.
933
934 # XXX The client does not inspect the Authentication-Info header
935 # in a successful response.
936
937 # XXX It should be possible to test this implementation against
938 # a mock server that just generates a static set of challenges.
939
940 # XXX qop="auth-int" supports is shaky
941
942 def __init__(self, passwd=None):
943 if passwd is None:
944 passwd = HTTPPasswordMgr()
945 self.passwd = passwd
946 self.add_password = self.passwd.add_password
947 self.retried = 0
948 self.nonce_count = 0
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000949 self.last_nonce = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000950
951 def reset_retry_count(self):
952 self.retried = 0
953
954 def http_error_auth_reqed(self, auth_header, host, req, headers):
955 authreq = headers.get(auth_header, None)
956 if self.retried > 5:
957 # Don't fail endlessly - if we failed once, we'll probably
958 # fail a second time. Hm. Unless the Password Manager is
959 # prompting for the information. Crap. This isn't great
960 # but it's better than the current 'repeat until recursion
961 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000962 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000963 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000964 else:
965 self.retried += 1
966 if authreq:
967 scheme = authreq.split()[0]
968 if scheme.lower() == 'digest':
969 return self.retry_http_digest_auth(req, authreq)
Senthil Kumaran1a129c82011-10-20 02:50:13 +0800970 elif scheme.lower() != 'basic':
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800971 raise ValueError("AbstractDigestAuthHandler does not support"
972 " the following scheme: '%s'" % scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000973
974 def retry_http_digest_auth(self, req, auth):
975 token, challenge = auth.split(' ', 1)
976 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
977 auth = self.get_authorization(req, chal)
978 if auth:
979 auth_val = 'Digest %s' % auth
980 if req.headers.get(self.auth_header, None) == auth_val:
981 return None
982 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000983 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000984 return resp
985
986 def get_cnonce(self, nonce):
987 # The cnonce-value is an opaque
988 # quoted string value provided by the client and used by both client
989 # and server to avoid chosen plaintext attacks, to provide mutual
990 # authentication, and to provide some message integrity protection.
991 # This isn't a fabulous effort, but it's probably Good Enough.
992 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800993 b = s.encode("ascii") + _randombytes(8)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000994 dig = hashlib.sha1(b).hexdigest()
995 return dig[:16]
996
997 def get_authorization(self, req, chal):
998 try:
999 realm = chal['realm']
1000 nonce = chal['nonce']
1001 qop = chal.get('qop')
1002 algorithm = chal.get('algorithm', 'MD5')
1003 # mod_digest doesn't send an opaque, even though it isn't
1004 # supposed to be optional
1005 opaque = chal.get('opaque', None)
1006 except KeyError:
1007 return None
1008
1009 H, KD = self.get_algorithm_impls(algorithm)
1010 if H is None:
1011 return None
1012
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001013 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001014 if user is None:
1015 return None
1016
1017 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001018 if req.data is not None:
1019 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001020 else:
1021 entdig = None
1022
1023 A1 = "%s:%s:%s" % (user, realm, pw)
1024 A2 = "%s:%s" % (req.get_method(),
1025 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001026 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001027 if qop == 'auth':
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +00001028 if nonce == self.last_nonce:
1029 self.nonce_count += 1
1030 else:
1031 self.nonce_count = 1
1032 self.last_nonce = nonce
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001033 ncvalue = '%08x' % self.nonce_count
1034 cnonce = self.get_cnonce(nonce)
1035 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
1036 respdig = KD(H(A1), noncebit)
1037 elif qop is None:
1038 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
1039 else:
1040 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +00001041 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001042
1043 # XXX should the partial digests be encoded too?
1044
1045 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001046 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001047 respdig)
1048 if opaque:
1049 base += ', opaque="%s"' % opaque
1050 if entdig:
1051 base += ', digest="%s"' % entdig
1052 base += ', algorithm="%s"' % algorithm
1053 if qop:
1054 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
1055 return base
1056
1057 def get_algorithm_impls(self, algorithm):
1058 # lambdas assume digest modules are imported at the top level
1059 if algorithm == 'MD5':
1060 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
1061 elif algorithm == 'SHA':
1062 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
1063 # XXX MD5-sess
1064 KD = lambda s, d: H("%s:%s" % (s, d))
1065 return H, KD
1066
1067 def get_entity_digest(self, data, chal):
1068 # XXX not implemented yet
1069 return None
1070
1071
1072class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1073 """An authentication protocol defined by RFC 2069
1074
1075 Digest authentication improves on basic authentication because it
1076 does not transmit passwords in the clear.
1077 """
1078
1079 auth_header = 'Authorization'
1080 handler_order = 490 # before Basic auth
1081
1082 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001083 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001084 retry = self.http_error_auth_reqed('www-authenticate',
1085 host, req, headers)
1086 self.reset_retry_count()
1087 return retry
1088
1089
1090class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1091
1092 auth_header = 'Proxy-Authorization'
1093 handler_order = 490 # before Basic auth
1094
1095 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001096 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001097 retry = self.http_error_auth_reqed('proxy-authenticate',
1098 host, req, headers)
1099 self.reset_retry_count()
1100 return retry
1101
1102class AbstractHTTPHandler(BaseHandler):
1103
1104 def __init__(self, debuglevel=0):
1105 self._debuglevel = debuglevel
1106
1107 def set_http_debuglevel(self, level):
1108 self._debuglevel = level
1109
1110 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001111 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001112 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001113 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001114
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001115 if request.data is not None: # POST
1116 data = request.data
Senthil Kumaran29333122011-02-11 11:25:47 +00001117 if isinstance(data, str):
Georg Brandlfcbdbf22012-06-24 19:56:31 +02001118 msg = "POST data should be bytes or an iterable of bytes. " \
1119 "It cannot be of type str."
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07001120 raise TypeError(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001121 if not request.has_header('Content-type'):
1122 request.add_unredirected_header(
1123 'Content-type',
1124 'application/x-www-form-urlencoded')
1125 if not request.has_header('Content-length'):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001126 try:
1127 mv = memoryview(data)
1128 except TypeError:
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001129 if isinstance(data, collections.Iterable):
Georg Brandl61536042011-02-03 07:46:41 +00001130 raise ValueError("Content-Length should be specified "
1131 "for iterable data of type %r %r" % (type(data),
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001132 data))
1133 else:
1134 request.add_unredirected_header(
Senthil Kumaran1e991f22010-12-24 04:03:59 +00001135 'Content-length', '%d' % (len(mv) * mv.itemsize))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001136
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001137 sel_host = host
1138 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001139 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001140 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001141 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001142 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001143 for name, value in self.parent.addheaders:
1144 name = name.capitalize()
1145 if not request.has_header(name):
1146 request.add_unredirected_header(name, value)
1147
1148 return request
1149
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001150 def do_open(self, http_class, req, **http_conn_args):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001151 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001152
1153 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001154 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001155 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001156 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001157 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001158
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001159 # will parse host:port
1160 h = http_class(host, timeout=req.timeout, **http_conn_args)
Senthil Kumaran42ef4b12010-09-27 01:26:03 +00001161
1162 headers = dict(req.unredirected_hdrs)
1163 headers.update(dict((k, v) for k, v in req.headers.items()
1164 if k not in headers))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001165
1166 # TODO(jhylton): Should this be redesigned to handle
1167 # persistent connections?
1168
1169 # We want to make an HTTP/1.1 request, but the addinfourl
1170 # class isn't prepared to deal with a persistent connection.
1171 # It will try to read all remaining data from the socket,
1172 # which will block while the server waits for the next request.
1173 # So make sure the connection gets closed after the (only)
1174 # request.
1175 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001176 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001177
1178 if req._tunnel_host:
Senthil Kumaran47fff872009-12-20 07:10:31 +00001179 tunnel_headers = {}
1180 proxy_auth_hdr = "Proxy-Authorization"
1181 if proxy_auth_hdr in headers:
1182 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1183 # Proxy-Authorization should not be sent to origin
1184 # server.
1185 del headers[proxy_auth_hdr]
1186 h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001187
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001188 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001189 h.request(req.get_method(), req.selector, req.data, headers)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001190 except OSError as err: # timeout error
Senthil Kumaran45686b42011-07-27 09:31:03 +08001191 h.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001192 raise URLError(err)
Senthil Kumaran45686b42011-07-27 09:31:03 +08001193 else:
1194 r = h.getresponse()
Nadeem Vawdabd26b542012-10-21 17:37:43 +02001195 # If the server does not send us a 'Connection: close' header,
1196 # HTTPConnection assumes the socket should be left open. Manually
1197 # mark the socket to be closed when this response object goes away.
1198 if h.sock:
1199 h.sock.close()
1200 h.sock = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001201
Senthil Kumaran26430412011-04-13 07:01:19 +08001202 r.url = req.get_full_url()
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001203 # This line replaces the .msg attribute of the HTTPResponse
1204 # with .headers, because urllib clients expect the response to
1205 # have the reason in .msg. It would be good to mark this
1206 # attribute is deprecated and get then to use info() or
1207 # .headers.
1208 r.msg = r.reason
1209 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001210
1211
1212class HTTPHandler(AbstractHTTPHandler):
1213
1214 def http_open(self, req):
1215 return self.do_open(http.client.HTTPConnection, req)
1216
1217 http_request = AbstractHTTPHandler.do_request_
1218
1219if hasattr(http.client, 'HTTPSConnection'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001220
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001221 class HTTPSHandler(AbstractHTTPHandler):
1222
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001223 def __init__(self, debuglevel=0, context=None, check_hostname=None):
1224 AbstractHTTPHandler.__init__(self, debuglevel)
1225 self._context = context
1226 self._check_hostname = check_hostname
1227
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001228 def https_open(self, req):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001229 return self.do_open(http.client.HTTPSConnection, req,
1230 context=self._context, check_hostname=self._check_hostname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001231
1232 https_request = AbstractHTTPHandler.do_request_
1233
Senthil Kumaran4c875a92011-11-01 23:57:57 +08001234 __all__.append('HTTPSHandler')
Senthil Kumaran0d54eb92011-11-01 23:49:46 +08001235
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001236class HTTPCookieProcessor(BaseHandler):
1237 def __init__(self, cookiejar=None):
1238 import http.cookiejar
1239 if cookiejar is None:
1240 cookiejar = http.cookiejar.CookieJar()
1241 self.cookiejar = cookiejar
1242
1243 def http_request(self, request):
1244 self.cookiejar.add_cookie_header(request)
1245 return request
1246
1247 def http_response(self, request, response):
1248 self.cookiejar.extract_cookies(response, request)
1249 return response
1250
1251 https_request = http_request
1252 https_response = http_response
1253
1254class UnknownHandler(BaseHandler):
1255 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001256 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001257 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001258
1259def parse_keqv_list(l):
1260 """Parse list of key=value strings where keys are not duplicated."""
1261 parsed = {}
1262 for elt in l:
1263 k, v = elt.split('=', 1)
1264 if v[0] == '"' and v[-1] == '"':
1265 v = v[1:-1]
1266 parsed[k] = v
1267 return parsed
1268
1269def parse_http_list(s):
1270 """Parse lists as described by RFC 2068 Section 2.
1271
1272 In particular, parse comma-separated lists where the elements of
1273 the list may include quoted-strings. A quoted-string could
1274 contain a comma. A non-quoted string could have quotes in the
1275 middle. Neither commas nor quotes count if they are escaped.
1276 Only double-quotes count, not single-quotes.
1277 """
1278 res = []
1279 part = ''
1280
1281 escape = quote = False
1282 for cur in s:
1283 if escape:
1284 part += cur
1285 escape = False
1286 continue
1287 if quote:
1288 if cur == '\\':
1289 escape = True
1290 continue
1291 elif cur == '"':
1292 quote = False
1293 part += cur
1294 continue
1295
1296 if cur == ',':
1297 res.append(part)
1298 part = ''
1299 continue
1300
1301 if cur == '"':
1302 quote = True
1303
1304 part += cur
1305
1306 # append last part
1307 if part:
1308 res.append(part)
1309
1310 return [part.strip() for part in res]
1311
1312class FileHandler(BaseHandler):
1313 # Use local file or FTP depending on form of URL
1314 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001315 url = req.selector
Senthil Kumaran2ef16322010-07-11 03:12:43 +00001316 if url[:2] == '//' and url[2:3] != '/' and (req.host and
1317 req.host != 'localhost'):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -07001318 if not req.host in self.get_names():
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001319 raise URLError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001320 else:
1321 return self.open_local_file(req)
1322
1323 # names for the localhost
1324 names = None
1325 def get_names(self):
1326 if FileHandler.names is None:
1327 try:
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001328 FileHandler.names = tuple(
1329 socket.gethostbyname_ex('localhost')[2] +
1330 socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001331 except socket.gaierror:
1332 FileHandler.names = (socket.gethostbyname('localhost'),)
1333 return FileHandler.names
1334
1335 # not entirely sure what the rules are here
1336 def open_local_file(self, req):
1337 import email.utils
1338 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001339 host = req.host
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001340 filename = req.selector
1341 localfile = url2pathname(filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001342 try:
1343 stats = os.stat(localfile)
1344 size = stats.st_size
1345 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001346 mtype = mimetypes.guess_type(filename)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001347 headers = email.message_from_string(
1348 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1349 (mtype or 'text/plain', size, modified))
1350 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001351 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001352 if not host or \
1353 (not port and _safe_gethostbyname(host) in self.get_names()):
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001354 if host:
1355 origurl = 'file://' + host + filename
1356 else:
1357 origurl = 'file://' + filename
1358 return addinfourl(open(localfile, 'rb'), headers, origurl)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001359 except OSError as exp:
Georg Brandl029986a2008-06-23 11:44:14 +00001360 # users shouldn't expect OSErrors coming from urlopen()
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001361 raise URLError(exp)
Georg Brandl13e89462008-07-01 19:56:00 +00001362 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001363
1364def _safe_gethostbyname(host):
1365 try:
1366 return socket.gethostbyname(host)
1367 except socket.gaierror:
1368 return None
1369
1370class FTPHandler(BaseHandler):
1371 def ftp_open(self, req):
1372 import ftplib
1373 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001374 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001375 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001376 raise URLError('ftp error: no host given')
1377 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001378 if port is None:
1379 port = ftplib.FTP_PORT
1380 else:
1381 port = int(port)
1382
1383 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001384 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001385 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001386 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001387 else:
1388 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001389 host = unquote(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +00001390 user = user or ''
1391 passwd = passwd or ''
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001392
1393 try:
1394 host = socket.gethostbyname(host)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001395 except OSError as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001396 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001397 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001398 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001399 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001400 dirs, file = dirs[:-1], dirs[-1]
1401 if dirs and not dirs[0]:
1402 dirs = dirs[1:]
1403 try:
1404 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1405 type = file and 'I' or 'D'
1406 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001407 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001408 if attr.lower() == 'type' and \
1409 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1410 type = value.upper()
1411 fp, retrlen = fw.retrfile(file, type)
1412 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001413 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001414 if mtype:
1415 headers += "Content-type: %s\n" % mtype
1416 if retrlen is not None and retrlen >= 0:
1417 headers += "Content-length: %d\n" % retrlen
1418 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001419 return addinfourl(fp, headers, req.full_url)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001420 except ftplib.all_errors as exp:
1421 exc = URLError('ftp error: %r' % exp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001422 raise exc.with_traceback(sys.exc_info()[2])
1423
1424 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001425 return ftpwrapper(user, passwd, host, port, dirs, timeout,
1426 persistent=False)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001427
1428class CacheFTPHandler(FTPHandler):
1429 # XXX would be nice to have pluggable cache strategies
1430 # XXX this stuff is definitely not thread safe
1431 def __init__(self):
1432 self.cache = {}
1433 self.timeout = {}
1434 self.soonest = 0
1435 self.delay = 60
1436 self.max_conns = 16
1437
1438 def setTimeout(self, t):
1439 self.delay = t
1440
1441 def setMaxConns(self, m):
1442 self.max_conns = m
1443
1444 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1445 key = user, host, port, '/'.join(dirs), timeout
1446 if key in self.cache:
1447 self.timeout[key] = time.time() + self.delay
1448 else:
1449 self.cache[key] = ftpwrapper(user, passwd, host, port,
1450 dirs, timeout)
1451 self.timeout[key] = time.time() + self.delay
1452 self.check_cache()
1453 return self.cache[key]
1454
1455 def check_cache(self):
1456 # first check for old ones
1457 t = time.time()
1458 if self.soonest <= t:
1459 for k, v in list(self.timeout.items()):
1460 if v < t:
1461 self.cache[k].close()
1462 del self.cache[k]
1463 del self.timeout[k]
1464 self.soonest = min(list(self.timeout.values()))
1465
1466 # then check the size
1467 if len(self.cache) == self.max_conns:
1468 for k, v in list(self.timeout.items()):
1469 if v == self.soonest:
1470 del self.cache[k]
1471 del self.timeout[k]
1472 break
1473 self.soonest = min(list(self.timeout.values()))
1474
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001475 def clear_cache(self):
1476 for conn in self.cache.values():
1477 conn.close()
1478 self.cache.clear()
1479 self.timeout.clear()
1480
Antoine Pitroudf204be2012-11-24 17:59:08 +01001481class DataHandler(BaseHandler):
1482 def data_open(self, req):
1483 # data URLs as specified in RFC 2397.
1484 #
1485 # ignores POSTed data
1486 #
1487 # syntax:
1488 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1489 # mediatype := [ type "/" subtype ] *( ";" parameter )
1490 # data := *urlchar
1491 # parameter := attribute "=" value
1492 url = req.full_url
1493
1494 scheme, data = url.split(":",1)
1495 mediatype, data = data.split(",",1)
1496
1497 # even base64 encoded data URLs might be quoted so unquote in any case:
1498 data = unquote_to_bytes(data)
1499 if mediatype.endswith(";base64"):
1500 data = base64.decodebytes(data)
1501 mediatype = mediatype[:-7]
1502
1503 if not mediatype:
1504 mediatype = "text/plain;charset=US-ASCII"
1505
1506 headers = email.message_from_string("Content-type: %s\nContent-length: %d\n" %
1507 (mediatype, len(data)))
1508
1509 return addinfourl(io.BytesIO(data), headers, url)
1510
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001511
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001512# Code move from the old urllib module
1513
1514MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1515
1516# Helper for non-unix systems
Ronald Oussoren94f25282010-05-05 19:11:21 +00001517if os.name == 'nt':
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001518 from nturl2path import url2pathname, pathname2url
1519else:
1520 def url2pathname(pathname):
1521 """OS-specific conversion from a relative URL of the 'file' scheme
1522 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001523 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001524
1525 def pathname2url(pathname):
1526 """OS-specific conversion from a file system path to a relative URL
1527 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001528 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001529
1530# This really consists of two pieces:
1531# (1) a class which handles opening of all sorts of URLs
1532# (plus assorted utilities etc.)
1533# (2) a set of functions for parsing URLs
1534# XXX Should these be separated out into different modules?
1535
1536
1537ftpcache = {}
1538class URLopener:
1539 """Class to open URLs.
1540 This is a class rather than just a subroutine because we may need
1541 more than one set of global protocol-specific options.
1542 Note -- this is a base class for those who don't want the
1543 automatic handling of errors type 302 (relocated) and 401
1544 (authorization needed)."""
1545
1546 __tempfiles = None
1547
1548 version = "Python-urllib/%s" % __version__
1549
1550 # Constructor
1551 def __init__(self, proxies=None, **x509):
Georg Brandlfcbdbf22012-06-24 19:56:31 +02001552 msg = "%(class)s style of invoking requests is deprecated. " \
Senthil Kumaran38b968b92012-03-14 13:43:53 -07001553 "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
1554 warnings.warn(msg, DeprecationWarning, stacklevel=3)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001555 if proxies is None:
1556 proxies = getproxies()
1557 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1558 self.proxies = proxies
1559 self.key_file = x509.get('key_file')
1560 self.cert_file = x509.get('cert_file')
1561 self.addheaders = [('User-Agent', self.version)]
1562 self.__tempfiles = []
1563 self.__unlink = os.unlink # See cleanup()
1564 self.tempcache = None
1565 # Undocumented feature: if you assign {} to tempcache,
1566 # it is used to cache files retrieved with
1567 # self.retrieve(). This is not enabled by default
1568 # since it does not work for changing documents (and I
1569 # haven't got the logic to check expiration headers
1570 # yet).
1571 self.ftpcache = ftpcache
1572 # Undocumented feature: you can use a different
1573 # ftp cache by assigning to the .ftpcache member;
1574 # in case you want logically independent URL openers
1575 # XXX This is not threadsafe. Bah.
1576
1577 def __del__(self):
1578 self.close()
1579
1580 def close(self):
1581 self.cleanup()
1582
1583 def cleanup(self):
1584 # This code sometimes runs when the rest of this module
1585 # has already been deleted, so it can't use any globals
1586 # or import anything.
1587 if self.__tempfiles:
1588 for file in self.__tempfiles:
1589 try:
1590 self.__unlink(file)
1591 except OSError:
1592 pass
1593 del self.__tempfiles[:]
1594 if self.tempcache:
1595 self.tempcache.clear()
1596
1597 def addheader(self, *args):
1598 """Add a header to be used by the HTTP interface only
1599 e.g. u.addheader('Accept', 'sound/basic')"""
1600 self.addheaders.append(args)
1601
1602 # External interface
1603 def open(self, fullurl, data=None):
1604 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001605 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran734f0592010-02-20 22:19:04 +00001606 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001607 if self.tempcache and fullurl in self.tempcache:
1608 filename, headers = self.tempcache[fullurl]
1609 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001610 return addinfourl(fp, headers, fullurl)
1611 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001612 if not urltype:
1613 urltype = 'file'
1614 if urltype in self.proxies:
1615 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001616 urltype, proxyhost = splittype(proxy)
1617 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001618 url = (host, fullurl) # Signal special case to open_*()
1619 else:
1620 proxy = None
1621 name = 'open_' + urltype
1622 self.type = urltype
1623 name = name.replace('-', '_')
1624 if not hasattr(self, name):
1625 if proxy:
1626 return self.open_unknown_proxy(proxy, fullurl, data)
1627 else:
1628 return self.open_unknown(fullurl, data)
1629 try:
1630 if data is None:
1631 return getattr(self, name)(url)
1632 else:
1633 return getattr(self, name)(url, data)
Senthil Kumaranf5776862012-10-21 13:30:02 -07001634 except (HTTPError, URLError):
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001635 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +02001636 except OSError as msg:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001637 raise OSError('socket error', msg).with_traceback(sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001638
1639 def open_unknown(self, fullurl, data=None):
1640 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001641 type, url = splittype(fullurl)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001642 raise OSError('url error', 'unknown url type', type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001643
1644 def open_unknown_proxy(self, proxy, fullurl, data=None):
1645 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001646 type, url = splittype(fullurl)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001647 raise OSError('url error', 'invalid proxy for %s' % type, proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001648
1649 # External interface
1650 def retrieve(self, url, filename=None, reporthook=None, data=None):
1651 """retrieve(url) returns (filename, headers) for a local object
1652 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001653 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001654 if self.tempcache and url in self.tempcache:
1655 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001656 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001657 if filename is None and (not type or type == 'file'):
1658 try:
1659 fp = self.open_local_file(url1)
1660 hdrs = fp.info()
Philip Jenveycb134d72009-12-03 02:45:01 +00001661 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001662 return url2pathname(splithost(url1)[1]), hdrs
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001663 except OSError as msg:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001664 pass
1665 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001666 try:
1667 headers = fp.info()
1668 if filename:
1669 tfp = open(filename, 'wb')
1670 else:
1671 import tempfile
1672 garbage, path = splittype(url)
1673 garbage, path = splithost(path or "")
1674 path, garbage = splitquery(path or "")
1675 path, garbage = splitattr(path or "")
1676 suffix = os.path.splitext(path)[1]
1677 (fd, filename) = tempfile.mkstemp(suffix)
1678 self.__tempfiles.append(filename)
1679 tfp = os.fdopen(fd, 'wb')
1680 try:
1681 result = filename, headers
1682 if self.tempcache is not None:
1683 self.tempcache[url] = result
1684 bs = 1024*8
1685 size = -1
1686 read = 0
1687 blocknum = 0
Senthil Kumarance260142011-11-01 01:35:17 +08001688 if "content-length" in headers:
1689 size = int(headers["Content-Length"])
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001690 if reporthook:
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001691 reporthook(blocknum, bs, size)
1692 while 1:
1693 block = fp.read(bs)
1694 if not block:
1695 break
1696 read += len(block)
1697 tfp.write(block)
1698 blocknum += 1
1699 if reporthook:
1700 reporthook(blocknum, bs, size)
1701 finally:
1702 tfp.close()
1703 finally:
1704 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001705
1706 # raise exception if actual size does not match content-length header
1707 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001708 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001709 "retrieval incomplete: got only %i out of %i bytes"
1710 % (read, size), result)
1711
1712 return result
1713
1714 # Each method named open_<type> knows how to open that type of URL
1715
1716 def _open_generic_http(self, connection_factory, url, data):
1717 """Make an HTTP connection using connection_class.
1718
1719 This is an internal method that should be called from
1720 open_http() or open_https().
1721
1722 Arguments:
1723 - connection_factory should take a host name and return an
1724 HTTPConnection instance.
1725 - url is the url to retrieval or a host, relative-path pair.
1726 - data is payload for a POST request or None.
1727 """
1728
1729 user_passwd = None
1730 proxy_passwd= None
1731 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001732 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001733 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001734 user_passwd, host = splituser(host)
1735 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001736 realhost = host
1737 else:
1738 host, selector = url
1739 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001740 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001741 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001742 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001743 url = rest
1744 user_passwd = None
1745 if urltype.lower() != 'http':
1746 realhost = None
1747 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001748 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001749 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001750 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001751 if user_passwd:
1752 selector = "%s://%s%s" % (urltype, realhost, rest)
1753 if proxy_bypass(realhost):
1754 host = realhost
1755
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001756 if not host: raise OSError('http error', 'no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001757
1758 if proxy_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001759 proxy_passwd = unquote(proxy_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001760 proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001761 else:
1762 proxy_auth = None
1763
1764 if user_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001765 user_passwd = unquote(user_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001766 auth = base64.b64encode(user_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001767 else:
1768 auth = None
1769 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001770 headers = {}
1771 if proxy_auth:
1772 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1773 if auth:
1774 headers["Authorization"] = "Basic %s" % auth
1775 if realhost:
1776 headers["Host"] = realhost
Senthil Kumarand91ffca2011-03-19 17:25:27 +08001777
1778 # Add Connection:close as we don't support persistent connections yet.
1779 # This helps in closing the socket and avoiding ResourceWarning
1780
1781 headers["Connection"] = "close"
1782
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001783 for header, value in self.addheaders:
1784 headers[header] = value
1785
1786 if data is not None:
1787 headers["Content-Type"] = "application/x-www-form-urlencoded"
1788 http_conn.request("POST", selector, data, headers)
1789 else:
1790 http_conn.request("GET", selector, headers=headers)
1791
1792 try:
1793 response = http_conn.getresponse()
1794 except http.client.BadStatusLine:
1795 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001796 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001797
1798 # According to RFC 2616, "2xx" code indicates that the client's
1799 # request was successfully received, understood, and accepted.
1800 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001801 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001802 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001803 else:
1804 return self.http_error(
1805 url, response.fp,
1806 response.status, response.reason, response.msg, data)
1807
1808 def open_http(self, url, data=None):
1809 """Use HTTP protocol."""
1810 return self._open_generic_http(http.client.HTTPConnection, url, data)
1811
1812 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1813 """Handle http errors.
1814
1815 Derived class can override this, or provide specific handlers
1816 named http_error_DDD where DDD is the 3-digit error code."""
1817 # First check if there's a specific handler for this error
1818 name = 'http_error_%d' % errcode
1819 if hasattr(self, name):
1820 method = getattr(self, name)
1821 if data is None:
1822 result = method(url, fp, errcode, errmsg, headers)
1823 else:
1824 result = method(url, fp, errcode, errmsg, headers, data)
1825 if result: return result
1826 return self.http_error_default(url, fp, errcode, errmsg, headers)
1827
1828 def http_error_default(self, url, fp, errcode, errmsg, headers):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001829 """Default error handler: close the connection and raise OSError."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001830 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001831 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001832
1833 if _have_ssl:
1834 def _https_connection(self, host):
1835 return http.client.HTTPSConnection(host,
1836 key_file=self.key_file,
1837 cert_file=self.cert_file)
1838
1839 def open_https(self, url, data=None):
1840 """Use HTTPS protocol."""
1841 return self._open_generic_http(self._https_connection, url, data)
1842
1843 def open_file(self, url):
1844 """Use local file or FTP depending on form of URL."""
1845 if not isinstance(url, str):
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001846 raise URLError('file error: proxy support for file protocol currently not implemented')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001847 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001848 raise ValueError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001849 else:
1850 return self.open_local_file(url)
1851
1852 def open_local_file(self, url):
1853 """Use local file."""
Senthil Kumaran6c5bd402011-11-01 23:20:31 +08001854 import email.utils
1855 import mimetypes
Georg Brandl13e89462008-07-01 19:56:00 +00001856 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001857 localname = url2pathname(file)
1858 try:
1859 stats = os.stat(localname)
1860 except OSError as e:
Senthil Kumaranf5776862012-10-21 13:30:02 -07001861 raise URLError(e.strerror, e.filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001862 size = stats.st_size
1863 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1864 mtype = mimetypes.guess_type(url)[0]
1865 headers = email.message_from_string(
1866 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1867 (mtype or 'text/plain', size, modified))
1868 if not host:
1869 urlfile = file
1870 if file[:1] == '/':
1871 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001872 return addinfourl(open(localname, 'rb'), headers, urlfile)
1873 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001874 if (not port
Senthil Kumaran40d80782012-10-22 09:43:04 -07001875 and socket.gethostbyname(host) in ((localhost(),) + thishost())):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001876 urlfile = file
1877 if file[:1] == '/':
1878 urlfile = 'file://' + file
Senthil Kumaran3800ea92012-01-21 11:52:48 +08001879 elif file[:2] == './':
1880 raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
Georg Brandl13e89462008-07-01 19:56:00 +00001881 return addinfourl(open(localname, 'rb'), headers, urlfile)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001882 raise URLError('local file error: not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001883
1884 def open_ftp(self, url):
1885 """Use FTP protocol."""
1886 if not isinstance(url, str):
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001887 raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001888 import mimetypes
Georg Brandl13e89462008-07-01 19:56:00 +00001889 host, path = splithost(url)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001890 if not host: raise URLError('ftp error: no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001891 host, port = splitport(host)
1892 user, host = splituser(host)
1893 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001894 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001895 host = unquote(host)
1896 user = unquote(user or '')
1897 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001898 host = socket.gethostbyname(host)
1899 if not port:
1900 import ftplib
1901 port = ftplib.FTP_PORT
1902 else:
1903 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001904 path, attrs = splitattr(path)
1905 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001906 dirs = path.split('/')
1907 dirs, file = dirs[:-1], dirs[-1]
1908 if dirs and not dirs[0]: dirs = dirs[1:]
1909 if dirs and not dirs[0]: dirs[0] = '/'
1910 key = user, host, port, '/'.join(dirs)
1911 # XXX thread unsafe!
1912 if len(self.ftpcache) > MAXFTPCACHE:
1913 # Prune the cache, rather arbitrarily
Benjamin Peterson3c2dca62014-06-07 15:08:04 -07001914 for k in list(self.ftpcache):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001915 if k != key:
1916 v = self.ftpcache[k]
1917 del self.ftpcache[k]
1918 v.close()
1919 try:
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08001920 if key not in self.ftpcache:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001921 self.ftpcache[key] = \
1922 ftpwrapper(user, passwd, host, port, dirs)
1923 if not file: type = 'D'
1924 else: type = 'I'
1925 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001926 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001927 if attr.lower() == 'type' and \
1928 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1929 type = value.upper()
1930 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1931 mtype = mimetypes.guess_type("ftp:" + url)[0]
1932 headers = ""
1933 if mtype:
1934 headers += "Content-Type: %s\n" % mtype
1935 if retrlen is not None and retrlen >= 0:
1936 headers += "Content-Length: %d\n" % retrlen
1937 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001938 return addinfourl(fp, headers, "ftp:" + url)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001939 except ftperrors() as exp:
1940 raise URLError('ftp error %r' % exp).with_traceback(sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001941
1942 def open_data(self, url, data=None):
1943 """Use "data" URL."""
1944 if not isinstance(url, str):
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001945 raise URLError('data error: proxy support for data protocol currently not implemented')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001946 # ignore POSTed data
1947 #
1948 # syntax of data URLs:
1949 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1950 # mediatype := [ type "/" subtype ] *( ";" parameter )
1951 # data := *urlchar
1952 # parameter := attribute "=" value
1953 try:
1954 [type, data] = url.split(',', 1)
1955 except ValueError:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001956 raise OSError('data error', 'bad data URL')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001957 if not type:
1958 type = 'text/plain;charset=US-ASCII'
1959 semi = type.rfind(';')
1960 if semi >= 0 and '=' not in type[semi:]:
1961 encoding = type[semi+1:]
1962 type = type[:semi]
1963 else:
1964 encoding = ''
1965 msg = []
Senthil Kumaranf6c456d2010-05-01 08:29:18 +00001966 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001967 time.gmtime(time.time())))
1968 msg.append('Content-type: %s' % type)
1969 if encoding == 'base64':
Georg Brandl706824f2009-06-04 09:42:55 +00001970 # XXX is this encoding/decoding ok?
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001971 data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001972 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001973 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001974 msg.append('Content-Length: %d' % len(data))
1975 msg.append('')
1976 msg.append(data)
1977 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001978 headers = email.message_from_string(msg)
1979 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001980 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001981 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001982
1983
1984class FancyURLopener(URLopener):
1985 """Derived class with handlers for errors we can handle (perhaps)."""
1986
1987 def __init__(self, *args, **kwargs):
1988 URLopener.__init__(self, *args, **kwargs)
1989 self.auth_cache = {}
1990 self.tries = 0
1991 self.maxtries = 10
1992
1993 def http_error_default(self, url, fp, errcode, errmsg, headers):
1994 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001995 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001996
1997 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1998 """Error 302 -- relocated (temporarily)."""
1999 self.tries += 1
2000 if self.maxtries and self.tries >= self.maxtries:
2001 if hasattr(self, "http_error_500"):
2002 meth = self.http_error_500
2003 else:
2004 meth = self.http_error_default
2005 self.tries = 0
2006 return meth(url, fp, 500,
2007 "Internal Server Error: Redirect Recursion", headers)
2008 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
2009 data)
2010 self.tries = 0
2011 return result
2012
2013 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
2014 if 'location' in headers:
2015 newurl = headers['location']
2016 elif 'uri' in headers:
2017 newurl = headers['uri']
2018 else:
2019 return
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002020 fp.close()
guido@google.coma119df92011-03-29 11:41:02 -07002021
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002022 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00002023 newurl = urljoin(self.type + ":" + url, newurl)
guido@google.coma119df92011-03-29 11:41:02 -07002024
2025 urlparts = urlparse(newurl)
2026
2027 # For security reasons, we don't allow redirection to anything other
2028 # than http, https and ftp.
2029
2030 # We are using newer HTTPError with older redirect_internal method
2031 # This older method will get deprecated in 3.3
2032
Senthil Kumaran6497aa32012-01-04 13:46:59 +08002033 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
guido@google.coma119df92011-03-29 11:41:02 -07002034 raise HTTPError(newurl, errcode,
2035 errmsg +
2036 " Redirection to url '%s' is not allowed." % newurl,
2037 headers, fp)
2038
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002039 return self.open(newurl)
2040
2041 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
2042 """Error 301 -- also relocated (permanently)."""
2043 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2044
2045 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
2046 """Error 303 -- also relocated (essentially identical to 302)."""
2047 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2048
2049 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
2050 """Error 307 -- relocated, but turn POST into error."""
2051 if data is None:
2052 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2053 else:
2054 return self.http_error_default(url, fp, errcode, errmsg, headers)
2055
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002056 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
2057 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002058 """Error 401 -- authentication required.
2059 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08002060 if 'www-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002061 URLopener.http_error_default(self, url, fp,
2062 errcode, errmsg, headers)
2063 stuff = headers['www-authenticate']
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002064 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2065 if not match:
2066 URLopener.http_error_default(self, url, fp,
2067 errcode, errmsg, headers)
2068 scheme, realm = match.groups()
2069 if scheme.lower() != 'basic':
2070 URLopener.http_error_default(self, url, fp,
2071 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002072 if not retry:
2073 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2074 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002075 name = 'retry_' + self.type + '_basic_auth'
2076 if data is None:
2077 return getattr(self,name)(url, realm)
2078 else:
2079 return getattr(self,name)(url, realm, data)
2080
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002081 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
2082 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002083 """Error 407 -- proxy authentication required.
2084 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08002085 if 'proxy-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002086 URLopener.http_error_default(self, url, fp,
2087 errcode, errmsg, headers)
2088 stuff = headers['proxy-authenticate']
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002089 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2090 if not match:
2091 URLopener.http_error_default(self, url, fp,
2092 errcode, errmsg, headers)
2093 scheme, realm = match.groups()
2094 if scheme.lower() != 'basic':
2095 URLopener.http_error_default(self, url, fp,
2096 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002097 if not retry:
2098 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2099 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002100 name = 'retry_proxy_' + self.type + '_basic_auth'
2101 if data is None:
2102 return getattr(self,name)(url, realm)
2103 else:
2104 return getattr(self,name)(url, realm, data)
2105
2106 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002107 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002108 newurl = 'http://' + host + selector
2109 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00002110 urltype, proxyhost = splittype(proxy)
2111 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002112 i = proxyhost.find('@') + 1
2113 proxyhost = proxyhost[i:]
2114 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2115 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002116 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002117 quote(passwd, safe=''), proxyhost)
2118 self.proxies['http'] = 'http://' + proxyhost + proxyselector
2119 if data is None:
2120 return self.open(newurl)
2121 else:
2122 return self.open(newurl, data)
2123
2124 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002125 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002126 newurl = 'https://' + host + selector
2127 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00002128 urltype, proxyhost = splittype(proxy)
2129 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002130 i = proxyhost.find('@') + 1
2131 proxyhost = proxyhost[i:]
2132 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2133 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002134 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002135 quote(passwd, safe=''), proxyhost)
2136 self.proxies['https'] = 'https://' + proxyhost + proxyselector
2137 if data is None:
2138 return self.open(newurl)
2139 else:
2140 return self.open(newurl, data)
2141
2142 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002143 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002144 i = host.find('@') + 1
2145 host = host[i:]
2146 user, passwd = self.get_user_passwd(host, realm, i)
2147 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002148 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002149 quote(passwd, safe=''), host)
2150 newurl = 'http://' + host + selector
2151 if data is None:
2152 return self.open(newurl)
2153 else:
2154 return self.open(newurl, data)
2155
2156 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002157 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002158 i = host.find('@') + 1
2159 host = host[i:]
2160 user, passwd = self.get_user_passwd(host, realm, i)
2161 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002162 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002163 quote(passwd, safe=''), host)
2164 newurl = 'https://' + host + selector
2165 if data is None:
2166 return self.open(newurl)
2167 else:
2168 return self.open(newurl, data)
2169
Florent Xicluna757445b2010-05-17 17:24:07 +00002170 def get_user_passwd(self, host, realm, clear_cache=0):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002171 key = realm + '@' + host.lower()
2172 if key in self.auth_cache:
2173 if clear_cache:
2174 del self.auth_cache[key]
2175 else:
2176 return self.auth_cache[key]
2177 user, passwd = self.prompt_user_passwd(host, realm)
2178 if user or passwd: self.auth_cache[key] = (user, passwd)
2179 return user, passwd
2180
2181 def prompt_user_passwd(self, host, realm):
2182 """Override this in a GUI environment!"""
2183 import getpass
2184 try:
2185 user = input("Enter username for %s at %s: " % (realm, host))
2186 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
2187 (user, realm, host))
2188 return user, passwd
2189 except KeyboardInterrupt:
2190 print()
2191 return None, None
2192
2193
2194# Utility functions
2195
2196_localhost = None
2197def localhost():
2198 """Return the IP address of the magic hostname 'localhost'."""
2199 global _localhost
2200 if _localhost is None:
2201 _localhost = socket.gethostbyname('localhost')
2202 return _localhost
2203
2204_thishost = None
2205def thishost():
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00002206 """Return the IP addresses of the current host."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002207 global _thishost
2208 if _thishost is None:
Senthil Kumarandcdadfe2013-06-01 11:12:17 -07002209 try:
2210 _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
2211 except socket.gaierror:
2212 _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002213 return _thishost
2214
2215_ftperrors = None
2216def ftperrors():
2217 """Return the set of errors raised by the FTP class."""
2218 global _ftperrors
2219 if _ftperrors is None:
2220 import ftplib
2221 _ftperrors = ftplib.all_errors
2222 return _ftperrors
2223
2224_noheaders = None
2225def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002226 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002227 global _noheaders
2228 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002229 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002230 return _noheaders
2231
2232
2233# Utility classes
2234
2235class ftpwrapper:
2236 """Class used by open_ftp() for cache of open FTP connections."""
2237
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002238 def __init__(self, user, passwd, host, port, dirs, timeout=None,
2239 persistent=True):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002240 self.user = user
2241 self.passwd = passwd
2242 self.host = host
2243 self.port = port
2244 self.dirs = dirs
2245 self.timeout = timeout
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002246 self.refcount = 0
2247 self.keepalive = persistent
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002248 self.init()
2249
2250 def init(self):
2251 import ftplib
2252 self.busy = 0
2253 self.ftp = ftplib.FTP()
2254 self.ftp.connect(self.host, self.port, self.timeout)
2255 self.ftp.login(self.user, self.passwd)
Senthil Kumarancaa00fe2013-06-02 11:59:47 -07002256 _target = '/'.join(self.dirs)
2257 self.ftp.cwd(_target)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002258
2259 def retrfile(self, file, type):
2260 import ftplib
2261 self.endtransfer()
2262 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2263 else: cmd = 'TYPE ' + type; isdir = 0
2264 try:
2265 self.ftp.voidcmd(cmd)
2266 except ftplib.all_errors:
2267 self.init()
2268 self.ftp.voidcmd(cmd)
2269 conn = None
2270 if file and not isdir:
2271 # Try to retrieve as a file
2272 try:
2273 cmd = 'RETR ' + file
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002274 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002275 except ftplib.error_perm as reason:
2276 if str(reason)[:3] != '550':
Benjamin Peterson901a2782013-05-12 19:01:52 -05002277 raise URLError('ftp error: %r' % reason).with_traceback(
Georg Brandl13e89462008-07-01 19:56:00 +00002278 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002279 if not conn:
2280 # Set transfer mode to ASCII!
2281 self.ftp.voidcmd('TYPE A')
2282 # Try a directory listing. Verify that directory exists.
2283 if file:
2284 pwd = self.ftp.pwd()
2285 try:
2286 try:
2287 self.ftp.cwd(file)
2288 except ftplib.error_perm as reason:
Benjamin Peterson901a2782013-05-12 19:01:52 -05002289 raise URLError('ftp error: %r' % reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002290 finally:
2291 self.ftp.cwd(pwd)
2292 cmd = 'LIST ' + file
2293 else:
2294 cmd = 'LIST'
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002295 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002296 self.busy = 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002297
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002298 ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
2299 self.refcount += 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002300 conn.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002301 # Pass back both a suitably decorated object and a retrieval length
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002302 return (ftpobj, retrlen)
2303
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002304 def endtransfer(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002305 self.busy = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002306
2307 def close(self):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002308 self.keepalive = False
2309 if self.refcount <= 0:
2310 self.real_close()
2311
2312 def file_close(self):
2313 self.endtransfer()
2314 self.refcount -= 1
2315 if self.refcount <= 0 and not self.keepalive:
2316 self.real_close()
2317
2318 def real_close(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002319 self.endtransfer()
2320 try:
2321 self.ftp.close()
2322 except ftperrors():
2323 pass
2324
2325# Proxy handling
2326def getproxies_environment():
2327 """Return a dictionary of scheme -> proxy server URL mappings.
2328
2329 Scan the environment for variables named <scheme>_proxy;
2330 this seems to be the standard convention. If you need a
2331 different way, you can pass a proxies dictionary to the
2332 [Fancy]URLopener constructor.
2333
2334 """
2335 proxies = {}
2336 for name, value in os.environ.items():
2337 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002338 if value and name[-6:] == '_proxy':
2339 proxies[name[:-6]] = value
2340 return proxies
2341
2342def proxy_bypass_environment(host):
2343 """Test if proxies should not be used for a particular host.
2344
2345 Checks the environment for a variable named no_proxy, which should
2346 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2347 """
2348 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2349 # '*' is special case for always bypass
2350 if no_proxy == '*':
2351 return 1
2352 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002353 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002354 # check if the host ends with any of the DNS suffixes
Senthil Kumaran89976f12011-08-06 12:27:40 +08002355 no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
2356 for name in no_proxy_list:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002357 if name and (hostonly.endswith(name) or host.endswith(name)):
2358 return 1
2359 # otherwise, don't bypass
2360 return 0
2361
2362
Ronald Oussorene72e1612011-03-14 18:15:25 -04002363# This code tests an OSX specific data structure but is testable on all
2364# platforms
2365def _proxy_bypass_macosx_sysconf(host, proxy_settings):
2366 """
2367 Return True iff this host shouldn't be accessed using a proxy
2368
2369 This function uses the MacOSX framework SystemConfiguration
2370 to fetch the proxy information.
2371
2372 proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
2373 { 'exclude_simple': bool,
2374 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
2375 }
2376 """
Ronald Oussorene72e1612011-03-14 18:15:25 -04002377 from fnmatch import fnmatch
2378
2379 hostonly, port = splitport(host)
2380
2381 def ip2num(ipAddr):
2382 parts = ipAddr.split('.')
2383 parts = list(map(int, parts))
2384 if len(parts) != 4:
2385 parts = (parts + [0, 0, 0, 0])[:4]
2386 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2387
2388 # Check for simple host names:
2389 if '.' not in host:
2390 if proxy_settings['exclude_simple']:
2391 return True
2392
2393 hostIP = None
2394
2395 for value in proxy_settings.get('exceptions', ()):
2396 # Items in the list are strings like these: *.local, 169.254/16
2397 if not value: continue
2398
2399 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2400 if m is not None:
2401 if hostIP is None:
2402 try:
2403 hostIP = socket.gethostbyname(hostonly)
2404 hostIP = ip2num(hostIP)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002405 except OSError:
Ronald Oussorene72e1612011-03-14 18:15:25 -04002406 continue
2407
2408 base = ip2num(m.group(1))
2409 mask = m.group(2)
2410 if mask is None:
2411 mask = 8 * (m.group(1).count('.') + 1)
2412 else:
2413 mask = int(mask[1:])
2414 mask = 32 - mask
2415
2416 if (hostIP >> mask) == (base >> mask):
2417 return True
2418
2419 elif fnmatch(host, value):
2420 return True
2421
2422 return False
2423
2424
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002425if sys.platform == 'darwin':
Ronald Oussoren84151202010-04-18 20:46:11 +00002426 from _scproxy import _get_proxy_settings, _get_proxies
2427
2428 def proxy_bypass_macosx_sysconf(host):
Ronald Oussoren84151202010-04-18 20:46:11 +00002429 proxy_settings = _get_proxy_settings()
Ronald Oussorene72e1612011-03-14 18:15:25 -04002430 return _proxy_bypass_macosx_sysconf(host, proxy_settings)
Ronald Oussoren84151202010-04-18 20:46:11 +00002431
2432 def getproxies_macosx_sysconf():
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002433 """Return a dictionary of scheme -> proxy server URL mappings.
2434
Ronald Oussoren84151202010-04-18 20:46:11 +00002435 This function uses the MacOSX framework SystemConfiguration
2436 to fetch the proxy information.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002437 """
Ronald Oussoren84151202010-04-18 20:46:11 +00002438 return _get_proxies()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002439
Ronald Oussoren84151202010-04-18 20:46:11 +00002440
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002441
2442 def proxy_bypass(host):
2443 if getproxies_environment():
2444 return proxy_bypass_environment(host)
2445 else:
Ronald Oussoren84151202010-04-18 20:46:11 +00002446 return proxy_bypass_macosx_sysconf(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002447
2448 def getproxies():
Ronald Oussoren84151202010-04-18 20:46:11 +00002449 return getproxies_environment() or getproxies_macosx_sysconf()
2450
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002451
2452elif os.name == 'nt':
2453 def getproxies_registry():
2454 """Return a dictionary of scheme -> proxy server URL mappings.
2455
2456 Win32 uses the registry to store proxies.
2457
2458 """
2459 proxies = {}
2460 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002461 import winreg
Brett Cannoncd171c82013-07-04 17:43:24 -04002462 except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002463 # Std module, so should be around - but you never know!
2464 return proxies
2465 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002466 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002467 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002468 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002469 'ProxyEnable')[0]
2470 if proxyEnable:
2471 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002472 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002473 'ProxyServer')[0])
2474 if '=' in proxyServer:
2475 # Per-protocol settings
2476 for p in proxyServer.split(';'):
2477 protocol, address = p.split('=', 1)
2478 # See if address has a type:// prefix
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002479 if not re.match('^([^/:]+)://', address):
2480 address = '%s://%s' % (protocol, address)
2481 proxies[protocol] = address
2482 else:
2483 # Use one setting for all protocols
2484 if proxyServer[:5] == 'http:':
2485 proxies['http'] = proxyServer
2486 else:
2487 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran04f31b82010-07-14 20:10:52 +00002488 proxies['https'] = 'https://%s' % proxyServer
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002489 proxies['ftp'] = 'ftp://%s' % proxyServer
2490 internetSettings.Close()
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02002491 except (OSError, ValueError, TypeError):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002492 # Either registry key not found etc, or the value in an
2493 # unexpected format.
2494 # proxies already set up to be empty so nothing to do
2495 pass
2496 return proxies
2497
2498 def getproxies():
2499 """Return a dictionary of scheme -> proxy server URL mappings.
2500
2501 Returns settings gathered from the environment, if specified,
2502 or the registry.
2503
2504 """
2505 return getproxies_environment() or getproxies_registry()
2506
2507 def proxy_bypass_registry(host):
2508 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002509 import winreg
Brett Cannoncd171c82013-07-04 17:43:24 -04002510 except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002511 # Std modules, so should be around - but you never know!
2512 return 0
2513 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002514 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002515 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002516 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002517 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002518 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002519 'ProxyOverride')[0])
2520 # ^^^^ Returned as Unicode but problems if not converted to ASCII
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02002521 except OSError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002522 return 0
2523 if not proxyEnable or not proxyOverride:
2524 return 0
2525 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002526 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002527 host = [rawHost]
2528 try:
2529 addr = socket.gethostbyname(rawHost)
2530 if addr != rawHost:
2531 host.append(addr)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002532 except OSError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002533 pass
2534 try:
2535 fqdn = socket.getfqdn(rawHost)
2536 if fqdn != rawHost:
2537 host.append(fqdn)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002538 except OSError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002539 pass
2540 # make a check value list from the registry entry: replace the
2541 # '<local>' string by the localhost entry and the corresponding
2542 # canonical entry.
2543 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002544 # now check if we match one of the registry values.
2545 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002546 if test == '<local>':
2547 if '.' not in rawHost:
2548 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002549 test = test.replace(".", r"\.") # mask dots
2550 test = test.replace("*", r".*") # change glob sequence
2551 test = test.replace("?", r".") # change glob char
2552 for val in host:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002553 if re.match(test, val, re.I):
2554 return 1
2555 return 0
2556
2557 def proxy_bypass(host):
2558 """Return a dictionary of scheme -> proxy server URL mappings.
2559
2560 Returns settings gathered from the environment, if specified,
2561 or the registry.
2562
2563 """
2564 if getproxies_environment():
2565 return proxy_bypass_environment(host)
2566 else:
2567 return proxy_bypass_registry(host)
2568
2569else:
2570 # By default use environment variables
2571 getproxies = getproxies_environment
2572 proxy_bypass = proxy_bypass_environment