blob: 96bb8d70686d044e953f31f038b09e95bc631b51 [file] [log] [blame]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001"""An extensible library for opening URLs using a variety of protocols
2
3The simplest way to use this module is to call the urlopen function,
4which accepts a string containing a URL or a Request object (described
5below). It opens the URL and returns the results as file-like
6object; the returned object has some extra methods described below.
7
8The OpenerDirector manages a collection of Handler objects that do
9all the actual work. Each Handler implements a particular protocol or
10option. The OpenerDirector is a composite object that invokes the
11Handlers needed to open the requested URL. For example, the
12HTTPHandler performs HTTP GET and POST requests and deals with
13non-error returns. The HTTPRedirectHandler automatically deals with
14HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15deals with digest authentication.
16
17urlopen(url, data=None) -- Basic usage is the same as original
18urllib. pass the url and optionally data to post to an HTTP URL, and
19get a file-like object back. One difference is that you can also pass
20a Request instance instead of URL. Raises a URLError (subclass of
21IOError); for HTTP errors, raises an HTTPError, which can also be
22treated as a valid response.
23
24build_opener -- Function that creates a new OpenerDirector instance.
25Will install the default handlers. Accepts one or more Handlers as
26arguments, either instances or Handler classes that it will
27instantiate. If one of the argument is a subclass of the default
28handler, the argument will be installed instead of the default.
29
30install_opener -- Installs a new opener as the default opener.
31
32objects of interest:
Senthil Kumaran1107c5d2009-11-15 06:20:55 +000033
Senthil Kumaran47fff872009-12-20 07:10:31 +000034OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
35the Handler classes, while dealing with requests and responses.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000036
37Request -- An object that encapsulates the state of a request. The
38state can be as simple as the URL. It can also include extra HTTP
39headers, e.g. a User-Agent.
40
41BaseHandler --
42
43internals:
44BaseHandler and parent
45_call_chain conventions
46
47Example usage:
48
Georg Brandl029986a2008-06-23 11:44:14 +000049import urllib.request
Jeremy Hylton1afc1692008-06-18 20:49:58 +000050
51# set up authentication info
Georg Brandl029986a2008-06-23 11:44:14 +000052authinfo = urllib.request.HTTPBasicAuthHandler()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000053authinfo.add_password(realm='PDQ Application',
54 uri='https://mahler:8092/site-updates.py',
55 user='klem',
56 passwd='geheim$parole')
57
Georg Brandl029986a2008-06-23 11:44:14 +000058proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
Jeremy Hylton1afc1692008-06-18 20:49:58 +000059
60# build a new opener that adds authentication and caching FTP handlers
Georg Brandl029986a2008-06-23 11:44:14 +000061opener = urllib.request.build_opener(proxy_support, authinfo,
62 urllib.request.CacheFTPHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000063
64# install it
Georg Brandl029986a2008-06-23 11:44:14 +000065urllib.request.install_opener(opener)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066
Georg Brandl029986a2008-06-23 11:44:14 +000067f = urllib.request.urlopen('http://www.python.org/')
Jeremy Hylton1afc1692008-06-18 20:49:58 +000068"""
69
70# XXX issues:
71# If an authentication error handler that tries to perform
72# authentication for some reason but fails, how should the error be
73# signalled? The client needs to know the HTTP error code. But if
74# the handler knows that the problem was, e.g., that it didn't know
75# that hash algo that requested in the challenge, it would be good to
76# pass that information along to the client, too.
77# ftp errors aren't handled cleanly
78# check digest against correct (i.e. non-apache) implementation
79
80# Possible extensions:
81# complex proxies XXX not sure what exactly was meant by this
82# abstract factory for opener
83
84import base64
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +000085import bisect
Jeremy Hylton1afc1692008-06-18 20:49:58 +000086import email
87import hashlib
88import http.client
89import io
90import os
91import posixpath
Jeremy Hylton1afc1692008-06-18 20:49:58 +000092import re
93import socket
94import sys
95import time
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000096import collections
Senthil Kumarane24f96a2012-03-13 19:29:33 -070097import tempfile
98import contextlib
Senthil Kumaran38b968b2012-03-14 13:43:53 -070099import warnings
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700100
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000101
Georg Brandl13e89462008-07-01 19:56:00 +0000102from urllib.error import URLError, HTTPError, ContentTooShortError
103from urllib.parse import (
104 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
105 splittype, splithost, splitport, splituser, splitpasswd,
Senthil Kumarand95cc752010-08-08 11:27:53 +0000106 splitattr, splitquery, splitvalue, splittag, to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000107from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000108
109# check for SSL
110try:
111 import ssl
Senthil Kumaranc2958622010-11-22 04:48:26 +0000112except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000113 _have_ssl = False
114else:
115 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000116
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800117__all__ = [
118 # Classes
119 'Request', 'OpenerDirector', 'BaseHandler', 'HTTPDefaultErrorHandler',
120 'HTTPRedirectHandler', 'HTTPCookieProcessor', 'ProxyHandler',
121 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm',
122 'AbstractBasicAuthHandler', 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',
123 'AbstractDigestAuthHandler', 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',
124 'HTTPHandler', 'FileHandler', 'FTPHandler', 'CacheFTPHandler',
125 'UnknownHandler', 'HTTPErrorProcessor',
126 # Functions
127 'urlopen', 'install_opener', 'build_opener',
128 'pathname2url', 'url2pathname', 'getproxies',
129 # Legacy interface
130 'urlretrieve', 'urlcleanup', 'URLopener', 'FancyURLopener',
131]
132
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000133# used in User-Agent header sent
134__version__ = sys.version[:3]
135
136_opener = None
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000137def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
138 *, cafile=None, capath=None):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000139 global _opener
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000140 if cafile or capath:
141 if not _have_ssl:
142 raise ValueError('SSL support not available')
143 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
144 context.options |= ssl.OP_NO_SSLv2
145 if cafile or capath:
146 context.verify_mode = ssl.CERT_REQUIRED
147 context.load_verify_locations(cafile, capath)
148 check_hostname = True
149 else:
150 check_hostname = False
151 https_handler = HTTPSHandler(context=context, check_hostname=check_hostname)
152 opener = build_opener(https_handler)
153 elif _opener is None:
154 _opener = opener = build_opener()
155 else:
156 opener = _opener
157 return opener.open(url, data, timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000158
159def install_opener(opener):
160 global _opener
161 _opener = opener
162
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700163_url_tempfiles = []
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000164def urlretrieve(url, filename=None, reporthook=None, data=None):
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700165 """
166 Retrieve a URL into a temporary location on disk.
167
168 Requires a URL argument. If a filename is passed, it is used as
169 the temporary file location. The reporthook argument should be
170 a callable that accepts a block number, a read size, and the
171 total file size of the URL target. The data argument should be
172 valid URL encoded data.
173
174 If a filename is passed and the URL points to a local resource,
175 the result is a copy from local file to new file.
176
177 Returns a tuple containing the path to the newly created
178 data file as well as the resulting HTTPMessage object.
179 """
180 url_type, path = splittype(url)
181
182 with contextlib.closing(urlopen(url, data)) as fp:
183 headers = fp.info()
184
185 # Just return the local path and the "headers" for file://
186 # URLs. No sense in performing a copy unless requested.
187 if url_type == "file" and not filename:
188 return os.path.normpath(path), headers
189
190 # Handle temporary file setup.
191 if filename:
192 tfp = open(filename, 'wb')
193 else:
194 tfp = tempfile.NamedTemporaryFile(delete=False)
195 filename = tfp.name
196 _url_tempfiles.append(filename)
197
198 with tfp:
199 result = filename, headers
200 bs = 1024*8
201 size = -1
202 read = 0
203 blocknum = 0
204 if "content-length" in headers:
205 size = int(headers["Content-Length"])
206
207 if reporthook:
208 reporthook(blocknum, 0, size)
209
210 while True:
211 block = fp.read(bs)
212 if not block:
213 break
214 read += len(block)
215 tfp.write(block)
216 blocknum += 1
217 if reporthook:
218 reporthook(blocknum, len(block), size)
219
220 if size >= 0 and read < size:
221 raise ContentTooShortError(
222 "retrieval incomplete: got only %i out of %i bytes"
223 % (read, size), result)
224
225 return result
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000226
227def urlcleanup():
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700228 for temp_file in _url_tempfiles:
229 try:
230 os.unlink(temp_file)
231 except EnvironmentError:
232 pass
233
234 del _url_tempfiles[:]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000235 global _opener
236 if _opener:
237 _opener = None
238
239# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000240_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000241def request_host(request):
242 """Return request-host, as defined by RFC 2965.
243
244 Variation from RFC: returned value is lowercased, for convenient
245 comparison.
246
247 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000248 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000249 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000250 if host == "":
251 host = request.get_header("Host", "")
252
253 # remove port, if present
254 host = _cut_port_re.sub("", host, 1)
255 return host.lower()
256
257class Request:
258
259 def __init__(self, url, data=None, headers={},
Senthil Kumarande49d642011-10-16 23:54:44 +0800260 origin_req_host=None, unverifiable=False,
261 method=None):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000262 # unwrap('<URL:type://host/path>') --> 'type://host/path'
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000263 self.full_url = unwrap(url)
Senthil Kumaran26430412011-04-13 07:01:19 +0800264 self.full_url, self.fragment = splittag(self.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000265 self.data = data
266 self.headers = {}
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000267 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000268 for key, value in headers.items():
269 self.add_header(key, value)
270 self.unredirected_hdrs = {}
271 if origin_req_host is None:
272 origin_req_host = request_host(self)
273 self.origin_req_host = origin_req_host
274 self.unverifiable = unverifiable
Senthil Kumarande49d642011-10-16 23:54:44 +0800275 self.method = method
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000276 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000277
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000278 def _parse(self):
279 self.type, rest = splittype(self.full_url)
280 if self.type is None:
281 raise ValueError("unknown url type: %s" % self.full_url)
282 self.host, self.selector = splithost(rest)
283 if self.host:
284 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000285
286 def get_method(self):
Senthil Kumarande49d642011-10-16 23:54:44 +0800287 """Return a string indicating the HTTP request method."""
288 if self.method is not None:
289 return self.method
290 elif self.data is not None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000291 return "POST"
292 else:
293 return "GET"
294
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000295 def get_full_url(self):
Senthil Kumaran26430412011-04-13 07:01:19 +0800296 if self.fragment:
297 return '%s#%s' % (self.full_url, self.fragment)
298 else:
299 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000300
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700301 # Begin deprecated methods
302
303 def add_data(self, data):
304 msg = "Request.add_data method is deprecated."
305 warnings.warn(msg, DeprecationWarning, stacklevel=1)
306 self.data = data
307
308 def has_data(self):
309 msg = "Request.has_data method is deprecated."
310 warnings.warn(msg, DeprecationWarning, stacklevel=1)
311 return self.data is not None
312
313 def get_data(self):
314 msg = "Request.get_data method is deprecated."
315 warnings.warn(msg, DeprecationWarning, stacklevel=1)
316 return self.data
317
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000318 def get_type(self):
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700319 msg = "Request.get_type method is deprecated."
320 warnings.warn(msg, DeprecationWarning, stacklevel=1)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000321 return self.type
322
323 def get_host(self):
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700324 msg = "Request.get_host method is deprecated."
325 warnings.warn(msg, DeprecationWarning, stacklevel=1)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000326 return self.host
327
328 def get_selector(self):
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700329 msg = "Request.get_selector method is deprecated."
330 warnings.warn(msg, DeprecationWarning, stacklevel=1)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000331 return self.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000332
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000333 def is_unverifiable(self):
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700334 msg = "Request.is_unverifiable method is deprecated."
335 warnings.warn(msg, DeprecationWarning, stacklevel=1)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000336 return self.unverifiable
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000337
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000338 def get_origin_req_host(self):
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700339 msg = "Request.get_origin_req_host method is deprecated."
340 warnings.warn(msg, DeprecationWarning, stacklevel=1)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000341 return self.origin_req_host
342
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000343 # End deprecated methods
344
345 def set_proxy(self, host, type):
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000346 if self.type == 'https' and not self._tunnel_host:
347 self._tunnel_host = self.host
348 else:
349 self.type= type
350 self.selector = self.full_url
351 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000352
353 def has_proxy(self):
354 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000355
356 def add_header(self, key, val):
357 # useful for something like authentication
358 self.headers[key.capitalize()] = val
359
360 def add_unredirected_header(self, key, val):
361 # will not be added to a redirected request
362 self.unredirected_hdrs[key.capitalize()] = val
363
364 def has_header(self, header_name):
365 return (header_name in self.headers or
366 header_name in self.unredirected_hdrs)
367
368 def get_header(self, header_name, default=None):
369 return self.headers.get(
370 header_name,
371 self.unredirected_hdrs.get(header_name, default))
372
373 def header_items(self):
374 hdrs = self.unredirected_hdrs.copy()
375 hdrs.update(self.headers)
376 return list(hdrs.items())
377
378class OpenerDirector:
379 def __init__(self):
380 client_version = "Python-urllib/%s" % __version__
381 self.addheaders = [('User-agent', client_version)]
R. David Murray25b8cca2010-12-23 19:44:49 +0000382 # self.handlers is retained only for backward compatibility
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000383 self.handlers = []
R. David Murray25b8cca2010-12-23 19:44:49 +0000384 # manage the individual handlers
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000385 self.handle_open = {}
386 self.handle_error = {}
387 self.process_response = {}
388 self.process_request = {}
389
390 def add_handler(self, handler):
391 if not hasattr(handler, "add_parent"):
392 raise TypeError("expected BaseHandler instance, got %r" %
393 type(handler))
394
395 added = False
396 for meth in dir(handler):
397 if meth in ["redirect_request", "do_open", "proxy_open"]:
398 # oops, coincidental match
399 continue
400
401 i = meth.find("_")
402 protocol = meth[:i]
403 condition = meth[i+1:]
404
405 if condition.startswith("error"):
406 j = condition.find("_") + i + 1
407 kind = meth[j+1:]
408 try:
409 kind = int(kind)
410 except ValueError:
411 pass
412 lookup = self.handle_error.get(protocol, {})
413 self.handle_error[protocol] = lookup
414 elif condition == "open":
415 kind = protocol
416 lookup = self.handle_open
417 elif condition == "response":
418 kind = protocol
419 lookup = self.process_response
420 elif condition == "request":
421 kind = protocol
422 lookup = self.process_request
423 else:
424 continue
425
426 handlers = lookup.setdefault(kind, [])
427 if handlers:
428 bisect.insort(handlers, handler)
429 else:
430 handlers.append(handler)
431 added = True
432
433 if added:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000434 bisect.insort(self.handlers, handler)
435 handler.add_parent(self)
436
437 def close(self):
438 # Only exists for backwards compatibility.
439 pass
440
441 def _call_chain(self, chain, kind, meth_name, *args):
442 # Handlers raise an exception if no one else should try to handle
443 # the request, or return None if they can't but another handler
444 # could. Otherwise, they return the response.
445 handlers = chain.get(kind, ())
446 for handler in handlers:
447 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000448 result = func(*args)
449 if result is not None:
450 return result
451
452 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
453 # accept a URL or a Request object
454 if isinstance(fullurl, str):
455 req = Request(fullurl, data)
456 else:
457 req = fullurl
458 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000459 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000460
461 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000462 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000463
464 # pre-process request
465 meth_name = protocol+"_request"
466 for processor in self.process_request.get(protocol, []):
467 meth = getattr(processor, meth_name)
468 req = meth(req)
469
470 response = self._open(req, data)
471
472 # post-process response
473 meth_name = protocol+"_response"
474 for processor in self.process_response.get(protocol, []):
475 meth = getattr(processor, meth_name)
476 response = meth(req, response)
477
478 return response
479
480 def _open(self, req, data=None):
481 result = self._call_chain(self.handle_open, 'default',
482 'default_open', req)
483 if result:
484 return result
485
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000486 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000487 result = self._call_chain(self.handle_open, protocol, protocol +
488 '_open', req)
489 if result:
490 return result
491
492 return self._call_chain(self.handle_open, 'unknown',
493 'unknown_open', req)
494
495 def error(self, proto, *args):
496 if proto in ('http', 'https'):
497 # XXX http[s] protocols are special-cased
498 dict = self.handle_error['http'] # https is not different than http
499 proto = args[2] # YUCK!
500 meth_name = 'http_error_%s' % proto
501 http_err = 1
502 orig_args = args
503 else:
504 dict = self.handle_error
505 meth_name = proto + '_error'
506 http_err = 0
507 args = (dict, proto, meth_name) + args
508 result = self._call_chain(*args)
509 if result:
510 return result
511
512 if http_err:
513 args = (dict, 'default', 'http_error_default') + orig_args
514 return self._call_chain(*args)
515
516# XXX probably also want an abstract factory that knows when it makes
517# sense to skip a superclass in favor of a subclass and when it might
518# make sense to include both
519
520def build_opener(*handlers):
521 """Create an opener object from a list of handlers.
522
523 The opener will use several default handlers, including support
Senthil Kumaran1107c5d2009-11-15 06:20:55 +0000524 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000525
526 If any of the handlers passed as arguments are subclasses of the
527 default handlers, the default handlers will not be used.
528 """
529 def isclass(obj):
530 return isinstance(obj, type) or hasattr(obj, "__bases__")
531
532 opener = OpenerDirector()
533 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
534 HTTPDefaultErrorHandler, HTTPRedirectHandler,
535 FTPHandler, FileHandler, HTTPErrorProcessor]
536 if hasattr(http.client, "HTTPSConnection"):
537 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000538 skip = set()
539 for klass in default_classes:
540 for check in handlers:
541 if isclass(check):
542 if issubclass(check, klass):
543 skip.add(klass)
544 elif isinstance(check, klass):
545 skip.add(klass)
546 for klass in skip:
547 default_classes.remove(klass)
548
549 for klass in default_classes:
550 opener.add_handler(klass())
551
552 for h in handlers:
553 if isclass(h):
554 h = h()
555 opener.add_handler(h)
556 return opener
557
558class BaseHandler:
559 handler_order = 500
560
561 def add_parent(self, parent):
562 self.parent = parent
563
564 def close(self):
565 # Only exists for backwards compatibility
566 pass
567
568 def __lt__(self, other):
569 if not hasattr(other, "handler_order"):
570 # Try to preserve the old behavior of having custom classes
571 # inserted after default ones (works only for custom user
572 # classes which are not aware of handler_order).
573 return True
574 return self.handler_order < other.handler_order
575
576
577class HTTPErrorProcessor(BaseHandler):
578 """Process HTTP error responses."""
579 handler_order = 1000 # after all other processing
580
581 def http_response(self, request, response):
582 code, msg, hdrs = response.code, response.msg, response.info()
583
584 # According to RFC 2616, "2xx" code indicates that the client's
585 # request was successfully received, understood, and accepted.
586 if not (200 <= code < 300):
587 response = self.parent.error(
588 'http', request, response, code, msg, hdrs)
589
590 return response
591
592 https_response = http_response
593
594class HTTPDefaultErrorHandler(BaseHandler):
595 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000596 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000597
598class HTTPRedirectHandler(BaseHandler):
599 # maximum number of redirections to any single URL
600 # this is needed because of the state that cookies introduce
601 max_repeats = 4
602 # maximum total number of redirections (regardless of URL) before
603 # assuming we're in a loop
604 max_redirections = 10
605
606 def redirect_request(self, req, fp, code, msg, headers, newurl):
607 """Return a Request or None in response to a redirect.
608
609 This is called by the http_error_30x methods when a
610 redirection response is received. If a redirection should
611 take place, return a new Request to allow http_error_30x to
612 perform the redirect. Otherwise, raise HTTPError if no-one
613 else should try to handle this url. Return None if you can't
614 but another Handler might.
615 """
616 m = req.get_method()
617 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
618 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000619 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000620
621 # Strictly (according to RFC 2616), 301 or 302 in response to
622 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000623 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000624 # essentially all clients do redirect in this case, so we do
625 # the same.
626 # be conciliant with URIs containing a space
627 newurl = newurl.replace(' ', '%20')
628 CONTENT_HEADERS = ("content-length", "content-type")
629 newheaders = dict((k, v) for k, v in req.headers.items()
630 if k.lower() not in CONTENT_HEADERS)
631 return Request(newurl,
632 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000633 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000634 unverifiable=True)
635
636 # Implementation note: To avoid the server sending us into an
637 # infinite loop, the request object needs to track what URLs we
638 # have already seen. Do this by adding a handler-specific
639 # attribute to the Request object.
640 def http_error_302(self, req, fp, code, msg, headers):
641 # Some servers (incorrectly) return multiple Location headers
642 # (so probably same goes for URI). Use first header.
643 if "location" in headers:
644 newurl = headers["location"]
645 elif "uri" in headers:
646 newurl = headers["uri"]
647 else:
648 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000649
650 # fix a possible malformed URL
651 urlparts = urlparse(newurl)
guido@google.coma119df92011-03-29 11:41:02 -0700652
653 # For security reasons we don't allow redirection to anything other
654 # than http, https or ftp.
655
Senthil Kumaran6497aa32012-01-04 13:46:59 +0800656 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800657 raise HTTPError(
658 newurl, code,
659 "%s - Redirection to url '%s' is not allowed" % (msg, newurl),
660 headers, fp)
guido@google.coma119df92011-03-29 11:41:02 -0700661
Facundo Batistaf24802c2008-08-17 03:36:03 +0000662 if not urlparts.path:
663 urlparts = list(urlparts)
664 urlparts[2] = "/"
665 newurl = urlunparse(urlparts)
666
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000667 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000668
669 # XXX Probably want to forget about the state of the current
670 # request, although that might interact poorly with other
671 # handlers that also use handler-specific request attributes
672 new = self.redirect_request(req, fp, code, msg, headers, newurl)
673 if new is None:
674 return
675
676 # loop detection
677 # .redirect_dict has a key url if url was previously visited.
678 if hasattr(req, 'redirect_dict'):
679 visited = new.redirect_dict = req.redirect_dict
680 if (visited.get(newurl, 0) >= self.max_repeats or
681 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000682 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000683 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000684 else:
685 visited = new.redirect_dict = req.redirect_dict = {}
686 visited[newurl] = visited.get(newurl, 0) + 1
687
688 # Don't close the fp until we are sure that we won't use it
689 # with HTTPError.
690 fp.read()
691 fp.close()
692
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000693 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000694
695 http_error_301 = http_error_303 = http_error_307 = http_error_302
696
697 inf_msg = "The HTTP server returned a redirect error that would " \
698 "lead to an infinite loop.\n" \
699 "The last 30x error message was:\n"
700
701
702def _parse_proxy(proxy):
703 """Return (scheme, user, password, host/port) given a URL or an authority.
704
705 If a URL is supplied, it must have an authority (host:port) component.
706 According to RFC 3986, having an authority component means the URL must
707 have two slashes after the scheme:
708
709 >>> _parse_proxy('file:/ftp.example.com/')
710 Traceback (most recent call last):
711 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
712
713 The first three items of the returned tuple may be None.
714
715 Examples of authority parsing:
716
717 >>> _parse_proxy('proxy.example.com')
718 (None, None, None, 'proxy.example.com')
719 >>> _parse_proxy('proxy.example.com:3128')
720 (None, None, None, 'proxy.example.com:3128')
721
722 The authority component may optionally include userinfo (assumed to be
723 username:password):
724
725 >>> _parse_proxy('joe:password@proxy.example.com')
726 (None, 'joe', 'password', 'proxy.example.com')
727 >>> _parse_proxy('joe:password@proxy.example.com:3128')
728 (None, 'joe', 'password', 'proxy.example.com:3128')
729
730 Same examples, but with URLs instead:
731
732 >>> _parse_proxy('http://proxy.example.com/')
733 ('http', None, None, 'proxy.example.com')
734 >>> _parse_proxy('http://proxy.example.com:3128/')
735 ('http', None, None, 'proxy.example.com:3128')
736 >>> _parse_proxy('http://joe:password@proxy.example.com/')
737 ('http', 'joe', 'password', 'proxy.example.com')
738 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
739 ('http', 'joe', 'password', 'proxy.example.com:3128')
740
741 Everything after the authority is ignored:
742
743 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
744 ('ftp', 'joe', 'password', 'proxy.example.com')
745
746 Test for no trailing '/' case:
747
748 >>> _parse_proxy('http://joe:password@proxy.example.com')
749 ('http', 'joe', 'password', 'proxy.example.com')
750
751 """
Georg Brandl13e89462008-07-01 19:56:00 +0000752 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000753 if not r_scheme.startswith("/"):
754 # authority
755 scheme = None
756 authority = proxy
757 else:
758 # URL
759 if not r_scheme.startswith("//"):
760 raise ValueError("proxy URL with no authority: %r" % proxy)
761 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
762 # and 3.3.), path is empty or starts with '/'
763 end = r_scheme.find("/", 2)
764 if end == -1:
765 end = None
766 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000767 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000768 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000769 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000770 else:
771 user = password = None
772 return scheme, user, password, hostport
773
774class ProxyHandler(BaseHandler):
775 # Proxies must be in front
776 handler_order = 100
777
778 def __init__(self, proxies=None):
779 if proxies is None:
780 proxies = getproxies()
781 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
782 self.proxies = proxies
783 for type, url in proxies.items():
784 setattr(self, '%s_open' % type,
785 lambda r, proxy=url, type=type, meth=self.proxy_open: \
786 meth(r, proxy, type))
787
788 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000789 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000790 proxy_type, user, password, hostport = _parse_proxy(proxy)
791 if proxy_type is None:
792 proxy_type = orig_type
Senthil Kumaran7bb04972009-10-11 04:58:55 +0000793
794 if req.host and proxy_bypass(req.host):
795 return None
796
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000797 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000798 user_pass = '%s:%s' % (unquote(user),
799 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000800 creds = base64.b64encode(user_pass.encode()).decode("ascii")
801 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000802 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000803 req.set_proxy(hostport, proxy_type)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000804 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000805 # let other handlers take care of it
806 return None
807 else:
808 # need to start over, because the other handlers don't
809 # grok the proxy's URL type
810 # e.g. if we have a constructor arg proxies like so:
811 # {'http': 'ftp://proxy.example.com'}, we may end up turning
812 # a request for http://acme.example.com/a into one for
813 # ftp://proxy.example.com/a
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000814 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000815
816class HTTPPasswordMgr:
817
818 def __init__(self):
819 self.passwd = {}
820
821 def add_password(self, realm, uri, user, passwd):
822 # uri could be a single URI or a sequence
823 if isinstance(uri, str):
824 uri = [uri]
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800825 if realm not in self.passwd:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000826 self.passwd[realm] = {}
827 for default_port in True, False:
828 reduced_uri = tuple(
829 [self.reduce_uri(u, default_port) for u in uri])
830 self.passwd[realm][reduced_uri] = (user, passwd)
831
832 def find_user_password(self, realm, authuri):
833 domains = self.passwd.get(realm, {})
834 for default_port in True, False:
835 reduced_authuri = self.reduce_uri(authuri, default_port)
836 for uris, authinfo in domains.items():
837 for uri in uris:
838 if self.is_suburi(uri, reduced_authuri):
839 return authinfo
840 return None, None
841
842 def reduce_uri(self, uri, default_port=True):
843 """Accept authority or URI and extract only the authority and path."""
844 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000845 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000846 if parts[1]:
847 # URI
848 scheme = parts[0]
849 authority = parts[1]
850 path = parts[2] or '/'
851 else:
852 # host or host:port
853 scheme = None
854 authority = uri
855 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000856 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000857 if default_port and port is None and scheme is not None:
858 dport = {"http": 80,
859 "https": 443,
860 }.get(scheme)
861 if dport is not None:
862 authority = "%s:%d" % (host, dport)
863 return authority, path
864
865 def is_suburi(self, base, test):
866 """Check if test is below base in a URI tree
867
868 Both args must be URIs in reduced form.
869 """
870 if base == test:
871 return True
872 if base[0] != test[0]:
873 return False
874 common = posixpath.commonprefix((base[1], test[1]))
875 if len(common) == len(base[1]):
876 return True
877 return False
878
879
880class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
881
882 def find_user_password(self, realm, authuri):
883 user, password = HTTPPasswordMgr.find_user_password(self, realm,
884 authuri)
885 if user is not None:
886 return user, password
887 return HTTPPasswordMgr.find_user_password(self, None, authuri)
888
889
890class AbstractBasicAuthHandler:
891
892 # XXX this allows for multiple auth-schemes, but will stupidly pick
893 # the last one with a realm specified.
894
895 # allow for double- and single-quoted realm values
896 # (single quotes are a violation of the RFC, but appear in the wild)
897 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +0800898 'realm=(["\']?)([^"\']*)\\2', re.I)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000899
900 # XXX could pre-emptively send auth info already accepted (RFC 2617,
901 # end of section 2, and section 1.2 immediately after "credentials"
902 # production).
903
904 def __init__(self, password_mgr=None):
905 if password_mgr is None:
906 password_mgr = HTTPPasswordMgr()
907 self.passwd = password_mgr
908 self.add_password = self.passwd.add_password
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000909 self.retried = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000910
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000911 def reset_retry_count(self):
912 self.retried = 0
913
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000914 def http_error_auth_reqed(self, authreq, host, req, headers):
915 # host may be an authority (without userinfo) or a URL with an
916 # authority
917 # XXX could be multiple headers
918 authreq = headers.get(authreq, None)
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000919
920 if self.retried > 5:
921 # retry sending the username:password 5 times before failing.
922 raise HTTPError(req.get_full_url(), 401, "basic auth failed",
923 headers, None)
924 else:
925 self.retried += 1
926
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000927 if authreq:
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800928 scheme = authreq.split()[0]
Senthil Kumaran1a129c82011-10-20 02:50:13 +0800929 if scheme.lower() != 'basic':
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800930 raise ValueError("AbstractBasicAuthHandler does not"
931 " support the following scheme: '%s'" %
932 scheme)
933 else:
934 mo = AbstractBasicAuthHandler.rx.search(authreq)
935 if mo:
936 scheme, quote, realm = mo.groups()
Senthil Kumaran92a5bf02012-05-16 00:03:29 +0800937 if quote not in ['"',"'"]:
938 warnings.warn("Basic Auth Realm was unquoted",
939 UserWarning, 2)
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800940 if scheme.lower() == 'basic':
941 response = self.retry_http_basic_auth(host, req, realm)
942 if response and response.code != 401:
943 self.retried = 0
944 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000945
946 def retry_http_basic_auth(self, host, req, realm):
947 user, pw = self.passwd.find_user_password(realm, host)
948 if pw is not None:
949 raw = "%s:%s" % (user, pw)
950 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
951 if req.headers.get(self.auth_header, None) == auth:
952 return None
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +0000953 req.add_unredirected_header(self.auth_header, auth)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000954 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000955 else:
956 return None
957
958
959class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
960
961 auth_header = 'Authorization'
962
963 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000964 url = req.full_url
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000965 response = self.http_error_auth_reqed('www-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000966 url, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000967 self.reset_retry_count()
968 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000969
970
971class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
972
973 auth_header = 'Proxy-authorization'
974
975 def http_error_407(self, req, fp, code, msg, headers):
976 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000977 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000978 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
979 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000980 authority = req.host
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000981 response = self.http_error_auth_reqed('proxy-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000982 authority, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000983 self.reset_retry_count()
984 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000985
986
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800987# Return n random bytes.
988_randombytes = os.urandom
989
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000990
991class AbstractDigestAuthHandler:
992 # Digest authentication is specified in RFC 2617.
993
994 # XXX The client does not inspect the Authentication-Info header
995 # in a successful response.
996
997 # XXX It should be possible to test this implementation against
998 # a mock server that just generates a static set of challenges.
999
1000 # XXX qop="auth-int" supports is shaky
1001
1002 def __init__(self, passwd=None):
1003 if passwd is None:
1004 passwd = HTTPPasswordMgr()
1005 self.passwd = passwd
1006 self.add_password = self.passwd.add_password
1007 self.retried = 0
1008 self.nonce_count = 0
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +00001009 self.last_nonce = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001010
1011 def reset_retry_count(self):
1012 self.retried = 0
1013
1014 def http_error_auth_reqed(self, auth_header, host, req, headers):
1015 authreq = headers.get(auth_header, None)
1016 if self.retried > 5:
1017 # Don't fail endlessly - if we failed once, we'll probably
1018 # fail a second time. Hm. Unless the Password Manager is
1019 # prompting for the information. Crap. This isn't great
1020 # but it's better than the current 'repeat until recursion
1021 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001022 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +00001023 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001024 else:
1025 self.retried += 1
1026 if authreq:
1027 scheme = authreq.split()[0]
1028 if scheme.lower() == 'digest':
1029 return self.retry_http_digest_auth(req, authreq)
Senthil Kumaran1a129c82011-10-20 02:50:13 +08001030 elif scheme.lower() != 'basic':
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001031 raise ValueError("AbstractDigestAuthHandler does not support"
1032 " the following scheme: '%s'" % scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001033
1034 def retry_http_digest_auth(self, req, auth):
1035 token, challenge = auth.split(' ', 1)
1036 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
1037 auth = self.get_authorization(req, chal)
1038 if auth:
1039 auth_val = 'Digest %s' % auth
1040 if req.headers.get(self.auth_header, None) == auth_val:
1041 return None
1042 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001043 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001044 return resp
1045
1046 def get_cnonce(self, nonce):
1047 # The cnonce-value is an opaque
1048 # quoted string value provided by the client and used by both client
1049 # and server to avoid chosen plaintext attacks, to provide mutual
1050 # authentication, and to provide some message integrity protection.
1051 # This isn't a fabulous effort, but it's probably Good Enough.
1052 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
Senthil Kumaran6c5bd402011-11-01 23:20:31 +08001053 b = s.encode("ascii") + _randombytes(8)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001054 dig = hashlib.sha1(b).hexdigest()
1055 return dig[:16]
1056
1057 def get_authorization(self, req, chal):
1058 try:
1059 realm = chal['realm']
1060 nonce = chal['nonce']
1061 qop = chal.get('qop')
1062 algorithm = chal.get('algorithm', 'MD5')
1063 # mod_digest doesn't send an opaque, even though it isn't
1064 # supposed to be optional
1065 opaque = chal.get('opaque', None)
1066 except KeyError:
1067 return None
1068
1069 H, KD = self.get_algorithm_impls(algorithm)
1070 if H is None:
1071 return None
1072
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001073 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001074 if user is None:
1075 return None
1076
1077 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001078 if req.data is not None:
1079 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001080 else:
1081 entdig = None
1082
1083 A1 = "%s:%s:%s" % (user, realm, pw)
1084 A2 = "%s:%s" % (req.get_method(),
1085 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001086 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001087 if qop == 'auth':
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +00001088 if nonce == self.last_nonce:
1089 self.nonce_count += 1
1090 else:
1091 self.nonce_count = 1
1092 self.last_nonce = nonce
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001093 ncvalue = '%08x' % self.nonce_count
1094 cnonce = self.get_cnonce(nonce)
1095 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
1096 respdig = KD(H(A1), noncebit)
1097 elif qop is None:
1098 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
1099 else:
1100 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +00001101 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001102
1103 # XXX should the partial digests be encoded too?
1104
1105 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001106 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001107 respdig)
1108 if opaque:
1109 base += ', opaque="%s"' % opaque
1110 if entdig:
1111 base += ', digest="%s"' % entdig
1112 base += ', algorithm="%s"' % algorithm
1113 if qop:
1114 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
1115 return base
1116
1117 def get_algorithm_impls(self, algorithm):
1118 # lambdas assume digest modules are imported at the top level
1119 if algorithm == 'MD5':
1120 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
1121 elif algorithm == 'SHA':
1122 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
1123 # XXX MD5-sess
1124 KD = lambda s, d: H("%s:%s" % (s, d))
1125 return H, KD
1126
1127 def get_entity_digest(self, data, chal):
1128 # XXX not implemented yet
1129 return None
1130
1131
1132class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1133 """An authentication protocol defined by RFC 2069
1134
1135 Digest authentication improves on basic authentication because it
1136 does not transmit passwords in the clear.
1137 """
1138
1139 auth_header = 'Authorization'
1140 handler_order = 490 # before Basic auth
1141
1142 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001143 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001144 retry = self.http_error_auth_reqed('www-authenticate',
1145 host, req, headers)
1146 self.reset_retry_count()
1147 return retry
1148
1149
1150class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1151
1152 auth_header = 'Proxy-Authorization'
1153 handler_order = 490 # before Basic auth
1154
1155 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001156 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001157 retry = self.http_error_auth_reqed('proxy-authenticate',
1158 host, req, headers)
1159 self.reset_retry_count()
1160 return retry
1161
1162class AbstractHTTPHandler(BaseHandler):
1163
1164 def __init__(self, debuglevel=0):
1165 self._debuglevel = debuglevel
1166
1167 def set_http_debuglevel(self, level):
1168 self._debuglevel = level
1169
1170 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001171 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001172 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001173 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001174
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001175 if request.data is not None: # POST
1176 data = request.data
Senthil Kumaran29333122011-02-11 11:25:47 +00001177 if isinstance(data, str):
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07001178 msg = "POST data should be bytes or an iterable of bytes."\
1179 "It cannot be str"
1180 raise TypeError(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001181 if not request.has_header('Content-type'):
1182 request.add_unredirected_header(
1183 'Content-type',
1184 'application/x-www-form-urlencoded')
1185 if not request.has_header('Content-length'):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001186 try:
1187 mv = memoryview(data)
1188 except TypeError:
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001189 if isinstance(data, collections.Iterable):
Georg Brandl61536042011-02-03 07:46:41 +00001190 raise ValueError("Content-Length should be specified "
1191 "for iterable data of type %r %r" % (type(data),
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001192 data))
1193 else:
1194 request.add_unredirected_header(
Senthil Kumaran1e991f22010-12-24 04:03:59 +00001195 'Content-length', '%d' % (len(mv) * mv.itemsize))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001196
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001197 sel_host = host
1198 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001199 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001200 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001201 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001202 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001203 for name, value in self.parent.addheaders:
1204 name = name.capitalize()
1205 if not request.has_header(name):
1206 request.add_unredirected_header(name, value)
1207
1208 return request
1209
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001210 def do_open(self, http_class, req, **http_conn_args):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001211 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001212
1213 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001214 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001215 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001216 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001217 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001218
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001219 # will parse host:port
1220 h = http_class(host, timeout=req.timeout, **http_conn_args)
Senthil Kumaran42ef4b12010-09-27 01:26:03 +00001221
1222 headers = dict(req.unredirected_hdrs)
1223 headers.update(dict((k, v) for k, v in req.headers.items()
1224 if k not in headers))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001225
1226 # TODO(jhylton): Should this be redesigned to handle
1227 # persistent connections?
1228
1229 # We want to make an HTTP/1.1 request, but the addinfourl
1230 # class isn't prepared to deal with a persistent connection.
1231 # It will try to read all remaining data from the socket,
1232 # which will block while the server waits for the next request.
1233 # So make sure the connection gets closed after the (only)
1234 # request.
1235 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001236 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001237
1238 if req._tunnel_host:
Senthil Kumaran47fff872009-12-20 07:10:31 +00001239 tunnel_headers = {}
1240 proxy_auth_hdr = "Proxy-Authorization"
1241 if proxy_auth_hdr in headers:
1242 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1243 # Proxy-Authorization should not be sent to origin
1244 # server.
1245 del headers[proxy_auth_hdr]
1246 h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001247
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001248 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001249 h.request(req.get_method(), req.selector, req.data, headers)
Senthil Kumaran1299a8f2011-07-27 08:05:58 +08001250 except socket.error as err: # timeout error
Senthil Kumaran45686b42011-07-27 09:31:03 +08001251 h.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001252 raise URLError(err)
Senthil Kumaran45686b42011-07-27 09:31:03 +08001253 else:
1254 r = h.getresponse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001255
Senthil Kumaran26430412011-04-13 07:01:19 +08001256 r.url = req.get_full_url()
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001257 # This line replaces the .msg attribute of the HTTPResponse
1258 # with .headers, because urllib clients expect the response to
1259 # have the reason in .msg. It would be good to mark this
1260 # attribute is deprecated and get then to use info() or
1261 # .headers.
1262 r.msg = r.reason
1263 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001264
1265
1266class HTTPHandler(AbstractHTTPHandler):
1267
1268 def http_open(self, req):
1269 return self.do_open(http.client.HTTPConnection, req)
1270
1271 http_request = AbstractHTTPHandler.do_request_
1272
1273if hasattr(http.client, 'HTTPSConnection'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001274
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001275 class HTTPSHandler(AbstractHTTPHandler):
1276
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001277 def __init__(self, debuglevel=0, context=None, check_hostname=None):
1278 AbstractHTTPHandler.__init__(self, debuglevel)
1279 self._context = context
1280 self._check_hostname = check_hostname
1281
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001282 def https_open(self, req):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001283 return self.do_open(http.client.HTTPSConnection, req,
1284 context=self._context, check_hostname=self._check_hostname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001285
1286 https_request = AbstractHTTPHandler.do_request_
1287
Senthil Kumaran4c875a92011-11-01 23:57:57 +08001288 __all__.append('HTTPSHandler')
Senthil Kumaran0d54eb92011-11-01 23:49:46 +08001289
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001290class HTTPCookieProcessor(BaseHandler):
1291 def __init__(self, cookiejar=None):
1292 import http.cookiejar
1293 if cookiejar is None:
1294 cookiejar = http.cookiejar.CookieJar()
1295 self.cookiejar = cookiejar
1296
1297 def http_request(self, request):
1298 self.cookiejar.add_cookie_header(request)
1299 return request
1300
1301 def http_response(self, request, response):
1302 self.cookiejar.extract_cookies(response, request)
1303 return response
1304
1305 https_request = http_request
1306 https_response = http_response
1307
1308class UnknownHandler(BaseHandler):
1309 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001310 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001311 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001312
1313def parse_keqv_list(l):
1314 """Parse list of key=value strings where keys are not duplicated."""
1315 parsed = {}
1316 for elt in l:
1317 k, v = elt.split('=', 1)
1318 if v[0] == '"' and v[-1] == '"':
1319 v = v[1:-1]
1320 parsed[k] = v
1321 return parsed
1322
1323def parse_http_list(s):
1324 """Parse lists as described by RFC 2068 Section 2.
1325
1326 In particular, parse comma-separated lists where the elements of
1327 the list may include quoted-strings. A quoted-string could
1328 contain a comma. A non-quoted string could have quotes in the
1329 middle. Neither commas nor quotes count if they are escaped.
1330 Only double-quotes count, not single-quotes.
1331 """
1332 res = []
1333 part = ''
1334
1335 escape = quote = False
1336 for cur in s:
1337 if escape:
1338 part += cur
1339 escape = False
1340 continue
1341 if quote:
1342 if cur == '\\':
1343 escape = True
1344 continue
1345 elif cur == '"':
1346 quote = False
1347 part += cur
1348 continue
1349
1350 if cur == ',':
1351 res.append(part)
1352 part = ''
1353 continue
1354
1355 if cur == '"':
1356 quote = True
1357
1358 part += cur
1359
1360 # append last part
1361 if part:
1362 res.append(part)
1363
1364 return [part.strip() for part in res]
1365
1366class FileHandler(BaseHandler):
1367 # Use local file or FTP depending on form of URL
1368 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001369 url = req.selector
Senthil Kumaran2ef16322010-07-11 03:12:43 +00001370 if url[:2] == '//' and url[2:3] != '/' and (req.host and
1371 req.host != 'localhost'):
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001372 if not req.host is self.get_names():
1373 raise URLError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001374 else:
1375 return self.open_local_file(req)
1376
1377 # names for the localhost
1378 names = None
1379 def get_names(self):
1380 if FileHandler.names is None:
1381 try:
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001382 FileHandler.names = tuple(
1383 socket.gethostbyname_ex('localhost')[2] +
1384 socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001385 except socket.gaierror:
1386 FileHandler.names = (socket.gethostbyname('localhost'),)
1387 return FileHandler.names
1388
1389 # not entirely sure what the rules are here
1390 def open_local_file(self, req):
1391 import email.utils
1392 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001393 host = req.host
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001394 filename = req.selector
1395 localfile = url2pathname(filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001396 try:
1397 stats = os.stat(localfile)
1398 size = stats.st_size
1399 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001400 mtype = mimetypes.guess_type(filename)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001401 headers = email.message_from_string(
1402 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1403 (mtype or 'text/plain', size, modified))
1404 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001405 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001406 if not host or \
1407 (not port and _safe_gethostbyname(host) in self.get_names()):
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001408 if host:
1409 origurl = 'file://' + host + filename
1410 else:
1411 origurl = 'file://' + filename
1412 return addinfourl(open(localfile, 'rb'), headers, origurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001413 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001414 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001415 raise URLError(msg)
1416 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001417
1418def _safe_gethostbyname(host):
1419 try:
1420 return socket.gethostbyname(host)
1421 except socket.gaierror:
1422 return None
1423
1424class FTPHandler(BaseHandler):
1425 def ftp_open(self, req):
1426 import ftplib
1427 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001428 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001429 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001430 raise URLError('ftp error: no host given')
1431 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001432 if port is None:
1433 port = ftplib.FTP_PORT
1434 else:
1435 port = int(port)
1436
1437 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001438 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001439 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001440 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001441 else:
1442 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001443 host = unquote(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +00001444 user = user or ''
1445 passwd = passwd or ''
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001446
1447 try:
1448 host = socket.gethostbyname(host)
1449 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001450 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001451 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001452 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001453 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001454 dirs, file = dirs[:-1], dirs[-1]
1455 if dirs and not dirs[0]:
1456 dirs = dirs[1:]
1457 try:
1458 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1459 type = file and 'I' or 'D'
1460 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001461 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001462 if attr.lower() == 'type' and \
1463 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1464 type = value.upper()
1465 fp, retrlen = fw.retrfile(file, type)
1466 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001467 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001468 if mtype:
1469 headers += "Content-type: %s\n" % mtype
1470 if retrlen is not None and retrlen >= 0:
1471 headers += "Content-length: %d\n" % retrlen
1472 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001473 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001474 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001475 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001476 raise exc.with_traceback(sys.exc_info()[2])
1477
1478 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001479 return ftpwrapper(user, passwd, host, port, dirs, timeout,
1480 persistent=False)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001481
1482class CacheFTPHandler(FTPHandler):
1483 # XXX would be nice to have pluggable cache strategies
1484 # XXX this stuff is definitely not thread safe
1485 def __init__(self):
1486 self.cache = {}
1487 self.timeout = {}
1488 self.soonest = 0
1489 self.delay = 60
1490 self.max_conns = 16
1491
1492 def setTimeout(self, t):
1493 self.delay = t
1494
1495 def setMaxConns(self, m):
1496 self.max_conns = m
1497
1498 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1499 key = user, host, port, '/'.join(dirs), timeout
1500 if key in self.cache:
1501 self.timeout[key] = time.time() + self.delay
1502 else:
1503 self.cache[key] = ftpwrapper(user, passwd, host, port,
1504 dirs, timeout)
1505 self.timeout[key] = time.time() + self.delay
1506 self.check_cache()
1507 return self.cache[key]
1508
1509 def check_cache(self):
1510 # first check for old ones
1511 t = time.time()
1512 if self.soonest <= t:
1513 for k, v in list(self.timeout.items()):
1514 if v < t:
1515 self.cache[k].close()
1516 del self.cache[k]
1517 del self.timeout[k]
1518 self.soonest = min(list(self.timeout.values()))
1519
1520 # then check the size
1521 if len(self.cache) == self.max_conns:
1522 for k, v in list(self.timeout.items()):
1523 if v == self.soonest:
1524 del self.cache[k]
1525 del self.timeout[k]
1526 break
1527 self.soonest = min(list(self.timeout.values()))
1528
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001529 def clear_cache(self):
1530 for conn in self.cache.values():
1531 conn.close()
1532 self.cache.clear()
1533 self.timeout.clear()
1534
1535
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001536# Code move from the old urllib module
1537
1538MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1539
1540# Helper for non-unix systems
Ronald Oussoren94f25282010-05-05 19:11:21 +00001541if os.name == 'nt':
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001542 from nturl2path import url2pathname, pathname2url
1543else:
1544 def url2pathname(pathname):
1545 """OS-specific conversion from a relative URL of the 'file' scheme
1546 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001547 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001548
1549 def pathname2url(pathname):
1550 """OS-specific conversion from a file system path to a relative URL
1551 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001552 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001553
1554# This really consists of two pieces:
1555# (1) a class which handles opening of all sorts of URLs
1556# (plus assorted utilities etc.)
1557# (2) a set of functions for parsing URLs
1558# XXX Should these be separated out into different modules?
1559
1560
1561ftpcache = {}
1562class URLopener:
1563 """Class to open URLs.
1564 This is a class rather than just a subroutine because we may need
1565 more than one set of global protocol-specific options.
1566 Note -- this is a base class for those who don't want the
1567 automatic handling of errors type 302 (relocated) and 401
1568 (authorization needed)."""
1569
1570 __tempfiles = None
1571
1572 version = "Python-urllib/%s" % __version__
1573
1574 # Constructor
1575 def __init__(self, proxies=None, **x509):
Senthil Kumaran38b968b2012-03-14 13:43:53 -07001576 msg = "%(class)s style of invoking requests is deprecated."\
1577 "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
1578 warnings.warn(msg, DeprecationWarning, stacklevel=3)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001579 if proxies is None:
1580 proxies = getproxies()
1581 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1582 self.proxies = proxies
1583 self.key_file = x509.get('key_file')
1584 self.cert_file = x509.get('cert_file')
1585 self.addheaders = [('User-Agent', self.version)]
1586 self.__tempfiles = []
1587 self.__unlink = os.unlink # See cleanup()
1588 self.tempcache = None
1589 # Undocumented feature: if you assign {} to tempcache,
1590 # it is used to cache files retrieved with
1591 # self.retrieve(). This is not enabled by default
1592 # since it does not work for changing documents (and I
1593 # haven't got the logic to check expiration headers
1594 # yet).
1595 self.ftpcache = ftpcache
1596 # Undocumented feature: you can use a different
1597 # ftp cache by assigning to the .ftpcache member;
1598 # in case you want logically independent URL openers
1599 # XXX This is not threadsafe. Bah.
1600
1601 def __del__(self):
1602 self.close()
1603
1604 def close(self):
1605 self.cleanup()
1606
1607 def cleanup(self):
1608 # This code sometimes runs when the rest of this module
1609 # has already been deleted, so it can't use any globals
1610 # or import anything.
1611 if self.__tempfiles:
1612 for file in self.__tempfiles:
1613 try:
1614 self.__unlink(file)
1615 except OSError:
1616 pass
1617 del self.__tempfiles[:]
1618 if self.tempcache:
1619 self.tempcache.clear()
1620
1621 def addheader(self, *args):
1622 """Add a header to be used by the HTTP interface only
1623 e.g. u.addheader('Accept', 'sound/basic')"""
1624 self.addheaders.append(args)
1625
1626 # External interface
1627 def open(self, fullurl, data=None):
1628 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001629 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran734f0592010-02-20 22:19:04 +00001630 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001631 if self.tempcache and fullurl in self.tempcache:
1632 filename, headers = self.tempcache[fullurl]
1633 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001634 return addinfourl(fp, headers, fullurl)
1635 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001636 if not urltype:
1637 urltype = 'file'
1638 if urltype in self.proxies:
1639 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001640 urltype, proxyhost = splittype(proxy)
1641 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001642 url = (host, fullurl) # Signal special case to open_*()
1643 else:
1644 proxy = None
1645 name = 'open_' + urltype
1646 self.type = urltype
1647 name = name.replace('-', '_')
1648 if not hasattr(self, name):
1649 if proxy:
1650 return self.open_unknown_proxy(proxy, fullurl, data)
1651 else:
1652 return self.open_unknown(fullurl, data)
1653 try:
1654 if data is None:
1655 return getattr(self, name)(url)
1656 else:
1657 return getattr(self, name)(url, data)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001658 except HTTPError:
1659 raise
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001660 except socket.error as msg:
1661 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1662
1663 def open_unknown(self, fullurl, data=None):
1664 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001665 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001666 raise IOError('url error', 'unknown url type', type)
1667
1668 def open_unknown_proxy(self, proxy, fullurl, data=None):
1669 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001670 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001671 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1672
1673 # External interface
1674 def retrieve(self, url, filename=None, reporthook=None, data=None):
1675 """retrieve(url) returns (filename, headers) for a local object
1676 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001677 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001678 if self.tempcache and url in self.tempcache:
1679 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001680 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001681 if filename is None and (not type or type == 'file'):
1682 try:
1683 fp = self.open_local_file(url1)
1684 hdrs = fp.info()
Philip Jenveycb134d72009-12-03 02:45:01 +00001685 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001686 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001687 except IOError as msg:
1688 pass
1689 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001690 try:
1691 headers = fp.info()
1692 if filename:
1693 tfp = open(filename, 'wb')
1694 else:
1695 import tempfile
1696 garbage, path = splittype(url)
1697 garbage, path = splithost(path or "")
1698 path, garbage = splitquery(path or "")
1699 path, garbage = splitattr(path or "")
1700 suffix = os.path.splitext(path)[1]
1701 (fd, filename) = tempfile.mkstemp(suffix)
1702 self.__tempfiles.append(filename)
1703 tfp = os.fdopen(fd, 'wb')
1704 try:
1705 result = filename, headers
1706 if self.tempcache is not None:
1707 self.tempcache[url] = result
1708 bs = 1024*8
1709 size = -1
1710 read = 0
1711 blocknum = 0
Senthil Kumarance260142011-11-01 01:35:17 +08001712 if "content-length" in headers:
1713 size = int(headers["Content-Length"])
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001714 if reporthook:
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001715 reporthook(blocknum, bs, size)
1716 while 1:
1717 block = fp.read(bs)
1718 if not block:
1719 break
1720 read += len(block)
1721 tfp.write(block)
1722 blocknum += 1
1723 if reporthook:
1724 reporthook(blocknum, bs, size)
1725 finally:
1726 tfp.close()
1727 finally:
1728 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001729
1730 # raise exception if actual size does not match content-length header
1731 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001732 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001733 "retrieval incomplete: got only %i out of %i bytes"
1734 % (read, size), result)
1735
1736 return result
1737
1738 # Each method named open_<type> knows how to open that type of URL
1739
1740 def _open_generic_http(self, connection_factory, url, data):
1741 """Make an HTTP connection using connection_class.
1742
1743 This is an internal method that should be called from
1744 open_http() or open_https().
1745
1746 Arguments:
1747 - connection_factory should take a host name and return an
1748 HTTPConnection instance.
1749 - url is the url to retrieval or a host, relative-path pair.
1750 - data is payload for a POST request or None.
1751 """
1752
1753 user_passwd = None
1754 proxy_passwd= None
1755 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001756 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001757 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001758 user_passwd, host = splituser(host)
1759 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001760 realhost = host
1761 else:
1762 host, selector = url
1763 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001764 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001765 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001766 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001767 url = rest
1768 user_passwd = None
1769 if urltype.lower() != 'http':
1770 realhost = None
1771 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001772 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001773 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001774 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001775 if user_passwd:
1776 selector = "%s://%s%s" % (urltype, realhost, rest)
1777 if proxy_bypass(realhost):
1778 host = realhost
1779
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001780 if not host: raise IOError('http error', 'no host given')
1781
1782 if proxy_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001783 proxy_passwd = unquote(proxy_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001784 proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001785 else:
1786 proxy_auth = None
1787
1788 if user_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001789 user_passwd = unquote(user_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001790 auth = base64.b64encode(user_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001791 else:
1792 auth = None
1793 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001794 headers = {}
1795 if proxy_auth:
1796 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1797 if auth:
1798 headers["Authorization"] = "Basic %s" % auth
1799 if realhost:
1800 headers["Host"] = realhost
Senthil Kumarand91ffca2011-03-19 17:25:27 +08001801
1802 # Add Connection:close as we don't support persistent connections yet.
1803 # This helps in closing the socket and avoiding ResourceWarning
1804
1805 headers["Connection"] = "close"
1806
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001807 for header, value in self.addheaders:
1808 headers[header] = value
1809
1810 if data is not None:
1811 headers["Content-Type"] = "application/x-www-form-urlencoded"
1812 http_conn.request("POST", selector, data, headers)
1813 else:
1814 http_conn.request("GET", selector, headers=headers)
1815
1816 try:
1817 response = http_conn.getresponse()
1818 except http.client.BadStatusLine:
1819 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001820 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001821
1822 # According to RFC 2616, "2xx" code indicates that the client's
1823 # request was successfully received, understood, and accepted.
1824 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001825 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001826 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001827 else:
1828 return self.http_error(
1829 url, response.fp,
1830 response.status, response.reason, response.msg, data)
1831
1832 def open_http(self, url, data=None):
1833 """Use HTTP protocol."""
1834 return self._open_generic_http(http.client.HTTPConnection, url, data)
1835
1836 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1837 """Handle http errors.
1838
1839 Derived class can override this, or provide specific handlers
1840 named http_error_DDD where DDD is the 3-digit error code."""
1841 # First check if there's a specific handler for this error
1842 name = 'http_error_%d' % errcode
1843 if hasattr(self, name):
1844 method = getattr(self, name)
1845 if data is None:
1846 result = method(url, fp, errcode, errmsg, headers)
1847 else:
1848 result = method(url, fp, errcode, errmsg, headers, data)
1849 if result: return result
1850 return self.http_error_default(url, fp, errcode, errmsg, headers)
1851
1852 def http_error_default(self, url, fp, errcode, errmsg, headers):
1853 """Default error handler: close the connection and raise IOError."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001854 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001855 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001856
1857 if _have_ssl:
1858 def _https_connection(self, host):
1859 return http.client.HTTPSConnection(host,
1860 key_file=self.key_file,
1861 cert_file=self.cert_file)
1862
1863 def open_https(self, url, data=None):
1864 """Use HTTPS protocol."""
1865 return self._open_generic_http(self._https_connection, url, data)
1866
1867 def open_file(self, url):
1868 """Use local file or FTP depending on form of URL."""
1869 if not isinstance(url, str):
1870 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1871 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001872 raise ValueError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001873 else:
1874 return self.open_local_file(url)
1875
1876 def open_local_file(self, url):
1877 """Use local file."""
Senthil Kumaran6c5bd402011-11-01 23:20:31 +08001878 import email.utils
1879 import mimetypes
Georg Brandl13e89462008-07-01 19:56:00 +00001880 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001881 localname = url2pathname(file)
1882 try:
1883 stats = os.stat(localname)
1884 except OSError as e:
1885 raise URLError(e.errno, e.strerror, e.filename)
1886 size = stats.st_size
1887 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1888 mtype = mimetypes.guess_type(url)[0]
1889 headers = email.message_from_string(
1890 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1891 (mtype or 'text/plain', size, modified))
1892 if not host:
1893 urlfile = file
1894 if file[:1] == '/':
1895 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001896 return addinfourl(open(localname, 'rb'), headers, urlfile)
1897 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001898 if (not port
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001899 and socket.gethostbyname(host) in (localhost() + thishost())):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001900 urlfile = file
1901 if file[:1] == '/':
1902 urlfile = 'file://' + file
Senthil Kumaran3800ea92012-01-21 11:52:48 +08001903 elif file[:2] == './':
1904 raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
Georg Brandl13e89462008-07-01 19:56:00 +00001905 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001906 raise URLError('local file error', 'not on local host')
1907
1908 def open_ftp(self, url):
1909 """Use FTP protocol."""
1910 if not isinstance(url, str):
1911 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1912 import mimetypes
Georg Brandl13e89462008-07-01 19:56:00 +00001913 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001914 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001915 host, port = splitport(host)
1916 user, host = splituser(host)
1917 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001918 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001919 host = unquote(host)
1920 user = unquote(user or '')
1921 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001922 host = socket.gethostbyname(host)
1923 if not port:
1924 import ftplib
1925 port = ftplib.FTP_PORT
1926 else:
1927 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001928 path, attrs = splitattr(path)
1929 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001930 dirs = path.split('/')
1931 dirs, file = dirs[:-1], dirs[-1]
1932 if dirs and not dirs[0]: dirs = dirs[1:]
1933 if dirs and not dirs[0]: dirs[0] = '/'
1934 key = user, host, port, '/'.join(dirs)
1935 # XXX thread unsafe!
1936 if len(self.ftpcache) > MAXFTPCACHE:
1937 # Prune the cache, rather arbitrarily
1938 for k in self.ftpcache.keys():
1939 if k != key:
1940 v = self.ftpcache[k]
1941 del self.ftpcache[k]
1942 v.close()
1943 try:
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08001944 if key not in self.ftpcache:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001945 self.ftpcache[key] = \
1946 ftpwrapper(user, passwd, host, port, dirs)
1947 if not file: type = 'D'
1948 else: type = 'I'
1949 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001950 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001951 if attr.lower() == 'type' and \
1952 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1953 type = value.upper()
1954 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1955 mtype = mimetypes.guess_type("ftp:" + url)[0]
1956 headers = ""
1957 if mtype:
1958 headers += "Content-Type: %s\n" % mtype
1959 if retrlen is not None and retrlen >= 0:
1960 headers += "Content-Length: %d\n" % retrlen
1961 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001962 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001963 except ftperrors() as msg:
1964 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1965
1966 def open_data(self, url, data=None):
1967 """Use "data" URL."""
1968 if not isinstance(url, str):
1969 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1970 # ignore POSTed data
1971 #
1972 # syntax of data URLs:
1973 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1974 # mediatype := [ type "/" subtype ] *( ";" parameter )
1975 # data := *urlchar
1976 # parameter := attribute "=" value
1977 try:
1978 [type, data] = url.split(',', 1)
1979 except ValueError:
1980 raise IOError('data error', 'bad data URL')
1981 if not type:
1982 type = 'text/plain;charset=US-ASCII'
1983 semi = type.rfind(';')
1984 if semi >= 0 and '=' not in type[semi:]:
1985 encoding = type[semi+1:]
1986 type = type[:semi]
1987 else:
1988 encoding = ''
1989 msg = []
Senthil Kumaranf6c456d2010-05-01 08:29:18 +00001990 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001991 time.gmtime(time.time())))
1992 msg.append('Content-type: %s' % type)
1993 if encoding == 'base64':
Georg Brandl706824f2009-06-04 09:42:55 +00001994 # XXX is this encoding/decoding ok?
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001995 data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001996 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001997 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001998 msg.append('Content-Length: %d' % len(data))
1999 msg.append('')
2000 msg.append(data)
2001 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00002002 headers = email.message_from_string(msg)
2003 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002004 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00002005 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002006
2007
2008class FancyURLopener(URLopener):
2009 """Derived class with handlers for errors we can handle (perhaps)."""
2010
2011 def __init__(self, *args, **kwargs):
2012 URLopener.__init__(self, *args, **kwargs)
2013 self.auth_cache = {}
2014 self.tries = 0
2015 self.maxtries = 10
2016
2017 def http_error_default(self, url, fp, errcode, errmsg, headers):
2018 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00002019 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002020
2021 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
2022 """Error 302 -- relocated (temporarily)."""
2023 self.tries += 1
2024 if self.maxtries and self.tries >= self.maxtries:
2025 if hasattr(self, "http_error_500"):
2026 meth = self.http_error_500
2027 else:
2028 meth = self.http_error_default
2029 self.tries = 0
2030 return meth(url, fp, 500,
2031 "Internal Server Error: Redirect Recursion", headers)
2032 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
2033 data)
2034 self.tries = 0
2035 return result
2036
2037 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
2038 if 'location' in headers:
2039 newurl = headers['location']
2040 elif 'uri' in headers:
2041 newurl = headers['uri']
2042 else:
2043 return
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002044 fp.close()
guido@google.coma119df92011-03-29 11:41:02 -07002045
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002046 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00002047 newurl = urljoin(self.type + ":" + url, newurl)
guido@google.coma119df92011-03-29 11:41:02 -07002048
2049 urlparts = urlparse(newurl)
2050
2051 # For security reasons, we don't allow redirection to anything other
2052 # than http, https and ftp.
2053
2054 # We are using newer HTTPError with older redirect_internal method
2055 # This older method will get deprecated in 3.3
2056
Senthil Kumaran6497aa32012-01-04 13:46:59 +08002057 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
guido@google.coma119df92011-03-29 11:41:02 -07002058 raise HTTPError(newurl, errcode,
2059 errmsg +
2060 " Redirection to url '%s' is not allowed." % newurl,
2061 headers, fp)
2062
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002063 return self.open(newurl)
2064
2065 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
2066 """Error 301 -- also relocated (permanently)."""
2067 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2068
2069 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
2070 """Error 303 -- also relocated (essentially identical to 302)."""
2071 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2072
2073 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
2074 """Error 307 -- relocated, but turn POST into error."""
2075 if data is None:
2076 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2077 else:
2078 return self.http_error_default(url, fp, errcode, errmsg, headers)
2079
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002080 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
2081 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002082 """Error 401 -- authentication required.
2083 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08002084 if 'www-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002085 URLopener.http_error_default(self, url, fp,
2086 errcode, errmsg, headers)
2087 stuff = headers['www-authenticate']
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002088 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2089 if not match:
2090 URLopener.http_error_default(self, url, fp,
2091 errcode, errmsg, headers)
2092 scheme, realm = match.groups()
2093 if scheme.lower() != 'basic':
2094 URLopener.http_error_default(self, url, fp,
2095 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002096 if not retry:
2097 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2098 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002099 name = 'retry_' + self.type + '_basic_auth'
2100 if data is None:
2101 return getattr(self,name)(url, realm)
2102 else:
2103 return getattr(self,name)(url, realm, data)
2104
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002105 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
2106 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002107 """Error 407 -- proxy authentication required.
2108 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08002109 if 'proxy-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002110 URLopener.http_error_default(self, url, fp,
2111 errcode, errmsg, headers)
2112 stuff = headers['proxy-authenticate']
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002113 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2114 if not match:
2115 URLopener.http_error_default(self, url, fp,
2116 errcode, errmsg, headers)
2117 scheme, realm = match.groups()
2118 if scheme.lower() != 'basic':
2119 URLopener.http_error_default(self, url, fp,
2120 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002121 if not retry:
2122 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2123 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002124 name = 'retry_proxy_' + self.type + '_basic_auth'
2125 if data is None:
2126 return getattr(self,name)(url, realm)
2127 else:
2128 return getattr(self,name)(url, realm, data)
2129
2130 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002131 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002132 newurl = 'http://' + host + selector
2133 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00002134 urltype, proxyhost = splittype(proxy)
2135 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002136 i = proxyhost.find('@') + 1
2137 proxyhost = proxyhost[i:]
2138 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2139 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002140 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002141 quote(passwd, safe=''), proxyhost)
2142 self.proxies['http'] = 'http://' + proxyhost + proxyselector
2143 if data is None:
2144 return self.open(newurl)
2145 else:
2146 return self.open(newurl, data)
2147
2148 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002149 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002150 newurl = 'https://' + host + selector
2151 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00002152 urltype, proxyhost = splittype(proxy)
2153 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002154 i = proxyhost.find('@') + 1
2155 proxyhost = proxyhost[i:]
2156 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2157 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002158 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002159 quote(passwd, safe=''), proxyhost)
2160 self.proxies['https'] = 'https://' + proxyhost + proxyselector
2161 if data is None:
2162 return self.open(newurl)
2163 else:
2164 return self.open(newurl, data)
2165
2166 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002167 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002168 i = host.find('@') + 1
2169 host = host[i:]
2170 user, passwd = self.get_user_passwd(host, realm, i)
2171 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002172 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002173 quote(passwd, safe=''), host)
2174 newurl = 'http://' + host + selector
2175 if data is None:
2176 return self.open(newurl)
2177 else:
2178 return self.open(newurl, data)
2179
2180 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002181 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002182 i = host.find('@') + 1
2183 host = host[i:]
2184 user, passwd = self.get_user_passwd(host, realm, i)
2185 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002186 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002187 quote(passwd, safe=''), host)
2188 newurl = 'https://' + host + selector
2189 if data is None:
2190 return self.open(newurl)
2191 else:
2192 return self.open(newurl, data)
2193
Florent Xicluna757445b2010-05-17 17:24:07 +00002194 def get_user_passwd(self, host, realm, clear_cache=0):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002195 key = realm + '@' + host.lower()
2196 if key in self.auth_cache:
2197 if clear_cache:
2198 del self.auth_cache[key]
2199 else:
2200 return self.auth_cache[key]
2201 user, passwd = self.prompt_user_passwd(host, realm)
2202 if user or passwd: self.auth_cache[key] = (user, passwd)
2203 return user, passwd
2204
2205 def prompt_user_passwd(self, host, realm):
2206 """Override this in a GUI environment!"""
2207 import getpass
2208 try:
2209 user = input("Enter username for %s at %s: " % (realm, host))
2210 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
2211 (user, realm, host))
2212 return user, passwd
2213 except KeyboardInterrupt:
2214 print()
2215 return None, None
2216
2217
2218# Utility functions
2219
2220_localhost = None
2221def localhost():
2222 """Return the IP address of the magic hostname 'localhost'."""
2223 global _localhost
2224 if _localhost is None:
2225 _localhost = socket.gethostbyname('localhost')
2226 return _localhost
2227
2228_thishost = None
2229def thishost():
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00002230 """Return the IP addresses of the current host."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002231 global _thishost
2232 if _thishost is None:
Senthil Kumaran1b7da512011-10-06 00:32:02 +08002233 _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002234 return _thishost
2235
2236_ftperrors = None
2237def ftperrors():
2238 """Return the set of errors raised by the FTP class."""
2239 global _ftperrors
2240 if _ftperrors is None:
2241 import ftplib
2242 _ftperrors = ftplib.all_errors
2243 return _ftperrors
2244
2245_noheaders = None
2246def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002247 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002248 global _noheaders
2249 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002250 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002251 return _noheaders
2252
2253
2254# Utility classes
2255
2256class ftpwrapper:
2257 """Class used by open_ftp() for cache of open FTP connections."""
2258
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002259 def __init__(self, user, passwd, host, port, dirs, timeout=None,
2260 persistent=True):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002261 self.user = user
2262 self.passwd = passwd
2263 self.host = host
2264 self.port = port
2265 self.dirs = dirs
2266 self.timeout = timeout
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002267 self.refcount = 0
2268 self.keepalive = persistent
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002269 self.init()
2270
2271 def init(self):
2272 import ftplib
2273 self.busy = 0
2274 self.ftp = ftplib.FTP()
2275 self.ftp.connect(self.host, self.port, self.timeout)
2276 self.ftp.login(self.user, self.passwd)
2277 for dir in self.dirs:
2278 self.ftp.cwd(dir)
2279
2280 def retrfile(self, file, type):
2281 import ftplib
2282 self.endtransfer()
2283 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2284 else: cmd = 'TYPE ' + type; isdir = 0
2285 try:
2286 self.ftp.voidcmd(cmd)
2287 except ftplib.all_errors:
2288 self.init()
2289 self.ftp.voidcmd(cmd)
2290 conn = None
2291 if file and not isdir:
2292 # Try to retrieve as a file
2293 try:
2294 cmd = 'RETR ' + file
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002295 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002296 except ftplib.error_perm as reason:
2297 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002298 raise URLError('ftp error', reason).with_traceback(
2299 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002300 if not conn:
2301 # Set transfer mode to ASCII!
2302 self.ftp.voidcmd('TYPE A')
2303 # Try a directory listing. Verify that directory exists.
2304 if file:
2305 pwd = self.ftp.pwd()
2306 try:
2307 try:
2308 self.ftp.cwd(file)
2309 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002310 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002311 finally:
2312 self.ftp.cwd(pwd)
2313 cmd = 'LIST ' + file
2314 else:
2315 cmd = 'LIST'
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002316 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002317 self.busy = 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002318
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002319 ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
2320 self.refcount += 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002321 conn.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002322 # Pass back both a suitably decorated object and a retrieval length
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002323 return (ftpobj, retrlen)
2324
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002325 def endtransfer(self):
2326 if not self.busy:
2327 return
2328 self.busy = 0
2329 try:
2330 self.ftp.voidresp()
2331 except ftperrors():
2332 pass
2333
2334 def close(self):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002335 self.keepalive = False
2336 if self.refcount <= 0:
2337 self.real_close()
2338
2339 def file_close(self):
2340 self.endtransfer()
2341 self.refcount -= 1
2342 if self.refcount <= 0 and not self.keepalive:
2343 self.real_close()
2344
2345 def real_close(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002346 self.endtransfer()
2347 try:
2348 self.ftp.close()
2349 except ftperrors():
2350 pass
2351
2352# Proxy handling
2353def getproxies_environment():
2354 """Return a dictionary of scheme -> proxy server URL mappings.
2355
2356 Scan the environment for variables named <scheme>_proxy;
2357 this seems to be the standard convention. If you need a
2358 different way, you can pass a proxies dictionary to the
2359 [Fancy]URLopener constructor.
2360
2361 """
2362 proxies = {}
2363 for name, value in os.environ.items():
2364 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002365 if value and name[-6:] == '_proxy':
2366 proxies[name[:-6]] = value
2367 return proxies
2368
2369def proxy_bypass_environment(host):
2370 """Test if proxies should not be used for a particular host.
2371
2372 Checks the environment for a variable named no_proxy, which should
2373 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2374 """
2375 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2376 # '*' is special case for always bypass
2377 if no_proxy == '*':
2378 return 1
2379 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002380 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002381 # check if the host ends with any of the DNS suffixes
Senthil Kumaran89976f12011-08-06 12:27:40 +08002382 no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
2383 for name in no_proxy_list:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002384 if name and (hostonly.endswith(name) or host.endswith(name)):
2385 return 1
2386 # otherwise, don't bypass
2387 return 0
2388
2389
Ronald Oussorene72e1612011-03-14 18:15:25 -04002390# This code tests an OSX specific data structure but is testable on all
2391# platforms
2392def _proxy_bypass_macosx_sysconf(host, proxy_settings):
2393 """
2394 Return True iff this host shouldn't be accessed using a proxy
2395
2396 This function uses the MacOSX framework SystemConfiguration
2397 to fetch the proxy information.
2398
2399 proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
2400 { 'exclude_simple': bool,
2401 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
2402 }
2403 """
Ronald Oussorene72e1612011-03-14 18:15:25 -04002404 from fnmatch import fnmatch
2405
2406 hostonly, port = splitport(host)
2407
2408 def ip2num(ipAddr):
2409 parts = ipAddr.split('.')
2410 parts = list(map(int, parts))
2411 if len(parts) != 4:
2412 parts = (parts + [0, 0, 0, 0])[:4]
2413 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2414
2415 # Check for simple host names:
2416 if '.' not in host:
2417 if proxy_settings['exclude_simple']:
2418 return True
2419
2420 hostIP = None
2421
2422 for value in proxy_settings.get('exceptions', ()):
2423 # Items in the list are strings like these: *.local, 169.254/16
2424 if not value: continue
2425
2426 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2427 if m is not None:
2428 if hostIP is None:
2429 try:
2430 hostIP = socket.gethostbyname(hostonly)
2431 hostIP = ip2num(hostIP)
2432 except socket.error:
2433 continue
2434
2435 base = ip2num(m.group(1))
2436 mask = m.group(2)
2437 if mask is None:
2438 mask = 8 * (m.group(1).count('.') + 1)
2439 else:
2440 mask = int(mask[1:])
2441 mask = 32 - mask
2442
2443 if (hostIP >> mask) == (base >> mask):
2444 return True
2445
2446 elif fnmatch(host, value):
2447 return True
2448
2449 return False
2450
2451
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002452if sys.platform == 'darwin':
Ronald Oussoren84151202010-04-18 20:46:11 +00002453 from _scproxy import _get_proxy_settings, _get_proxies
2454
2455 def proxy_bypass_macosx_sysconf(host):
Ronald Oussoren84151202010-04-18 20:46:11 +00002456 proxy_settings = _get_proxy_settings()
Ronald Oussorene72e1612011-03-14 18:15:25 -04002457 return _proxy_bypass_macosx_sysconf(host, proxy_settings)
Ronald Oussoren84151202010-04-18 20:46:11 +00002458
2459 def getproxies_macosx_sysconf():
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002460 """Return a dictionary of scheme -> proxy server URL mappings.
2461
Ronald Oussoren84151202010-04-18 20:46:11 +00002462 This function uses the MacOSX framework SystemConfiguration
2463 to fetch the proxy information.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002464 """
Ronald Oussoren84151202010-04-18 20:46:11 +00002465 return _get_proxies()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002466
Ronald Oussoren84151202010-04-18 20:46:11 +00002467
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002468
2469 def proxy_bypass(host):
2470 if getproxies_environment():
2471 return proxy_bypass_environment(host)
2472 else:
Ronald Oussoren84151202010-04-18 20:46:11 +00002473 return proxy_bypass_macosx_sysconf(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002474
2475 def getproxies():
Ronald Oussoren84151202010-04-18 20:46:11 +00002476 return getproxies_environment() or getproxies_macosx_sysconf()
2477
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002478
2479elif os.name == 'nt':
2480 def getproxies_registry():
2481 """Return a dictionary of scheme -> proxy server URL mappings.
2482
2483 Win32 uses the registry to store proxies.
2484
2485 """
2486 proxies = {}
2487 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002488 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002489 except ImportError:
2490 # Std module, so should be around - but you never know!
2491 return proxies
2492 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002493 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002494 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002495 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002496 'ProxyEnable')[0]
2497 if proxyEnable:
2498 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002499 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002500 'ProxyServer')[0])
2501 if '=' in proxyServer:
2502 # Per-protocol settings
2503 for p in proxyServer.split(';'):
2504 protocol, address = p.split('=', 1)
2505 # See if address has a type:// prefix
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002506 if not re.match('^([^/:]+)://', address):
2507 address = '%s://%s' % (protocol, address)
2508 proxies[protocol] = address
2509 else:
2510 # Use one setting for all protocols
2511 if proxyServer[:5] == 'http:':
2512 proxies['http'] = proxyServer
2513 else:
2514 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran04f31b82010-07-14 20:10:52 +00002515 proxies['https'] = 'https://%s' % proxyServer
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002516 proxies['ftp'] = 'ftp://%s' % proxyServer
2517 internetSettings.Close()
2518 except (WindowsError, ValueError, TypeError):
2519 # Either registry key not found etc, or the value in an
2520 # unexpected format.
2521 # proxies already set up to be empty so nothing to do
2522 pass
2523 return proxies
2524
2525 def getproxies():
2526 """Return a dictionary of scheme -> proxy server URL mappings.
2527
2528 Returns settings gathered from the environment, if specified,
2529 or the registry.
2530
2531 """
2532 return getproxies_environment() or getproxies_registry()
2533
2534 def proxy_bypass_registry(host):
2535 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002536 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002537 except ImportError:
2538 # Std modules, so should be around - but you never know!
2539 return 0
2540 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002541 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002542 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002543 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002544 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002545 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002546 'ProxyOverride')[0])
2547 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2548 except WindowsError:
2549 return 0
2550 if not proxyEnable or not proxyOverride:
2551 return 0
2552 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002553 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002554 host = [rawHost]
2555 try:
2556 addr = socket.gethostbyname(rawHost)
2557 if addr != rawHost:
2558 host.append(addr)
2559 except socket.error:
2560 pass
2561 try:
2562 fqdn = socket.getfqdn(rawHost)
2563 if fqdn != rawHost:
2564 host.append(fqdn)
2565 except socket.error:
2566 pass
2567 # make a check value list from the registry entry: replace the
2568 # '<local>' string by the localhost entry and the corresponding
2569 # canonical entry.
2570 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002571 # now check if we match one of the registry values.
2572 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002573 if test == '<local>':
2574 if '.' not in rawHost:
2575 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002576 test = test.replace(".", r"\.") # mask dots
2577 test = test.replace("*", r".*") # change glob sequence
2578 test = test.replace("?", r".") # change glob char
2579 for val in host:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002580 if re.match(test, val, re.I):
2581 return 1
2582 return 0
2583
2584 def proxy_bypass(host):
2585 """Return a dictionary of scheme -> proxy server URL mappings.
2586
2587 Returns settings gathered from the environment, if specified,
2588 or the registry.
2589
2590 """
2591 if getproxies_environment():
2592 return proxy_bypass_environment(host)
2593 else:
2594 return proxy_bypass_registry(host)
2595
2596else:
2597 # By default use environment variables
2598 getproxies = getproxies_environment
2599 proxy_bypass = proxy_bypass_environment