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