Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1 | """An extensible library for opening URLs using a variety of protocols |
| 2 | |
| 3 | The simplest way to use this module is to call the urlopen function, |
| 4 | which accepts a string containing a URL or a Request object (described |
| 5 | below). It opens the URL and returns the results as file-like |
| 6 | object; the returned object has some extra methods described below. |
| 7 | |
| 8 | The OpenerDirector manages a collection of Handler objects that do |
| 9 | all the actual work. Each Handler implements a particular protocol or |
| 10 | option. The OpenerDirector is a composite object that invokes the |
| 11 | Handlers needed to open the requested URL. For example, the |
| 12 | HTTPHandler performs HTTP GET and POST requests and deals with |
| 13 | non-error returns. The HTTPRedirectHandler automatically deals with |
| 14 | HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler |
| 15 | deals with digest authentication. |
| 16 | |
| 17 | urlopen(url, data=None) -- Basic usage is the same as original |
| 18 | urllib. pass the url and optionally data to post to an HTTP URL, and |
| 19 | get a file-like object back. One difference is that you can also pass |
| 20 | a Request instance instead of URL. Raises a URLError (subclass of |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 21 | OSError); for HTTP errors, raises an HTTPError, which can also be |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 22 | treated as a valid response. |
| 23 | |
| 24 | build_opener -- Function that creates a new OpenerDirector instance. |
| 25 | Will install the default handlers. Accepts one or more Handlers as |
| 26 | arguments, either instances or Handler classes that it will |
| 27 | instantiate. If one of the argument is a subclass of the default |
| 28 | handler, the argument will be installed instead of the default. |
| 29 | |
| 30 | install_opener -- Installs a new opener as the default opener. |
| 31 | |
| 32 | objects of interest: |
Senthil Kumaran | 1107c5d | 2009-11-15 06:20:55 +0000 | [diff] [blame] | 33 | |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 34 | OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages |
| 35 | the Handler classes, while dealing with requests and responses. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 36 | |
| 37 | Request -- An object that encapsulates the state of a request. The |
| 38 | state can be as simple as the URL. It can also include extra HTTP |
| 39 | headers, e.g. a User-Agent. |
| 40 | |
| 41 | BaseHandler -- |
| 42 | |
| 43 | internals: |
| 44 | BaseHandler and parent |
| 45 | _call_chain conventions |
| 46 | |
| 47 | Example usage: |
| 48 | |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 49 | import urllib.request |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 50 | |
| 51 | # set up authentication info |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 52 | authinfo = urllib.request.HTTPBasicAuthHandler() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 53 | authinfo.add_password(realm='PDQ Application', |
| 54 | uri='https://mahler:8092/site-updates.py', |
| 55 | user='klem', |
| 56 | passwd='geheim$parole') |
| 57 | |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 58 | proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 59 | |
| 60 | # build a new opener that adds authentication and caching FTP handlers |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 61 | opener = urllib.request.build_opener(proxy_support, authinfo, |
| 62 | urllib.request.CacheFTPHandler) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 63 | |
| 64 | # install it |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 65 | urllib.request.install_opener(opener) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 66 | |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 67 | f = urllib.request.urlopen('http://www.python.org/') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 68 | """ |
| 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 | |
| 84 | import base64 |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 85 | import bisect |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 86 | import email |
| 87 | import hashlib |
| 88 | import http.client |
| 89 | import io |
| 90 | import os |
| 91 | import posixpath |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 92 | import re |
| 93 | import socket |
| 94 | import sys |
| 95 | import time |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 96 | import collections |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 97 | import tempfile |
| 98 | import contextlib |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 99 | import warnings |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 100 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 101 | |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 102 | from urllib.error import URLError, HTTPError, ContentTooShortError |
| 103 | from urllib.parse import ( |
| 104 | urlparse, urlsplit, urljoin, unwrap, quote, unquote, |
| 105 | splittype, splithost, splitport, splituser, splitpasswd, |
Antoine Pitrou | df204be | 2012-11-24 17:59:08 +0100 | [diff] [blame] | 106 | splitattr, splitquery, splitvalue, splittag, to_bytes, |
| 107 | unquote_to_bytes, urlunparse) |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 108 | from urllib.response import addinfourl, addclosehook |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 109 | |
| 110 | # check for SSL |
| 111 | try: |
| 112 | import ssl |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 113 | except ImportError: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 114 | _have_ssl = False |
| 115 | else: |
| 116 | _have_ssl = True |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 117 | |
Senthil Kumaran | 6c5bd40 | 2011-11-01 23:20:31 +0800 | [diff] [blame] | 118 | __all__ = [ |
| 119 | # Classes |
| 120 | 'Request', 'OpenerDirector', 'BaseHandler', 'HTTPDefaultErrorHandler', |
| 121 | 'HTTPRedirectHandler', 'HTTPCookieProcessor', 'ProxyHandler', |
| 122 | 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm', |
| 123 | 'AbstractBasicAuthHandler', 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler', |
| 124 | 'AbstractDigestAuthHandler', 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler', |
Antoine Pitrou | df204be | 2012-11-24 17:59:08 +0100 | [diff] [blame] | 125 | 'HTTPHandler', 'FileHandler', 'FTPHandler', 'CacheFTPHandler', 'DataHandler', |
Senthil Kumaran | 6c5bd40 | 2011-11-01 23:20:31 +0800 | [diff] [blame] | 126 | '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 Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 134 | # used in User-Agent header sent |
| 135 | __version__ = sys.version[:3] |
| 136 | |
| 137 | _opener = None |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 138 | def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, |
Antoine Pitrou | de9ac6c | 2012-05-16 21:40:01 +0200 | [diff] [blame] | 139 | *, cafile=None, capath=None, cadefault=False): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 140 | global _opener |
Antoine Pitrou | de9ac6c | 2012-05-16 21:40:01 +0200 | [diff] [blame] | 141 | if cafile or capath or cadefault: |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 142 | if not _have_ssl: |
| 143 | raise ValueError('SSL support not available') |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 144 | context = ssl._create_stdlib_context(cert_reqs=ssl.CERT_REQUIRED, |
| 145 | cafile=cafile, |
| 146 | capath=capath) |
Antoine Pitrou | 9a8d693 | 2013-04-01 18:55:35 +0200 | [diff] [blame] | 147 | https_handler = HTTPSHandler(context=context, check_hostname=True) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 148 | 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 Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 154 | |
| 155 | def install_opener(opener): |
| 156 | global _opener |
| 157 | _opener = opener |
| 158 | |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 159 | _url_tempfiles = [] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 160 | def urlretrieve(url, filename=None, reporthook=None, data=None): |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 161 | """ |
| 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. Smith | 6b0bdab | 2012-11-10 13:43:44 -0800 | [diff] [blame] | 204 | reporthook(blocknum, bs, size) |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 205 | |
| 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. Smith | 6b0bdab | 2012-11-10 13:43:44 -0800 | [diff] [blame] | 214 | reporthook(blocknum, bs, size) |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 215 | |
| 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 Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 222 | |
| 223 | def urlcleanup(): |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 224 | for temp_file in _url_tempfiles: |
| 225 | try: |
| 226 | os.unlink(temp_file) |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 227 | except OSError: |
Senthil Kumaran | e24f96a | 2012-03-13 19:29:33 -0700 | [diff] [blame] | 228 | pass |
| 229 | |
| 230 | del _url_tempfiles[:] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 231 | global _opener |
| 232 | if _opener: |
| 233 | _opener = None |
| 234 | |
| 235 | # copied from cookielib.py |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 236 | _cut_port_re = re.compile(r":\d+$", re.ASCII) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 237 | def 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 244 | url = request.full_url |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 245 | host = urlparse(url)[1] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 246 | 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 | |
| 253 | class Request: |
| 254 | |
| 255 | def __init__(self, url, data=None, headers={}, |
Senthil Kumaran | de49d64 | 2011-10-16 23:54:44 +0800 | [diff] [blame] | 256 | origin_req_host=None, unverifiable=False, |
| 257 | method=None): |
Senthil Kumaran | 5238092 | 2013-04-25 05:45:48 -0700 | [diff] [blame] | 258 | self.full_url = url |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 259 | self.headers = {} |
Andrew Svetlov | bff98fe | 2012-11-27 23:06:19 +0200 | [diff] [blame] | 260 | self.unredirected_hdrs = {} |
| 261 | self._data = None |
| 262 | self.data = data |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 263 | self._tunnel_host = None |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 264 | for key, value in headers.items(): |
| 265 | self.add_header(key, value) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 266 | 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. Coombs | 7dc4f4b | 2013-09-08 12:47:07 -0400 | [diff] [blame] | 270 | if method: |
| 271 | self.method = method |
Senthil Kumaran | 5238092 | 2013-04-25 05:45:48 -0700 | [diff] [blame] | 272 | |
| 273 | @property |
| 274 | def full_url(self): |
Senthil Kumaran | 8307075 | 2013-05-24 09:14:12 -0700 | [diff] [blame] | 275 | if self.fragment: |
| 276 | return '{}#{}'.format(self._full_url, self.fragment) |
Senthil Kumaran | 5238092 | 2013-04-25 05:45:48 -0700 | [diff] [blame] | 277 | 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 284 | self._parse() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 285 | |
Senthil Kumaran | 5238092 | 2013-04-25 05:45:48 -0700 | [diff] [blame] | 286 | @full_url.deleter |
| 287 | def full_url(self): |
| 288 | self._full_url = None |
| 289 | self.fragment = None |
| 290 | self.selector = '' |
| 291 | |
Andrew Svetlov | bff98fe | 2012-11-27 23:06:19 +0200 | [diff] [blame] | 292 | @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 Murray | 9cc7d45 | 2013-03-20 00:10:51 -0400 | [diff] [blame] | 308 | self.data = None |
Andrew Svetlov | bff98fe | 2012-11-27 23:06:19 +0200 | [diff] [blame] | 309 | |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 310 | def _parse(self): |
Senthil Kumaran | 5238092 | 2013-04-25 05:45:48 -0700 | [diff] [blame] | 311 | self.type, rest = splittype(self._full_url) |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 312 | if self.type is None: |
R David Murray | d8a4696 | 2013-04-03 06:58:34 -0400 | [diff] [blame] | 313 | raise ValueError("unknown url type: %r" % self.full_url) |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 314 | self.host, self.selector = splithost(rest) |
| 315 | if self.host: |
| 316 | self.host = unquote(self.host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 317 | |
| 318 | def get_method(self): |
Senthil Kumaran | de49d64 | 2011-10-16 23:54:44 +0800 | [diff] [blame] | 319 | """Return a string indicating the HTTP request method.""" |
Jason R. Coombs | aae6a1d | 2013-09-08 12:54:33 -0400 | [diff] [blame] | 320 | default_method = "POST" if self.data is not None else "GET" |
| 321 | return getattr(self, 'method', default_method) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 322 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 323 | def get_full_url(self): |
Senthil Kumaran | 5238092 | 2013-04-25 05:45:48 -0700 | [diff] [blame] | 324 | return self.full_url |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 325 | |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 326 | def set_proxy(self, host, type): |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 327 | 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 333 | |
| 334 | def has_proxy(self): |
| 335 | return self.selector == self.full_url |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 336 | |
| 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 Svetlov | bff98fe | 2012-11-27 23:06:19 +0200 | [diff] [blame] | 354 | def remove_header(self, header_name): |
| 355 | self.headers.pop(header_name, None) |
| 356 | self.unredirected_hdrs.pop(header_name, None) |
| 357 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 358 | def header_items(self): |
| 359 | hdrs = self.unredirected_hdrs.copy() |
| 360 | hdrs.update(self.headers) |
| 361 | return list(hdrs.items()) |
| 362 | |
| 363 | class OpenerDirector: |
| 364 | def __init__(self): |
| 365 | client_version = "Python-urllib/%s" % __version__ |
| 366 | self.addheaders = [('User-agent', client_version)] |
R. David Murray | 25b8cca | 2010-12-23 19:44:49 +0000 | [diff] [blame] | 367 | # self.handlers is retained only for backward compatibility |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 368 | self.handlers = [] |
R. David Murray | 25b8cca | 2010-12-23 19:44:49 +0000 | [diff] [blame] | 369 | # manage the individual handlers |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 370 | 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 Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 419 | 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 Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 433 | 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 444 | req.data = data |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 445 | |
| 446 | req.timeout = timeout |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 447 | protocol = req.type |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 448 | |
| 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 471 | protocol = req.type |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 472 | 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 | |
| 505 | def 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 Kumaran | 1107c5d | 2009-11-15 06:20:55 +0000 | [diff] [blame] | 509 | for HTTP, FTP and when applicable HTTPS. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 510 | |
| 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 Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 514 | opener = OpenerDirector() |
| 515 | default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, |
| 516 | HTTPDefaultErrorHandler, HTTPRedirectHandler, |
Antoine Pitrou | df204be | 2012-11-24 17:59:08 +0100 | [diff] [blame] | 517 | FTPHandler, FileHandler, HTTPErrorProcessor, |
| 518 | DataHandler] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 519 | if hasattr(http.client, "HTTPSConnection"): |
| 520 | default_classes.append(HTTPSHandler) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 521 | skip = set() |
| 522 | for klass in default_classes: |
| 523 | for check in handlers: |
Benjamin Peterson | 78c8538 | 2014-04-01 16:27:30 -0400 | [diff] [blame] | 524 | if isinstance(check, type): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 525 | 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 Peterson | 5dd3cae | 2014-04-01 14:20:56 -0400 | [diff] [blame] | 536 | if isinstance(h, type): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 537 | h = h() |
| 538 | opener.add_handler(h) |
| 539 | return opener |
| 540 | |
| 541 | class 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 | |
| 560 | class 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 | |
| 577 | class HTTPDefaultErrorHandler(BaseHandler): |
| 578 | def http_error_default(self, req, fp, code, msg, hdrs): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 579 | raise HTTPError(req.full_url, code, msg, hdrs, fp) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 580 | |
| 581 | class 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 602 | raise HTTPError(req.full_url, code, msg, headers, fp) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 603 | |
| 604 | # Strictly (according to RFC 2616), 301 or 302 in response to |
| 605 | # a POST MUST NOT cause a redirection without confirmation |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 606 | # from the user (of urllib.request, in this case). In practice, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 607 | # 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 616 | origin_req_host=req.origin_req_host, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 617 | 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 Batista | f24802c | 2008-08-17 03:36:03 +0000 | [diff] [blame] | 632 | |
| 633 | # fix a possible malformed URL |
| 634 | urlparts = urlparse(newurl) |
guido@google.com | a119df9 | 2011-03-29 11:41:02 -0700 | [diff] [blame] | 635 | |
| 636 | # For security reasons we don't allow redirection to anything other |
| 637 | # than http, https or ftp. |
| 638 | |
Senthil Kumaran | 6497aa3 | 2012-01-04 13:46:59 +0800 | [diff] [blame] | 639 | if urlparts.scheme not in ('http', 'https', 'ftp', ''): |
Senthil Kumaran | 34d38dc | 2011-10-20 02:48:01 +0800 | [diff] [blame] | 640 | raise HTTPError( |
| 641 | newurl, code, |
| 642 | "%s - Redirection to url '%s' is not allowed" % (msg, newurl), |
| 643 | headers, fp) |
guido@google.com | a119df9 | 2011-03-29 11:41:02 -0700 | [diff] [blame] | 644 | |
Facundo Batista | f24802c | 2008-08-17 03:36:03 +0000 | [diff] [blame] | 645 | if not urlparts.path: |
| 646 | urlparts = list(urlparts) |
| 647 | urlparts[2] = "/" |
| 648 | newurl = urlunparse(urlparts) |
| 649 | |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 650 | newurl = urljoin(req.full_url, newurl) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 651 | |
| 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 Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 665 | raise HTTPError(req.full_url, code, |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 666 | self.inf_msg + msg, headers, fp) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 667 | 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 Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 676 | return self.parent.open(new, timeout=req.timeout) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 677 | |
| 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 | |
| 685 | def _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 Kumaran | d8e24f1 | 2014-04-14 16:32:20 -0400 | [diff] [blame] | 690 | have two slashes after the scheme. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 691 | """ |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 692 | scheme, r_scheme = splittype(proxy) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 693 | 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 Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 707 | userinfo, hostport = splituser(authority) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 708 | if userinfo is not None: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 709 | user, password = splitpasswd(userinfo) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 710 | else: |
| 711 | user = password = None |
| 712 | return scheme, user, password, hostport |
| 713 | |
| 714 | class 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 Brandl | fcbdbf2 | 2012-06-24 19:56:31 +0200 | [diff] [blame] | 725 | lambda r, proxy=url, type=type, meth=self.proxy_open: |
| 726 | meth(r, proxy, type)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 727 | |
| 728 | def proxy_open(self, req, proxy, type): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 729 | orig_type = req.type |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 730 | proxy_type, user, password, hostport = _parse_proxy(proxy) |
| 731 | if proxy_type is None: |
| 732 | proxy_type = orig_type |
Senthil Kumaran | 7bb0497 | 2009-10-11 04:58:55 +0000 | [diff] [blame] | 733 | |
| 734 | if req.host and proxy_bypass(req.host): |
| 735 | return None |
| 736 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 737 | if user and password: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 738 | user_pass = '%s:%s' % (unquote(user), |
| 739 | unquote(password)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 740 | creds = base64.b64encode(user_pass.encode()).decode("ascii") |
| 741 | req.add_header('Proxy-authorization', 'Basic ' + creds) |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 742 | hostport = unquote(hostport) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 743 | req.set_proxy(hostport, proxy_type) |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 744 | if orig_type == proxy_type or orig_type == 'https': |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 745 | # 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 Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 754 | return self.parent.open(req, timeout=req.timeout) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 755 | |
| 756 | class 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 Kumaran | 34d38dc | 2011-10-20 02:48:01 +0800 | [diff] [blame] | 765 | if realm not in self.passwd: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 766 | 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 Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 785 | parts = urlsplit(uri) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 786 | 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 Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 796 | host, port = splitport(authority) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 797 | 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 | |
| 820 | class 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 | |
| 830 | class 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 Kumaran | 34f3fcc | 2012-05-15 22:30:25 +0800 | [diff] [blame] | 838 | 'realm=(["\']?)([^"\']*)\\2', re.I) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 839 | |
| 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 Kumaran | 67a62a4 | 2010-08-19 17:50:31 +0000 | [diff] [blame] | 849 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 850 | def http_error_auth_reqed(self, authreq, host, req, headers): |
| 851 | # host may be an authority (without userinfo) or a URL with an |
| 852 | # authority |
| 853 | # XXX could be multiple headers |
| 854 | authreq = headers.get(authreq, None) |
Senthil Kumaran | f4998ac | 2010-06-01 12:53:48 +0000 | [diff] [blame] | 855 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 856 | if authreq: |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 857 | scheme = authreq.split()[0] |
Senthil Kumaran | 1a129c8 | 2011-10-20 02:50:13 +0800 | [diff] [blame] | 858 | if scheme.lower() != 'basic': |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 859 | raise ValueError("AbstractBasicAuthHandler does not" |
| 860 | " support the following scheme: '%s'" % |
| 861 | scheme) |
| 862 | else: |
| 863 | mo = AbstractBasicAuthHandler.rx.search(authreq) |
| 864 | if mo: |
| 865 | scheme, quote, realm = mo.groups() |
Senthil Kumaran | 92a5bf0 | 2012-05-16 00:03:29 +0800 | [diff] [blame] | 866 | if quote not in ['"',"'"]: |
| 867 | warnings.warn("Basic Auth Realm was unquoted", |
| 868 | UserWarning, 2) |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 869 | if scheme.lower() == 'basic': |
Senthil Kumaran | 7837376 | 2014-08-20 07:53:58 +0530 | [diff] [blame] | 870 | return self.retry_http_basic_auth(host, req, realm) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 871 | |
| 872 | def retry_http_basic_auth(self, host, req, realm): |
| 873 | user, pw = self.passwd.find_user_password(realm, host) |
| 874 | if pw is not None: |
| 875 | raw = "%s:%s" % (user, pw) |
| 876 | auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii") |
Senthil Kumaran | 7837376 | 2014-08-20 07:53:58 +0530 | [diff] [blame] | 877 | if req.get_header(self.auth_header, None) == auth: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 878 | return None |
Senthil Kumaran | ca2fc9e | 2010-02-24 16:53:16 +0000 | [diff] [blame] | 879 | req.add_unredirected_header(self.auth_header, auth) |
Senthil Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 880 | return self.parent.open(req, timeout=req.timeout) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 881 | else: |
| 882 | return None |
| 883 | |
| 884 | |
| 885 | class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): |
| 886 | |
| 887 | auth_header = 'Authorization' |
| 888 | |
| 889 | def http_error_401(self, req, fp, code, msg, headers): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 890 | url = req.full_url |
Senthil Kumaran | 67a62a4 | 2010-08-19 17:50:31 +0000 | [diff] [blame] | 891 | response = self.http_error_auth_reqed('www-authenticate', |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 892 | url, req, headers) |
Senthil Kumaran | 67a62a4 | 2010-08-19 17:50:31 +0000 | [diff] [blame] | 893 | return response |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 894 | |
| 895 | |
| 896 | class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): |
| 897 | |
| 898 | auth_header = 'Proxy-authorization' |
| 899 | |
| 900 | def http_error_407(self, req, fp, code, msg, headers): |
| 901 | # http_error_auth_reqed requires that there is no userinfo component in |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 902 | # authority. Assume there isn't one, since urllib.request does not (and |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 903 | # should not, RFC 3986 s. 3.2.1) support requests for URLs containing |
| 904 | # userinfo. |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 905 | authority = req.host |
Senthil Kumaran | 67a62a4 | 2010-08-19 17:50:31 +0000 | [diff] [blame] | 906 | response = self.http_error_auth_reqed('proxy-authenticate', |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 907 | authority, req, headers) |
Senthil Kumaran | 67a62a4 | 2010-08-19 17:50:31 +0000 | [diff] [blame] | 908 | return response |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 909 | |
| 910 | |
Senthil Kumaran | 6c5bd40 | 2011-11-01 23:20:31 +0800 | [diff] [blame] | 911 | # Return n random bytes. |
| 912 | _randombytes = os.urandom |
| 913 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 914 | |
| 915 | class AbstractDigestAuthHandler: |
| 916 | # Digest authentication is specified in RFC 2617. |
| 917 | |
| 918 | # XXX The client does not inspect the Authentication-Info header |
| 919 | # in a successful response. |
| 920 | |
| 921 | # XXX It should be possible to test this implementation against |
| 922 | # a mock server that just generates a static set of challenges. |
| 923 | |
| 924 | # XXX qop="auth-int" supports is shaky |
| 925 | |
| 926 | def __init__(self, passwd=None): |
| 927 | if passwd is None: |
| 928 | passwd = HTTPPasswordMgr() |
| 929 | self.passwd = passwd |
| 930 | self.add_password = self.passwd.add_password |
| 931 | self.retried = 0 |
| 932 | self.nonce_count = 0 |
Senthil Kumaran | 4c7eaee | 2009-11-15 08:43:45 +0000 | [diff] [blame] | 933 | self.last_nonce = None |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 934 | |
| 935 | def reset_retry_count(self): |
| 936 | self.retried = 0 |
| 937 | |
| 938 | def http_error_auth_reqed(self, auth_header, host, req, headers): |
| 939 | authreq = headers.get(auth_header, None) |
| 940 | if self.retried > 5: |
| 941 | # Don't fail endlessly - if we failed once, we'll probably |
| 942 | # fail a second time. Hm. Unless the Password Manager is |
| 943 | # prompting for the information. Crap. This isn't great |
| 944 | # but it's better than the current 'repeat until recursion |
| 945 | # depth exceeded' approach <wink> |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 946 | raise HTTPError(req.full_url, 401, "digest auth failed", |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 947 | headers, None) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 948 | else: |
| 949 | self.retried += 1 |
| 950 | if authreq: |
| 951 | scheme = authreq.split()[0] |
| 952 | if scheme.lower() == 'digest': |
| 953 | return self.retry_http_digest_auth(req, authreq) |
Senthil Kumaran | 1a129c8 | 2011-10-20 02:50:13 +0800 | [diff] [blame] | 954 | elif scheme.lower() != 'basic': |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 955 | raise ValueError("AbstractDigestAuthHandler does not support" |
| 956 | " the following scheme: '%s'" % scheme) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 957 | |
| 958 | def retry_http_digest_auth(self, req, auth): |
| 959 | token, challenge = auth.split(' ', 1) |
| 960 | chal = parse_keqv_list(filter(None, parse_http_list(challenge))) |
| 961 | auth = self.get_authorization(req, chal) |
| 962 | if auth: |
| 963 | auth_val = 'Digest %s' % auth |
| 964 | if req.headers.get(self.auth_header, None) == auth_val: |
| 965 | return None |
| 966 | req.add_unredirected_header(self.auth_header, auth_val) |
Senthil Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 967 | resp = self.parent.open(req, timeout=req.timeout) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 968 | return resp |
| 969 | |
| 970 | def get_cnonce(self, nonce): |
| 971 | # The cnonce-value is an opaque |
| 972 | # quoted string value provided by the client and used by both client |
| 973 | # and server to avoid chosen plaintext attacks, to provide mutual |
| 974 | # authentication, and to provide some message integrity protection. |
| 975 | # This isn't a fabulous effort, but it's probably Good Enough. |
| 976 | s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime()) |
Senthil Kumaran | 6c5bd40 | 2011-11-01 23:20:31 +0800 | [diff] [blame] | 977 | b = s.encode("ascii") + _randombytes(8) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 978 | dig = hashlib.sha1(b).hexdigest() |
| 979 | return dig[:16] |
| 980 | |
| 981 | def get_authorization(self, req, chal): |
| 982 | try: |
| 983 | realm = chal['realm'] |
| 984 | nonce = chal['nonce'] |
| 985 | qop = chal.get('qop') |
| 986 | algorithm = chal.get('algorithm', 'MD5') |
| 987 | # mod_digest doesn't send an opaque, even though it isn't |
| 988 | # supposed to be optional |
| 989 | opaque = chal.get('opaque', None) |
| 990 | except KeyError: |
| 991 | return None |
| 992 | |
| 993 | H, KD = self.get_algorithm_impls(algorithm) |
| 994 | if H is None: |
| 995 | return None |
| 996 | |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 997 | user, pw = self.passwd.find_user_password(realm, req.full_url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 998 | if user is None: |
| 999 | return None |
| 1000 | |
| 1001 | # XXX not implemented yet |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1002 | if req.data is not None: |
| 1003 | entdig = self.get_entity_digest(req.data, chal) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1004 | else: |
| 1005 | entdig = None |
| 1006 | |
| 1007 | A1 = "%s:%s:%s" % (user, realm, pw) |
| 1008 | A2 = "%s:%s" % (req.get_method(), |
| 1009 | # XXX selector: what about proxies and full urls |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1010 | req.selector) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1011 | if qop == 'auth': |
Senthil Kumaran | 4c7eaee | 2009-11-15 08:43:45 +0000 | [diff] [blame] | 1012 | if nonce == self.last_nonce: |
| 1013 | self.nonce_count += 1 |
| 1014 | else: |
| 1015 | self.nonce_count = 1 |
| 1016 | self.last_nonce = nonce |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1017 | ncvalue = '%08x' % self.nonce_count |
| 1018 | cnonce = self.get_cnonce(nonce) |
| 1019 | noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2)) |
| 1020 | respdig = KD(H(A1), noncebit) |
| 1021 | elif qop is None: |
| 1022 | respdig = KD(H(A1), "%s:%s" % (nonce, H(A2))) |
| 1023 | else: |
| 1024 | # XXX handle auth-int. |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1025 | raise URLError("qop '%s' is not supported." % qop) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1026 | |
| 1027 | # XXX should the partial digests be encoded too? |
| 1028 | |
| 1029 | base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1030 | 'response="%s"' % (user, realm, nonce, req.selector, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1031 | respdig) |
| 1032 | if opaque: |
| 1033 | base += ', opaque="%s"' % opaque |
| 1034 | if entdig: |
| 1035 | base += ', digest="%s"' % entdig |
| 1036 | base += ', algorithm="%s"' % algorithm |
| 1037 | if qop: |
| 1038 | base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce) |
| 1039 | return base |
| 1040 | |
| 1041 | def get_algorithm_impls(self, algorithm): |
| 1042 | # lambdas assume digest modules are imported at the top level |
| 1043 | if algorithm == 'MD5': |
| 1044 | H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest() |
| 1045 | elif algorithm == 'SHA': |
| 1046 | H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest() |
| 1047 | # XXX MD5-sess |
| 1048 | KD = lambda s, d: H("%s:%s" % (s, d)) |
| 1049 | return H, KD |
| 1050 | |
| 1051 | def get_entity_digest(self, data, chal): |
| 1052 | # XXX not implemented yet |
| 1053 | return None |
| 1054 | |
| 1055 | |
| 1056 | class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): |
| 1057 | """An authentication protocol defined by RFC 2069 |
| 1058 | |
| 1059 | Digest authentication improves on basic authentication because it |
| 1060 | does not transmit passwords in the clear. |
| 1061 | """ |
| 1062 | |
| 1063 | auth_header = 'Authorization' |
| 1064 | handler_order = 490 # before Basic auth |
| 1065 | |
| 1066 | def http_error_401(self, req, fp, code, msg, headers): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1067 | host = urlparse(req.full_url)[1] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1068 | retry = self.http_error_auth_reqed('www-authenticate', |
| 1069 | host, req, headers) |
| 1070 | self.reset_retry_count() |
| 1071 | return retry |
| 1072 | |
| 1073 | |
| 1074 | class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): |
| 1075 | |
| 1076 | auth_header = 'Proxy-Authorization' |
| 1077 | handler_order = 490 # before Basic auth |
| 1078 | |
| 1079 | def http_error_407(self, req, fp, code, msg, headers): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1080 | host = req.host |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1081 | retry = self.http_error_auth_reqed('proxy-authenticate', |
| 1082 | host, req, headers) |
| 1083 | self.reset_retry_count() |
| 1084 | return retry |
| 1085 | |
| 1086 | class AbstractHTTPHandler(BaseHandler): |
| 1087 | |
| 1088 | def __init__(self, debuglevel=0): |
| 1089 | self._debuglevel = debuglevel |
| 1090 | |
| 1091 | def set_http_debuglevel(self, level): |
| 1092 | self._debuglevel = level |
| 1093 | |
| 1094 | def do_request_(self, request): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1095 | host = request.host |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1096 | if not host: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1097 | raise URLError('no host given') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1098 | |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1099 | if request.data is not None: # POST |
| 1100 | data = request.data |
Senthil Kumaran | 2933312 | 2011-02-11 11:25:47 +0000 | [diff] [blame] | 1101 | if isinstance(data, str): |
Georg Brandl | fcbdbf2 | 2012-06-24 19:56:31 +0200 | [diff] [blame] | 1102 | msg = "POST data should be bytes or an iterable of bytes. " \ |
| 1103 | "It cannot be of type str." |
Senthil Kumaran | 6b3434a | 2012-03-15 18:11:16 -0700 | [diff] [blame] | 1104 | raise TypeError(msg) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1105 | if not request.has_header('Content-type'): |
| 1106 | request.add_unredirected_header( |
| 1107 | 'Content-type', |
| 1108 | 'application/x-www-form-urlencoded') |
| 1109 | if not request.has_header('Content-length'): |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 1110 | try: |
| 1111 | mv = memoryview(data) |
| 1112 | except TypeError: |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 1113 | if isinstance(data, collections.Iterable): |
Georg Brandl | 6153604 | 2011-02-03 07:46:41 +0000 | [diff] [blame] | 1114 | raise ValueError("Content-Length should be specified " |
| 1115 | "for iterable data of type %r %r" % (type(data), |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 1116 | data)) |
| 1117 | else: |
| 1118 | request.add_unredirected_header( |
Senthil Kumaran | 1e991f2 | 2010-12-24 04:03:59 +0000 | [diff] [blame] | 1119 | 'Content-length', '%d' % (len(mv) * mv.itemsize)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1120 | |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 1121 | sel_host = host |
| 1122 | if request.has_proxy(): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1123 | scheme, sel = splittype(request.selector) |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 1124 | sel_host, sel_path = splithost(sel) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1125 | if not request.has_header('Host'): |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 1126 | request.add_unredirected_header('Host', sel_host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1127 | for name, value in self.parent.addheaders: |
| 1128 | name = name.capitalize() |
| 1129 | if not request.has_header(name): |
| 1130 | request.add_unredirected_header(name, value) |
| 1131 | |
| 1132 | return request |
| 1133 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1134 | def do_open(self, http_class, req, **http_conn_args): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1135 | """Return an HTTPResponse object for the request, using http_class. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1136 | |
| 1137 | http_class must implement the HTTPConnection API from http.client. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1138 | """ |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1139 | host = req.host |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1140 | if not host: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1141 | raise URLError('no host given') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1142 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1143 | # will parse host:port |
| 1144 | h = http_class(host, timeout=req.timeout, **http_conn_args) |
Senthil Kumaran | 42ef4b1 | 2010-09-27 01:26:03 +0000 | [diff] [blame] | 1145 | |
| 1146 | headers = dict(req.unredirected_hdrs) |
| 1147 | headers.update(dict((k, v) for k, v in req.headers.items() |
| 1148 | if k not in headers)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1149 | |
| 1150 | # TODO(jhylton): Should this be redesigned to handle |
| 1151 | # persistent connections? |
| 1152 | |
| 1153 | # We want to make an HTTP/1.1 request, but the addinfourl |
| 1154 | # class isn't prepared to deal with a persistent connection. |
| 1155 | # It will try to read all remaining data from the socket, |
| 1156 | # which will block while the server waits for the next request. |
| 1157 | # So make sure the connection gets closed after the (only) |
| 1158 | # request. |
| 1159 | headers["Connection"] = "close" |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1160 | headers = dict((name.title(), val) for name, val in headers.items()) |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 1161 | |
| 1162 | if req._tunnel_host: |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 1163 | tunnel_headers = {} |
| 1164 | proxy_auth_hdr = "Proxy-Authorization" |
| 1165 | if proxy_auth_hdr in headers: |
| 1166 | tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr] |
| 1167 | # Proxy-Authorization should not be sent to origin |
| 1168 | # server. |
| 1169 | del headers[proxy_auth_hdr] |
| 1170 | h.set_tunnel(req._tunnel_host, headers=tunnel_headers) |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 1171 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1172 | try: |
Serhiy Storchaka | f54c350 | 2014-09-06 21:41:39 +0300 | [diff] [blame] | 1173 | try: |
| 1174 | h.request(req.get_method(), req.selector, req.data, headers) |
| 1175 | except OSError as err: # timeout error |
| 1176 | raise URLError(err) |
Senthil Kumaran | 45686b4 | 2011-07-27 09:31:03 +0800 | [diff] [blame] | 1177 | r = h.getresponse() |
Serhiy Storchaka | f54c350 | 2014-09-06 21:41:39 +0300 | [diff] [blame] | 1178 | except: |
| 1179 | h.close() |
| 1180 | raise |
| 1181 | |
| 1182 | # If the server does not send us a 'Connection: close' header, |
| 1183 | # HTTPConnection assumes the socket should be left open. Manually |
| 1184 | # mark the socket to be closed when this response object goes away. |
| 1185 | if h.sock: |
| 1186 | h.sock.close() |
| 1187 | h.sock = None |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1188 | |
Senthil Kumaran | 2643041 | 2011-04-13 07:01:19 +0800 | [diff] [blame] | 1189 | r.url = req.get_full_url() |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1190 | # This line replaces the .msg attribute of the HTTPResponse |
| 1191 | # with .headers, because urllib clients expect the response to |
| 1192 | # have the reason in .msg. It would be good to mark this |
| 1193 | # attribute is deprecated and get then to use info() or |
| 1194 | # .headers. |
| 1195 | r.msg = r.reason |
| 1196 | return r |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1197 | |
| 1198 | |
| 1199 | class HTTPHandler(AbstractHTTPHandler): |
| 1200 | |
| 1201 | def http_open(self, req): |
| 1202 | return self.do_open(http.client.HTTPConnection, req) |
| 1203 | |
| 1204 | http_request = AbstractHTTPHandler.do_request_ |
| 1205 | |
| 1206 | if hasattr(http.client, 'HTTPSConnection'): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1207 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1208 | class HTTPSHandler(AbstractHTTPHandler): |
| 1209 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1210 | def __init__(self, debuglevel=0, context=None, check_hostname=None): |
| 1211 | AbstractHTTPHandler.__init__(self, debuglevel) |
| 1212 | self._context = context |
| 1213 | self._check_hostname = check_hostname |
| 1214 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1215 | def https_open(self, req): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1216 | return self.do_open(http.client.HTTPSConnection, req, |
| 1217 | context=self._context, check_hostname=self._check_hostname) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1218 | |
| 1219 | https_request = AbstractHTTPHandler.do_request_ |
| 1220 | |
Senthil Kumaran | 4c875a9 | 2011-11-01 23:57:57 +0800 | [diff] [blame] | 1221 | __all__.append('HTTPSHandler') |
Senthil Kumaran | 0d54eb9 | 2011-11-01 23:49:46 +0800 | [diff] [blame] | 1222 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1223 | class HTTPCookieProcessor(BaseHandler): |
| 1224 | def __init__(self, cookiejar=None): |
| 1225 | import http.cookiejar |
| 1226 | if cookiejar is None: |
| 1227 | cookiejar = http.cookiejar.CookieJar() |
| 1228 | self.cookiejar = cookiejar |
| 1229 | |
| 1230 | def http_request(self, request): |
| 1231 | self.cookiejar.add_cookie_header(request) |
| 1232 | return request |
| 1233 | |
| 1234 | def http_response(self, request, response): |
| 1235 | self.cookiejar.extract_cookies(response, request) |
| 1236 | return response |
| 1237 | |
| 1238 | https_request = http_request |
| 1239 | https_response = http_response |
| 1240 | |
| 1241 | class UnknownHandler(BaseHandler): |
| 1242 | def unknown_open(self, req): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1243 | type = req.type |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1244 | raise URLError('unknown url type: %s' % type) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1245 | |
| 1246 | def parse_keqv_list(l): |
| 1247 | """Parse list of key=value strings where keys are not duplicated.""" |
| 1248 | parsed = {} |
| 1249 | for elt in l: |
| 1250 | k, v = elt.split('=', 1) |
| 1251 | if v[0] == '"' and v[-1] == '"': |
| 1252 | v = v[1:-1] |
| 1253 | parsed[k] = v |
| 1254 | return parsed |
| 1255 | |
| 1256 | def parse_http_list(s): |
| 1257 | """Parse lists as described by RFC 2068 Section 2. |
| 1258 | |
| 1259 | In particular, parse comma-separated lists where the elements of |
| 1260 | the list may include quoted-strings. A quoted-string could |
| 1261 | contain a comma. A non-quoted string could have quotes in the |
| 1262 | middle. Neither commas nor quotes count if they are escaped. |
| 1263 | Only double-quotes count, not single-quotes. |
| 1264 | """ |
| 1265 | res = [] |
| 1266 | part = '' |
| 1267 | |
| 1268 | escape = quote = False |
| 1269 | for cur in s: |
| 1270 | if escape: |
| 1271 | part += cur |
| 1272 | escape = False |
| 1273 | continue |
| 1274 | if quote: |
| 1275 | if cur == '\\': |
| 1276 | escape = True |
| 1277 | continue |
| 1278 | elif cur == '"': |
| 1279 | quote = False |
| 1280 | part += cur |
| 1281 | continue |
| 1282 | |
| 1283 | if cur == ',': |
| 1284 | res.append(part) |
| 1285 | part = '' |
| 1286 | continue |
| 1287 | |
| 1288 | if cur == '"': |
| 1289 | quote = True |
| 1290 | |
| 1291 | part += cur |
| 1292 | |
| 1293 | # append last part |
| 1294 | if part: |
| 1295 | res.append(part) |
| 1296 | |
| 1297 | return [part.strip() for part in res] |
| 1298 | |
| 1299 | class FileHandler(BaseHandler): |
| 1300 | # Use local file or FTP depending on form of URL |
| 1301 | def file_open(self, req): |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1302 | url = req.selector |
Senthil Kumaran | 2ef1632 | 2010-07-11 03:12:43 +0000 | [diff] [blame] | 1303 | if url[:2] == '//' and url[2:3] != '/' and (req.host and |
| 1304 | req.host != 'localhost'): |
Senthil Kumaran | bc07ac5 | 2014-07-22 00:15:20 -0700 | [diff] [blame] | 1305 | if not req.host in self.get_names(): |
Senthil Kumaran | 383c32d | 2010-10-14 11:57:35 +0000 | [diff] [blame] | 1306 | raise URLError("file:// scheme is supported only on localhost") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1307 | else: |
| 1308 | return self.open_local_file(req) |
| 1309 | |
| 1310 | # names for the localhost |
| 1311 | names = None |
| 1312 | def get_names(self): |
| 1313 | if FileHandler.names is None: |
| 1314 | try: |
Senthil Kumaran | 99b2c8f | 2009-12-27 10:13:39 +0000 | [diff] [blame] | 1315 | FileHandler.names = tuple( |
| 1316 | socket.gethostbyname_ex('localhost')[2] + |
| 1317 | socket.gethostbyname_ex(socket.gethostname())[2]) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1318 | except socket.gaierror: |
| 1319 | FileHandler.names = (socket.gethostbyname('localhost'),) |
| 1320 | return FileHandler.names |
| 1321 | |
| 1322 | # not entirely sure what the rules are here |
| 1323 | def open_local_file(self, req): |
| 1324 | import email.utils |
| 1325 | import mimetypes |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1326 | host = req.host |
Senthil Kumaran | 06f5a53 | 2010-05-08 05:12:05 +0000 | [diff] [blame] | 1327 | filename = req.selector |
| 1328 | localfile = url2pathname(filename) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1329 | try: |
| 1330 | stats = os.stat(localfile) |
| 1331 | size = stats.st_size |
| 1332 | modified = email.utils.formatdate(stats.st_mtime, usegmt=True) |
Senthil Kumaran | 06f5a53 | 2010-05-08 05:12:05 +0000 | [diff] [blame] | 1333 | mtype = mimetypes.guess_type(filename)[0] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1334 | headers = email.message_from_string( |
| 1335 | 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % |
| 1336 | (mtype or 'text/plain', size, modified)) |
| 1337 | if host: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1338 | host, port = splitport(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1339 | if not host or \ |
| 1340 | (not port and _safe_gethostbyname(host) in self.get_names()): |
Senthil Kumaran | 06f5a53 | 2010-05-08 05:12:05 +0000 | [diff] [blame] | 1341 | if host: |
| 1342 | origurl = 'file://' + host + filename |
| 1343 | else: |
| 1344 | origurl = 'file://' + filename |
| 1345 | return addinfourl(open(localfile, 'rb'), headers, origurl) |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1346 | except OSError as exp: |
Georg Brandl | 029986a | 2008-06-23 11:44:14 +0000 | [diff] [blame] | 1347 | # users shouldn't expect OSErrors coming from urlopen() |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1348 | raise URLError(exp) |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1349 | raise URLError('file not on local host') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1350 | |
| 1351 | def _safe_gethostbyname(host): |
| 1352 | try: |
| 1353 | return socket.gethostbyname(host) |
| 1354 | except socket.gaierror: |
| 1355 | return None |
| 1356 | |
| 1357 | class FTPHandler(BaseHandler): |
| 1358 | def ftp_open(self, req): |
| 1359 | import ftplib |
| 1360 | import mimetypes |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1361 | host = req.host |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1362 | if not host: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1363 | raise URLError('ftp error: no host given') |
| 1364 | host, port = splitport(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1365 | if port is None: |
| 1366 | port = ftplib.FTP_PORT |
| 1367 | else: |
| 1368 | port = int(port) |
| 1369 | |
| 1370 | # username/password handling |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1371 | user, host = splituser(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1372 | if user: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1373 | user, passwd = splitpasswd(user) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1374 | else: |
| 1375 | passwd = None |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1376 | host = unquote(host) |
Senthil Kumaran | daa29d0 | 2010-11-18 15:36:41 +0000 | [diff] [blame] | 1377 | user = user or '' |
| 1378 | passwd = passwd or '' |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1379 | |
| 1380 | try: |
| 1381 | host = socket.gethostbyname(host) |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 1382 | except OSError as msg: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1383 | raise URLError(msg) |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1384 | path, attrs = splitattr(req.selector) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1385 | dirs = path.split('/') |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1386 | dirs = list(map(unquote, dirs)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1387 | dirs, file = dirs[:-1], dirs[-1] |
| 1388 | if dirs and not dirs[0]: |
| 1389 | dirs = dirs[1:] |
| 1390 | try: |
| 1391 | fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout) |
| 1392 | type = file and 'I' or 'D' |
| 1393 | for attr in attrs: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1394 | attr, value = splitvalue(attr) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1395 | if attr.lower() == 'type' and \ |
| 1396 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
| 1397 | type = value.upper() |
| 1398 | fp, retrlen = fw.retrfile(file, type) |
| 1399 | headers = "" |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1400 | mtype = mimetypes.guess_type(req.full_url)[0] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1401 | if mtype: |
| 1402 | headers += "Content-type: %s\n" % mtype |
| 1403 | if retrlen is not None and retrlen >= 0: |
| 1404 | headers += "Content-length: %d\n" % retrlen |
| 1405 | headers = email.message_from_string(headers) |
Jeremy Hylton | 6c5e28c | 2009-03-31 14:35:53 +0000 | [diff] [blame] | 1406 | return addinfourl(fp, headers, req.full_url) |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1407 | except ftplib.all_errors as exp: |
| 1408 | exc = URLError('ftp error: %r' % exp) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1409 | raise exc.with_traceback(sys.exc_info()[2]) |
| 1410 | |
| 1411 | def connect_ftp(self, user, passwd, host, port, dirs, timeout): |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 1412 | return ftpwrapper(user, passwd, host, port, dirs, timeout, |
| 1413 | persistent=False) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1414 | |
| 1415 | class CacheFTPHandler(FTPHandler): |
| 1416 | # XXX would be nice to have pluggable cache strategies |
| 1417 | # XXX this stuff is definitely not thread safe |
| 1418 | def __init__(self): |
| 1419 | self.cache = {} |
| 1420 | self.timeout = {} |
| 1421 | self.soonest = 0 |
| 1422 | self.delay = 60 |
| 1423 | self.max_conns = 16 |
| 1424 | |
| 1425 | def setTimeout(self, t): |
| 1426 | self.delay = t |
| 1427 | |
| 1428 | def setMaxConns(self, m): |
| 1429 | self.max_conns = m |
| 1430 | |
| 1431 | def connect_ftp(self, user, passwd, host, port, dirs, timeout): |
| 1432 | key = user, host, port, '/'.join(dirs), timeout |
| 1433 | if key in self.cache: |
| 1434 | self.timeout[key] = time.time() + self.delay |
| 1435 | else: |
| 1436 | self.cache[key] = ftpwrapper(user, passwd, host, port, |
| 1437 | dirs, timeout) |
| 1438 | self.timeout[key] = time.time() + self.delay |
| 1439 | self.check_cache() |
| 1440 | return self.cache[key] |
| 1441 | |
| 1442 | def check_cache(self): |
| 1443 | # first check for old ones |
| 1444 | t = time.time() |
| 1445 | if self.soonest <= t: |
| 1446 | for k, v in list(self.timeout.items()): |
| 1447 | if v < t: |
| 1448 | self.cache[k].close() |
| 1449 | del self.cache[k] |
| 1450 | del self.timeout[k] |
| 1451 | self.soonest = min(list(self.timeout.values())) |
| 1452 | |
| 1453 | # then check the size |
| 1454 | if len(self.cache) == self.max_conns: |
| 1455 | for k, v in list(self.timeout.items()): |
| 1456 | if v == self.soonest: |
| 1457 | del self.cache[k] |
| 1458 | del self.timeout[k] |
| 1459 | break |
| 1460 | self.soonest = min(list(self.timeout.values())) |
| 1461 | |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 1462 | def clear_cache(self): |
| 1463 | for conn in self.cache.values(): |
| 1464 | conn.close() |
| 1465 | self.cache.clear() |
| 1466 | self.timeout.clear() |
| 1467 | |
Antoine Pitrou | df204be | 2012-11-24 17:59:08 +0100 | [diff] [blame] | 1468 | class DataHandler(BaseHandler): |
| 1469 | def data_open(self, req): |
| 1470 | # data URLs as specified in RFC 2397. |
| 1471 | # |
| 1472 | # ignores POSTed data |
| 1473 | # |
| 1474 | # syntax: |
| 1475 | # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data |
| 1476 | # mediatype := [ type "/" subtype ] *( ";" parameter ) |
| 1477 | # data := *urlchar |
| 1478 | # parameter := attribute "=" value |
| 1479 | url = req.full_url |
| 1480 | |
| 1481 | scheme, data = url.split(":",1) |
| 1482 | mediatype, data = data.split(",",1) |
| 1483 | |
| 1484 | # even base64 encoded data URLs might be quoted so unquote in any case: |
| 1485 | data = unquote_to_bytes(data) |
| 1486 | if mediatype.endswith(";base64"): |
| 1487 | data = base64.decodebytes(data) |
| 1488 | mediatype = mediatype[:-7] |
| 1489 | |
| 1490 | if not mediatype: |
| 1491 | mediatype = "text/plain;charset=US-ASCII" |
| 1492 | |
| 1493 | headers = email.message_from_string("Content-type: %s\nContent-length: %d\n" % |
| 1494 | (mediatype, len(data))) |
| 1495 | |
| 1496 | return addinfourl(io.BytesIO(data), headers, url) |
| 1497 | |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 1498 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1499 | # Code move from the old urllib module |
| 1500 | |
| 1501 | MAXFTPCACHE = 10 # Trim the ftp cache beyond this size |
| 1502 | |
| 1503 | # Helper for non-unix systems |
Ronald Oussoren | 94f2528 | 2010-05-05 19:11:21 +0000 | [diff] [blame] | 1504 | if os.name == 'nt': |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1505 | from nturl2path import url2pathname, pathname2url |
| 1506 | else: |
| 1507 | def url2pathname(pathname): |
| 1508 | """OS-specific conversion from a relative URL of the 'file' scheme |
| 1509 | to a file system path; not recommended for general use.""" |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1510 | return unquote(pathname) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1511 | |
| 1512 | def pathname2url(pathname): |
| 1513 | """OS-specific conversion from a file system path to a relative URL |
| 1514 | of the 'file' scheme; not recommended for general use.""" |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1515 | return quote(pathname) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1516 | |
| 1517 | # This really consists of two pieces: |
| 1518 | # (1) a class which handles opening of all sorts of URLs |
| 1519 | # (plus assorted utilities etc.) |
| 1520 | # (2) a set of functions for parsing URLs |
| 1521 | # XXX Should these be separated out into different modules? |
| 1522 | |
| 1523 | |
| 1524 | ftpcache = {} |
| 1525 | class URLopener: |
| 1526 | """Class to open URLs. |
| 1527 | This is a class rather than just a subroutine because we may need |
| 1528 | more than one set of global protocol-specific options. |
| 1529 | Note -- this is a base class for those who don't want the |
| 1530 | automatic handling of errors type 302 (relocated) and 401 |
| 1531 | (authorization needed).""" |
| 1532 | |
| 1533 | __tempfiles = None |
| 1534 | |
| 1535 | version = "Python-urllib/%s" % __version__ |
| 1536 | |
| 1537 | # Constructor |
| 1538 | def __init__(self, proxies=None, **x509): |
Georg Brandl | fcbdbf2 | 2012-06-24 19:56:31 +0200 | [diff] [blame] | 1539 | msg = "%(class)s style of invoking requests is deprecated. " \ |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 1540 | "Use newer urlopen functions/methods" % {'class': self.__class__.__name__} |
| 1541 | warnings.warn(msg, DeprecationWarning, stacklevel=3) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1542 | if proxies is None: |
| 1543 | proxies = getproxies() |
| 1544 | assert hasattr(proxies, 'keys'), "proxies must be a mapping" |
| 1545 | self.proxies = proxies |
| 1546 | self.key_file = x509.get('key_file') |
| 1547 | self.cert_file = x509.get('cert_file') |
| 1548 | self.addheaders = [('User-Agent', self.version)] |
| 1549 | self.__tempfiles = [] |
| 1550 | self.__unlink = os.unlink # See cleanup() |
| 1551 | self.tempcache = None |
| 1552 | # Undocumented feature: if you assign {} to tempcache, |
| 1553 | # it is used to cache files retrieved with |
| 1554 | # self.retrieve(). This is not enabled by default |
| 1555 | # since it does not work for changing documents (and I |
| 1556 | # haven't got the logic to check expiration headers |
| 1557 | # yet). |
| 1558 | self.ftpcache = ftpcache |
| 1559 | # Undocumented feature: you can use a different |
| 1560 | # ftp cache by assigning to the .ftpcache member; |
| 1561 | # in case you want logically independent URL openers |
| 1562 | # XXX This is not threadsafe. Bah. |
| 1563 | |
| 1564 | def __del__(self): |
| 1565 | self.close() |
| 1566 | |
| 1567 | def close(self): |
| 1568 | self.cleanup() |
| 1569 | |
| 1570 | def cleanup(self): |
| 1571 | # This code sometimes runs when the rest of this module |
| 1572 | # has already been deleted, so it can't use any globals |
| 1573 | # or import anything. |
| 1574 | if self.__tempfiles: |
| 1575 | for file in self.__tempfiles: |
| 1576 | try: |
| 1577 | self.__unlink(file) |
| 1578 | except OSError: |
| 1579 | pass |
| 1580 | del self.__tempfiles[:] |
| 1581 | if self.tempcache: |
| 1582 | self.tempcache.clear() |
| 1583 | |
| 1584 | def addheader(self, *args): |
| 1585 | """Add a header to be used by the HTTP interface only |
| 1586 | e.g. u.addheader('Accept', 'sound/basic')""" |
| 1587 | self.addheaders.append(args) |
| 1588 | |
| 1589 | # External interface |
| 1590 | def open(self, fullurl, data=None): |
| 1591 | """Use URLopener().open(file) instead of open(file, 'r').""" |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1592 | fullurl = unwrap(to_bytes(fullurl)) |
Senthil Kumaran | 734f059 | 2010-02-20 22:19:04 +0000 | [diff] [blame] | 1593 | fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1594 | if self.tempcache and fullurl in self.tempcache: |
| 1595 | filename, headers = self.tempcache[fullurl] |
| 1596 | fp = open(filename, 'rb') |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1597 | return addinfourl(fp, headers, fullurl) |
| 1598 | urltype, url = splittype(fullurl) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1599 | if not urltype: |
| 1600 | urltype = 'file' |
| 1601 | if urltype in self.proxies: |
| 1602 | proxy = self.proxies[urltype] |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1603 | urltype, proxyhost = splittype(proxy) |
| 1604 | host, selector = splithost(proxyhost) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1605 | url = (host, fullurl) # Signal special case to open_*() |
| 1606 | else: |
| 1607 | proxy = None |
| 1608 | name = 'open_' + urltype |
| 1609 | self.type = urltype |
| 1610 | name = name.replace('-', '_') |
| 1611 | if not hasattr(self, name): |
| 1612 | if proxy: |
| 1613 | return self.open_unknown_proxy(proxy, fullurl, data) |
| 1614 | else: |
| 1615 | return self.open_unknown(fullurl, data) |
| 1616 | try: |
| 1617 | if data is None: |
| 1618 | return getattr(self, name)(url) |
| 1619 | else: |
| 1620 | return getattr(self, name)(url, data) |
Senthil Kumaran | f577686 | 2012-10-21 13:30:02 -0700 | [diff] [blame] | 1621 | except (HTTPError, URLError): |
Antoine Pitrou | 6b4883d | 2011-10-12 02:54:14 +0200 | [diff] [blame] | 1622 | raise |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 1623 | except OSError as msg: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1624 | raise OSError('socket error', msg).with_traceback(sys.exc_info()[2]) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1625 | |
| 1626 | def open_unknown(self, fullurl, data=None): |
| 1627 | """Overridable interface to open unknown URL type.""" |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1628 | type, url = splittype(fullurl) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1629 | raise OSError('url error', 'unknown url type', type) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1630 | |
| 1631 | def open_unknown_proxy(self, proxy, fullurl, data=None): |
| 1632 | """Overridable interface to open unknown URL type.""" |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1633 | type, url = splittype(fullurl) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1634 | raise OSError('url error', 'invalid proxy for %s' % type, proxy) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1635 | |
| 1636 | # External interface |
| 1637 | def retrieve(self, url, filename=None, reporthook=None, data=None): |
| 1638 | """retrieve(url) returns (filename, headers) for a local object |
| 1639 | or (tempfilename, headers) for a remote object.""" |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1640 | url = unwrap(to_bytes(url)) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1641 | if self.tempcache and url in self.tempcache: |
| 1642 | return self.tempcache[url] |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1643 | type, url1 = splittype(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1644 | if filename is None and (not type or type == 'file'): |
| 1645 | try: |
| 1646 | fp = self.open_local_file(url1) |
| 1647 | hdrs = fp.info() |
Philip Jenvey | cb134d7 | 2009-12-03 02:45:01 +0000 | [diff] [blame] | 1648 | fp.close() |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1649 | return url2pathname(splithost(url1)[1]), hdrs |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1650 | except OSError as msg: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1651 | pass |
| 1652 | fp = self.open(url, data) |
Benjamin Peterson | 5f28b7b | 2009-03-26 21:49:58 +0000 | [diff] [blame] | 1653 | try: |
| 1654 | headers = fp.info() |
| 1655 | if filename: |
| 1656 | tfp = open(filename, 'wb') |
| 1657 | else: |
| 1658 | import tempfile |
| 1659 | garbage, path = splittype(url) |
| 1660 | garbage, path = splithost(path or "") |
| 1661 | path, garbage = splitquery(path or "") |
| 1662 | path, garbage = splitattr(path or "") |
| 1663 | suffix = os.path.splitext(path)[1] |
| 1664 | (fd, filename) = tempfile.mkstemp(suffix) |
| 1665 | self.__tempfiles.append(filename) |
| 1666 | tfp = os.fdopen(fd, 'wb') |
| 1667 | try: |
| 1668 | result = filename, headers |
| 1669 | if self.tempcache is not None: |
| 1670 | self.tempcache[url] = result |
| 1671 | bs = 1024*8 |
| 1672 | size = -1 |
| 1673 | read = 0 |
| 1674 | blocknum = 0 |
Senthil Kumaran | ce26014 | 2011-11-01 01:35:17 +0800 | [diff] [blame] | 1675 | if "content-length" in headers: |
| 1676 | size = int(headers["Content-Length"]) |
Benjamin Peterson | 5f28b7b | 2009-03-26 21:49:58 +0000 | [diff] [blame] | 1677 | if reporthook: |
Benjamin Peterson | 5f28b7b | 2009-03-26 21:49:58 +0000 | [diff] [blame] | 1678 | reporthook(blocknum, bs, size) |
| 1679 | while 1: |
| 1680 | block = fp.read(bs) |
| 1681 | if not block: |
| 1682 | break |
| 1683 | read += len(block) |
| 1684 | tfp.write(block) |
| 1685 | blocknum += 1 |
| 1686 | if reporthook: |
| 1687 | reporthook(blocknum, bs, size) |
| 1688 | finally: |
| 1689 | tfp.close() |
| 1690 | finally: |
| 1691 | fp.close() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1692 | |
| 1693 | # raise exception if actual size does not match content-length header |
| 1694 | if size >= 0 and read < size: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1695 | raise ContentTooShortError( |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1696 | "retrieval incomplete: got only %i out of %i bytes" |
| 1697 | % (read, size), result) |
| 1698 | |
| 1699 | return result |
| 1700 | |
| 1701 | # Each method named open_<type> knows how to open that type of URL |
| 1702 | |
| 1703 | def _open_generic_http(self, connection_factory, url, data): |
| 1704 | """Make an HTTP connection using connection_class. |
| 1705 | |
| 1706 | This is an internal method that should be called from |
| 1707 | open_http() or open_https(). |
| 1708 | |
| 1709 | Arguments: |
| 1710 | - connection_factory should take a host name and return an |
| 1711 | HTTPConnection instance. |
| 1712 | - url is the url to retrieval or a host, relative-path pair. |
| 1713 | - data is payload for a POST request or None. |
| 1714 | """ |
| 1715 | |
| 1716 | user_passwd = None |
| 1717 | proxy_passwd= None |
| 1718 | if isinstance(url, str): |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1719 | host, selector = splithost(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1720 | if host: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1721 | user_passwd, host = splituser(host) |
| 1722 | host = unquote(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1723 | realhost = host |
| 1724 | else: |
| 1725 | host, selector = url |
| 1726 | # check whether the proxy contains authorization information |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1727 | proxy_passwd, host = splituser(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1728 | # now we proceed with the url we want to obtain |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1729 | urltype, rest = splittype(selector) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1730 | url = rest |
| 1731 | user_passwd = None |
| 1732 | if urltype.lower() != 'http': |
| 1733 | realhost = None |
| 1734 | else: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1735 | realhost, rest = splithost(rest) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1736 | if realhost: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1737 | user_passwd, realhost = splituser(realhost) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1738 | if user_passwd: |
| 1739 | selector = "%s://%s%s" % (urltype, realhost, rest) |
| 1740 | if proxy_bypass(realhost): |
| 1741 | host = realhost |
| 1742 | |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1743 | if not host: raise OSError('http error', 'no host given') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1744 | |
| 1745 | if proxy_passwd: |
Senthil Kumaran | c5c5a14 | 2012-01-14 19:09:04 +0800 | [diff] [blame] | 1746 | proxy_passwd = unquote(proxy_passwd) |
Senthil Kumaran | 5626eec | 2010-08-04 17:46:23 +0000 | [diff] [blame] | 1747 | proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1748 | else: |
| 1749 | proxy_auth = None |
| 1750 | |
| 1751 | if user_passwd: |
Senthil Kumaran | c5c5a14 | 2012-01-14 19:09:04 +0800 | [diff] [blame] | 1752 | user_passwd = unquote(user_passwd) |
Senthil Kumaran | 5626eec | 2010-08-04 17:46:23 +0000 | [diff] [blame] | 1753 | auth = base64.b64encode(user_passwd.encode()).decode('ascii') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1754 | else: |
| 1755 | auth = None |
| 1756 | http_conn = connection_factory(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1757 | headers = {} |
| 1758 | if proxy_auth: |
| 1759 | headers["Proxy-Authorization"] = "Basic %s" % proxy_auth |
| 1760 | if auth: |
| 1761 | headers["Authorization"] = "Basic %s" % auth |
| 1762 | if realhost: |
| 1763 | headers["Host"] = realhost |
Senthil Kumaran | d91ffca | 2011-03-19 17:25:27 +0800 | [diff] [blame] | 1764 | |
| 1765 | # Add Connection:close as we don't support persistent connections yet. |
| 1766 | # This helps in closing the socket and avoiding ResourceWarning |
| 1767 | |
| 1768 | headers["Connection"] = "close" |
| 1769 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1770 | for header, value in self.addheaders: |
| 1771 | headers[header] = value |
| 1772 | |
| 1773 | if data is not None: |
| 1774 | headers["Content-Type"] = "application/x-www-form-urlencoded" |
| 1775 | http_conn.request("POST", selector, data, headers) |
| 1776 | else: |
| 1777 | http_conn.request("GET", selector, headers=headers) |
| 1778 | |
| 1779 | try: |
| 1780 | response = http_conn.getresponse() |
| 1781 | except http.client.BadStatusLine: |
| 1782 | # something went wrong with the HTTP status line |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1783 | raise URLError("http protocol error: bad status line") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1784 | |
| 1785 | # According to RFC 2616, "2xx" code indicates that the client's |
| 1786 | # request was successfully received, understood, and accepted. |
| 1787 | if 200 <= response.status < 300: |
Antoine Pitrou | b353c12 | 2009-02-11 00:39:14 +0000 | [diff] [blame] | 1788 | return addinfourl(response, response.msg, "http:" + url, |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1789 | response.status) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1790 | else: |
| 1791 | return self.http_error( |
| 1792 | url, response.fp, |
| 1793 | response.status, response.reason, response.msg, data) |
| 1794 | |
| 1795 | def open_http(self, url, data=None): |
| 1796 | """Use HTTP protocol.""" |
| 1797 | return self._open_generic_http(http.client.HTTPConnection, url, data) |
| 1798 | |
| 1799 | def http_error(self, url, fp, errcode, errmsg, headers, data=None): |
| 1800 | """Handle http errors. |
| 1801 | |
| 1802 | Derived class can override this, or provide specific handlers |
| 1803 | named http_error_DDD where DDD is the 3-digit error code.""" |
| 1804 | # First check if there's a specific handler for this error |
| 1805 | name = 'http_error_%d' % errcode |
| 1806 | if hasattr(self, name): |
| 1807 | method = getattr(self, name) |
| 1808 | if data is None: |
| 1809 | result = method(url, fp, errcode, errmsg, headers) |
| 1810 | else: |
| 1811 | result = method(url, fp, errcode, errmsg, headers, data) |
| 1812 | if result: return result |
| 1813 | return self.http_error_default(url, fp, errcode, errmsg, headers) |
| 1814 | |
| 1815 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1816 | """Default error handler: close the connection and raise OSError.""" |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1817 | fp.close() |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1818 | raise HTTPError(url, errcode, errmsg, headers, None) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1819 | |
| 1820 | if _have_ssl: |
| 1821 | def _https_connection(self, host): |
| 1822 | return http.client.HTTPSConnection(host, |
| 1823 | key_file=self.key_file, |
| 1824 | cert_file=self.cert_file) |
| 1825 | |
| 1826 | def open_https(self, url, data=None): |
| 1827 | """Use HTTPS protocol.""" |
| 1828 | return self._open_generic_http(self._https_connection, url, data) |
| 1829 | |
| 1830 | def open_file(self, url): |
| 1831 | """Use local file or FTP depending on form of URL.""" |
| 1832 | if not isinstance(url, str): |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1833 | raise URLError('file error: proxy support for file protocol currently not implemented') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1834 | if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/': |
Senthil Kumaran | 383c32d | 2010-10-14 11:57:35 +0000 | [diff] [blame] | 1835 | raise ValueError("file:// scheme is supported only on localhost") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1836 | else: |
| 1837 | return self.open_local_file(url) |
| 1838 | |
| 1839 | def open_local_file(self, url): |
| 1840 | """Use local file.""" |
Senthil Kumaran | 6c5bd40 | 2011-11-01 23:20:31 +0800 | [diff] [blame] | 1841 | import email.utils |
| 1842 | import mimetypes |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1843 | host, file = splithost(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1844 | localname = url2pathname(file) |
| 1845 | try: |
| 1846 | stats = os.stat(localname) |
| 1847 | except OSError as e: |
Senthil Kumaran | f577686 | 2012-10-21 13:30:02 -0700 | [diff] [blame] | 1848 | raise URLError(e.strerror, e.filename) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1849 | size = stats.st_size |
| 1850 | modified = email.utils.formatdate(stats.st_mtime, usegmt=True) |
| 1851 | mtype = mimetypes.guess_type(url)[0] |
| 1852 | headers = email.message_from_string( |
| 1853 | 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % |
| 1854 | (mtype or 'text/plain', size, modified)) |
| 1855 | if not host: |
| 1856 | urlfile = file |
| 1857 | if file[:1] == '/': |
| 1858 | urlfile = 'file://' + file |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1859 | return addinfourl(open(localname, 'rb'), headers, urlfile) |
| 1860 | host, port = splitport(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1861 | if (not port |
Senthil Kumaran | 40d8078 | 2012-10-22 09:43:04 -0700 | [diff] [blame] | 1862 | and socket.gethostbyname(host) in ((localhost(),) + thishost())): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1863 | urlfile = file |
| 1864 | if file[:1] == '/': |
| 1865 | urlfile = 'file://' + file |
Senthil Kumaran | 3800ea9 | 2012-01-21 11:52:48 +0800 | [diff] [blame] | 1866 | elif file[:2] == './': |
| 1867 | raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url) |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1868 | return addinfourl(open(localname, 'rb'), headers, urlfile) |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1869 | raise URLError('local file error: not on local host') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1870 | |
| 1871 | def open_ftp(self, url): |
| 1872 | """Use FTP protocol.""" |
| 1873 | if not isinstance(url, str): |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1874 | raise URLError('ftp error: proxy support for ftp protocol currently not implemented') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1875 | import mimetypes |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1876 | host, path = splithost(url) |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1877 | if not host: raise URLError('ftp error: no host given') |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1878 | host, port = splitport(host) |
| 1879 | user, host = splituser(host) |
| 1880 | if user: user, passwd = splitpasswd(user) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1881 | else: passwd = None |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1882 | host = unquote(host) |
| 1883 | user = unquote(user or '') |
| 1884 | passwd = unquote(passwd or '') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1885 | host = socket.gethostbyname(host) |
| 1886 | if not port: |
| 1887 | import ftplib |
| 1888 | port = ftplib.FTP_PORT |
| 1889 | else: |
| 1890 | port = int(port) |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1891 | path, attrs = splitattr(path) |
| 1892 | path = unquote(path) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1893 | dirs = path.split('/') |
| 1894 | dirs, file = dirs[:-1], dirs[-1] |
| 1895 | if dirs and not dirs[0]: dirs = dirs[1:] |
| 1896 | if dirs and not dirs[0]: dirs[0] = '/' |
| 1897 | key = user, host, port, '/'.join(dirs) |
| 1898 | # XXX thread unsafe! |
| 1899 | if len(self.ftpcache) > MAXFTPCACHE: |
| 1900 | # Prune the cache, rather arbitrarily |
Benjamin Peterson | 3c2dca6 | 2014-06-07 15:08:04 -0700 | [diff] [blame] | 1901 | for k in list(self.ftpcache): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1902 | if k != key: |
| 1903 | v = self.ftpcache[k] |
| 1904 | del self.ftpcache[k] |
| 1905 | v.close() |
| 1906 | try: |
Senthil Kumaran | 34d38dc | 2011-10-20 02:48:01 +0800 | [diff] [blame] | 1907 | if key not in self.ftpcache: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1908 | self.ftpcache[key] = \ |
| 1909 | ftpwrapper(user, passwd, host, port, dirs) |
| 1910 | if not file: type = 'D' |
| 1911 | else: type = 'I' |
| 1912 | for attr in attrs: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1913 | attr, value = splitvalue(attr) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1914 | if attr.lower() == 'type' and \ |
| 1915 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
| 1916 | type = value.upper() |
| 1917 | (fp, retrlen) = self.ftpcache[key].retrfile(file, type) |
| 1918 | mtype = mimetypes.guess_type("ftp:" + url)[0] |
| 1919 | headers = "" |
| 1920 | if mtype: |
| 1921 | headers += "Content-Type: %s\n" % mtype |
| 1922 | if retrlen is not None and retrlen >= 0: |
| 1923 | headers += "Content-Length: %d\n" % retrlen |
| 1924 | headers = email.message_from_string(headers) |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1925 | return addinfourl(fp, headers, "ftp:" + url) |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1926 | except ftperrors() as exp: |
| 1927 | raise URLError('ftp error %r' % exp).with_traceback(sys.exc_info()[2]) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1928 | |
| 1929 | def open_data(self, url, data=None): |
| 1930 | """Use "data" URL.""" |
| 1931 | if not isinstance(url, str): |
Senthil Kumaran | 3ebef36 | 2012-10-21 18:31:25 -0700 | [diff] [blame] | 1932 | raise URLError('data error: proxy support for data protocol currently not implemented') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1933 | # ignore POSTed data |
| 1934 | # |
| 1935 | # syntax of data URLs: |
| 1936 | # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data |
| 1937 | # mediatype := [ type "/" subtype ] *( ";" parameter ) |
| 1938 | # data := *urlchar |
| 1939 | # parameter := attribute "=" value |
| 1940 | try: |
| 1941 | [type, data] = url.split(',', 1) |
| 1942 | except ValueError: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1943 | raise OSError('data error', 'bad data URL') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1944 | if not type: |
| 1945 | type = 'text/plain;charset=US-ASCII' |
| 1946 | semi = type.rfind(';') |
| 1947 | if semi >= 0 and '=' not in type[semi:]: |
| 1948 | encoding = type[semi+1:] |
| 1949 | type = type[:semi] |
| 1950 | else: |
| 1951 | encoding = '' |
| 1952 | msg = [] |
Senthil Kumaran | f6c456d | 2010-05-01 08:29:18 +0000 | [diff] [blame] | 1953 | msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1954 | time.gmtime(time.time()))) |
| 1955 | msg.append('Content-type: %s' % type) |
| 1956 | if encoding == 'base64': |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 1957 | # XXX is this encoding/decoding ok? |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1958 | data = base64.decodebytes(data.encode('ascii')).decode('latin-1') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1959 | else: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1960 | data = unquote(data) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1961 | msg.append('Content-Length: %d' % len(data)) |
| 1962 | msg.append('') |
| 1963 | msg.append(data) |
| 1964 | msg = '\n'.join(msg) |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1965 | headers = email.message_from_string(msg) |
| 1966 | f = io.StringIO(msg) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1967 | #f.fileno = None # needed for addinfourl |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1968 | return addinfourl(f, headers, url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1969 | |
| 1970 | |
| 1971 | class FancyURLopener(URLopener): |
| 1972 | """Derived class with handlers for errors we can handle (perhaps).""" |
| 1973 | |
| 1974 | def __init__(self, *args, **kwargs): |
| 1975 | URLopener.__init__(self, *args, **kwargs) |
| 1976 | self.auth_cache = {} |
| 1977 | self.tries = 0 |
| 1978 | self.maxtries = 10 |
| 1979 | |
| 1980 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
| 1981 | """Default error handling -- don't raise an exception.""" |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 1982 | return addinfourl(fp, headers, "http:" + url, errcode) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1983 | |
| 1984 | def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): |
| 1985 | """Error 302 -- relocated (temporarily).""" |
| 1986 | self.tries += 1 |
| 1987 | if self.maxtries and self.tries >= self.maxtries: |
| 1988 | if hasattr(self, "http_error_500"): |
| 1989 | meth = self.http_error_500 |
| 1990 | else: |
| 1991 | meth = self.http_error_default |
| 1992 | self.tries = 0 |
| 1993 | return meth(url, fp, 500, |
| 1994 | "Internal Server Error: Redirect Recursion", headers) |
| 1995 | result = self.redirect_internal(url, fp, errcode, errmsg, headers, |
| 1996 | data) |
| 1997 | self.tries = 0 |
| 1998 | return result |
| 1999 | |
| 2000 | def redirect_internal(self, url, fp, errcode, errmsg, headers, data): |
| 2001 | if 'location' in headers: |
| 2002 | newurl = headers['location'] |
| 2003 | elif 'uri' in headers: |
| 2004 | newurl = headers['uri'] |
| 2005 | else: |
| 2006 | return |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2007 | fp.close() |
guido@google.com | a119df9 | 2011-03-29 11:41:02 -0700 | [diff] [blame] | 2008 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2009 | # In case the server sent a relative URL, join with original: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2010 | newurl = urljoin(self.type + ":" + url, newurl) |
guido@google.com | a119df9 | 2011-03-29 11:41:02 -0700 | [diff] [blame] | 2011 | |
| 2012 | urlparts = urlparse(newurl) |
| 2013 | |
| 2014 | # For security reasons, we don't allow redirection to anything other |
| 2015 | # than http, https and ftp. |
| 2016 | |
| 2017 | # We are using newer HTTPError with older redirect_internal method |
| 2018 | # This older method will get deprecated in 3.3 |
| 2019 | |
Senthil Kumaran | 6497aa3 | 2012-01-04 13:46:59 +0800 | [diff] [blame] | 2020 | if urlparts.scheme not in ('http', 'https', 'ftp', ''): |
guido@google.com | a119df9 | 2011-03-29 11:41:02 -0700 | [diff] [blame] | 2021 | raise HTTPError(newurl, errcode, |
| 2022 | errmsg + |
| 2023 | " Redirection to url '%s' is not allowed." % newurl, |
| 2024 | headers, fp) |
| 2025 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2026 | return self.open(newurl) |
| 2027 | |
| 2028 | def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): |
| 2029 | """Error 301 -- also relocated (permanently).""" |
| 2030 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
| 2031 | |
| 2032 | def http_error_303(self, url, fp, errcode, errmsg, headers, data=None): |
| 2033 | """Error 303 -- also relocated (essentially identical to 302).""" |
| 2034 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
| 2035 | |
| 2036 | def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): |
| 2037 | """Error 307 -- relocated, but turn POST into error.""" |
| 2038 | if data is None: |
| 2039 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
| 2040 | else: |
| 2041 | return self.http_error_default(url, fp, errcode, errmsg, headers) |
| 2042 | |
Senthil Kumaran | 80f1b05 | 2010-06-18 15:08:18 +0000 | [diff] [blame] | 2043 | def http_error_401(self, url, fp, errcode, errmsg, headers, data=None, |
| 2044 | retry=False): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2045 | """Error 401 -- authentication required. |
| 2046 | This function supports Basic authentication only.""" |
Senthil Kumaran | 34d38dc | 2011-10-20 02:48:01 +0800 | [diff] [blame] | 2047 | if 'www-authenticate' not in headers: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2048 | URLopener.http_error_default(self, url, fp, |
| 2049 | errcode, errmsg, headers) |
| 2050 | stuff = headers['www-authenticate'] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2051 | match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 2052 | if not match: |
| 2053 | URLopener.http_error_default(self, url, fp, |
| 2054 | errcode, errmsg, headers) |
| 2055 | scheme, realm = match.groups() |
| 2056 | if scheme.lower() != 'basic': |
| 2057 | URLopener.http_error_default(self, url, fp, |
| 2058 | errcode, errmsg, headers) |
Senthil Kumaran | 80f1b05 | 2010-06-18 15:08:18 +0000 | [diff] [blame] | 2059 | if not retry: |
| 2060 | URLopener.http_error_default(self, url, fp, errcode, errmsg, |
| 2061 | headers) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2062 | name = 'retry_' + self.type + '_basic_auth' |
| 2063 | if data is None: |
| 2064 | return getattr(self,name)(url, realm) |
| 2065 | else: |
| 2066 | return getattr(self,name)(url, realm, data) |
| 2067 | |
Senthil Kumaran | 80f1b05 | 2010-06-18 15:08:18 +0000 | [diff] [blame] | 2068 | def http_error_407(self, url, fp, errcode, errmsg, headers, data=None, |
| 2069 | retry=False): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2070 | """Error 407 -- proxy authentication required. |
| 2071 | This function supports Basic authentication only.""" |
Senthil Kumaran | 34d38dc | 2011-10-20 02:48:01 +0800 | [diff] [blame] | 2072 | if 'proxy-authenticate' not in headers: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2073 | URLopener.http_error_default(self, url, fp, |
| 2074 | errcode, errmsg, headers) |
| 2075 | stuff = headers['proxy-authenticate'] |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2076 | match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 2077 | if not match: |
| 2078 | URLopener.http_error_default(self, url, fp, |
| 2079 | errcode, errmsg, headers) |
| 2080 | scheme, realm = match.groups() |
| 2081 | if scheme.lower() != 'basic': |
| 2082 | URLopener.http_error_default(self, url, fp, |
| 2083 | errcode, errmsg, headers) |
Senthil Kumaran | 80f1b05 | 2010-06-18 15:08:18 +0000 | [diff] [blame] | 2084 | if not retry: |
| 2085 | URLopener.http_error_default(self, url, fp, errcode, errmsg, |
| 2086 | headers) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2087 | name = 'retry_proxy_' + self.type + '_basic_auth' |
| 2088 | if data is None: |
| 2089 | return getattr(self,name)(url, realm) |
| 2090 | else: |
| 2091 | return getattr(self,name)(url, realm, data) |
| 2092 | |
| 2093 | def retry_proxy_http_basic_auth(self, url, realm, data=None): |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2094 | host, selector = splithost(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2095 | newurl = 'http://' + host + selector |
| 2096 | proxy = self.proxies['http'] |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2097 | urltype, proxyhost = splittype(proxy) |
| 2098 | proxyhost, proxyselector = splithost(proxyhost) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2099 | i = proxyhost.find('@') + 1 |
| 2100 | proxyhost = proxyhost[i:] |
| 2101 | user, passwd = self.get_user_passwd(proxyhost, realm, i) |
| 2102 | if not (user or passwd): return None |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2103 | proxyhost = "%s:%s@%s" % (quote(user, safe=''), |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2104 | quote(passwd, safe=''), proxyhost) |
| 2105 | self.proxies['http'] = 'http://' + proxyhost + proxyselector |
| 2106 | if data is None: |
| 2107 | return self.open(newurl) |
| 2108 | else: |
| 2109 | return self.open(newurl, data) |
| 2110 | |
| 2111 | def retry_proxy_https_basic_auth(self, url, realm, data=None): |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2112 | host, selector = splithost(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2113 | newurl = 'https://' + host + selector |
| 2114 | proxy = self.proxies['https'] |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2115 | urltype, proxyhost = splittype(proxy) |
| 2116 | proxyhost, proxyselector = splithost(proxyhost) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2117 | i = proxyhost.find('@') + 1 |
| 2118 | proxyhost = proxyhost[i:] |
| 2119 | user, passwd = self.get_user_passwd(proxyhost, realm, i) |
| 2120 | if not (user or passwd): return None |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2121 | proxyhost = "%s:%s@%s" % (quote(user, safe=''), |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2122 | quote(passwd, safe=''), proxyhost) |
| 2123 | self.proxies['https'] = 'https://' + proxyhost + proxyselector |
| 2124 | if data is None: |
| 2125 | return self.open(newurl) |
| 2126 | else: |
| 2127 | return self.open(newurl, data) |
| 2128 | |
| 2129 | def retry_http_basic_auth(self, url, realm, data=None): |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2130 | host, selector = splithost(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2131 | i = host.find('@') + 1 |
| 2132 | host = host[i:] |
| 2133 | user, passwd = self.get_user_passwd(host, realm, i) |
| 2134 | if not (user or passwd): return None |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2135 | host = "%s:%s@%s" % (quote(user, safe=''), |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2136 | quote(passwd, safe=''), host) |
| 2137 | newurl = 'http://' + host + selector |
| 2138 | if data is None: |
| 2139 | return self.open(newurl) |
| 2140 | else: |
| 2141 | return self.open(newurl, data) |
| 2142 | |
| 2143 | def retry_https_basic_auth(self, url, realm, data=None): |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2144 | host, selector = splithost(url) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2145 | i = host.find('@') + 1 |
| 2146 | host = host[i:] |
| 2147 | user, passwd = self.get_user_passwd(host, realm, i) |
| 2148 | if not (user or passwd): return None |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2149 | host = "%s:%s@%s" % (quote(user, safe=''), |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2150 | quote(passwd, safe=''), host) |
| 2151 | newurl = 'https://' + host + selector |
| 2152 | if data is None: |
| 2153 | return self.open(newurl) |
| 2154 | else: |
| 2155 | return self.open(newurl, data) |
| 2156 | |
Florent Xicluna | 757445b | 2010-05-17 17:24:07 +0000 | [diff] [blame] | 2157 | def get_user_passwd(self, host, realm, clear_cache=0): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2158 | key = realm + '@' + host.lower() |
| 2159 | if key in self.auth_cache: |
| 2160 | if clear_cache: |
| 2161 | del self.auth_cache[key] |
| 2162 | else: |
| 2163 | return self.auth_cache[key] |
| 2164 | user, passwd = self.prompt_user_passwd(host, realm) |
| 2165 | if user or passwd: self.auth_cache[key] = (user, passwd) |
| 2166 | return user, passwd |
| 2167 | |
| 2168 | def prompt_user_passwd(self, host, realm): |
| 2169 | """Override this in a GUI environment!""" |
| 2170 | import getpass |
| 2171 | try: |
| 2172 | user = input("Enter username for %s at %s: " % (realm, host)) |
| 2173 | passwd = getpass.getpass("Enter password for %s in %s at %s: " % |
| 2174 | (user, realm, host)) |
| 2175 | return user, passwd |
| 2176 | except KeyboardInterrupt: |
| 2177 | print() |
| 2178 | return None, None |
| 2179 | |
| 2180 | |
| 2181 | # Utility functions |
| 2182 | |
| 2183 | _localhost = None |
| 2184 | def localhost(): |
| 2185 | """Return the IP address of the magic hostname 'localhost'.""" |
| 2186 | global _localhost |
| 2187 | if _localhost is None: |
| 2188 | _localhost = socket.gethostbyname('localhost') |
| 2189 | return _localhost |
| 2190 | |
| 2191 | _thishost = None |
| 2192 | def thishost(): |
Senthil Kumaran | 99b2c8f | 2009-12-27 10:13:39 +0000 | [diff] [blame] | 2193 | """Return the IP addresses of the current host.""" |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2194 | global _thishost |
| 2195 | if _thishost is None: |
Senthil Kumaran | dcdadfe | 2013-06-01 11:12:17 -0700 | [diff] [blame] | 2196 | try: |
| 2197 | _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2]) |
| 2198 | except socket.gaierror: |
| 2199 | _thishost = tuple(socket.gethostbyname_ex('localhost')[2]) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2200 | return _thishost |
| 2201 | |
| 2202 | _ftperrors = None |
| 2203 | def ftperrors(): |
| 2204 | """Return the set of errors raised by the FTP class.""" |
| 2205 | global _ftperrors |
| 2206 | if _ftperrors is None: |
| 2207 | import ftplib |
| 2208 | _ftperrors = ftplib.all_errors |
| 2209 | return _ftperrors |
| 2210 | |
| 2211 | _noheaders = None |
| 2212 | def noheaders(): |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2213 | """Return an empty email Message object.""" |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2214 | global _noheaders |
| 2215 | if _noheaders is None: |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2216 | _noheaders = email.message_from_string("") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2217 | return _noheaders |
| 2218 | |
| 2219 | |
| 2220 | # Utility classes |
| 2221 | |
| 2222 | class ftpwrapper: |
| 2223 | """Class used by open_ftp() for cache of open FTP connections.""" |
| 2224 | |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 2225 | def __init__(self, user, passwd, host, port, dirs, timeout=None, |
| 2226 | persistent=True): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2227 | self.user = user |
| 2228 | self.passwd = passwd |
| 2229 | self.host = host |
| 2230 | self.port = port |
| 2231 | self.dirs = dirs |
| 2232 | self.timeout = timeout |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 2233 | self.refcount = 0 |
| 2234 | self.keepalive = persistent |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2235 | self.init() |
| 2236 | |
| 2237 | def init(self): |
| 2238 | import ftplib |
| 2239 | self.busy = 0 |
| 2240 | self.ftp = ftplib.FTP() |
| 2241 | self.ftp.connect(self.host, self.port, self.timeout) |
| 2242 | self.ftp.login(self.user, self.passwd) |
Senthil Kumaran | caa00fe | 2013-06-02 11:59:47 -0700 | [diff] [blame] | 2243 | _target = '/'.join(self.dirs) |
| 2244 | self.ftp.cwd(_target) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2245 | |
| 2246 | def retrfile(self, file, type): |
| 2247 | import ftplib |
| 2248 | self.endtransfer() |
| 2249 | if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 |
| 2250 | else: cmd = 'TYPE ' + type; isdir = 0 |
| 2251 | try: |
| 2252 | self.ftp.voidcmd(cmd) |
| 2253 | except ftplib.all_errors: |
| 2254 | self.init() |
| 2255 | self.ftp.voidcmd(cmd) |
| 2256 | conn = None |
| 2257 | if file and not isdir: |
| 2258 | # Try to retrieve as a file |
| 2259 | try: |
| 2260 | cmd = 'RETR ' + file |
Senthil Kumaran | 2024acd | 2011-03-24 11:46:19 +0800 | [diff] [blame] | 2261 | conn, retrlen = self.ftp.ntransfercmd(cmd) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2262 | except ftplib.error_perm as reason: |
| 2263 | if str(reason)[:3] != '550': |
Benjamin Peterson | 901a278 | 2013-05-12 19:01:52 -0500 | [diff] [blame] | 2264 | raise URLError('ftp error: %r' % reason).with_traceback( |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2265 | sys.exc_info()[2]) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2266 | if not conn: |
| 2267 | # Set transfer mode to ASCII! |
| 2268 | self.ftp.voidcmd('TYPE A') |
| 2269 | # Try a directory listing. Verify that directory exists. |
| 2270 | if file: |
| 2271 | pwd = self.ftp.pwd() |
| 2272 | try: |
| 2273 | try: |
| 2274 | self.ftp.cwd(file) |
| 2275 | except ftplib.error_perm as reason: |
Benjamin Peterson | 901a278 | 2013-05-12 19:01:52 -0500 | [diff] [blame] | 2276 | raise URLError('ftp error: %r' % reason) from reason |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2277 | finally: |
| 2278 | self.ftp.cwd(pwd) |
| 2279 | cmd = 'LIST ' + file |
| 2280 | else: |
| 2281 | cmd = 'LIST' |
Senthil Kumaran | 2024acd | 2011-03-24 11:46:19 +0800 | [diff] [blame] | 2282 | conn, retrlen = self.ftp.ntransfercmd(cmd) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2283 | self.busy = 1 |
Senthil Kumaran | 2024acd | 2011-03-24 11:46:19 +0800 | [diff] [blame] | 2284 | |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 2285 | ftpobj = addclosehook(conn.makefile('rb'), self.file_close) |
| 2286 | self.refcount += 1 |
Senthil Kumaran | 2024acd | 2011-03-24 11:46:19 +0800 | [diff] [blame] | 2287 | conn.close() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2288 | # Pass back both a suitably decorated object and a retrieval length |
Senthil Kumaran | 2024acd | 2011-03-24 11:46:19 +0800 | [diff] [blame] | 2289 | return (ftpobj, retrlen) |
| 2290 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2291 | def endtransfer(self): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2292 | self.busy = 0 |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2293 | |
| 2294 | def close(self): |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 2295 | self.keepalive = False |
| 2296 | if self.refcount <= 0: |
| 2297 | self.real_close() |
| 2298 | |
| 2299 | def file_close(self): |
| 2300 | self.endtransfer() |
| 2301 | self.refcount -= 1 |
| 2302 | if self.refcount <= 0 and not self.keepalive: |
| 2303 | self.real_close() |
| 2304 | |
| 2305 | def real_close(self): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2306 | self.endtransfer() |
| 2307 | try: |
| 2308 | self.ftp.close() |
| 2309 | except ftperrors(): |
| 2310 | pass |
| 2311 | |
| 2312 | # Proxy handling |
| 2313 | def getproxies_environment(): |
| 2314 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 2315 | |
| 2316 | Scan the environment for variables named <scheme>_proxy; |
| 2317 | this seems to be the standard convention. If you need a |
| 2318 | different way, you can pass a proxies dictionary to the |
| 2319 | [Fancy]URLopener constructor. |
| 2320 | |
| 2321 | """ |
| 2322 | proxies = {} |
| 2323 | for name, value in os.environ.items(): |
| 2324 | name = name.lower() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2325 | if value and name[-6:] == '_proxy': |
| 2326 | proxies[name[:-6]] = value |
| 2327 | return proxies |
| 2328 | |
| 2329 | def proxy_bypass_environment(host): |
| 2330 | """Test if proxies should not be used for a particular host. |
| 2331 | |
| 2332 | Checks the environment for a variable named no_proxy, which should |
| 2333 | be a list of DNS suffixes separated by commas, or '*' for all hosts. |
| 2334 | """ |
| 2335 | no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '') |
| 2336 | # '*' is special case for always bypass |
| 2337 | if no_proxy == '*': |
| 2338 | return 1 |
| 2339 | # strip port off host |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2340 | hostonly, port = splitport(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2341 | # check if the host ends with any of the DNS suffixes |
Senthil Kumaran | 89976f1 | 2011-08-06 12:27:40 +0800 | [diff] [blame] | 2342 | no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')] |
| 2343 | for name in no_proxy_list: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2344 | if name and (hostonly.endswith(name) or host.endswith(name)): |
| 2345 | return 1 |
| 2346 | # otherwise, don't bypass |
| 2347 | return 0 |
| 2348 | |
| 2349 | |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 2350 | # This code tests an OSX specific data structure but is testable on all |
| 2351 | # platforms |
| 2352 | def _proxy_bypass_macosx_sysconf(host, proxy_settings): |
| 2353 | """ |
| 2354 | Return True iff this host shouldn't be accessed using a proxy |
| 2355 | |
| 2356 | This function uses the MacOSX framework SystemConfiguration |
| 2357 | to fetch the proxy information. |
| 2358 | |
| 2359 | proxy_settings come from _scproxy._get_proxy_settings or get mocked ie: |
| 2360 | { 'exclude_simple': bool, |
| 2361 | 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16'] |
| 2362 | } |
| 2363 | """ |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 2364 | from fnmatch import fnmatch |
| 2365 | |
| 2366 | hostonly, port = splitport(host) |
| 2367 | |
| 2368 | def ip2num(ipAddr): |
| 2369 | parts = ipAddr.split('.') |
| 2370 | parts = list(map(int, parts)) |
| 2371 | if len(parts) != 4: |
| 2372 | parts = (parts + [0, 0, 0, 0])[:4] |
| 2373 | return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3] |
| 2374 | |
| 2375 | # Check for simple host names: |
| 2376 | if '.' not in host: |
| 2377 | if proxy_settings['exclude_simple']: |
| 2378 | return True |
| 2379 | |
| 2380 | hostIP = None |
| 2381 | |
| 2382 | for value in proxy_settings.get('exceptions', ()): |
| 2383 | # Items in the list are strings like these: *.local, 169.254/16 |
| 2384 | if not value: continue |
| 2385 | |
| 2386 | m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value) |
| 2387 | if m is not None: |
| 2388 | if hostIP is None: |
| 2389 | try: |
| 2390 | hostIP = socket.gethostbyname(hostonly) |
| 2391 | hostIP = ip2num(hostIP) |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 2392 | except OSError: |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 2393 | continue |
| 2394 | |
| 2395 | base = ip2num(m.group(1)) |
| 2396 | mask = m.group(2) |
| 2397 | if mask is None: |
| 2398 | mask = 8 * (m.group(1).count('.') + 1) |
| 2399 | else: |
| 2400 | mask = int(mask[1:]) |
| 2401 | mask = 32 - mask |
| 2402 | |
| 2403 | if (hostIP >> mask) == (base >> mask): |
| 2404 | return True |
| 2405 | |
| 2406 | elif fnmatch(host, value): |
| 2407 | return True |
| 2408 | |
| 2409 | return False |
| 2410 | |
| 2411 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2412 | if sys.platform == 'darwin': |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2413 | from _scproxy import _get_proxy_settings, _get_proxies |
| 2414 | |
| 2415 | def proxy_bypass_macosx_sysconf(host): |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2416 | proxy_settings = _get_proxy_settings() |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 2417 | return _proxy_bypass_macosx_sysconf(host, proxy_settings) |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2418 | |
| 2419 | def getproxies_macosx_sysconf(): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2420 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 2421 | |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2422 | This function uses the MacOSX framework SystemConfiguration |
| 2423 | to fetch the proxy information. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2424 | """ |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2425 | return _get_proxies() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2426 | |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2427 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2428 | |
| 2429 | def proxy_bypass(host): |
| 2430 | if getproxies_environment(): |
| 2431 | return proxy_bypass_environment(host) |
| 2432 | else: |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2433 | return proxy_bypass_macosx_sysconf(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2434 | |
| 2435 | def getproxies(): |
Ronald Oussoren | 8415120 | 2010-04-18 20:46:11 +0000 | [diff] [blame] | 2436 | return getproxies_environment() or getproxies_macosx_sysconf() |
| 2437 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2438 | |
| 2439 | elif os.name == 'nt': |
| 2440 | def getproxies_registry(): |
| 2441 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 2442 | |
| 2443 | Win32 uses the registry to store proxies. |
| 2444 | |
| 2445 | """ |
| 2446 | proxies = {} |
| 2447 | try: |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2448 | import winreg |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 2449 | except ImportError: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2450 | # Std module, so should be around - but you never know! |
| 2451 | return proxies |
| 2452 | try: |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2453 | internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2454 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2455 | proxyEnable = winreg.QueryValueEx(internetSettings, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2456 | 'ProxyEnable')[0] |
| 2457 | if proxyEnable: |
| 2458 | # Returned as Unicode but problems if not converted to ASCII |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2459 | proxyServer = str(winreg.QueryValueEx(internetSettings, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2460 | 'ProxyServer')[0]) |
| 2461 | if '=' in proxyServer: |
| 2462 | # Per-protocol settings |
| 2463 | for p in proxyServer.split(';'): |
| 2464 | protocol, address = p.split('=', 1) |
| 2465 | # See if address has a type:// prefix |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2466 | if not re.match('^([^/:]+)://', address): |
| 2467 | address = '%s://%s' % (protocol, address) |
| 2468 | proxies[protocol] = address |
| 2469 | else: |
| 2470 | # Use one setting for all protocols |
| 2471 | if proxyServer[:5] == 'http:': |
| 2472 | proxies['http'] = proxyServer |
| 2473 | else: |
| 2474 | proxies['http'] = 'http://%s' % proxyServer |
Senthil Kumaran | 04f31b8 | 2010-07-14 20:10:52 +0000 | [diff] [blame] | 2475 | proxies['https'] = 'https://%s' % proxyServer |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2476 | proxies['ftp'] = 'ftp://%s' % proxyServer |
| 2477 | internetSettings.Close() |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 2478 | except (OSError, ValueError, TypeError): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2479 | # Either registry key not found etc, or the value in an |
| 2480 | # unexpected format. |
| 2481 | # proxies already set up to be empty so nothing to do |
| 2482 | pass |
| 2483 | return proxies |
| 2484 | |
| 2485 | def getproxies(): |
| 2486 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 2487 | |
| 2488 | Returns settings gathered from the environment, if specified, |
| 2489 | or the registry. |
| 2490 | |
| 2491 | """ |
| 2492 | return getproxies_environment() or getproxies_registry() |
| 2493 | |
| 2494 | def proxy_bypass_registry(host): |
| 2495 | try: |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2496 | import winreg |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 2497 | except ImportError: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2498 | # Std modules, so should be around - but you never know! |
| 2499 | return 0 |
| 2500 | try: |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2501 | internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2502 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2503 | proxyEnable = winreg.QueryValueEx(internetSettings, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2504 | 'ProxyEnable')[0] |
Georg Brandl | 4ed72ac | 2009-04-01 04:28:33 +0000 | [diff] [blame] | 2505 | proxyOverride = str(winreg.QueryValueEx(internetSettings, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2506 | 'ProxyOverride')[0]) |
| 2507 | # ^^^^ Returned as Unicode but problems if not converted to ASCII |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 2508 | except OSError: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2509 | return 0 |
| 2510 | if not proxyEnable or not proxyOverride: |
| 2511 | return 0 |
| 2512 | # try to make a host list from name and IP address. |
Georg Brandl | 13e8946 | 2008-07-01 19:56:00 +0000 | [diff] [blame] | 2513 | rawHost, port = splitport(host) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2514 | host = [rawHost] |
| 2515 | try: |
| 2516 | addr = socket.gethostbyname(rawHost) |
| 2517 | if addr != rawHost: |
| 2518 | host.append(addr) |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 2519 | except OSError: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2520 | pass |
| 2521 | try: |
| 2522 | fqdn = socket.getfqdn(rawHost) |
| 2523 | if fqdn != rawHost: |
| 2524 | host.append(fqdn) |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 2525 | except OSError: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2526 | pass |
| 2527 | # make a check value list from the registry entry: replace the |
| 2528 | # '<local>' string by the localhost entry and the corresponding |
| 2529 | # canonical entry. |
| 2530 | proxyOverride = proxyOverride.split(';') |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2531 | # now check if we match one of the registry values. |
| 2532 | for test in proxyOverride: |
Senthil Kumaran | 4947606 | 2009-05-01 06:00:23 +0000 | [diff] [blame] | 2533 | if test == '<local>': |
| 2534 | if '.' not in rawHost: |
| 2535 | return 1 |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2536 | test = test.replace(".", r"\.") # mask dots |
| 2537 | test = test.replace("*", r".*") # change glob sequence |
| 2538 | test = test.replace("?", r".") # change glob char |
| 2539 | for val in host: |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 2540 | if re.match(test, val, re.I): |
| 2541 | return 1 |
| 2542 | return 0 |
| 2543 | |
| 2544 | def proxy_bypass(host): |
| 2545 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 2546 | |
| 2547 | Returns settings gathered from the environment, if specified, |
| 2548 | or the registry. |
| 2549 | |
| 2550 | """ |
| 2551 | if getproxies_environment(): |
| 2552 | return proxy_bypass_environment(host) |
| 2553 | else: |
| 2554 | return proxy_bypass_registry(host) |
| 2555 | |
| 2556 | else: |
| 2557 | # By default use environment variables |
| 2558 | getproxies = getproxies_environment |
| 2559 | proxy_bypass = proxy_bypass_environment |