blob: 5995cbe24f0df0336d0dd2a2640850b7a6e02605 [file] [log] [blame]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001"""An extensible library for opening URLs using a variety of protocols
2
3The simplest way to use this module is to call the urlopen function,
4which accepts a string containing a URL or a Request object (described
5below). It opens the URL and returns the results as file-like
6object; the returned object has some extra methods described below.
7
8The OpenerDirector manages a collection of Handler objects that do
9all the actual work. Each Handler implements a particular protocol or
10option. The OpenerDirector is a composite object that invokes the
11Handlers needed to open the requested URL. For example, the
12HTTPHandler performs HTTP GET and POST requests and deals with
13non-error returns. The HTTPRedirectHandler automatically deals with
14HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15deals with digest authentication.
16
17urlopen(url, data=None) -- Basic usage is the same as original
18urllib. pass the url and optionally data to post to an HTTP URL, and
19get a file-like object back. One difference is that you can also pass
20a Request instance instead of URL. Raises a URLError (subclass of
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020021OSError); for HTTP errors, raises an HTTPError, which can also be
Jeremy Hylton1afc1692008-06-18 20:49:58 +000022treated as a valid response.
23
24build_opener -- Function that creates a new OpenerDirector instance.
25Will install the default handlers. Accepts one or more Handlers as
26arguments, either instances or Handler classes that it will
27instantiate. If one of the argument is a subclass of the default
28handler, the argument will be installed instead of the default.
29
30install_opener -- Installs a new opener as the default opener.
31
32objects of interest:
Senthil Kumaran1107c5d2009-11-15 06:20:55 +000033
Senthil Kumaran47fff872009-12-20 07:10:31 +000034OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
35the Handler classes, while dealing with requests and responses.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000036
37Request -- An object that encapsulates the state of a request. The
38state can be as simple as the URL. It can also include extra HTTP
39headers, e.g. a User-Agent.
40
41BaseHandler --
42
43internals:
44BaseHandler and parent
45_call_chain conventions
46
47Example usage:
48
Georg Brandl029986a2008-06-23 11:44:14 +000049import urllib.request
Jeremy Hylton1afc1692008-06-18 20:49:58 +000050
51# set up authentication info
Georg Brandl029986a2008-06-23 11:44:14 +000052authinfo = urllib.request.HTTPBasicAuthHandler()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000053authinfo.add_password(realm='PDQ Application',
54 uri='https://mahler:8092/site-updates.py',
55 user='klem',
56 passwd='geheim$parole')
57
Georg Brandl029986a2008-06-23 11:44:14 +000058proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
Jeremy Hylton1afc1692008-06-18 20:49:58 +000059
60# build a new opener that adds authentication and caching FTP handlers
Georg Brandl029986a2008-06-23 11:44:14 +000061opener = urllib.request.build_opener(proxy_support, authinfo,
62 urllib.request.CacheFTPHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000063
64# install it
Georg Brandl029986a2008-06-23 11:44:14 +000065urllib.request.install_opener(opener)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066
Georg Brandl029986a2008-06-23 11:44:14 +000067f = urllib.request.urlopen('http://www.python.org/')
Jeremy Hylton1afc1692008-06-18 20:49:58 +000068"""
69
70# XXX issues:
71# If an authentication error handler that tries to perform
72# authentication for some reason but fails, how should the error be
73# signalled? The client needs to know the HTTP error code. But if
74# the handler knows that the problem was, e.g., that it didn't know
75# that hash algo that requested in the challenge, it would be good to
76# pass that information along to the client, too.
77# ftp errors aren't handled cleanly
78# check digest against correct (i.e. non-apache) implementation
79
80# Possible extensions:
81# complex proxies XXX not sure what exactly was meant by this
82# abstract factory for opener
83
84import base64
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +000085import bisect
Jeremy Hylton1afc1692008-06-18 20:49:58 +000086import email
87import hashlib
88import http.client
89import io
90import os
91import posixpath
Jeremy Hylton1afc1692008-06-18 20:49:58 +000092import re
93import socket
94import sys
95import time
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000096import collections
Senthil Kumarane24f96a2012-03-13 19:29:33 -070097import tempfile
98import contextlib
Senthil Kumaran38b968b92012-03-14 13:43:53 -070099import warnings
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700100
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000101
Georg Brandl13e89462008-07-01 19:56:00 +0000102from urllib.error import URLError, HTTPError, ContentTooShortError
103from urllib.parse import (
104 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
105 splittype, splithost, splitport, splituser, splitpasswd,
Antoine Pitroudf204be2012-11-24 17:59:08 +0100106 splitattr, splitquery, splitvalue, splittag, to_bytes,
107 unquote_to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000108from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000109
110# check for SSL
111try:
112 import ssl
Brett Cannoncd171c82013-07-04 17:43:24 -0400113except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000114 _have_ssl = False
115else:
116 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000117
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800118__all__ = [
119 # Classes
120 'Request', 'OpenerDirector', 'BaseHandler', 'HTTPDefaultErrorHandler',
121 'HTTPRedirectHandler', 'HTTPCookieProcessor', 'ProxyHandler',
122 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm',
123 'AbstractBasicAuthHandler', 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',
124 'AbstractDigestAuthHandler', 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',
Antoine Pitroudf204be2012-11-24 17:59:08 +0100125 'HTTPHandler', 'FileHandler', 'FTPHandler', 'CacheFTPHandler', 'DataHandler',
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800126 'UnknownHandler', 'HTTPErrorProcessor',
127 # Functions
128 'urlopen', 'install_opener', 'build_opener',
129 'pathname2url', 'url2pathname', 'getproxies',
130 # Legacy interface
131 'urlretrieve', 'urlcleanup', 'URLopener', 'FancyURLopener',
132]
133
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000134# used in User-Agent header sent
135__version__ = sys.version[:3]
136
137_opener = None
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000138def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
Antoine Pitroude9ac6c2012-05-16 21:40:01 +0200139 *, cafile=None, capath=None, cadefault=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000140 global _opener
Antoine Pitroude9ac6c2012-05-16 21:40:01 +0200141 if cafile or capath or cadefault:
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000142 if not _have_ssl:
143 raise ValueError('SSL support not available')
Christian Heimes67986f92013-11-23 22:43:47 +0100144 context = ssl._create_stdlib_context(cert_reqs=ssl.CERT_REQUIRED,
145 cafile=cafile,
146 capath=capath)
Antoine Pitrou9a8d6932013-04-01 18:55:35 +0200147 https_handler = HTTPSHandler(context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000148 opener = build_opener(https_handler)
149 elif _opener is None:
150 _opener = opener = build_opener()
151 else:
152 opener = _opener
153 return opener.open(url, data, timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000154
155def install_opener(opener):
156 global _opener
157 _opener = opener
158
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700159_url_tempfiles = []
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000160def urlretrieve(url, filename=None, reporthook=None, data=None):
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700161 """
162 Retrieve a URL into a temporary location on disk.
163
164 Requires a URL argument. If a filename is passed, it is used as
165 the temporary file location. The reporthook argument should be
166 a callable that accepts a block number, a read size, and the
167 total file size of the URL target. The data argument should be
168 valid URL encoded data.
169
170 If a filename is passed and the URL points to a local resource,
171 the result is a copy from local file to new file.
172
173 Returns a tuple containing the path to the newly created
174 data file as well as the resulting HTTPMessage object.
175 """
176 url_type, path = splittype(url)
177
178 with contextlib.closing(urlopen(url, data)) as fp:
179 headers = fp.info()
180
181 # Just return the local path and the "headers" for file://
182 # URLs. No sense in performing a copy unless requested.
183 if url_type == "file" and not filename:
184 return os.path.normpath(path), headers
185
186 # Handle temporary file setup.
187 if filename:
188 tfp = open(filename, 'wb')
189 else:
190 tfp = tempfile.NamedTemporaryFile(delete=False)
191 filename = tfp.name
192 _url_tempfiles.append(filename)
193
194 with tfp:
195 result = filename, headers
196 bs = 1024*8
197 size = -1
198 read = 0
199 blocknum = 0
200 if "content-length" in headers:
201 size = int(headers["Content-Length"])
202
203 if reporthook:
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800204 reporthook(blocknum, bs, size)
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700205
206 while True:
207 block = fp.read(bs)
208 if not block:
209 break
210 read += len(block)
211 tfp.write(block)
212 blocknum += 1
213 if reporthook:
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800214 reporthook(blocknum, bs, size)
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700215
216 if size >= 0 and read < size:
217 raise ContentTooShortError(
218 "retrieval incomplete: got only %i out of %i bytes"
219 % (read, size), result)
220
221 return result
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000222
223def urlcleanup():
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700224 for temp_file in _url_tempfiles:
225 try:
226 os.unlink(temp_file)
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200227 except OSError:
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700228 pass
229
230 del _url_tempfiles[:]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000231 global _opener
232 if _opener:
233 _opener = None
234
235# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000236_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000237def request_host(request):
238 """Return request-host, as defined by RFC 2965.
239
240 Variation from RFC: returned value is lowercased, for convenient
241 comparison.
242
243 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000244 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000245 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000246 if host == "":
247 host = request.get_header("Host", "")
248
249 # remove port, if present
250 host = _cut_port_re.sub("", host, 1)
251 return host.lower()
252
253class Request:
254
255 def __init__(self, url, data=None, headers={},
Senthil Kumarande49d642011-10-16 23:54:44 +0800256 origin_req_host=None, unverifiable=False,
257 method=None):
Senthil Kumaran52380922013-04-25 05:45:48 -0700258 self.full_url = url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000259 self.headers = {}
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200260 self.unredirected_hdrs = {}
261 self._data = None
262 self.data = data
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000263 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000264 for key, value in headers.items():
265 self.add_header(key, value)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000266 if origin_req_host is None:
267 origin_req_host = request_host(self)
268 self.origin_req_host = origin_req_host
269 self.unverifiable = unverifiable
Jason R. Coombs7dc4f4b2013-09-08 12:47:07 -0400270 if method:
271 self.method = method
Senthil Kumaran52380922013-04-25 05:45:48 -0700272
273 @property
274 def full_url(self):
Senthil Kumaran83070752013-05-24 09:14:12 -0700275 if self.fragment:
276 return '{}#{}'.format(self._full_url, self.fragment)
Senthil Kumaran52380922013-04-25 05:45:48 -0700277 return self._full_url
278
279 @full_url.setter
280 def full_url(self, url):
281 # unwrap('<URL:type://host/path>') --> 'type://host/path'
282 self._full_url = unwrap(url)
283 self._full_url, self.fragment = splittag(self._full_url)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000284 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000285
Senthil Kumaran52380922013-04-25 05:45:48 -0700286 @full_url.deleter
287 def full_url(self):
288 self._full_url = None
289 self.fragment = None
290 self.selector = ''
291
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200292 @property
293 def data(self):
294 return self._data
295
296 @data.setter
297 def data(self, data):
298 if data != self._data:
299 self._data = data
300 # issue 16464
301 # if we change data we need to remove content-length header
302 # (cause it's most probably calculated for previous value)
303 if self.has_header("Content-length"):
304 self.remove_header("Content-length")
305
306 @data.deleter
307 def data(self):
R David Murray9cc7d452013-03-20 00:10:51 -0400308 self.data = None
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200309
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000310 def _parse(self):
Senthil Kumaran52380922013-04-25 05:45:48 -0700311 self.type, rest = splittype(self._full_url)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000312 if self.type is None:
R David Murrayd8a46962013-04-03 06:58:34 -0400313 raise ValueError("unknown url type: %r" % self.full_url)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000314 self.host, self.selector = splithost(rest)
315 if self.host:
316 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000317
318 def get_method(self):
Senthil Kumarande49d642011-10-16 23:54:44 +0800319 """Return a string indicating the HTTP request method."""
Jason R. Coombsaae6a1d2013-09-08 12:54:33 -0400320 default_method = "POST" if self.data is not None else "GET"
321 return getattr(self, 'method', default_method)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000322
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000323 def get_full_url(self):
Senthil Kumaran52380922013-04-25 05:45:48 -0700324 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000325
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000326 def set_proxy(self, host, type):
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000327 if self.type == 'https' and not self._tunnel_host:
328 self._tunnel_host = self.host
329 else:
330 self.type= type
331 self.selector = self.full_url
332 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000333
334 def has_proxy(self):
335 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000336
337 def add_header(self, key, val):
338 # useful for something like authentication
339 self.headers[key.capitalize()] = val
340
341 def add_unredirected_header(self, key, val):
342 # will not be added to a redirected request
343 self.unredirected_hdrs[key.capitalize()] = val
344
345 def has_header(self, header_name):
346 return (header_name in self.headers or
347 header_name in self.unredirected_hdrs)
348
349 def get_header(self, header_name, default=None):
350 return self.headers.get(
351 header_name,
352 self.unredirected_hdrs.get(header_name, default))
353
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200354 def remove_header(self, header_name):
355 self.headers.pop(header_name, None)
356 self.unredirected_hdrs.pop(header_name, None)
357
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000358 def header_items(self):
359 hdrs = self.unredirected_hdrs.copy()
360 hdrs.update(self.headers)
361 return list(hdrs.items())
362
363class OpenerDirector:
364 def __init__(self):
365 client_version = "Python-urllib/%s" % __version__
366 self.addheaders = [('User-agent', client_version)]
R. David Murray25b8cca2010-12-23 19:44:49 +0000367 # self.handlers is retained only for backward compatibility
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000368 self.handlers = []
R. David Murray25b8cca2010-12-23 19:44:49 +0000369 # manage the individual handlers
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000370 self.handle_open = {}
371 self.handle_error = {}
372 self.process_response = {}
373 self.process_request = {}
374
375 def add_handler(self, handler):
376 if not hasattr(handler, "add_parent"):
377 raise TypeError("expected BaseHandler instance, got %r" %
378 type(handler))
379
380 added = False
381 for meth in dir(handler):
382 if meth in ["redirect_request", "do_open", "proxy_open"]:
383 # oops, coincidental match
384 continue
385
386 i = meth.find("_")
387 protocol = meth[:i]
388 condition = meth[i+1:]
389
390 if condition.startswith("error"):
391 j = condition.find("_") + i + 1
392 kind = meth[j+1:]
393 try:
394 kind = int(kind)
395 except ValueError:
396 pass
397 lookup = self.handle_error.get(protocol, {})
398 self.handle_error[protocol] = lookup
399 elif condition == "open":
400 kind = protocol
401 lookup = self.handle_open
402 elif condition == "response":
403 kind = protocol
404 lookup = self.process_response
405 elif condition == "request":
406 kind = protocol
407 lookup = self.process_request
408 else:
409 continue
410
411 handlers = lookup.setdefault(kind, [])
412 if handlers:
413 bisect.insort(handlers, handler)
414 else:
415 handlers.append(handler)
416 added = True
417
418 if added:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000419 bisect.insort(self.handlers, handler)
420 handler.add_parent(self)
421
422 def close(self):
423 # Only exists for backwards compatibility.
424 pass
425
426 def _call_chain(self, chain, kind, meth_name, *args):
427 # Handlers raise an exception if no one else should try to handle
428 # the request, or return None if they can't but another handler
429 # could. Otherwise, they return the response.
430 handlers = chain.get(kind, ())
431 for handler in handlers:
432 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000433 result = func(*args)
434 if result is not None:
435 return result
436
437 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
438 # accept a URL or a Request object
439 if isinstance(fullurl, str):
440 req = Request(fullurl, data)
441 else:
442 req = fullurl
443 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000444 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000445
446 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000447 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000448
449 # pre-process request
450 meth_name = protocol+"_request"
451 for processor in self.process_request.get(protocol, []):
452 meth = getattr(processor, meth_name)
453 req = meth(req)
454
455 response = self._open(req, data)
456
457 # post-process response
458 meth_name = protocol+"_response"
459 for processor in self.process_response.get(protocol, []):
460 meth = getattr(processor, meth_name)
461 response = meth(req, response)
462
463 return response
464
465 def _open(self, req, data=None):
466 result = self._call_chain(self.handle_open, 'default',
467 'default_open', req)
468 if result:
469 return result
470
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000471 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000472 result = self._call_chain(self.handle_open, protocol, protocol +
473 '_open', req)
474 if result:
475 return result
476
477 return self._call_chain(self.handle_open, 'unknown',
478 'unknown_open', req)
479
480 def error(self, proto, *args):
481 if proto in ('http', 'https'):
482 # XXX http[s] protocols are special-cased
483 dict = self.handle_error['http'] # https is not different than http
484 proto = args[2] # YUCK!
485 meth_name = 'http_error_%s' % proto
486 http_err = 1
487 orig_args = args
488 else:
489 dict = self.handle_error
490 meth_name = proto + '_error'
491 http_err = 0
492 args = (dict, proto, meth_name) + args
493 result = self._call_chain(*args)
494 if result:
495 return result
496
497 if http_err:
498 args = (dict, 'default', 'http_error_default') + orig_args
499 return self._call_chain(*args)
500
501# XXX probably also want an abstract factory that knows when it makes
502# sense to skip a superclass in favor of a subclass and when it might
503# make sense to include both
504
505def build_opener(*handlers):
506 """Create an opener object from a list of handlers.
507
508 The opener will use several default handlers, including support
Senthil Kumaran1107c5d2009-11-15 06:20:55 +0000509 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000510
511 If any of the handlers passed as arguments are subclasses of the
512 default handlers, the default handlers will not be used.
513 """
514 def isclass(obj):
515 return isinstance(obj, type) or hasattr(obj, "__bases__")
516
517 opener = OpenerDirector()
518 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
519 HTTPDefaultErrorHandler, HTTPRedirectHandler,
Antoine Pitroudf204be2012-11-24 17:59:08 +0100520 FTPHandler, FileHandler, HTTPErrorProcessor,
521 DataHandler]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000522 if hasattr(http.client, "HTTPSConnection"):
523 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000524 skip = set()
525 for klass in default_classes:
526 for check in handlers:
527 if isclass(check):
528 if issubclass(check, klass):
529 skip.add(klass)
530 elif isinstance(check, klass):
531 skip.add(klass)
532 for klass in skip:
533 default_classes.remove(klass)
534
535 for klass in default_classes:
536 opener.add_handler(klass())
537
538 for h in handlers:
539 if isclass(h):
540 h = h()
541 opener.add_handler(h)
542 return opener
543
544class BaseHandler:
545 handler_order = 500
546
547 def add_parent(self, parent):
548 self.parent = parent
549
550 def close(self):
551 # Only exists for backwards compatibility
552 pass
553
554 def __lt__(self, other):
555 if not hasattr(other, "handler_order"):
556 # Try to preserve the old behavior of having custom classes
557 # inserted after default ones (works only for custom user
558 # classes which are not aware of handler_order).
559 return True
560 return self.handler_order < other.handler_order
561
562
563class HTTPErrorProcessor(BaseHandler):
564 """Process HTTP error responses."""
565 handler_order = 1000 # after all other processing
566
567 def http_response(self, request, response):
568 code, msg, hdrs = response.code, response.msg, response.info()
569
570 # According to RFC 2616, "2xx" code indicates that the client's
571 # request was successfully received, understood, and accepted.
572 if not (200 <= code < 300):
573 response = self.parent.error(
574 'http', request, response, code, msg, hdrs)
575
576 return response
577
578 https_response = http_response
579
580class HTTPDefaultErrorHandler(BaseHandler):
581 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000582 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000583
584class HTTPRedirectHandler(BaseHandler):
585 # maximum number of redirections to any single URL
586 # this is needed because of the state that cookies introduce
587 max_repeats = 4
588 # maximum total number of redirections (regardless of URL) before
589 # assuming we're in a loop
590 max_redirections = 10
591
592 def redirect_request(self, req, fp, code, msg, headers, newurl):
593 """Return a Request or None in response to a redirect.
594
595 This is called by the http_error_30x methods when a
596 redirection response is received. If a redirection should
597 take place, return a new Request to allow http_error_30x to
598 perform the redirect. Otherwise, raise HTTPError if no-one
599 else should try to handle this url. Return None if you can't
600 but another Handler might.
601 """
602 m = req.get_method()
603 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
604 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000605 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000606
607 # Strictly (according to RFC 2616), 301 or 302 in response to
608 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000609 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000610 # essentially all clients do redirect in this case, so we do
611 # the same.
612 # be conciliant with URIs containing a space
613 newurl = newurl.replace(' ', '%20')
614 CONTENT_HEADERS = ("content-length", "content-type")
615 newheaders = dict((k, v) for k, v in req.headers.items()
616 if k.lower() not in CONTENT_HEADERS)
617 return Request(newurl,
618 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000619 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000620 unverifiable=True)
621
622 # Implementation note: To avoid the server sending us into an
623 # infinite loop, the request object needs to track what URLs we
624 # have already seen. Do this by adding a handler-specific
625 # attribute to the Request object.
626 def http_error_302(self, req, fp, code, msg, headers):
627 # Some servers (incorrectly) return multiple Location headers
628 # (so probably same goes for URI). Use first header.
629 if "location" in headers:
630 newurl = headers["location"]
631 elif "uri" in headers:
632 newurl = headers["uri"]
633 else:
634 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000635
636 # fix a possible malformed URL
637 urlparts = urlparse(newurl)
guido@google.coma119df92011-03-29 11:41:02 -0700638
639 # For security reasons we don't allow redirection to anything other
640 # than http, https or ftp.
641
Senthil Kumaran6497aa32012-01-04 13:46:59 +0800642 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800643 raise HTTPError(
644 newurl, code,
645 "%s - Redirection to url '%s' is not allowed" % (msg, newurl),
646 headers, fp)
guido@google.coma119df92011-03-29 11:41:02 -0700647
Facundo Batistaf24802c2008-08-17 03:36:03 +0000648 if not urlparts.path:
649 urlparts = list(urlparts)
650 urlparts[2] = "/"
651 newurl = urlunparse(urlparts)
652
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000653 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000654
655 # XXX Probably want to forget about the state of the current
656 # request, although that might interact poorly with other
657 # handlers that also use handler-specific request attributes
658 new = self.redirect_request(req, fp, code, msg, headers, newurl)
659 if new is None:
660 return
661
662 # loop detection
663 # .redirect_dict has a key url if url was previously visited.
664 if hasattr(req, 'redirect_dict'):
665 visited = new.redirect_dict = req.redirect_dict
666 if (visited.get(newurl, 0) >= self.max_repeats or
667 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000668 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000669 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000670 else:
671 visited = new.redirect_dict = req.redirect_dict = {}
672 visited[newurl] = visited.get(newurl, 0) + 1
673
674 # Don't close the fp until we are sure that we won't use it
675 # with HTTPError.
676 fp.read()
677 fp.close()
678
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000679 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000680
681 http_error_301 = http_error_303 = http_error_307 = http_error_302
682
683 inf_msg = "The HTTP server returned a redirect error that would " \
684 "lead to an infinite loop.\n" \
685 "The last 30x error message was:\n"
686
687
688def _parse_proxy(proxy):
689 """Return (scheme, user, password, host/port) given a URL or an authority.
690
691 If a URL is supplied, it must have an authority (host:port) component.
692 According to RFC 3986, having an authority component means the URL must
693 have two slashes after the scheme:
694
695 >>> _parse_proxy('file:/ftp.example.com/')
696 Traceback (most recent call last):
697 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
698
699 The first three items of the returned tuple may be None.
700
701 Examples of authority parsing:
702
703 >>> _parse_proxy('proxy.example.com')
704 (None, None, None, 'proxy.example.com')
705 >>> _parse_proxy('proxy.example.com:3128')
706 (None, None, None, 'proxy.example.com:3128')
707
708 The authority component may optionally include userinfo (assumed to be
709 username:password):
710
711 >>> _parse_proxy('joe:password@proxy.example.com')
712 (None, 'joe', 'password', 'proxy.example.com')
713 >>> _parse_proxy('joe:password@proxy.example.com:3128')
714 (None, 'joe', 'password', 'proxy.example.com:3128')
715
716 Same examples, but with URLs instead:
717
718 >>> _parse_proxy('http://proxy.example.com/')
719 ('http', None, None, 'proxy.example.com')
720 >>> _parse_proxy('http://proxy.example.com:3128/')
721 ('http', None, None, 'proxy.example.com:3128')
722 >>> _parse_proxy('http://joe:password@proxy.example.com/')
723 ('http', 'joe', 'password', 'proxy.example.com')
724 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
725 ('http', 'joe', 'password', 'proxy.example.com:3128')
726
727 Everything after the authority is ignored:
728
729 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
730 ('ftp', 'joe', 'password', 'proxy.example.com')
731
732 Test for no trailing '/' case:
733
734 >>> _parse_proxy('http://joe:password@proxy.example.com')
735 ('http', 'joe', 'password', 'proxy.example.com')
736
737 """
Georg Brandl13e89462008-07-01 19:56:00 +0000738 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000739 if not r_scheme.startswith("/"):
740 # authority
741 scheme = None
742 authority = proxy
743 else:
744 # URL
745 if not r_scheme.startswith("//"):
746 raise ValueError("proxy URL with no authority: %r" % proxy)
747 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
748 # and 3.3.), path is empty or starts with '/'
749 end = r_scheme.find("/", 2)
750 if end == -1:
751 end = None
752 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000753 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000754 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000755 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000756 else:
757 user = password = None
758 return scheme, user, password, hostport
759
760class ProxyHandler(BaseHandler):
761 # Proxies must be in front
762 handler_order = 100
763
764 def __init__(self, proxies=None):
765 if proxies is None:
766 proxies = getproxies()
767 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
768 self.proxies = proxies
769 for type, url in proxies.items():
770 setattr(self, '%s_open' % type,
Georg Brandlfcbdbf22012-06-24 19:56:31 +0200771 lambda r, proxy=url, type=type, meth=self.proxy_open:
772 meth(r, proxy, type))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000773
774 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000775 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000776 proxy_type, user, password, hostport = _parse_proxy(proxy)
777 if proxy_type is None:
778 proxy_type = orig_type
Senthil Kumaran7bb04972009-10-11 04:58:55 +0000779
780 if req.host and proxy_bypass(req.host):
781 return None
782
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000783 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000784 user_pass = '%s:%s' % (unquote(user),
785 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000786 creds = base64.b64encode(user_pass.encode()).decode("ascii")
787 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000788 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000789 req.set_proxy(hostport, proxy_type)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000790 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000791 # let other handlers take care of it
792 return None
793 else:
794 # need to start over, because the other handlers don't
795 # grok the proxy's URL type
796 # e.g. if we have a constructor arg proxies like so:
797 # {'http': 'ftp://proxy.example.com'}, we may end up turning
798 # a request for http://acme.example.com/a into one for
799 # ftp://proxy.example.com/a
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000800 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000801
802class HTTPPasswordMgr:
803
804 def __init__(self):
805 self.passwd = {}
806
807 def add_password(self, realm, uri, user, passwd):
808 # uri could be a single URI or a sequence
809 if isinstance(uri, str):
810 uri = [uri]
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800811 if realm not in self.passwd:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000812 self.passwd[realm] = {}
813 for default_port in True, False:
814 reduced_uri = tuple(
815 [self.reduce_uri(u, default_port) for u in uri])
816 self.passwd[realm][reduced_uri] = (user, passwd)
817
818 def find_user_password(self, realm, authuri):
819 domains = self.passwd.get(realm, {})
820 for default_port in True, False:
821 reduced_authuri = self.reduce_uri(authuri, default_port)
822 for uris, authinfo in domains.items():
823 for uri in uris:
824 if self.is_suburi(uri, reduced_authuri):
825 return authinfo
826 return None, None
827
828 def reduce_uri(self, uri, default_port=True):
829 """Accept authority or URI and extract only the authority and path."""
830 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000831 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000832 if parts[1]:
833 # URI
834 scheme = parts[0]
835 authority = parts[1]
836 path = parts[2] or '/'
837 else:
838 # host or host:port
839 scheme = None
840 authority = uri
841 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000842 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000843 if default_port and port is None and scheme is not None:
844 dport = {"http": 80,
845 "https": 443,
846 }.get(scheme)
847 if dport is not None:
848 authority = "%s:%d" % (host, dport)
849 return authority, path
850
851 def is_suburi(self, base, test):
852 """Check if test is below base in a URI tree
853
854 Both args must be URIs in reduced form.
855 """
856 if base == test:
857 return True
858 if base[0] != test[0]:
859 return False
860 common = posixpath.commonprefix((base[1], test[1]))
861 if len(common) == len(base[1]):
862 return True
863 return False
864
865
866class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
867
868 def find_user_password(self, realm, authuri):
869 user, password = HTTPPasswordMgr.find_user_password(self, realm,
870 authuri)
871 if user is not None:
872 return user, password
873 return HTTPPasswordMgr.find_user_password(self, None, authuri)
874
875
876class AbstractBasicAuthHandler:
877
878 # XXX this allows for multiple auth-schemes, but will stupidly pick
879 # the last one with a realm specified.
880
881 # allow for double- and single-quoted realm values
882 # (single quotes are a violation of the RFC, but appear in the wild)
883 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +0800884 'realm=(["\']?)([^"\']*)\\2', re.I)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000885
886 # XXX could pre-emptively send auth info already accepted (RFC 2617,
887 # end of section 2, and section 1.2 immediately after "credentials"
888 # production).
889
890 def __init__(self, password_mgr=None):
891 if password_mgr is None:
892 password_mgr = HTTPPasswordMgr()
893 self.passwd = password_mgr
894 self.add_password = self.passwd.add_password
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000895 self.retried = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000896
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000897 def reset_retry_count(self):
898 self.retried = 0
899
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000900 def http_error_auth_reqed(self, authreq, host, req, headers):
901 # host may be an authority (without userinfo) or a URL with an
902 # authority
903 # XXX could be multiple headers
904 authreq = headers.get(authreq, None)
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000905
906 if self.retried > 5:
907 # retry sending the username:password 5 times before failing.
908 raise HTTPError(req.get_full_url(), 401, "basic auth failed",
909 headers, None)
910 else:
911 self.retried += 1
912
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000913 if authreq:
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800914 scheme = authreq.split()[0]
Senthil Kumaran1a129c82011-10-20 02:50:13 +0800915 if scheme.lower() != 'basic':
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800916 raise ValueError("AbstractBasicAuthHandler does not"
917 " support the following scheme: '%s'" %
918 scheme)
919 else:
920 mo = AbstractBasicAuthHandler.rx.search(authreq)
921 if mo:
922 scheme, quote, realm = mo.groups()
Senthil Kumaran92a5bf02012-05-16 00:03:29 +0800923 if quote not in ['"',"'"]:
924 warnings.warn("Basic Auth Realm was unquoted",
925 UserWarning, 2)
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800926 if scheme.lower() == 'basic':
927 response = self.retry_http_basic_auth(host, req, realm)
928 if response and response.code != 401:
929 self.retried = 0
930 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000931
932 def retry_http_basic_auth(self, host, req, realm):
933 user, pw = self.passwd.find_user_password(realm, host)
934 if pw is not None:
935 raw = "%s:%s" % (user, pw)
936 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
937 if req.headers.get(self.auth_header, None) == auth:
938 return None
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +0000939 req.add_unredirected_header(self.auth_header, auth)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000940 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000941 else:
942 return None
943
944
945class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
946
947 auth_header = 'Authorization'
948
949 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000950 url = req.full_url
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000951 response = self.http_error_auth_reqed('www-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000952 url, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000953 self.reset_retry_count()
954 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000955
956
957class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
958
959 auth_header = 'Proxy-authorization'
960
961 def http_error_407(self, req, fp, code, msg, headers):
962 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000963 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000964 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
965 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000966 authority = req.host
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000967 response = self.http_error_auth_reqed('proxy-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000968 authority, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000969 self.reset_retry_count()
970 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000971
972
Senthil Kumaran6c5bd402011-11-01 23:20:31 +0800973# Return n random bytes.
974_randombytes = os.urandom
975
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000976
977class AbstractDigestAuthHandler:
978 # Digest authentication is specified in RFC 2617.
979
980 # XXX The client does not inspect the Authentication-Info header
981 # in a successful response.
982
983 # XXX It should be possible to test this implementation against
984 # a mock server that just generates a static set of challenges.
985
986 # XXX qop="auth-int" supports is shaky
987
988 def __init__(self, passwd=None):
989 if passwd is None:
990 passwd = HTTPPasswordMgr()
991 self.passwd = passwd
992 self.add_password = self.passwd.add_password
993 self.retried = 0
994 self.nonce_count = 0
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000995 self.last_nonce = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000996
997 def reset_retry_count(self):
998 self.retried = 0
999
1000 def http_error_auth_reqed(self, auth_header, host, req, headers):
1001 authreq = headers.get(auth_header, None)
1002 if self.retried > 5:
1003 # Don't fail endlessly - if we failed once, we'll probably
1004 # fail a second time. Hm. Unless the Password Manager is
1005 # prompting for the information. Crap. This isn't great
1006 # but it's better than the current 'repeat until recursion
1007 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001008 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +00001009 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001010 else:
1011 self.retried += 1
1012 if authreq:
1013 scheme = authreq.split()[0]
1014 if scheme.lower() == 'digest':
1015 return self.retry_http_digest_auth(req, authreq)
Senthil Kumaran1a129c82011-10-20 02:50:13 +08001016 elif scheme.lower() != 'basic':
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001017 raise ValueError("AbstractDigestAuthHandler does not support"
1018 " the following scheme: '%s'" % scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001019
1020 def retry_http_digest_auth(self, req, auth):
1021 token, challenge = auth.split(' ', 1)
1022 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
1023 auth = self.get_authorization(req, chal)
1024 if auth:
1025 auth_val = 'Digest %s' % auth
1026 if req.headers.get(self.auth_header, None) == auth_val:
1027 return None
1028 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001029 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001030 return resp
1031
1032 def get_cnonce(self, nonce):
1033 # The cnonce-value is an opaque
1034 # quoted string value provided by the client and used by both client
1035 # and server to avoid chosen plaintext attacks, to provide mutual
1036 # authentication, and to provide some message integrity protection.
1037 # This isn't a fabulous effort, but it's probably Good Enough.
1038 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
Senthil Kumaran6c5bd402011-11-01 23:20:31 +08001039 b = s.encode("ascii") + _randombytes(8)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001040 dig = hashlib.sha1(b).hexdigest()
1041 return dig[:16]
1042
1043 def get_authorization(self, req, chal):
1044 try:
1045 realm = chal['realm']
1046 nonce = chal['nonce']
1047 qop = chal.get('qop')
1048 algorithm = chal.get('algorithm', 'MD5')
1049 # mod_digest doesn't send an opaque, even though it isn't
1050 # supposed to be optional
1051 opaque = chal.get('opaque', None)
1052 except KeyError:
1053 return None
1054
1055 H, KD = self.get_algorithm_impls(algorithm)
1056 if H is None:
1057 return None
1058
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001059 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001060 if user is None:
1061 return None
1062
1063 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001064 if req.data is not None:
1065 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001066 else:
1067 entdig = None
1068
1069 A1 = "%s:%s:%s" % (user, realm, pw)
1070 A2 = "%s:%s" % (req.get_method(),
1071 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001072 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001073 if qop == 'auth':
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +00001074 if nonce == self.last_nonce:
1075 self.nonce_count += 1
1076 else:
1077 self.nonce_count = 1
1078 self.last_nonce = nonce
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001079 ncvalue = '%08x' % self.nonce_count
1080 cnonce = self.get_cnonce(nonce)
1081 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
1082 respdig = KD(H(A1), noncebit)
1083 elif qop is None:
1084 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
1085 else:
1086 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +00001087 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001088
1089 # XXX should the partial digests be encoded too?
1090
1091 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001092 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001093 respdig)
1094 if opaque:
1095 base += ', opaque="%s"' % opaque
1096 if entdig:
1097 base += ', digest="%s"' % entdig
1098 base += ', algorithm="%s"' % algorithm
1099 if qop:
1100 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
1101 return base
1102
1103 def get_algorithm_impls(self, algorithm):
1104 # lambdas assume digest modules are imported at the top level
1105 if algorithm == 'MD5':
1106 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
1107 elif algorithm == 'SHA':
1108 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
1109 # XXX MD5-sess
1110 KD = lambda s, d: H("%s:%s" % (s, d))
1111 return H, KD
1112
1113 def get_entity_digest(self, data, chal):
1114 # XXX not implemented yet
1115 return None
1116
1117
1118class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1119 """An authentication protocol defined by RFC 2069
1120
1121 Digest authentication improves on basic authentication because it
1122 does not transmit passwords in the clear.
1123 """
1124
1125 auth_header = 'Authorization'
1126 handler_order = 490 # before Basic auth
1127
1128 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001129 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001130 retry = self.http_error_auth_reqed('www-authenticate',
1131 host, req, headers)
1132 self.reset_retry_count()
1133 return retry
1134
1135
1136class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1137
1138 auth_header = 'Proxy-Authorization'
1139 handler_order = 490 # before Basic auth
1140
1141 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001142 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001143 retry = self.http_error_auth_reqed('proxy-authenticate',
1144 host, req, headers)
1145 self.reset_retry_count()
1146 return retry
1147
1148class AbstractHTTPHandler(BaseHandler):
1149
1150 def __init__(self, debuglevel=0):
1151 self._debuglevel = debuglevel
1152
1153 def set_http_debuglevel(self, level):
1154 self._debuglevel = level
1155
1156 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001157 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001158 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001159 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001160
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001161 if request.data is not None: # POST
1162 data = request.data
Senthil Kumaran29333122011-02-11 11:25:47 +00001163 if isinstance(data, str):
Georg Brandlfcbdbf22012-06-24 19:56:31 +02001164 msg = "POST data should be bytes or an iterable of bytes. " \
1165 "It cannot be of type str."
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07001166 raise TypeError(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001167 if not request.has_header('Content-type'):
1168 request.add_unredirected_header(
1169 'Content-type',
1170 'application/x-www-form-urlencoded')
1171 if not request.has_header('Content-length'):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001172 try:
1173 mv = memoryview(data)
1174 except TypeError:
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001175 if isinstance(data, collections.Iterable):
Georg Brandl61536042011-02-03 07:46:41 +00001176 raise ValueError("Content-Length should be specified "
1177 "for iterable data of type %r %r" % (type(data),
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001178 data))
1179 else:
1180 request.add_unredirected_header(
Senthil Kumaran1e991f22010-12-24 04:03:59 +00001181 'Content-length', '%d' % (len(mv) * mv.itemsize))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001182
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001183 sel_host = host
1184 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001185 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001186 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001187 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001188 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001189 for name, value in self.parent.addheaders:
1190 name = name.capitalize()
1191 if not request.has_header(name):
1192 request.add_unredirected_header(name, value)
1193
1194 return request
1195
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001196 def do_open(self, http_class, req, **http_conn_args):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001197 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001198
1199 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001200 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001201 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001202 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001203 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001204
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001205 # will parse host:port
1206 h = http_class(host, timeout=req.timeout, **http_conn_args)
Senthil Kumaran42ef4b12010-09-27 01:26:03 +00001207
1208 headers = dict(req.unredirected_hdrs)
1209 headers.update(dict((k, v) for k, v in req.headers.items()
1210 if k not in headers))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001211
1212 # TODO(jhylton): Should this be redesigned to handle
1213 # persistent connections?
1214
1215 # We want to make an HTTP/1.1 request, but the addinfourl
1216 # class isn't prepared to deal with a persistent connection.
1217 # It will try to read all remaining data from the socket,
1218 # which will block while the server waits for the next request.
1219 # So make sure the connection gets closed after the (only)
1220 # request.
1221 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001222 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001223
1224 if req._tunnel_host:
Senthil Kumaran47fff872009-12-20 07:10:31 +00001225 tunnel_headers = {}
1226 proxy_auth_hdr = "Proxy-Authorization"
1227 if proxy_auth_hdr in headers:
1228 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1229 # Proxy-Authorization should not be sent to origin
1230 # server.
1231 del headers[proxy_auth_hdr]
1232 h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001233
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001234 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001235 h.request(req.get_method(), req.selector, req.data, headers)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001236 except OSError as err: # timeout error
Senthil Kumaran45686b42011-07-27 09:31:03 +08001237 h.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001238 raise URLError(err)
Senthil Kumaran45686b42011-07-27 09:31:03 +08001239 else:
1240 r = h.getresponse()
Nadeem Vawdabd26b542012-10-21 17:37:43 +02001241 # If the server does not send us a 'Connection: close' header,
1242 # HTTPConnection assumes the socket should be left open. Manually
1243 # mark the socket to be closed when this response object goes away.
1244 if h.sock:
1245 h.sock.close()
1246 h.sock = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001247
Senthil Kumaran26430412011-04-13 07:01:19 +08001248 r.url = req.get_full_url()
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001249 # This line replaces the .msg attribute of the HTTPResponse
1250 # with .headers, because urllib clients expect the response to
1251 # have the reason in .msg. It would be good to mark this
1252 # attribute is deprecated and get then to use info() or
1253 # .headers.
1254 r.msg = r.reason
1255 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001256
1257
1258class HTTPHandler(AbstractHTTPHandler):
1259
1260 def http_open(self, req):
1261 return self.do_open(http.client.HTTPConnection, req)
1262
1263 http_request = AbstractHTTPHandler.do_request_
1264
1265if hasattr(http.client, 'HTTPSConnection'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001266
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001267 class HTTPSHandler(AbstractHTTPHandler):
1268
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001269 def __init__(self, debuglevel=0, context=None, check_hostname=None):
1270 AbstractHTTPHandler.__init__(self, debuglevel)
1271 self._context = context
1272 self._check_hostname = check_hostname
1273
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001274 def https_open(self, req):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001275 return self.do_open(http.client.HTTPSConnection, req,
1276 context=self._context, check_hostname=self._check_hostname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001277
1278 https_request = AbstractHTTPHandler.do_request_
1279
Senthil Kumaran4c875a92011-11-01 23:57:57 +08001280 __all__.append('HTTPSHandler')
Senthil Kumaran0d54eb92011-11-01 23:49:46 +08001281
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001282class HTTPCookieProcessor(BaseHandler):
1283 def __init__(self, cookiejar=None):
1284 import http.cookiejar
1285 if cookiejar is None:
1286 cookiejar = http.cookiejar.CookieJar()
1287 self.cookiejar = cookiejar
1288
1289 def http_request(self, request):
1290 self.cookiejar.add_cookie_header(request)
1291 return request
1292
1293 def http_response(self, request, response):
1294 self.cookiejar.extract_cookies(response, request)
1295 return response
1296
1297 https_request = http_request
1298 https_response = http_response
1299
1300class UnknownHandler(BaseHandler):
1301 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001302 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001303 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001304
1305def parse_keqv_list(l):
1306 """Parse list of key=value strings where keys are not duplicated."""
1307 parsed = {}
1308 for elt in l:
1309 k, v = elt.split('=', 1)
1310 if v[0] == '"' and v[-1] == '"':
1311 v = v[1:-1]
1312 parsed[k] = v
1313 return parsed
1314
1315def parse_http_list(s):
1316 """Parse lists as described by RFC 2068 Section 2.
1317
1318 In particular, parse comma-separated lists where the elements of
1319 the list may include quoted-strings. A quoted-string could
1320 contain a comma. A non-quoted string could have quotes in the
1321 middle. Neither commas nor quotes count if they are escaped.
1322 Only double-quotes count, not single-quotes.
1323 """
1324 res = []
1325 part = ''
1326
1327 escape = quote = False
1328 for cur in s:
1329 if escape:
1330 part += cur
1331 escape = False
1332 continue
1333 if quote:
1334 if cur == '\\':
1335 escape = True
1336 continue
1337 elif cur == '"':
1338 quote = False
1339 part += cur
1340 continue
1341
1342 if cur == ',':
1343 res.append(part)
1344 part = ''
1345 continue
1346
1347 if cur == '"':
1348 quote = True
1349
1350 part += cur
1351
1352 # append last part
1353 if part:
1354 res.append(part)
1355
1356 return [part.strip() for part in res]
1357
1358class FileHandler(BaseHandler):
1359 # Use local file or FTP depending on form of URL
1360 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001361 url = req.selector
Senthil Kumaran2ef16322010-07-11 03:12:43 +00001362 if url[:2] == '//' and url[2:3] != '/' and (req.host and
1363 req.host != 'localhost'):
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001364 if not req.host is self.get_names():
1365 raise URLError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001366 else:
1367 return self.open_local_file(req)
1368
1369 # names for the localhost
1370 names = None
1371 def get_names(self):
1372 if FileHandler.names is None:
1373 try:
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001374 FileHandler.names = tuple(
1375 socket.gethostbyname_ex('localhost')[2] +
1376 socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001377 except socket.gaierror:
1378 FileHandler.names = (socket.gethostbyname('localhost'),)
1379 return FileHandler.names
1380
1381 # not entirely sure what the rules are here
1382 def open_local_file(self, req):
1383 import email.utils
1384 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001385 host = req.host
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001386 filename = req.selector
1387 localfile = url2pathname(filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001388 try:
1389 stats = os.stat(localfile)
1390 size = stats.st_size
1391 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001392 mtype = mimetypes.guess_type(filename)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001393 headers = email.message_from_string(
1394 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1395 (mtype or 'text/plain', size, modified))
1396 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001397 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001398 if not host or \
1399 (not port and _safe_gethostbyname(host) in self.get_names()):
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001400 if host:
1401 origurl = 'file://' + host + filename
1402 else:
1403 origurl = 'file://' + filename
1404 return addinfourl(open(localfile, 'rb'), headers, origurl)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001405 except OSError as exp:
Georg Brandl029986a2008-06-23 11:44:14 +00001406 # users shouldn't expect OSErrors coming from urlopen()
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001407 raise URLError(exp)
Georg Brandl13e89462008-07-01 19:56:00 +00001408 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001409
1410def _safe_gethostbyname(host):
1411 try:
1412 return socket.gethostbyname(host)
1413 except socket.gaierror:
1414 return None
1415
1416class FTPHandler(BaseHandler):
1417 def ftp_open(self, req):
1418 import ftplib
1419 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001420 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001421 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001422 raise URLError('ftp error: no host given')
1423 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001424 if port is None:
1425 port = ftplib.FTP_PORT
1426 else:
1427 port = int(port)
1428
1429 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001430 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001431 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001432 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001433 else:
1434 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001435 host = unquote(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +00001436 user = user or ''
1437 passwd = passwd or ''
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001438
1439 try:
1440 host = socket.gethostbyname(host)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001441 except OSError as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001442 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001443 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001444 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001445 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001446 dirs, file = dirs[:-1], dirs[-1]
1447 if dirs and not dirs[0]:
1448 dirs = dirs[1:]
1449 try:
1450 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1451 type = file and 'I' or 'D'
1452 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001453 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001454 if attr.lower() == 'type' and \
1455 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1456 type = value.upper()
1457 fp, retrlen = fw.retrfile(file, type)
1458 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001459 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001460 if mtype:
1461 headers += "Content-type: %s\n" % mtype
1462 if retrlen is not None and retrlen >= 0:
1463 headers += "Content-length: %d\n" % retrlen
1464 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001465 return addinfourl(fp, headers, req.full_url)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001466 except ftplib.all_errors as exp:
1467 exc = URLError('ftp error: %r' % exp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001468 raise exc.with_traceback(sys.exc_info()[2])
1469
1470 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001471 return ftpwrapper(user, passwd, host, port, dirs, timeout,
1472 persistent=False)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001473
1474class CacheFTPHandler(FTPHandler):
1475 # XXX would be nice to have pluggable cache strategies
1476 # XXX this stuff is definitely not thread safe
1477 def __init__(self):
1478 self.cache = {}
1479 self.timeout = {}
1480 self.soonest = 0
1481 self.delay = 60
1482 self.max_conns = 16
1483
1484 def setTimeout(self, t):
1485 self.delay = t
1486
1487 def setMaxConns(self, m):
1488 self.max_conns = m
1489
1490 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1491 key = user, host, port, '/'.join(dirs), timeout
1492 if key in self.cache:
1493 self.timeout[key] = time.time() + self.delay
1494 else:
1495 self.cache[key] = ftpwrapper(user, passwd, host, port,
1496 dirs, timeout)
1497 self.timeout[key] = time.time() + self.delay
1498 self.check_cache()
1499 return self.cache[key]
1500
1501 def check_cache(self):
1502 # first check for old ones
1503 t = time.time()
1504 if self.soonest <= t:
1505 for k, v in list(self.timeout.items()):
1506 if v < t:
1507 self.cache[k].close()
1508 del self.cache[k]
1509 del self.timeout[k]
1510 self.soonest = min(list(self.timeout.values()))
1511
1512 # then check the size
1513 if len(self.cache) == self.max_conns:
1514 for k, v in list(self.timeout.items()):
1515 if v == self.soonest:
1516 del self.cache[k]
1517 del self.timeout[k]
1518 break
1519 self.soonest = min(list(self.timeout.values()))
1520
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001521 def clear_cache(self):
1522 for conn in self.cache.values():
1523 conn.close()
1524 self.cache.clear()
1525 self.timeout.clear()
1526
Antoine Pitroudf204be2012-11-24 17:59:08 +01001527class DataHandler(BaseHandler):
1528 def data_open(self, req):
1529 # data URLs as specified in RFC 2397.
1530 #
1531 # ignores POSTed data
1532 #
1533 # syntax:
1534 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1535 # mediatype := [ type "/" subtype ] *( ";" parameter )
1536 # data := *urlchar
1537 # parameter := attribute "=" value
1538 url = req.full_url
1539
1540 scheme, data = url.split(":",1)
1541 mediatype, data = data.split(",",1)
1542
1543 # even base64 encoded data URLs might be quoted so unquote in any case:
1544 data = unquote_to_bytes(data)
1545 if mediatype.endswith(";base64"):
1546 data = base64.decodebytes(data)
1547 mediatype = mediatype[:-7]
1548
1549 if not mediatype:
1550 mediatype = "text/plain;charset=US-ASCII"
1551
1552 headers = email.message_from_string("Content-type: %s\nContent-length: %d\n" %
1553 (mediatype, len(data)))
1554
1555 return addinfourl(io.BytesIO(data), headers, url)
1556
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001557
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001558# Code move from the old urllib module
1559
1560MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1561
1562# Helper for non-unix systems
Ronald Oussoren94f25282010-05-05 19:11:21 +00001563if os.name == 'nt':
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001564 from nturl2path import url2pathname, pathname2url
1565else:
1566 def url2pathname(pathname):
1567 """OS-specific conversion from a relative URL of the 'file' scheme
1568 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001569 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001570
1571 def pathname2url(pathname):
1572 """OS-specific conversion from a file system path to a relative URL
1573 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001574 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001575
1576# This really consists of two pieces:
1577# (1) a class which handles opening of all sorts of URLs
1578# (plus assorted utilities etc.)
1579# (2) a set of functions for parsing URLs
1580# XXX Should these be separated out into different modules?
1581
1582
1583ftpcache = {}
1584class URLopener:
1585 """Class to open URLs.
1586 This is a class rather than just a subroutine because we may need
1587 more than one set of global protocol-specific options.
1588 Note -- this is a base class for those who don't want the
1589 automatic handling of errors type 302 (relocated) and 401
1590 (authorization needed)."""
1591
1592 __tempfiles = None
1593
1594 version = "Python-urllib/%s" % __version__
1595
1596 # Constructor
1597 def __init__(self, proxies=None, **x509):
Georg Brandlfcbdbf22012-06-24 19:56:31 +02001598 msg = "%(class)s style of invoking requests is deprecated. " \
Senthil Kumaran38b968b92012-03-14 13:43:53 -07001599 "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
1600 warnings.warn(msg, DeprecationWarning, stacklevel=3)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001601 if proxies is None:
1602 proxies = getproxies()
1603 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1604 self.proxies = proxies
1605 self.key_file = x509.get('key_file')
1606 self.cert_file = x509.get('cert_file')
1607 self.addheaders = [('User-Agent', self.version)]
1608 self.__tempfiles = []
1609 self.__unlink = os.unlink # See cleanup()
1610 self.tempcache = None
1611 # Undocumented feature: if you assign {} to tempcache,
1612 # it is used to cache files retrieved with
1613 # self.retrieve(). This is not enabled by default
1614 # since it does not work for changing documents (and I
1615 # haven't got the logic to check expiration headers
1616 # yet).
1617 self.ftpcache = ftpcache
1618 # Undocumented feature: you can use a different
1619 # ftp cache by assigning to the .ftpcache member;
1620 # in case you want logically independent URL openers
1621 # XXX This is not threadsafe. Bah.
1622
1623 def __del__(self):
1624 self.close()
1625
1626 def close(self):
1627 self.cleanup()
1628
1629 def cleanup(self):
1630 # This code sometimes runs when the rest of this module
1631 # has already been deleted, so it can't use any globals
1632 # or import anything.
1633 if self.__tempfiles:
1634 for file in self.__tempfiles:
1635 try:
1636 self.__unlink(file)
1637 except OSError:
1638 pass
1639 del self.__tempfiles[:]
1640 if self.tempcache:
1641 self.tempcache.clear()
1642
1643 def addheader(self, *args):
1644 """Add a header to be used by the HTTP interface only
1645 e.g. u.addheader('Accept', 'sound/basic')"""
1646 self.addheaders.append(args)
1647
1648 # External interface
1649 def open(self, fullurl, data=None):
1650 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001651 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran734f0592010-02-20 22:19:04 +00001652 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001653 if self.tempcache and fullurl in self.tempcache:
1654 filename, headers = self.tempcache[fullurl]
1655 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001656 return addinfourl(fp, headers, fullurl)
1657 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001658 if not urltype:
1659 urltype = 'file'
1660 if urltype in self.proxies:
1661 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001662 urltype, proxyhost = splittype(proxy)
1663 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001664 url = (host, fullurl) # Signal special case to open_*()
1665 else:
1666 proxy = None
1667 name = 'open_' + urltype
1668 self.type = urltype
1669 name = name.replace('-', '_')
1670 if not hasattr(self, name):
1671 if proxy:
1672 return self.open_unknown_proxy(proxy, fullurl, data)
1673 else:
1674 return self.open_unknown(fullurl, data)
1675 try:
1676 if data is None:
1677 return getattr(self, name)(url)
1678 else:
1679 return getattr(self, name)(url, data)
Senthil Kumaranf5776862012-10-21 13:30:02 -07001680 except (HTTPError, URLError):
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001681 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +02001682 except OSError as msg:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001683 raise OSError('socket error', msg).with_traceback(sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001684
1685 def open_unknown(self, fullurl, data=None):
1686 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001687 type, url = splittype(fullurl)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001688 raise OSError('url error', 'unknown url type', type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001689
1690 def open_unknown_proxy(self, proxy, fullurl, data=None):
1691 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001692 type, url = splittype(fullurl)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001693 raise OSError('url error', 'invalid proxy for %s' % type, proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001694
1695 # External interface
1696 def retrieve(self, url, filename=None, reporthook=None, data=None):
1697 """retrieve(url) returns (filename, headers) for a local object
1698 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001699 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001700 if self.tempcache and url in self.tempcache:
1701 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001702 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001703 if filename is None and (not type or type == 'file'):
1704 try:
1705 fp = self.open_local_file(url1)
1706 hdrs = fp.info()
Philip Jenveycb134d72009-12-03 02:45:01 +00001707 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001708 return url2pathname(splithost(url1)[1]), hdrs
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001709 except OSError as msg:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001710 pass
1711 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001712 try:
1713 headers = fp.info()
1714 if filename:
1715 tfp = open(filename, 'wb')
1716 else:
1717 import tempfile
1718 garbage, path = splittype(url)
1719 garbage, path = splithost(path or "")
1720 path, garbage = splitquery(path or "")
1721 path, garbage = splitattr(path or "")
1722 suffix = os.path.splitext(path)[1]
1723 (fd, filename) = tempfile.mkstemp(suffix)
1724 self.__tempfiles.append(filename)
1725 tfp = os.fdopen(fd, 'wb')
1726 try:
1727 result = filename, headers
1728 if self.tempcache is not None:
1729 self.tempcache[url] = result
1730 bs = 1024*8
1731 size = -1
1732 read = 0
1733 blocknum = 0
Senthil Kumarance260142011-11-01 01:35:17 +08001734 if "content-length" in headers:
1735 size = int(headers["Content-Length"])
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001736 if reporthook:
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001737 reporthook(blocknum, bs, size)
1738 while 1:
1739 block = fp.read(bs)
1740 if not block:
1741 break
1742 read += len(block)
1743 tfp.write(block)
1744 blocknum += 1
1745 if reporthook:
1746 reporthook(blocknum, bs, size)
1747 finally:
1748 tfp.close()
1749 finally:
1750 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001751
1752 # raise exception if actual size does not match content-length header
1753 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001754 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001755 "retrieval incomplete: got only %i out of %i bytes"
1756 % (read, size), result)
1757
1758 return result
1759
1760 # Each method named open_<type> knows how to open that type of URL
1761
1762 def _open_generic_http(self, connection_factory, url, data):
1763 """Make an HTTP connection using connection_class.
1764
1765 This is an internal method that should be called from
1766 open_http() or open_https().
1767
1768 Arguments:
1769 - connection_factory should take a host name and return an
1770 HTTPConnection instance.
1771 - url is the url to retrieval or a host, relative-path pair.
1772 - data is payload for a POST request or None.
1773 """
1774
1775 user_passwd = None
1776 proxy_passwd= None
1777 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001778 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001779 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001780 user_passwd, host = splituser(host)
1781 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001782 realhost = host
1783 else:
1784 host, selector = url
1785 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001786 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001787 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001788 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001789 url = rest
1790 user_passwd = None
1791 if urltype.lower() != 'http':
1792 realhost = None
1793 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001794 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001795 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001796 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001797 if user_passwd:
1798 selector = "%s://%s%s" % (urltype, realhost, rest)
1799 if proxy_bypass(realhost):
1800 host = realhost
1801
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001802 if not host: raise OSError('http error', 'no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001803
1804 if proxy_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001805 proxy_passwd = unquote(proxy_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001806 proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001807 else:
1808 proxy_auth = None
1809
1810 if user_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001811 user_passwd = unquote(user_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001812 auth = base64.b64encode(user_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001813 else:
1814 auth = None
1815 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001816 headers = {}
1817 if proxy_auth:
1818 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1819 if auth:
1820 headers["Authorization"] = "Basic %s" % auth
1821 if realhost:
1822 headers["Host"] = realhost
Senthil Kumarand91ffca2011-03-19 17:25:27 +08001823
1824 # Add Connection:close as we don't support persistent connections yet.
1825 # This helps in closing the socket and avoiding ResourceWarning
1826
1827 headers["Connection"] = "close"
1828
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001829 for header, value in self.addheaders:
1830 headers[header] = value
1831
1832 if data is not None:
1833 headers["Content-Type"] = "application/x-www-form-urlencoded"
1834 http_conn.request("POST", selector, data, headers)
1835 else:
1836 http_conn.request("GET", selector, headers=headers)
1837
1838 try:
1839 response = http_conn.getresponse()
1840 except http.client.BadStatusLine:
1841 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001842 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001843
1844 # According to RFC 2616, "2xx" code indicates that the client's
1845 # request was successfully received, understood, and accepted.
1846 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001847 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001848 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001849 else:
1850 return self.http_error(
1851 url, response.fp,
1852 response.status, response.reason, response.msg, data)
1853
1854 def open_http(self, url, data=None):
1855 """Use HTTP protocol."""
1856 return self._open_generic_http(http.client.HTTPConnection, url, data)
1857
1858 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1859 """Handle http errors.
1860
1861 Derived class can override this, or provide specific handlers
1862 named http_error_DDD where DDD is the 3-digit error code."""
1863 # First check if there's a specific handler for this error
1864 name = 'http_error_%d' % errcode
1865 if hasattr(self, name):
1866 method = getattr(self, name)
1867 if data is None:
1868 result = method(url, fp, errcode, errmsg, headers)
1869 else:
1870 result = method(url, fp, errcode, errmsg, headers, data)
1871 if result: return result
1872 return self.http_error_default(url, fp, errcode, errmsg, headers)
1873
1874 def http_error_default(self, url, fp, errcode, errmsg, headers):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001875 """Default error handler: close the connection and raise OSError."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001876 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001877 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001878
1879 if _have_ssl:
1880 def _https_connection(self, host):
1881 return http.client.HTTPSConnection(host,
1882 key_file=self.key_file,
1883 cert_file=self.cert_file)
1884
1885 def open_https(self, url, data=None):
1886 """Use HTTPS protocol."""
1887 return self._open_generic_http(self._https_connection, url, data)
1888
1889 def open_file(self, url):
1890 """Use local file or FTP depending on form of URL."""
1891 if not isinstance(url, str):
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001892 raise URLError('file error: proxy support for file protocol currently not implemented')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001893 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001894 raise ValueError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001895 else:
1896 return self.open_local_file(url)
1897
1898 def open_local_file(self, url):
1899 """Use local file."""
Senthil Kumaran6c5bd402011-11-01 23:20:31 +08001900 import email.utils
1901 import mimetypes
Georg Brandl13e89462008-07-01 19:56:00 +00001902 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001903 localname = url2pathname(file)
1904 try:
1905 stats = os.stat(localname)
1906 except OSError as e:
Senthil Kumaranf5776862012-10-21 13:30:02 -07001907 raise URLError(e.strerror, e.filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001908 size = stats.st_size
1909 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1910 mtype = mimetypes.guess_type(url)[0]
1911 headers = email.message_from_string(
1912 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1913 (mtype or 'text/plain', size, modified))
1914 if not host:
1915 urlfile = file
1916 if file[:1] == '/':
1917 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001918 return addinfourl(open(localname, 'rb'), headers, urlfile)
1919 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001920 if (not port
Senthil Kumaran40d80782012-10-22 09:43:04 -07001921 and socket.gethostbyname(host) in ((localhost(),) + thishost())):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001922 urlfile = file
1923 if file[:1] == '/':
1924 urlfile = 'file://' + file
Senthil Kumaran3800ea92012-01-21 11:52:48 +08001925 elif file[:2] == './':
1926 raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
Georg Brandl13e89462008-07-01 19:56:00 +00001927 return addinfourl(open(localname, 'rb'), headers, urlfile)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001928 raise URLError('local file error: not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001929
1930 def open_ftp(self, url):
1931 """Use FTP protocol."""
1932 if not isinstance(url, str):
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001933 raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001934 import mimetypes
Georg Brandl13e89462008-07-01 19:56:00 +00001935 host, path = splithost(url)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001936 if not host: raise URLError('ftp error: no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001937 host, port = splitport(host)
1938 user, host = splituser(host)
1939 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001940 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001941 host = unquote(host)
1942 user = unquote(user or '')
1943 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001944 host = socket.gethostbyname(host)
1945 if not port:
1946 import ftplib
1947 port = ftplib.FTP_PORT
1948 else:
1949 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001950 path, attrs = splitattr(path)
1951 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001952 dirs = path.split('/')
1953 dirs, file = dirs[:-1], dirs[-1]
1954 if dirs and not dirs[0]: dirs = dirs[1:]
1955 if dirs and not dirs[0]: dirs[0] = '/'
1956 key = user, host, port, '/'.join(dirs)
1957 # XXX thread unsafe!
1958 if len(self.ftpcache) > MAXFTPCACHE:
1959 # Prune the cache, rather arbitrarily
1960 for k in self.ftpcache.keys():
1961 if k != key:
1962 v = self.ftpcache[k]
1963 del self.ftpcache[k]
1964 v.close()
1965 try:
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08001966 if key not in self.ftpcache:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001967 self.ftpcache[key] = \
1968 ftpwrapper(user, passwd, host, port, dirs)
1969 if not file: type = 'D'
1970 else: type = 'I'
1971 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001972 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001973 if attr.lower() == 'type' and \
1974 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1975 type = value.upper()
1976 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1977 mtype = mimetypes.guess_type("ftp:" + url)[0]
1978 headers = ""
1979 if mtype:
1980 headers += "Content-Type: %s\n" % mtype
1981 if retrlen is not None and retrlen >= 0:
1982 headers += "Content-Length: %d\n" % retrlen
1983 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001984 return addinfourl(fp, headers, "ftp:" + url)
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001985 except ftperrors() as exp:
1986 raise URLError('ftp error %r' % exp).with_traceback(sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001987
1988 def open_data(self, url, data=None):
1989 """Use "data" URL."""
1990 if not isinstance(url, str):
Senthil Kumaran3ebef362012-10-21 18:31:25 -07001991 raise URLError('data error: proxy support for data protocol currently not implemented')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001992 # ignore POSTed data
1993 #
1994 # syntax of data URLs:
1995 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1996 # mediatype := [ type "/" subtype ] *( ";" parameter )
1997 # data := *urlchar
1998 # parameter := attribute "=" value
1999 try:
2000 [type, data] = url.split(',', 1)
2001 except ValueError:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002002 raise OSError('data error', 'bad data URL')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002003 if not type:
2004 type = 'text/plain;charset=US-ASCII'
2005 semi = type.rfind(';')
2006 if semi >= 0 and '=' not in type[semi:]:
2007 encoding = type[semi+1:]
2008 type = type[:semi]
2009 else:
2010 encoding = ''
2011 msg = []
Senthil Kumaranf6c456d2010-05-01 08:29:18 +00002012 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002013 time.gmtime(time.time())))
2014 msg.append('Content-type: %s' % type)
2015 if encoding == 'base64':
Georg Brandl706824f2009-06-04 09:42:55 +00002016 # XXX is this encoding/decoding ok?
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002017 data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002018 else:
Georg Brandl13e89462008-07-01 19:56:00 +00002019 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002020 msg.append('Content-Length: %d' % len(data))
2021 msg.append('')
2022 msg.append(data)
2023 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00002024 headers = email.message_from_string(msg)
2025 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002026 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00002027 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002028
2029
2030class FancyURLopener(URLopener):
2031 """Derived class with handlers for errors we can handle (perhaps)."""
2032
2033 def __init__(self, *args, **kwargs):
2034 URLopener.__init__(self, *args, **kwargs)
2035 self.auth_cache = {}
2036 self.tries = 0
2037 self.maxtries = 10
2038
2039 def http_error_default(self, url, fp, errcode, errmsg, headers):
2040 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00002041 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002042
2043 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
2044 """Error 302 -- relocated (temporarily)."""
2045 self.tries += 1
2046 if self.maxtries and self.tries >= self.maxtries:
2047 if hasattr(self, "http_error_500"):
2048 meth = self.http_error_500
2049 else:
2050 meth = self.http_error_default
2051 self.tries = 0
2052 return meth(url, fp, 500,
2053 "Internal Server Error: Redirect Recursion", headers)
2054 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
2055 data)
2056 self.tries = 0
2057 return result
2058
2059 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
2060 if 'location' in headers:
2061 newurl = headers['location']
2062 elif 'uri' in headers:
2063 newurl = headers['uri']
2064 else:
2065 return
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002066 fp.close()
guido@google.coma119df92011-03-29 11:41:02 -07002067
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002068 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00002069 newurl = urljoin(self.type + ":" + url, newurl)
guido@google.coma119df92011-03-29 11:41:02 -07002070
2071 urlparts = urlparse(newurl)
2072
2073 # For security reasons, we don't allow redirection to anything other
2074 # than http, https and ftp.
2075
2076 # We are using newer HTTPError with older redirect_internal method
2077 # This older method will get deprecated in 3.3
2078
Senthil Kumaran6497aa32012-01-04 13:46:59 +08002079 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
guido@google.coma119df92011-03-29 11:41:02 -07002080 raise HTTPError(newurl, errcode,
2081 errmsg +
2082 " Redirection to url '%s' is not allowed." % newurl,
2083 headers, fp)
2084
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002085 return self.open(newurl)
2086
2087 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
2088 """Error 301 -- also relocated (permanently)."""
2089 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2090
2091 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
2092 """Error 303 -- also relocated (essentially identical to 302)."""
2093 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2094
2095 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
2096 """Error 307 -- relocated, but turn POST into error."""
2097 if data is None:
2098 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2099 else:
2100 return self.http_error_default(url, fp, errcode, errmsg, headers)
2101
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002102 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
2103 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002104 """Error 401 -- authentication required.
2105 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08002106 if 'www-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002107 URLopener.http_error_default(self, url, fp,
2108 errcode, errmsg, headers)
2109 stuff = headers['www-authenticate']
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002110 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2111 if not match:
2112 URLopener.http_error_default(self, url, fp,
2113 errcode, errmsg, headers)
2114 scheme, realm = match.groups()
2115 if scheme.lower() != 'basic':
2116 URLopener.http_error_default(self, url, fp,
2117 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002118 if not retry:
2119 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2120 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002121 name = 'retry_' + self.type + '_basic_auth'
2122 if data is None:
2123 return getattr(self,name)(url, realm)
2124 else:
2125 return getattr(self,name)(url, realm, data)
2126
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002127 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
2128 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002129 """Error 407 -- proxy authentication required.
2130 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08002131 if 'proxy-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002132 URLopener.http_error_default(self, url, fp,
2133 errcode, errmsg, headers)
2134 stuff = headers['proxy-authenticate']
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002135 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2136 if not match:
2137 URLopener.http_error_default(self, url, fp,
2138 errcode, errmsg, headers)
2139 scheme, realm = match.groups()
2140 if scheme.lower() != 'basic':
2141 URLopener.http_error_default(self, url, fp,
2142 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002143 if not retry:
2144 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2145 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002146 name = 'retry_proxy_' + self.type + '_basic_auth'
2147 if data is None:
2148 return getattr(self,name)(url, realm)
2149 else:
2150 return getattr(self,name)(url, realm, data)
2151
2152 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002153 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002154 newurl = 'http://' + host + selector
2155 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00002156 urltype, proxyhost = splittype(proxy)
2157 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002158 i = proxyhost.find('@') + 1
2159 proxyhost = proxyhost[i:]
2160 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2161 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002162 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002163 quote(passwd, safe=''), proxyhost)
2164 self.proxies['http'] = 'http://' + proxyhost + proxyselector
2165 if data is None:
2166 return self.open(newurl)
2167 else:
2168 return self.open(newurl, data)
2169
2170 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002171 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002172 newurl = 'https://' + host + selector
2173 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00002174 urltype, proxyhost = splittype(proxy)
2175 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002176 i = proxyhost.find('@') + 1
2177 proxyhost = proxyhost[i:]
2178 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2179 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002180 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002181 quote(passwd, safe=''), proxyhost)
2182 self.proxies['https'] = 'https://' + proxyhost + proxyselector
2183 if data is None:
2184 return self.open(newurl)
2185 else:
2186 return self.open(newurl, data)
2187
2188 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002189 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002190 i = host.find('@') + 1
2191 host = host[i:]
2192 user, passwd = self.get_user_passwd(host, realm, i)
2193 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002194 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002195 quote(passwd, safe=''), host)
2196 newurl = 'http://' + host + selector
2197 if data is None:
2198 return self.open(newurl)
2199 else:
2200 return self.open(newurl, data)
2201
2202 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002203 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002204 i = host.find('@') + 1
2205 host = host[i:]
2206 user, passwd = self.get_user_passwd(host, realm, i)
2207 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002208 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002209 quote(passwd, safe=''), host)
2210 newurl = 'https://' + host + selector
2211 if data is None:
2212 return self.open(newurl)
2213 else:
2214 return self.open(newurl, data)
2215
Florent Xicluna757445b2010-05-17 17:24:07 +00002216 def get_user_passwd(self, host, realm, clear_cache=0):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002217 key = realm + '@' + host.lower()
2218 if key in self.auth_cache:
2219 if clear_cache:
2220 del self.auth_cache[key]
2221 else:
2222 return self.auth_cache[key]
2223 user, passwd = self.prompt_user_passwd(host, realm)
2224 if user or passwd: self.auth_cache[key] = (user, passwd)
2225 return user, passwd
2226
2227 def prompt_user_passwd(self, host, realm):
2228 """Override this in a GUI environment!"""
2229 import getpass
2230 try:
2231 user = input("Enter username for %s at %s: " % (realm, host))
2232 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
2233 (user, realm, host))
2234 return user, passwd
2235 except KeyboardInterrupt:
2236 print()
2237 return None, None
2238
2239
2240# Utility functions
2241
2242_localhost = None
2243def localhost():
2244 """Return the IP address of the magic hostname 'localhost'."""
2245 global _localhost
2246 if _localhost is None:
2247 _localhost = socket.gethostbyname('localhost')
2248 return _localhost
2249
2250_thishost = None
2251def thishost():
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00002252 """Return the IP addresses of the current host."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002253 global _thishost
2254 if _thishost is None:
Senthil Kumarandcdadfe2013-06-01 11:12:17 -07002255 try:
2256 _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
2257 except socket.gaierror:
2258 _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002259 return _thishost
2260
2261_ftperrors = None
2262def ftperrors():
2263 """Return the set of errors raised by the FTP class."""
2264 global _ftperrors
2265 if _ftperrors is None:
2266 import ftplib
2267 _ftperrors = ftplib.all_errors
2268 return _ftperrors
2269
2270_noheaders = None
2271def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002272 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002273 global _noheaders
2274 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002275 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002276 return _noheaders
2277
2278
2279# Utility classes
2280
2281class ftpwrapper:
2282 """Class used by open_ftp() for cache of open FTP connections."""
2283
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002284 def __init__(self, user, passwd, host, port, dirs, timeout=None,
2285 persistent=True):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002286 self.user = user
2287 self.passwd = passwd
2288 self.host = host
2289 self.port = port
2290 self.dirs = dirs
2291 self.timeout = timeout
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002292 self.refcount = 0
2293 self.keepalive = persistent
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002294 self.init()
2295
2296 def init(self):
2297 import ftplib
2298 self.busy = 0
2299 self.ftp = ftplib.FTP()
2300 self.ftp.connect(self.host, self.port, self.timeout)
2301 self.ftp.login(self.user, self.passwd)
Senthil Kumarancaa00fe2013-06-02 11:59:47 -07002302 _target = '/'.join(self.dirs)
2303 self.ftp.cwd(_target)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002304
2305 def retrfile(self, file, type):
2306 import ftplib
2307 self.endtransfer()
2308 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2309 else: cmd = 'TYPE ' + type; isdir = 0
2310 try:
2311 self.ftp.voidcmd(cmd)
2312 except ftplib.all_errors:
2313 self.init()
2314 self.ftp.voidcmd(cmd)
2315 conn = None
2316 if file and not isdir:
2317 # Try to retrieve as a file
2318 try:
2319 cmd = 'RETR ' + file
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002320 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002321 except ftplib.error_perm as reason:
2322 if str(reason)[:3] != '550':
Benjamin Peterson901a2782013-05-12 19:01:52 -05002323 raise URLError('ftp error: %r' % reason).with_traceback(
Georg Brandl13e89462008-07-01 19:56:00 +00002324 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002325 if not conn:
2326 # Set transfer mode to ASCII!
2327 self.ftp.voidcmd('TYPE A')
2328 # Try a directory listing. Verify that directory exists.
2329 if file:
2330 pwd = self.ftp.pwd()
2331 try:
2332 try:
2333 self.ftp.cwd(file)
2334 except ftplib.error_perm as reason:
Benjamin Peterson901a2782013-05-12 19:01:52 -05002335 raise URLError('ftp error: %r' % reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002336 finally:
2337 self.ftp.cwd(pwd)
2338 cmd = 'LIST ' + file
2339 else:
2340 cmd = 'LIST'
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002341 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002342 self.busy = 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002343
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002344 ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
2345 self.refcount += 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002346 conn.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002347 # Pass back both a suitably decorated object and a retrieval length
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002348 return (ftpobj, retrlen)
2349
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002350 def endtransfer(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002351 self.busy = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002352
2353 def close(self):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002354 self.keepalive = False
2355 if self.refcount <= 0:
2356 self.real_close()
2357
2358 def file_close(self):
2359 self.endtransfer()
2360 self.refcount -= 1
2361 if self.refcount <= 0 and not self.keepalive:
2362 self.real_close()
2363
2364 def real_close(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002365 self.endtransfer()
2366 try:
2367 self.ftp.close()
2368 except ftperrors():
2369 pass
2370
2371# Proxy handling
2372def getproxies_environment():
2373 """Return a dictionary of scheme -> proxy server URL mappings.
2374
2375 Scan the environment for variables named <scheme>_proxy;
2376 this seems to be the standard convention. If you need a
2377 different way, you can pass a proxies dictionary to the
2378 [Fancy]URLopener constructor.
2379
2380 """
2381 proxies = {}
2382 for name, value in os.environ.items():
2383 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002384 if value and name[-6:] == '_proxy':
2385 proxies[name[:-6]] = value
2386 return proxies
2387
2388def proxy_bypass_environment(host):
2389 """Test if proxies should not be used for a particular host.
2390
2391 Checks the environment for a variable named no_proxy, which should
2392 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2393 """
2394 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2395 # '*' is special case for always bypass
2396 if no_proxy == '*':
2397 return 1
2398 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002399 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002400 # check if the host ends with any of the DNS suffixes
Senthil Kumaran89976f12011-08-06 12:27:40 +08002401 no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
2402 for name in no_proxy_list:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002403 if name and (hostonly.endswith(name) or host.endswith(name)):
2404 return 1
2405 # otherwise, don't bypass
2406 return 0
2407
2408
Ronald Oussorene72e1612011-03-14 18:15:25 -04002409# This code tests an OSX specific data structure but is testable on all
2410# platforms
2411def _proxy_bypass_macosx_sysconf(host, proxy_settings):
2412 """
2413 Return True iff this host shouldn't be accessed using a proxy
2414
2415 This function uses the MacOSX framework SystemConfiguration
2416 to fetch the proxy information.
2417
2418 proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
2419 { 'exclude_simple': bool,
2420 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
2421 }
2422 """
Ronald Oussorene72e1612011-03-14 18:15:25 -04002423 from fnmatch import fnmatch
2424
2425 hostonly, port = splitport(host)
2426
2427 def ip2num(ipAddr):
2428 parts = ipAddr.split('.')
2429 parts = list(map(int, parts))
2430 if len(parts) != 4:
2431 parts = (parts + [0, 0, 0, 0])[:4]
2432 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2433
2434 # Check for simple host names:
2435 if '.' not in host:
2436 if proxy_settings['exclude_simple']:
2437 return True
2438
2439 hostIP = None
2440
2441 for value in proxy_settings.get('exceptions', ()):
2442 # Items in the list are strings like these: *.local, 169.254/16
2443 if not value: continue
2444
2445 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2446 if m is not None:
2447 if hostIP is None:
2448 try:
2449 hostIP = socket.gethostbyname(hostonly)
2450 hostIP = ip2num(hostIP)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002451 except OSError:
Ronald Oussorene72e1612011-03-14 18:15:25 -04002452 continue
2453
2454 base = ip2num(m.group(1))
2455 mask = m.group(2)
2456 if mask is None:
2457 mask = 8 * (m.group(1).count('.') + 1)
2458 else:
2459 mask = int(mask[1:])
2460 mask = 32 - mask
2461
2462 if (hostIP >> mask) == (base >> mask):
2463 return True
2464
2465 elif fnmatch(host, value):
2466 return True
2467
2468 return False
2469
2470
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002471if sys.platform == 'darwin':
Ronald Oussoren84151202010-04-18 20:46:11 +00002472 from _scproxy import _get_proxy_settings, _get_proxies
2473
2474 def proxy_bypass_macosx_sysconf(host):
Ronald Oussoren84151202010-04-18 20:46:11 +00002475 proxy_settings = _get_proxy_settings()
Ronald Oussorene72e1612011-03-14 18:15:25 -04002476 return _proxy_bypass_macosx_sysconf(host, proxy_settings)
Ronald Oussoren84151202010-04-18 20:46:11 +00002477
2478 def getproxies_macosx_sysconf():
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002479 """Return a dictionary of scheme -> proxy server URL mappings.
2480
Ronald Oussoren84151202010-04-18 20:46:11 +00002481 This function uses the MacOSX framework SystemConfiguration
2482 to fetch the proxy information.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002483 """
Ronald Oussoren84151202010-04-18 20:46:11 +00002484 return _get_proxies()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002485
Ronald Oussoren84151202010-04-18 20:46:11 +00002486
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002487
2488 def proxy_bypass(host):
2489 if getproxies_environment():
2490 return proxy_bypass_environment(host)
2491 else:
Ronald Oussoren84151202010-04-18 20:46:11 +00002492 return proxy_bypass_macosx_sysconf(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002493
2494 def getproxies():
Ronald Oussoren84151202010-04-18 20:46:11 +00002495 return getproxies_environment() or getproxies_macosx_sysconf()
2496
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002497
2498elif os.name == 'nt':
2499 def getproxies_registry():
2500 """Return a dictionary of scheme -> proxy server URL mappings.
2501
2502 Win32 uses the registry to store proxies.
2503
2504 """
2505 proxies = {}
2506 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002507 import winreg
Brett Cannoncd171c82013-07-04 17:43:24 -04002508 except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002509 # Std module, so should be around - but you never know!
2510 return proxies
2511 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002512 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002513 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002514 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002515 'ProxyEnable')[0]
2516 if proxyEnable:
2517 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002518 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002519 'ProxyServer')[0])
2520 if '=' in proxyServer:
2521 # Per-protocol settings
2522 for p in proxyServer.split(';'):
2523 protocol, address = p.split('=', 1)
2524 # See if address has a type:// prefix
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002525 if not re.match('^([^/:]+)://', address):
2526 address = '%s://%s' % (protocol, address)
2527 proxies[protocol] = address
2528 else:
2529 # Use one setting for all protocols
2530 if proxyServer[:5] == 'http:':
2531 proxies['http'] = proxyServer
2532 else:
2533 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran04f31b82010-07-14 20:10:52 +00002534 proxies['https'] = 'https://%s' % proxyServer
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002535 proxies['ftp'] = 'ftp://%s' % proxyServer
2536 internetSettings.Close()
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02002537 except (OSError, ValueError, TypeError):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002538 # Either registry key not found etc, or the value in an
2539 # unexpected format.
2540 # proxies already set up to be empty so nothing to do
2541 pass
2542 return proxies
2543
2544 def getproxies():
2545 """Return a dictionary of scheme -> proxy server URL mappings.
2546
2547 Returns settings gathered from the environment, if specified,
2548 or the registry.
2549
2550 """
2551 return getproxies_environment() or getproxies_registry()
2552
2553 def proxy_bypass_registry(host):
2554 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002555 import winreg
Brett Cannoncd171c82013-07-04 17:43:24 -04002556 except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002557 # Std modules, so should be around - but you never know!
2558 return 0
2559 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002560 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002561 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002562 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002563 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002564 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002565 'ProxyOverride')[0])
2566 # ^^^^ Returned as Unicode but problems if not converted to ASCII
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02002567 except OSError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002568 return 0
2569 if not proxyEnable or not proxyOverride:
2570 return 0
2571 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002572 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002573 host = [rawHost]
2574 try:
2575 addr = socket.gethostbyname(rawHost)
2576 if addr != rawHost:
2577 host.append(addr)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002578 except OSError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002579 pass
2580 try:
2581 fqdn = socket.getfqdn(rawHost)
2582 if fqdn != rawHost:
2583 host.append(fqdn)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002584 except OSError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002585 pass
2586 # make a check value list from the registry entry: replace the
2587 # '<local>' string by the localhost entry and the corresponding
2588 # canonical entry.
2589 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002590 # now check if we match one of the registry values.
2591 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002592 if test == '<local>':
2593 if '.' not in rawHost:
2594 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002595 test = test.replace(".", r"\.") # mask dots
2596 test = test.replace("*", r".*") # change glob sequence
2597 test = test.replace("?", r".") # change glob char
2598 for val in host:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002599 if re.match(test, val, re.I):
2600 return 1
2601 return 0
2602
2603 def proxy_bypass(host):
2604 """Return a dictionary of scheme -> proxy server URL mappings.
2605
2606 Returns settings gathered from the environment, if specified,
2607 or the registry.
2608
2609 """
2610 if getproxies_environment():
2611 return proxy_bypass_environment(host)
2612 else:
2613 return proxy_bypass_registry(host)
2614
2615else:
2616 # By default use environment variables
2617 getproxies = getproxies_environment
2618 proxy_bypass = proxy_bypass_environment