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