blob: 796b700f99b663c7be688a7407b045583812cdc0 [file] [log] [blame]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001"""An extensible library for opening URLs using a variety of protocols
2
3The simplest way to use this module is to call the urlopen function,
4which accepts a string containing a URL or a Request object (described
5below). It opens the URL and returns the results as file-like
6object; the returned object has some extra methods described below.
7
8The OpenerDirector manages a collection of Handler objects that do
9all the actual work. Each Handler implements a particular protocol or
10option. The OpenerDirector is a composite object that invokes the
11Handlers needed to open the requested URL. For example, the
12HTTPHandler performs HTTP GET and POST requests and deals with
13non-error returns. The HTTPRedirectHandler automatically deals with
14HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15deals with digest authentication.
16
17urlopen(url, data=None) -- Basic usage is the same as original
18urllib. pass the url and optionally data to post to an HTTP URL, and
19get a file-like object back. One difference is that you can also pass
20a Request instance instead of URL. Raises a URLError (subclass of
21IOError); for HTTP errors, raises an HTTPError, which can also be
22treated as a valid response.
23
24build_opener -- Function that creates a new OpenerDirector instance.
25Will install the default handlers. Accepts one or more Handlers as
26arguments, either instances or Handler classes that it will
27instantiate. If one of the argument is a subclass of the default
28handler, the argument will be installed instead of the default.
29
30install_opener -- Installs a new opener as the default opener.
31
32objects of interest:
Senthil Kumaran1107c5d2009-11-15 06:20:55 +000033
Senthil Kumaran47fff872009-12-20 07:10:31 +000034OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
35the Handler classes, while dealing with requests and responses.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000036
37Request -- An object that encapsulates the state of a request. The
38state can be as simple as the URL. It can also include extra HTTP
39headers, e.g. a User-Agent.
40
41BaseHandler --
42
43internals:
44BaseHandler and parent
45_call_chain conventions
46
47Example usage:
48
Georg Brandl029986a2008-06-23 11:44:14 +000049import urllib.request
Jeremy Hylton1afc1692008-06-18 20:49:58 +000050
51# set up authentication info
Georg Brandl029986a2008-06-23 11:44:14 +000052authinfo = urllib.request.HTTPBasicAuthHandler()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000053authinfo.add_password(realm='PDQ Application',
54 uri='https://mahler:8092/site-updates.py',
55 user='klem',
56 passwd='geheim$parole')
57
Georg Brandl029986a2008-06-23 11:44:14 +000058proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
Jeremy Hylton1afc1692008-06-18 20:49:58 +000059
60# build a new opener that adds authentication and caching FTP handlers
Georg Brandl029986a2008-06-23 11:44:14 +000061opener = urllib.request.build_opener(proxy_support, authinfo,
62 urllib.request.CacheFTPHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000063
64# install it
Georg Brandl029986a2008-06-23 11:44:14 +000065urllib.request.install_opener(opener)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066
Georg Brandl029986a2008-06-23 11:44:14 +000067f = urllib.request.urlopen('http://www.python.org/')
Jeremy Hylton1afc1692008-06-18 20:49:58 +000068"""
69
70# XXX issues:
71# If an authentication error handler that tries to perform
72# authentication for some reason but fails, how should the error be
73# signalled? The client needs to know the HTTP error code. But if
74# the handler knows that the problem was, e.g., that it didn't know
75# that hash algo that requested in the challenge, it would be good to
76# pass that information along to the client, too.
77# ftp errors aren't handled cleanly
78# check digest against correct (i.e. non-apache) implementation
79
80# Possible extensions:
81# complex proxies XXX not sure what exactly was meant by this
82# abstract factory for opener
83
84import base64
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +000085import bisect
Jeremy Hylton1afc1692008-06-18 20:49:58 +000086import email
87import hashlib
88import http.client
89import io
90import os
91import posixpath
92import random
93import re
94import socket
95import sys
96import time
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000097import collections
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +080098import warnings
Jeremy Hylton1afc1692008-06-18 20:49:58 +000099
Georg Brandl13e89462008-07-01 19:56:00 +0000100from urllib.error import URLError, HTTPError, ContentTooShortError
101from urllib.parse import (
102 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
103 splittype, splithost, splitport, splituser, splitpasswd,
Senthil Kumarand95cc752010-08-08 11:27:53 +0000104 splitattr, splitquery, splitvalue, splittag, to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000105from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000106
107# check for SSL
108try:
109 import ssl
Senthil Kumaranc2958622010-11-22 04:48:26 +0000110except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000111 _have_ssl = False
112else:
113 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000114
115# used in User-Agent header sent
116__version__ = sys.version[:3]
117
118_opener = None
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000119def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
120 *, cafile=None, capath=None):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000121 global _opener
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000122 if cafile or capath:
123 if not _have_ssl:
124 raise ValueError('SSL support not available')
125 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
126 context.options |= ssl.OP_NO_SSLv2
127 if cafile or capath:
128 context.verify_mode = ssl.CERT_REQUIRED
129 context.load_verify_locations(cafile, capath)
130 check_hostname = True
131 else:
132 check_hostname = False
133 https_handler = HTTPSHandler(context=context, check_hostname=check_hostname)
134 opener = build_opener(https_handler)
135 elif _opener is None:
136 _opener = opener = build_opener()
137 else:
138 opener = _opener
139 return opener.open(url, data, timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000140
141def install_opener(opener):
142 global _opener
143 _opener = opener
144
145# TODO(jhylton): Make this work with the same global opener.
146_urlopener = None
147def urlretrieve(url, filename=None, reporthook=None, data=None):
148 global _urlopener
149 if not _urlopener:
150 _urlopener = FancyURLopener()
151 return _urlopener.retrieve(url, filename, reporthook, data)
152
153def urlcleanup():
154 if _urlopener:
155 _urlopener.cleanup()
156 global _opener
157 if _opener:
158 _opener = None
159
160# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000161_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000162def request_host(request):
163 """Return request-host, as defined by RFC 2965.
164
165 Variation from RFC: returned value is lowercased, for convenient
166 comparison.
167
168 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000169 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000170 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000171 if host == "":
172 host = request.get_header("Host", "")
173
174 # remove port, if present
175 host = _cut_port_re.sub("", host, 1)
176 return host.lower()
177
178class Request:
179
180 def __init__(self, url, data=None, headers={},
181 origin_req_host=None, unverifiable=False):
182 # unwrap('<URL:type://host/path>') --> 'type://host/path'
Senthil Kumaranb7451ce2012-07-07 17:11:44 -0700183 self.full_url = unwrap(to_bytes(url))
184 self.full_url = quote(self.full_url, safe="%/:=&?~#+!$,;'@()*[]|")
Senthil Kumaran26430412011-04-13 07:01:19 +0800185 self.full_url, self.fragment = splittag(self.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000186 self.data = data
187 self.headers = {}
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000188 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000189 for key, value in headers.items():
190 self.add_header(key, value)
191 self.unredirected_hdrs = {}
192 if origin_req_host is None:
193 origin_req_host = request_host(self)
194 self.origin_req_host = origin_req_host
195 self.unverifiable = unverifiable
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000196 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000197
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000198 def _parse(self):
199 self.type, rest = splittype(self.full_url)
200 if self.type is None:
201 raise ValueError("unknown url type: %s" % self.full_url)
202 self.host, self.selector = splithost(rest)
203 if self.host:
204 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000205
206 def get_method(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000207 if self.data is not None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000208 return "POST"
209 else:
210 return "GET"
211
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000212 # Begin deprecated methods
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000213
214 def add_data(self, data):
215 self.data = data
216
217 def has_data(self):
218 return self.data is not None
219
220 def get_data(self):
221 return self.data
222
223 def get_full_url(self):
Senthil Kumaran26430412011-04-13 07:01:19 +0800224 if self.fragment:
225 return '%s#%s' % (self.full_url, self.fragment)
226 else:
227 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000228
229 def get_type(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000230 return self.type
231
232 def get_host(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000233 return self.host
234
235 def get_selector(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000236 return self.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000237
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000238 def is_unverifiable(self):
239 return self.unverifiable
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000240
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000241 def get_origin_req_host(self):
242 return self.origin_req_host
243
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000244 # End deprecated methods
245
246 def set_proxy(self, host, type):
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000247 if self.type == 'https' and not self._tunnel_host:
248 self._tunnel_host = self.host
249 else:
250 self.type= type
251 self.selector = self.full_url
252 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000253
254 def has_proxy(self):
255 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000256
257 def add_header(self, key, val):
258 # useful for something like authentication
259 self.headers[key.capitalize()] = val
260
261 def add_unredirected_header(self, key, val):
262 # will not be added to a redirected request
263 self.unredirected_hdrs[key.capitalize()] = val
264
265 def has_header(self, header_name):
266 return (header_name in self.headers or
267 header_name in self.unredirected_hdrs)
268
269 def get_header(self, header_name, default=None):
270 return self.headers.get(
271 header_name,
272 self.unredirected_hdrs.get(header_name, default))
273
274 def header_items(self):
275 hdrs = self.unredirected_hdrs.copy()
276 hdrs.update(self.headers)
277 return list(hdrs.items())
278
279class OpenerDirector:
280 def __init__(self):
281 client_version = "Python-urllib/%s" % __version__
282 self.addheaders = [('User-agent', client_version)]
R. David Murray25b8cca2010-12-23 19:44:49 +0000283 # self.handlers is retained only for backward compatibility
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000284 self.handlers = []
R. David Murray25b8cca2010-12-23 19:44:49 +0000285 # manage the individual handlers
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000286 self.handle_open = {}
287 self.handle_error = {}
288 self.process_response = {}
289 self.process_request = {}
290
291 def add_handler(self, handler):
292 if not hasattr(handler, "add_parent"):
293 raise TypeError("expected BaseHandler instance, got %r" %
294 type(handler))
295
296 added = False
297 for meth in dir(handler):
298 if meth in ["redirect_request", "do_open", "proxy_open"]:
299 # oops, coincidental match
300 continue
301
302 i = meth.find("_")
303 protocol = meth[:i]
304 condition = meth[i+1:]
305
306 if condition.startswith("error"):
307 j = condition.find("_") + i + 1
308 kind = meth[j+1:]
309 try:
310 kind = int(kind)
311 except ValueError:
312 pass
313 lookup = self.handle_error.get(protocol, {})
314 self.handle_error[protocol] = lookup
315 elif condition == "open":
316 kind = protocol
317 lookup = self.handle_open
318 elif condition == "response":
319 kind = protocol
320 lookup = self.process_response
321 elif condition == "request":
322 kind = protocol
323 lookup = self.process_request
324 else:
325 continue
326
327 handlers = lookup.setdefault(kind, [])
328 if handlers:
329 bisect.insort(handlers, handler)
330 else:
331 handlers.append(handler)
332 added = True
333
334 if added:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000335 bisect.insort(self.handlers, handler)
336 handler.add_parent(self)
337
338 def close(self):
339 # Only exists for backwards compatibility.
340 pass
341
342 def _call_chain(self, chain, kind, meth_name, *args):
343 # Handlers raise an exception if no one else should try to handle
344 # the request, or return None if they can't but another handler
345 # could. Otherwise, they return the response.
346 handlers = chain.get(kind, ())
347 for handler in handlers:
348 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000349 result = func(*args)
350 if result is not None:
351 return result
352
353 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
354 # accept a URL or a Request object
355 if isinstance(fullurl, str):
356 req = Request(fullurl, data)
357 else:
358 req = fullurl
359 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000360 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000361
362 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000363 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000364
365 # pre-process request
366 meth_name = protocol+"_request"
367 for processor in self.process_request.get(protocol, []):
368 meth = getattr(processor, meth_name)
369 req = meth(req)
370
371 response = self._open(req, data)
372
373 # post-process response
374 meth_name = protocol+"_response"
375 for processor in self.process_response.get(protocol, []):
376 meth = getattr(processor, meth_name)
377 response = meth(req, response)
378
379 return response
380
381 def _open(self, req, data=None):
382 result = self._call_chain(self.handle_open, 'default',
383 'default_open', req)
384 if result:
385 return result
386
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000387 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000388 result = self._call_chain(self.handle_open, protocol, protocol +
389 '_open', req)
390 if result:
391 return result
392
393 return self._call_chain(self.handle_open, 'unknown',
394 'unknown_open', req)
395
396 def error(self, proto, *args):
397 if proto in ('http', 'https'):
398 # XXX http[s] protocols are special-cased
399 dict = self.handle_error['http'] # https is not different than http
400 proto = args[2] # YUCK!
401 meth_name = 'http_error_%s' % proto
402 http_err = 1
403 orig_args = args
404 else:
405 dict = self.handle_error
406 meth_name = proto + '_error'
407 http_err = 0
408 args = (dict, proto, meth_name) + args
409 result = self._call_chain(*args)
410 if result:
411 return result
412
413 if http_err:
414 args = (dict, 'default', 'http_error_default') + orig_args
415 return self._call_chain(*args)
416
417# XXX probably also want an abstract factory that knows when it makes
418# sense to skip a superclass in favor of a subclass and when it might
419# make sense to include both
420
421def build_opener(*handlers):
422 """Create an opener object from a list of handlers.
423
424 The opener will use several default handlers, including support
Senthil Kumaran1107c5d2009-11-15 06:20:55 +0000425 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000426
427 If any of the handlers passed as arguments are subclasses of the
428 default handlers, the default handlers will not be used.
429 """
430 def isclass(obj):
431 return isinstance(obj, type) or hasattr(obj, "__bases__")
432
433 opener = OpenerDirector()
434 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
435 HTTPDefaultErrorHandler, HTTPRedirectHandler,
436 FTPHandler, FileHandler, HTTPErrorProcessor]
437 if hasattr(http.client, "HTTPSConnection"):
438 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000439 skip = set()
440 for klass in default_classes:
441 for check in handlers:
442 if isclass(check):
443 if issubclass(check, klass):
444 skip.add(klass)
445 elif isinstance(check, klass):
446 skip.add(klass)
447 for klass in skip:
448 default_classes.remove(klass)
449
450 for klass in default_classes:
451 opener.add_handler(klass())
452
453 for h in handlers:
454 if isclass(h):
455 h = h()
456 opener.add_handler(h)
457 return opener
458
459class BaseHandler:
460 handler_order = 500
461
462 def add_parent(self, parent):
463 self.parent = parent
464
465 def close(self):
466 # Only exists for backwards compatibility
467 pass
468
469 def __lt__(self, other):
470 if not hasattr(other, "handler_order"):
471 # Try to preserve the old behavior of having custom classes
472 # inserted after default ones (works only for custom user
473 # classes which are not aware of handler_order).
474 return True
475 return self.handler_order < other.handler_order
476
477
478class HTTPErrorProcessor(BaseHandler):
479 """Process HTTP error responses."""
480 handler_order = 1000 # after all other processing
481
482 def http_response(self, request, response):
483 code, msg, hdrs = response.code, response.msg, response.info()
484
485 # According to RFC 2616, "2xx" code indicates that the client's
486 # request was successfully received, understood, and accepted.
487 if not (200 <= code < 300):
488 response = self.parent.error(
489 'http', request, response, code, msg, hdrs)
490
491 return response
492
493 https_response = http_response
494
495class HTTPDefaultErrorHandler(BaseHandler):
496 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000497 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000498
499class HTTPRedirectHandler(BaseHandler):
500 # maximum number of redirections to any single URL
501 # this is needed because of the state that cookies introduce
502 max_repeats = 4
503 # maximum total number of redirections (regardless of URL) before
504 # assuming we're in a loop
505 max_redirections = 10
506
507 def redirect_request(self, req, fp, code, msg, headers, newurl):
508 """Return a Request or None in response to a redirect.
509
510 This is called by the http_error_30x methods when a
511 redirection response is received. If a redirection should
512 take place, return a new Request to allow http_error_30x to
513 perform the redirect. Otherwise, raise HTTPError if no-one
514 else should try to handle this url. Return None if you can't
515 but another Handler might.
516 """
517 m = req.get_method()
518 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
519 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000520 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000521
522 # Strictly (according to RFC 2616), 301 or 302 in response to
523 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000524 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000525 # essentially all clients do redirect in this case, so we do
526 # the same.
527 # be conciliant with URIs containing a space
528 newurl = newurl.replace(' ', '%20')
529 CONTENT_HEADERS = ("content-length", "content-type")
530 newheaders = dict((k, v) for k, v in req.headers.items()
531 if k.lower() not in CONTENT_HEADERS)
532 return Request(newurl,
533 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000534 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000535 unverifiable=True)
536
537 # Implementation note: To avoid the server sending us into an
538 # infinite loop, the request object needs to track what URLs we
539 # have already seen. Do this by adding a handler-specific
540 # attribute to the Request object.
541 def http_error_302(self, req, fp, code, msg, headers):
542 # Some servers (incorrectly) return multiple Location headers
543 # (so probably same goes for URI). Use first header.
544 if "location" in headers:
545 newurl = headers["location"]
546 elif "uri" in headers:
547 newurl = headers["uri"]
548 else:
549 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000550
551 # fix a possible malformed URL
552 urlparts = urlparse(newurl)
guido@google.coma119df92011-03-29 11:41:02 -0700553
554 # For security reasons we don't allow redirection to anything other
555 # than http, https or ftp.
556
Senthil Kumaran6497aa32012-01-04 13:46:59 +0800557 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800558 raise HTTPError(
559 newurl, code,
560 "%s - Redirection to url '%s' is not allowed" % (msg, newurl),
561 headers, fp)
guido@google.coma119df92011-03-29 11:41:02 -0700562
Facundo Batistaf24802c2008-08-17 03:36:03 +0000563 if not urlparts.path:
564 urlparts = list(urlparts)
565 urlparts[2] = "/"
566 newurl = urlunparse(urlparts)
567
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000568 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000569
570 # XXX Probably want to forget about the state of the current
571 # request, although that might interact poorly with other
572 # handlers that also use handler-specific request attributes
573 new = self.redirect_request(req, fp, code, msg, headers, newurl)
574 if new is None:
575 return
576
577 # loop detection
578 # .redirect_dict has a key url if url was previously visited.
579 if hasattr(req, 'redirect_dict'):
580 visited = new.redirect_dict = req.redirect_dict
581 if (visited.get(newurl, 0) >= self.max_repeats or
582 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000583 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000584 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000585 else:
586 visited = new.redirect_dict = req.redirect_dict = {}
587 visited[newurl] = visited.get(newurl, 0) + 1
588
589 # Don't close the fp until we are sure that we won't use it
590 # with HTTPError.
591 fp.read()
592 fp.close()
593
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000594 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000595
596 http_error_301 = http_error_303 = http_error_307 = http_error_302
597
598 inf_msg = "The HTTP server returned a redirect error that would " \
599 "lead to an infinite loop.\n" \
600 "The last 30x error message was:\n"
601
602
603def _parse_proxy(proxy):
604 """Return (scheme, user, password, host/port) given a URL or an authority.
605
606 If a URL is supplied, it must have an authority (host:port) component.
607 According to RFC 3986, having an authority component means the URL must
608 have two slashes after the scheme:
609
610 >>> _parse_proxy('file:/ftp.example.com/')
611 Traceback (most recent call last):
612 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
613
614 The first three items of the returned tuple may be None.
615
616 Examples of authority parsing:
617
618 >>> _parse_proxy('proxy.example.com')
619 (None, None, None, 'proxy.example.com')
620 >>> _parse_proxy('proxy.example.com:3128')
621 (None, None, None, 'proxy.example.com:3128')
622
623 The authority component may optionally include userinfo (assumed to be
624 username:password):
625
626 >>> _parse_proxy('joe:password@proxy.example.com')
627 (None, 'joe', 'password', 'proxy.example.com')
628 >>> _parse_proxy('joe:password@proxy.example.com:3128')
629 (None, 'joe', 'password', 'proxy.example.com:3128')
630
631 Same examples, but with URLs instead:
632
633 >>> _parse_proxy('http://proxy.example.com/')
634 ('http', None, None, 'proxy.example.com')
635 >>> _parse_proxy('http://proxy.example.com:3128/')
636 ('http', None, None, 'proxy.example.com:3128')
637 >>> _parse_proxy('http://joe:password@proxy.example.com/')
638 ('http', 'joe', 'password', 'proxy.example.com')
639 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
640 ('http', 'joe', 'password', 'proxy.example.com:3128')
641
642 Everything after the authority is ignored:
643
644 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
645 ('ftp', 'joe', 'password', 'proxy.example.com')
646
647 Test for no trailing '/' case:
648
649 >>> _parse_proxy('http://joe:password@proxy.example.com')
650 ('http', 'joe', 'password', 'proxy.example.com')
651
652 """
Georg Brandl13e89462008-07-01 19:56:00 +0000653 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000654 if not r_scheme.startswith("/"):
655 # authority
656 scheme = None
657 authority = proxy
658 else:
659 # URL
660 if not r_scheme.startswith("//"):
661 raise ValueError("proxy URL with no authority: %r" % proxy)
662 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
663 # and 3.3.), path is empty or starts with '/'
664 end = r_scheme.find("/", 2)
665 if end == -1:
666 end = None
667 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000668 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000669 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000670 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000671 else:
672 user = password = None
673 return scheme, user, password, hostport
674
675class ProxyHandler(BaseHandler):
676 # Proxies must be in front
677 handler_order = 100
678
679 def __init__(self, proxies=None):
680 if proxies is None:
681 proxies = getproxies()
682 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
683 self.proxies = proxies
684 for type, url in proxies.items():
685 setattr(self, '%s_open' % type,
686 lambda r, proxy=url, type=type, meth=self.proxy_open: \
687 meth(r, proxy, type))
688
689 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000690 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000691 proxy_type, user, password, hostport = _parse_proxy(proxy)
692 if proxy_type is None:
693 proxy_type = orig_type
Senthil Kumaran7bb04972009-10-11 04:58:55 +0000694
695 if req.host and proxy_bypass(req.host):
696 return None
697
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000698 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000699 user_pass = '%s:%s' % (unquote(user),
700 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000701 creds = base64.b64encode(user_pass.encode()).decode("ascii")
702 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000703 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000704 req.set_proxy(hostport, proxy_type)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000705 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000706 # let other handlers take care of it
707 return None
708 else:
709 # need to start over, because the other handlers don't
710 # grok the proxy's URL type
711 # e.g. if we have a constructor arg proxies like so:
712 # {'http': 'ftp://proxy.example.com'}, we may end up turning
713 # a request for http://acme.example.com/a into one for
714 # ftp://proxy.example.com/a
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000715 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000716
717class HTTPPasswordMgr:
718
719 def __init__(self):
720 self.passwd = {}
721
722 def add_password(self, realm, uri, user, passwd):
723 # uri could be a single URI or a sequence
724 if isinstance(uri, str):
725 uri = [uri]
Senthil Kumaran34d38dc2011-10-20 02:48:01 +0800726 if realm not in self.passwd:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000727 self.passwd[realm] = {}
728 for default_port in True, False:
729 reduced_uri = tuple(
730 [self.reduce_uri(u, default_port) for u in uri])
731 self.passwd[realm][reduced_uri] = (user, passwd)
732
733 def find_user_password(self, realm, authuri):
734 domains = self.passwd.get(realm, {})
735 for default_port in True, False:
736 reduced_authuri = self.reduce_uri(authuri, default_port)
737 for uris, authinfo in domains.items():
738 for uri in uris:
739 if self.is_suburi(uri, reduced_authuri):
740 return authinfo
741 return None, None
742
743 def reduce_uri(self, uri, default_port=True):
744 """Accept authority or URI and extract only the authority and path."""
745 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000746 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000747 if parts[1]:
748 # URI
749 scheme = parts[0]
750 authority = parts[1]
751 path = parts[2] or '/'
752 else:
753 # host or host:port
754 scheme = None
755 authority = uri
756 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000757 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000758 if default_port and port is None and scheme is not None:
759 dport = {"http": 80,
760 "https": 443,
761 }.get(scheme)
762 if dport is not None:
763 authority = "%s:%d" % (host, dport)
764 return authority, path
765
766 def is_suburi(self, base, test):
767 """Check if test is below base in a URI tree
768
769 Both args must be URIs in reduced form.
770 """
771 if base == test:
772 return True
773 if base[0] != test[0]:
774 return False
775 common = posixpath.commonprefix((base[1], test[1]))
776 if len(common) == len(base[1]):
777 return True
778 return False
779
780
781class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
782
783 def find_user_password(self, realm, authuri):
784 user, password = HTTPPasswordMgr.find_user_password(self, realm,
785 authuri)
786 if user is not None:
787 return user, password
788 return HTTPPasswordMgr.find_user_password(self, None, authuri)
789
790
791class AbstractBasicAuthHandler:
792
793 # XXX this allows for multiple auth-schemes, but will stupidly pick
794 # the last one with a realm specified.
795
796 # allow for double- and single-quoted realm values
797 # (single quotes are a violation of the RFC, but appear in the wild)
798 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +0800799 'realm=(["\']?)([^"\']*)\\2', re.I)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000800
801 # XXX could pre-emptively send auth info already accepted (RFC 2617,
802 # end of section 2, and section 1.2 immediately after "credentials"
803 # production).
804
805 def __init__(self, password_mgr=None):
806 if password_mgr is None:
807 password_mgr = HTTPPasswordMgr()
808 self.passwd = password_mgr
809 self.add_password = self.passwd.add_password
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000810 self.retried = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000811
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000812 def reset_retry_count(self):
813 self.retried = 0
814
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000815 def http_error_auth_reqed(self, authreq, host, req, headers):
816 # host may be an authority (without userinfo) or a URL with an
817 # authority
818 # XXX could be multiple headers
819 authreq = headers.get(authreq, None)
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000820
821 if self.retried > 5:
822 # retry sending the username:password 5 times before failing.
823 raise HTTPError(req.get_full_url(), 401, "basic auth failed",
824 headers, None)
825 else:
826 self.retried += 1
827
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000828 if authreq:
829 mo = AbstractBasicAuthHandler.rx.search(authreq)
830 if mo:
831 scheme, quote, realm = mo.groups()
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +0800832 if quote not in ["'", '"']:
833 warnings.warn("Basic Auth Realm was unquoted",
834 UserWarning, 2)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000835 if scheme.lower() == 'basic':
Senthil Kumaran4bb5c272010-08-26 06:16:22 +0000836 response = self.retry_http_basic_auth(host, req, realm)
837 if response and response.code != 401:
838 self.retried = 0
839 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000840
841 def retry_http_basic_auth(self, host, req, realm):
842 user, pw = self.passwd.find_user_password(realm, host)
843 if pw is not None:
844 raw = "%s:%s" % (user, pw)
845 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
846 if req.headers.get(self.auth_header, None) == auth:
847 return None
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +0000848 req.add_unredirected_header(self.auth_header, auth)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000849 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000850 else:
851 return None
852
853
854class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
855
856 auth_header = 'Authorization'
857
858 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000859 url = req.full_url
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000860 response = self.http_error_auth_reqed('www-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000861 url, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000862 self.reset_retry_count()
863 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000864
865
866class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
867
868 auth_header = 'Proxy-authorization'
869
870 def http_error_407(self, req, fp, code, msg, headers):
871 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000872 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000873 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
874 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000875 authority = req.host
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000876 response = self.http_error_auth_reqed('proxy-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000877 authority, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000878 self.reset_retry_count()
879 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000880
881
882def randombytes(n):
883 """Return n random bytes."""
884 return os.urandom(n)
885
886class AbstractDigestAuthHandler:
887 # Digest authentication is specified in RFC 2617.
888
889 # XXX The client does not inspect the Authentication-Info header
890 # in a successful response.
891
892 # XXX It should be possible to test this implementation against
893 # a mock server that just generates a static set of challenges.
894
895 # XXX qop="auth-int" supports is shaky
896
897 def __init__(self, passwd=None):
898 if passwd is None:
899 passwd = HTTPPasswordMgr()
900 self.passwd = passwd
901 self.add_password = self.passwd.add_password
902 self.retried = 0
903 self.nonce_count = 0
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000904 self.last_nonce = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000905
906 def reset_retry_count(self):
907 self.retried = 0
908
909 def http_error_auth_reqed(self, auth_header, host, req, headers):
910 authreq = headers.get(auth_header, None)
911 if self.retried > 5:
912 # Don't fail endlessly - if we failed once, we'll probably
913 # fail a second time. Hm. Unless the Password Manager is
914 # prompting for the information. Crap. This isn't great
915 # but it's better than the current 'repeat until recursion
916 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000917 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000918 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000919 else:
920 self.retried += 1
921 if authreq:
922 scheme = authreq.split()[0]
923 if scheme.lower() == 'digest':
924 return self.retry_http_digest_auth(req, authreq)
925
926 def retry_http_digest_auth(self, req, auth):
927 token, challenge = auth.split(' ', 1)
928 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
929 auth = self.get_authorization(req, chal)
930 if auth:
931 auth_val = 'Digest %s' % auth
932 if req.headers.get(self.auth_header, None) == auth_val:
933 return None
934 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000935 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000936 return resp
937
938 def get_cnonce(self, nonce):
939 # The cnonce-value is an opaque
940 # quoted string value provided by the client and used by both client
941 # and server to avoid chosen plaintext attacks, to provide mutual
942 # authentication, and to provide some message integrity protection.
943 # This isn't a fabulous effort, but it's probably Good Enough.
944 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
945 b = s.encode("ascii") + randombytes(8)
946 dig = hashlib.sha1(b).hexdigest()
947 return dig[:16]
948
949 def get_authorization(self, req, chal):
950 try:
951 realm = chal['realm']
952 nonce = chal['nonce']
953 qop = chal.get('qop')
954 algorithm = chal.get('algorithm', 'MD5')
955 # mod_digest doesn't send an opaque, even though it isn't
956 # supposed to be optional
957 opaque = chal.get('opaque', None)
958 except KeyError:
959 return None
960
961 H, KD = self.get_algorithm_impls(algorithm)
962 if H is None:
963 return None
964
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000965 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000966 if user is None:
967 return None
968
969 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000970 if req.data is not None:
971 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000972 else:
973 entdig = None
974
975 A1 = "%s:%s:%s" % (user, realm, pw)
976 A2 = "%s:%s" % (req.get_method(),
977 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000978 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000979 if qop == 'auth':
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000980 if nonce == self.last_nonce:
981 self.nonce_count += 1
982 else:
983 self.nonce_count = 1
984 self.last_nonce = nonce
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000985 ncvalue = '%08x' % self.nonce_count
986 cnonce = self.get_cnonce(nonce)
987 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
988 respdig = KD(H(A1), noncebit)
989 elif qop is None:
990 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
991 else:
992 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +0000993 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000994
995 # XXX should the partial digests be encoded too?
996
997 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000998 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000999 respdig)
1000 if opaque:
1001 base += ', opaque="%s"' % opaque
1002 if entdig:
1003 base += ', digest="%s"' % entdig
1004 base += ', algorithm="%s"' % algorithm
1005 if qop:
1006 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
1007 return base
1008
1009 def get_algorithm_impls(self, algorithm):
1010 # lambdas assume digest modules are imported at the top level
1011 if algorithm == 'MD5':
1012 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
1013 elif algorithm == 'SHA':
1014 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
1015 # XXX MD5-sess
1016 KD = lambda s, d: H("%s:%s" % (s, d))
1017 return H, KD
1018
1019 def get_entity_digest(self, data, chal):
1020 # XXX not implemented yet
1021 return None
1022
1023
1024class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1025 """An authentication protocol defined by RFC 2069
1026
1027 Digest authentication improves on basic authentication because it
1028 does not transmit passwords in the clear.
1029 """
1030
1031 auth_header = 'Authorization'
1032 handler_order = 490 # before Basic auth
1033
1034 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001035 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001036 retry = self.http_error_auth_reqed('www-authenticate',
1037 host, req, headers)
1038 self.reset_retry_count()
1039 return retry
1040
1041
1042class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1043
1044 auth_header = 'Proxy-Authorization'
1045 handler_order = 490 # before Basic auth
1046
1047 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001048 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001049 retry = self.http_error_auth_reqed('proxy-authenticate',
1050 host, req, headers)
1051 self.reset_retry_count()
1052 return retry
1053
1054class AbstractHTTPHandler(BaseHandler):
1055
1056 def __init__(self, debuglevel=0):
1057 self._debuglevel = debuglevel
1058
1059 def set_http_debuglevel(self, level):
1060 self._debuglevel = level
1061
1062 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001063 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001064 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001065 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001066
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001067 if request.data is not None: # POST
1068 data = request.data
Senthil Kumaran29333122011-02-11 11:25:47 +00001069 if isinstance(data, str):
Georg Brandl496660c2012-06-24 20:01:05 +02001070 msg = "POST data should be bytes or an iterable of bytes. "\
1071 "It cannot be of type str."
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07001072 raise TypeError(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001073 if not request.has_header('Content-type'):
1074 request.add_unredirected_header(
1075 'Content-type',
1076 'application/x-www-form-urlencoded')
1077 if not request.has_header('Content-length'):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001078 try:
1079 mv = memoryview(data)
1080 except TypeError:
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001081 if isinstance(data, collections.Iterable):
Georg Brandl61536042011-02-03 07:46:41 +00001082 raise ValueError("Content-Length should be specified "
1083 "for iterable data of type %r %r" % (type(data),
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001084 data))
1085 else:
1086 request.add_unredirected_header(
Senthil Kumaran1e991f22010-12-24 04:03:59 +00001087 'Content-length', '%d' % (len(mv) * mv.itemsize))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001088
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001089 sel_host = host
1090 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001091 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001092 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001093 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001094 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001095 for name, value in self.parent.addheaders:
1096 name = name.capitalize()
1097 if not request.has_header(name):
1098 request.add_unredirected_header(name, value)
1099
1100 return request
1101
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001102 def do_open(self, http_class, req, **http_conn_args):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001103 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001104
1105 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001106 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001107 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001108 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001109 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001110
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001111 # will parse host:port
1112 h = http_class(host, timeout=req.timeout, **http_conn_args)
Senthil Kumaran42ef4b12010-09-27 01:26:03 +00001113
1114 headers = dict(req.unredirected_hdrs)
1115 headers.update(dict((k, v) for k, v in req.headers.items()
1116 if k not in headers))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001117
1118 # TODO(jhylton): Should this be redesigned to handle
1119 # persistent connections?
1120
1121 # We want to make an HTTP/1.1 request, but the addinfourl
1122 # class isn't prepared to deal with a persistent connection.
1123 # It will try to read all remaining data from the socket,
1124 # which will block while the server waits for the next request.
1125 # So make sure the connection gets closed after the (only)
1126 # request.
1127 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001128 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001129
1130 if req._tunnel_host:
Senthil Kumaran47fff872009-12-20 07:10:31 +00001131 tunnel_headers = {}
1132 proxy_auth_hdr = "Proxy-Authorization"
1133 if proxy_auth_hdr in headers:
1134 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1135 # Proxy-Authorization should not be sent to origin
1136 # server.
1137 del headers[proxy_auth_hdr]
1138 h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001139
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001140 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001141 h.request(req.get_method(), req.selector, req.data, headers)
Senthil Kumaran1299a8f2011-07-27 08:05:58 +08001142 except socket.error as err: # timeout error
Senthil Kumaran45686b42011-07-27 09:31:03 +08001143 h.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001144 raise URLError(err)
Senthil Kumaran45686b42011-07-27 09:31:03 +08001145 else:
1146 r = h.getresponse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001147
Senthil Kumaran26430412011-04-13 07:01:19 +08001148 r.url = req.get_full_url()
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001149 # This line replaces the .msg attribute of the HTTPResponse
1150 # with .headers, because urllib clients expect the response to
1151 # have the reason in .msg. It would be good to mark this
1152 # attribute is deprecated and get then to use info() or
1153 # .headers.
1154 r.msg = r.reason
1155 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001156
1157
1158class HTTPHandler(AbstractHTTPHandler):
1159
1160 def http_open(self, req):
1161 return self.do_open(http.client.HTTPConnection, req)
1162
1163 http_request = AbstractHTTPHandler.do_request_
1164
1165if hasattr(http.client, 'HTTPSConnection'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001166 import ssl
1167
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001168 class HTTPSHandler(AbstractHTTPHandler):
1169
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001170 def __init__(self, debuglevel=0, context=None, check_hostname=None):
1171 AbstractHTTPHandler.__init__(self, debuglevel)
1172 self._context = context
1173 self._check_hostname = check_hostname
1174
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001175 def https_open(self, req):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001176 return self.do_open(http.client.HTTPSConnection, req,
1177 context=self._context, check_hostname=self._check_hostname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001178
1179 https_request = AbstractHTTPHandler.do_request_
1180
1181class HTTPCookieProcessor(BaseHandler):
1182 def __init__(self, cookiejar=None):
1183 import http.cookiejar
1184 if cookiejar is None:
1185 cookiejar = http.cookiejar.CookieJar()
1186 self.cookiejar = cookiejar
1187
1188 def http_request(self, request):
1189 self.cookiejar.add_cookie_header(request)
1190 return request
1191
1192 def http_response(self, request, response):
1193 self.cookiejar.extract_cookies(response, request)
1194 return response
1195
1196 https_request = http_request
1197 https_response = http_response
1198
1199class UnknownHandler(BaseHandler):
1200 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001201 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001202 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001203
1204def parse_keqv_list(l):
1205 """Parse list of key=value strings where keys are not duplicated."""
1206 parsed = {}
1207 for elt in l:
1208 k, v = elt.split('=', 1)
1209 if v[0] == '"' and v[-1] == '"':
1210 v = v[1:-1]
1211 parsed[k] = v
1212 return parsed
1213
1214def parse_http_list(s):
1215 """Parse lists as described by RFC 2068 Section 2.
1216
1217 In particular, parse comma-separated lists where the elements of
1218 the list may include quoted-strings. A quoted-string could
1219 contain a comma. A non-quoted string could have quotes in the
1220 middle. Neither commas nor quotes count if they are escaped.
1221 Only double-quotes count, not single-quotes.
1222 """
1223 res = []
1224 part = ''
1225
1226 escape = quote = False
1227 for cur in s:
1228 if escape:
1229 part += cur
1230 escape = False
1231 continue
1232 if quote:
1233 if cur == '\\':
1234 escape = True
1235 continue
1236 elif cur == '"':
1237 quote = False
1238 part += cur
1239 continue
1240
1241 if cur == ',':
1242 res.append(part)
1243 part = ''
1244 continue
1245
1246 if cur == '"':
1247 quote = True
1248
1249 part += cur
1250
1251 # append last part
1252 if part:
1253 res.append(part)
1254
1255 return [part.strip() for part in res]
1256
1257class FileHandler(BaseHandler):
1258 # Use local file or FTP depending on form of URL
1259 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001260 url = req.selector
Senthil Kumaran2ef16322010-07-11 03:12:43 +00001261 if url[:2] == '//' and url[2:3] != '/' and (req.host and
1262 req.host != 'localhost'):
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001263 if not req.host is self.get_names():
1264 raise URLError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001265 else:
1266 return self.open_local_file(req)
1267
1268 # names for the localhost
1269 names = None
1270 def get_names(self):
1271 if FileHandler.names is None:
1272 try:
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001273 FileHandler.names = tuple(
1274 socket.gethostbyname_ex('localhost')[2] +
1275 socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001276 except socket.gaierror:
1277 FileHandler.names = (socket.gethostbyname('localhost'),)
1278 return FileHandler.names
1279
1280 # not entirely sure what the rules are here
1281 def open_local_file(self, req):
1282 import email.utils
1283 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001284 host = req.host
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001285 filename = req.selector
1286 localfile = url2pathname(filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001287 try:
1288 stats = os.stat(localfile)
1289 size = stats.st_size
1290 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001291 mtype = mimetypes.guess_type(filename)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001292 headers = email.message_from_string(
1293 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1294 (mtype or 'text/plain', size, modified))
1295 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001296 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001297 if not host or \
1298 (not port and _safe_gethostbyname(host) in self.get_names()):
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001299 if host:
1300 origurl = 'file://' + host + filename
1301 else:
1302 origurl = 'file://' + filename
1303 return addinfourl(open(localfile, 'rb'), headers, origurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001304 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001305 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001306 raise URLError(msg)
1307 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001308
1309def _safe_gethostbyname(host):
1310 try:
1311 return socket.gethostbyname(host)
1312 except socket.gaierror:
1313 return None
1314
1315class FTPHandler(BaseHandler):
1316 def ftp_open(self, req):
1317 import ftplib
1318 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001319 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001320 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001321 raise URLError('ftp error: no host given')
1322 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001323 if port is None:
1324 port = ftplib.FTP_PORT
1325 else:
1326 port = int(port)
1327
1328 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001329 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001330 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001331 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001332 else:
1333 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001334 host = unquote(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +00001335 user = user or ''
1336 passwd = passwd or ''
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001337
1338 try:
1339 host = socket.gethostbyname(host)
1340 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001341 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001342 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001343 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001344 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001345 dirs, file = dirs[:-1], dirs[-1]
1346 if dirs and not dirs[0]:
1347 dirs = dirs[1:]
1348 try:
1349 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1350 type = file and 'I' or 'D'
1351 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001352 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001353 if attr.lower() == 'type' and \
1354 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1355 type = value.upper()
1356 fp, retrlen = fw.retrfile(file, type)
1357 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001358 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001359 if mtype:
1360 headers += "Content-type: %s\n" % mtype
1361 if retrlen is not None and retrlen >= 0:
1362 headers += "Content-length: %d\n" % retrlen
1363 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001364 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001365 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001366 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001367 raise exc.with_traceback(sys.exc_info()[2])
1368
1369 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001370 return ftpwrapper(user, passwd, host, port, dirs, timeout,
1371 persistent=False)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001372
1373class CacheFTPHandler(FTPHandler):
1374 # XXX would be nice to have pluggable cache strategies
1375 # XXX this stuff is definitely not thread safe
1376 def __init__(self):
1377 self.cache = {}
1378 self.timeout = {}
1379 self.soonest = 0
1380 self.delay = 60
1381 self.max_conns = 16
1382
1383 def setTimeout(self, t):
1384 self.delay = t
1385
1386 def setMaxConns(self, m):
1387 self.max_conns = m
1388
1389 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1390 key = user, host, port, '/'.join(dirs), timeout
1391 if key in self.cache:
1392 self.timeout[key] = time.time() + self.delay
1393 else:
1394 self.cache[key] = ftpwrapper(user, passwd, host, port,
1395 dirs, timeout)
1396 self.timeout[key] = time.time() + self.delay
1397 self.check_cache()
1398 return self.cache[key]
1399
1400 def check_cache(self):
1401 # first check for old ones
1402 t = time.time()
1403 if self.soonest <= t:
1404 for k, v in list(self.timeout.items()):
1405 if v < t:
1406 self.cache[k].close()
1407 del self.cache[k]
1408 del self.timeout[k]
1409 self.soonest = min(list(self.timeout.values()))
1410
1411 # then check the size
1412 if len(self.cache) == self.max_conns:
1413 for k, v in list(self.timeout.items()):
1414 if v == self.soonest:
1415 del self.cache[k]
1416 del self.timeout[k]
1417 break
1418 self.soonest = min(list(self.timeout.values()))
1419
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001420 def clear_cache(self):
1421 for conn in self.cache.values():
1422 conn.close()
1423 self.cache.clear()
1424 self.timeout.clear()
1425
1426
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001427# Code move from the old urllib module
1428
1429MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1430
1431# Helper for non-unix systems
Ronald Oussoren94f25282010-05-05 19:11:21 +00001432if os.name == 'nt':
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001433 from nturl2path import url2pathname, pathname2url
1434else:
1435 def url2pathname(pathname):
1436 """OS-specific conversion from a relative URL of the 'file' scheme
1437 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001438 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001439
1440 def pathname2url(pathname):
1441 """OS-specific conversion from a file system path to a relative URL
1442 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001443 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001444
1445# This really consists of two pieces:
1446# (1) a class which handles opening of all sorts of URLs
1447# (plus assorted utilities etc.)
1448# (2) a set of functions for parsing URLs
1449# XXX Should these be separated out into different modules?
1450
1451
1452ftpcache = {}
1453class URLopener:
1454 """Class to open URLs.
1455 This is a class rather than just a subroutine because we may need
1456 more than one set of global protocol-specific options.
1457 Note -- this is a base class for those who don't want the
1458 automatic handling of errors type 302 (relocated) and 401
1459 (authorization needed)."""
1460
1461 __tempfiles = None
1462
1463 version = "Python-urllib/%s" % __version__
1464
1465 # Constructor
1466 def __init__(self, proxies=None, **x509):
1467 if proxies is None:
1468 proxies = getproxies()
1469 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1470 self.proxies = proxies
1471 self.key_file = x509.get('key_file')
1472 self.cert_file = x509.get('cert_file')
1473 self.addheaders = [('User-Agent', self.version)]
1474 self.__tempfiles = []
1475 self.__unlink = os.unlink # See cleanup()
1476 self.tempcache = None
1477 # Undocumented feature: if you assign {} to tempcache,
1478 # it is used to cache files retrieved with
1479 # self.retrieve(). This is not enabled by default
1480 # since it does not work for changing documents (and I
1481 # haven't got the logic to check expiration headers
1482 # yet).
1483 self.ftpcache = ftpcache
1484 # Undocumented feature: you can use a different
1485 # ftp cache by assigning to the .ftpcache member;
1486 # in case you want logically independent URL openers
1487 # XXX This is not threadsafe. Bah.
1488
1489 def __del__(self):
1490 self.close()
1491
1492 def close(self):
1493 self.cleanup()
1494
1495 def cleanup(self):
1496 # This code sometimes runs when the rest of this module
1497 # has already been deleted, so it can't use any globals
1498 # or import anything.
1499 if self.__tempfiles:
1500 for file in self.__tempfiles:
1501 try:
1502 self.__unlink(file)
1503 except OSError:
1504 pass
1505 del self.__tempfiles[:]
1506 if self.tempcache:
1507 self.tempcache.clear()
1508
1509 def addheader(self, *args):
1510 """Add a header to be used by the HTTP interface only
1511 e.g. u.addheader('Accept', 'sound/basic')"""
1512 self.addheaders.append(args)
1513
1514 # External interface
1515 def open(self, fullurl, data=None):
1516 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001517 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran734f0592010-02-20 22:19:04 +00001518 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001519 if self.tempcache and fullurl in self.tempcache:
1520 filename, headers = self.tempcache[fullurl]
1521 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001522 return addinfourl(fp, headers, fullurl)
1523 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001524 if not urltype:
1525 urltype = 'file'
1526 if urltype in self.proxies:
1527 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001528 urltype, proxyhost = splittype(proxy)
1529 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001530 url = (host, fullurl) # Signal special case to open_*()
1531 else:
1532 proxy = None
1533 name = 'open_' + urltype
1534 self.type = urltype
1535 name = name.replace('-', '_')
1536 if not hasattr(self, name):
1537 if proxy:
1538 return self.open_unknown_proxy(proxy, fullurl, data)
1539 else:
1540 return self.open_unknown(fullurl, data)
1541 try:
1542 if data is None:
1543 return getattr(self, name)(url)
1544 else:
1545 return getattr(self, name)(url, data)
1546 except socket.error as msg:
1547 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1548
1549 def open_unknown(self, fullurl, data=None):
1550 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001551 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001552 raise IOError('url error', 'unknown url type', type)
1553
1554 def open_unknown_proxy(self, proxy, fullurl, data=None):
1555 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001556 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001557 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1558
1559 # External interface
1560 def retrieve(self, url, filename=None, reporthook=None, data=None):
1561 """retrieve(url) returns (filename, headers) for a local object
1562 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001563 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001564 if self.tempcache and url in self.tempcache:
1565 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001566 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001567 if filename is None and (not type or type == 'file'):
1568 try:
1569 fp = self.open_local_file(url1)
1570 hdrs = fp.info()
Philip Jenveycb134d72009-12-03 02:45:01 +00001571 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001572 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001573 except IOError as msg:
1574 pass
1575 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001576 try:
1577 headers = fp.info()
1578 if filename:
1579 tfp = open(filename, 'wb')
1580 else:
1581 import tempfile
1582 garbage, path = splittype(url)
1583 garbage, path = splithost(path or "")
1584 path, garbage = splitquery(path or "")
1585 path, garbage = splitattr(path or "")
1586 suffix = os.path.splitext(path)[1]
1587 (fd, filename) = tempfile.mkstemp(suffix)
1588 self.__tempfiles.append(filename)
1589 tfp = os.fdopen(fd, 'wb')
1590 try:
1591 result = filename, headers
1592 if self.tempcache is not None:
1593 self.tempcache[url] = result
1594 bs = 1024*8
1595 size = -1
1596 read = 0
1597 blocknum = 0
Senthil Kumarance260142011-11-01 01:35:17 +08001598 if "content-length" in headers:
1599 size = int(headers["Content-Length"])
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001600 if reporthook:
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001601 reporthook(blocknum, bs, size)
1602 while 1:
1603 block = fp.read(bs)
1604 if not block:
1605 break
1606 read += len(block)
1607 tfp.write(block)
1608 blocknum += 1
1609 if reporthook:
1610 reporthook(blocknum, bs, size)
1611 finally:
1612 tfp.close()
1613 finally:
1614 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001615
1616 # raise exception if actual size does not match content-length header
1617 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001618 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001619 "retrieval incomplete: got only %i out of %i bytes"
1620 % (read, size), result)
1621
1622 return result
1623
1624 # Each method named open_<type> knows how to open that type of URL
1625
1626 def _open_generic_http(self, connection_factory, url, data):
1627 """Make an HTTP connection using connection_class.
1628
1629 This is an internal method that should be called from
1630 open_http() or open_https().
1631
1632 Arguments:
1633 - connection_factory should take a host name and return an
1634 HTTPConnection instance.
1635 - url is the url to retrieval or a host, relative-path pair.
1636 - data is payload for a POST request or None.
1637 """
1638
1639 user_passwd = None
1640 proxy_passwd= None
1641 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001642 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001643 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001644 user_passwd, host = splituser(host)
1645 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001646 realhost = host
1647 else:
1648 host, selector = url
1649 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001650 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001651 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001652 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001653 url = rest
1654 user_passwd = None
1655 if urltype.lower() != 'http':
1656 realhost = None
1657 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001658 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001659 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001660 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001661 if user_passwd:
1662 selector = "%s://%s%s" % (urltype, realhost, rest)
1663 if proxy_bypass(realhost):
1664 host = realhost
1665
1666 #print "proxy via http:", host, selector
1667 if not host: raise IOError('http error', 'no host given')
1668
1669 if proxy_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001670 proxy_passwd = unquote(proxy_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001671 proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001672 else:
1673 proxy_auth = None
1674
1675 if user_passwd:
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001676 user_passwd = unquote(user_passwd)
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001677 auth = base64.b64encode(user_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001678 else:
1679 auth = None
1680 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001681 headers = {}
1682 if proxy_auth:
1683 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1684 if auth:
1685 headers["Authorization"] = "Basic %s" % auth
1686 if realhost:
1687 headers["Host"] = realhost
Senthil Kumarand91ffca2011-03-19 17:25:27 +08001688
1689 # Add Connection:close as we don't support persistent connections yet.
1690 # This helps in closing the socket and avoiding ResourceWarning
1691
1692 headers["Connection"] = "close"
1693
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001694 for header, value in self.addheaders:
1695 headers[header] = value
1696
1697 if data is not None:
1698 headers["Content-Type"] = "application/x-www-form-urlencoded"
1699 http_conn.request("POST", selector, data, headers)
1700 else:
1701 http_conn.request("GET", selector, headers=headers)
1702
1703 try:
1704 response = http_conn.getresponse()
1705 except http.client.BadStatusLine:
1706 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001707 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001708
1709 # According to RFC 2616, "2xx" code indicates that the client's
1710 # request was successfully received, understood, and accepted.
1711 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001712 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001713 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001714 else:
1715 return self.http_error(
1716 url, response.fp,
1717 response.status, response.reason, response.msg, data)
1718
1719 def open_http(self, url, data=None):
1720 """Use HTTP protocol."""
1721 return self._open_generic_http(http.client.HTTPConnection, url, data)
1722
1723 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1724 """Handle http errors.
1725
1726 Derived class can override this, or provide specific handlers
1727 named http_error_DDD where DDD is the 3-digit error code."""
1728 # First check if there's a specific handler for this error
1729 name = 'http_error_%d' % errcode
1730 if hasattr(self, name):
1731 method = getattr(self, name)
1732 if data is None:
1733 result = method(url, fp, errcode, errmsg, headers)
1734 else:
1735 result = method(url, fp, errcode, errmsg, headers, data)
1736 if result: return result
1737 return self.http_error_default(url, fp, errcode, errmsg, headers)
1738
1739 def http_error_default(self, url, fp, errcode, errmsg, headers):
1740 """Default error handler: close the connection and raise IOError."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001741 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001742 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001743
1744 if _have_ssl:
1745 def _https_connection(self, host):
1746 return http.client.HTTPSConnection(host,
1747 key_file=self.key_file,
1748 cert_file=self.cert_file)
1749
1750 def open_https(self, url, data=None):
1751 """Use HTTPS protocol."""
1752 return self._open_generic_http(self._https_connection, url, data)
1753
1754 def open_file(self, url):
1755 """Use local file or FTP depending on form of URL."""
1756 if not isinstance(url, str):
1757 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1758 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001759 raise ValueError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001760 else:
1761 return self.open_local_file(url)
1762
1763 def open_local_file(self, url):
1764 """Use local file."""
1765 import mimetypes, email.utils
1766 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001767 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001768 localname = url2pathname(file)
1769 try:
1770 stats = os.stat(localname)
1771 except OSError as e:
1772 raise URLError(e.errno, e.strerror, e.filename)
1773 size = stats.st_size
1774 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1775 mtype = mimetypes.guess_type(url)[0]
1776 headers = email.message_from_string(
1777 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1778 (mtype or 'text/plain', size, modified))
1779 if not host:
1780 urlfile = file
1781 if file[:1] == '/':
1782 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001783 return addinfourl(open(localname, 'rb'), headers, urlfile)
1784 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001785 if (not port
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001786 and socket.gethostbyname(host) in (localhost() + thishost())):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001787 urlfile = file
1788 if file[:1] == '/':
1789 urlfile = 'file://' + file
Senthil Kumaran3800ea92012-01-21 11:52:48 +08001790 elif file[:2] == './':
1791 raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
Georg Brandl13e89462008-07-01 19:56:00 +00001792 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001793 raise URLError('local file error', 'not on local host')
1794
1795 def open_ftp(self, url):
1796 """Use FTP protocol."""
1797 if not isinstance(url, str):
1798 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1799 import mimetypes
1800 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001801 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001802 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001803 host, port = splitport(host)
1804 user, host = splituser(host)
1805 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001806 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001807 host = unquote(host)
1808 user = unquote(user or '')
1809 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001810 host = socket.gethostbyname(host)
1811 if not port:
1812 import ftplib
1813 port = ftplib.FTP_PORT
1814 else:
1815 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001816 path, attrs = splitattr(path)
1817 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001818 dirs = path.split('/')
1819 dirs, file = dirs[:-1], dirs[-1]
1820 if dirs and not dirs[0]: dirs = dirs[1:]
1821 if dirs and not dirs[0]: dirs[0] = '/'
1822 key = user, host, port, '/'.join(dirs)
1823 # XXX thread unsafe!
1824 if len(self.ftpcache) > MAXFTPCACHE:
1825 # Prune the cache, rather arbitrarily
1826 for k in self.ftpcache.keys():
1827 if k != key:
1828 v = self.ftpcache[k]
1829 del self.ftpcache[k]
1830 v.close()
1831 try:
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08001832 if key not in self.ftpcache:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001833 self.ftpcache[key] = \
1834 ftpwrapper(user, passwd, host, port, dirs)
1835 if not file: type = 'D'
1836 else: type = 'I'
1837 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001838 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001839 if attr.lower() == 'type' and \
1840 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1841 type = value.upper()
1842 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1843 mtype = mimetypes.guess_type("ftp:" + url)[0]
1844 headers = ""
1845 if mtype:
1846 headers += "Content-Type: %s\n" % mtype
1847 if retrlen is not None and retrlen >= 0:
1848 headers += "Content-Length: %d\n" % retrlen
1849 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001850 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001851 except ftperrors() as msg:
1852 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1853
1854 def open_data(self, url, data=None):
1855 """Use "data" URL."""
1856 if not isinstance(url, str):
1857 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1858 # ignore POSTed data
1859 #
1860 # syntax of data URLs:
1861 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1862 # mediatype := [ type "/" subtype ] *( ";" parameter )
1863 # data := *urlchar
1864 # parameter := attribute "=" value
1865 try:
1866 [type, data] = url.split(',', 1)
1867 except ValueError:
1868 raise IOError('data error', 'bad data URL')
1869 if not type:
1870 type = 'text/plain;charset=US-ASCII'
1871 semi = type.rfind(';')
1872 if semi >= 0 and '=' not in type[semi:]:
1873 encoding = type[semi+1:]
1874 type = type[:semi]
1875 else:
1876 encoding = ''
1877 msg = []
Senthil Kumaranf6c456d2010-05-01 08:29:18 +00001878 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001879 time.gmtime(time.time())))
1880 msg.append('Content-type: %s' % type)
1881 if encoding == 'base64':
Georg Brandl706824f2009-06-04 09:42:55 +00001882 # XXX is this encoding/decoding ok?
1883 data = base64.decodebytes(data.encode('ascii')).decode('latin1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001884 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001885 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001886 msg.append('Content-Length: %d' % len(data))
1887 msg.append('')
1888 msg.append(data)
1889 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001890 headers = email.message_from_string(msg)
1891 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001892 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001893 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001894
1895
1896class FancyURLopener(URLopener):
1897 """Derived class with handlers for errors we can handle (perhaps)."""
1898
1899 def __init__(self, *args, **kwargs):
1900 URLopener.__init__(self, *args, **kwargs)
1901 self.auth_cache = {}
1902 self.tries = 0
1903 self.maxtries = 10
1904
1905 def http_error_default(self, url, fp, errcode, errmsg, headers):
1906 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001907 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001908
1909 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1910 """Error 302 -- relocated (temporarily)."""
1911 self.tries += 1
1912 if self.maxtries and self.tries >= self.maxtries:
1913 if hasattr(self, "http_error_500"):
1914 meth = self.http_error_500
1915 else:
1916 meth = self.http_error_default
1917 self.tries = 0
1918 return meth(url, fp, 500,
1919 "Internal Server Error: Redirect Recursion", headers)
1920 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
1921 data)
1922 self.tries = 0
1923 return result
1924
1925 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
1926 if 'location' in headers:
1927 newurl = headers['location']
1928 elif 'uri' in headers:
1929 newurl = headers['uri']
1930 else:
1931 return
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001932 fp.close()
guido@google.coma119df92011-03-29 11:41:02 -07001933
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001934 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00001935 newurl = urljoin(self.type + ":" + url, newurl)
guido@google.coma119df92011-03-29 11:41:02 -07001936
1937 urlparts = urlparse(newurl)
1938
1939 # For security reasons, we don't allow redirection to anything other
1940 # than http, https and ftp.
1941
1942 # We are using newer HTTPError with older redirect_internal method
1943 # This older method will get deprecated in 3.3
1944
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001945 if urlparts.scheme not in ('http', 'https', 'ftp', ''):
guido@google.coma119df92011-03-29 11:41:02 -07001946 raise HTTPError(newurl, errcode,
1947 errmsg +
1948 " Redirection to url '%s' is not allowed." % newurl,
1949 headers, fp)
1950
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001951 return self.open(newurl)
1952
1953 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
1954 """Error 301 -- also relocated (permanently)."""
1955 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1956
1957 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
1958 """Error 303 -- also relocated (essentially identical to 302)."""
1959 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1960
1961 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
1962 """Error 307 -- relocated, but turn POST into error."""
1963 if data is None:
1964 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1965 else:
1966 return self.http_error_default(url, fp, errcode, errmsg, headers)
1967
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001968 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
1969 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001970 """Error 401 -- authentication required.
1971 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08001972 if 'www-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001973 URLopener.http_error_default(self, url, fp,
1974 errcode, errmsg, headers)
1975 stuff = headers['www-authenticate']
1976 import re
1977 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1978 if not match:
1979 URLopener.http_error_default(self, url, fp,
1980 errcode, errmsg, headers)
1981 scheme, realm = match.groups()
1982 if scheme.lower() != 'basic':
1983 URLopener.http_error_default(self, url, fp,
1984 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001985 if not retry:
1986 URLopener.http_error_default(self, url, fp, errcode, errmsg,
1987 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001988 name = 'retry_' + self.type + '_basic_auth'
1989 if data is None:
1990 return getattr(self,name)(url, realm)
1991 else:
1992 return getattr(self,name)(url, realm, data)
1993
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001994 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
1995 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001996 """Error 407 -- proxy authentication required.
1997 This function supports Basic authentication only."""
Senthil Kumaran34d38dc2011-10-20 02:48:01 +08001998 if 'proxy-authenticate' not in headers:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001999 URLopener.http_error_default(self, url, fp,
2000 errcode, errmsg, headers)
2001 stuff = headers['proxy-authenticate']
2002 import re
2003 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2004 if not match:
2005 URLopener.http_error_default(self, url, fp,
2006 errcode, errmsg, headers)
2007 scheme, realm = match.groups()
2008 if scheme.lower() != 'basic':
2009 URLopener.http_error_default(self, url, fp,
2010 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002011 if not retry:
2012 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2013 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002014 name = 'retry_proxy_' + self.type + '_basic_auth'
2015 if data is None:
2016 return getattr(self,name)(url, realm)
2017 else:
2018 return getattr(self,name)(url, realm, data)
2019
2020 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002021 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002022 newurl = 'http://' + host + selector
2023 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00002024 urltype, proxyhost = splittype(proxy)
2025 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002026 i = proxyhost.find('@') + 1
2027 proxyhost = proxyhost[i:]
2028 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2029 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002030 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002031 quote(passwd, safe=''), proxyhost)
2032 self.proxies['http'] = 'http://' + proxyhost + proxyselector
2033 if data is None:
2034 return self.open(newurl)
2035 else:
2036 return self.open(newurl, data)
2037
2038 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002039 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002040 newurl = 'https://' + host + selector
2041 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00002042 urltype, proxyhost = splittype(proxy)
2043 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002044 i = proxyhost.find('@') + 1
2045 proxyhost = proxyhost[i:]
2046 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2047 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002048 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002049 quote(passwd, safe=''), proxyhost)
2050 self.proxies['https'] = 'https://' + proxyhost + proxyselector
2051 if data is None:
2052 return self.open(newurl)
2053 else:
2054 return self.open(newurl, data)
2055
2056 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002057 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002058 i = host.find('@') + 1
2059 host = host[i:]
2060 user, passwd = self.get_user_passwd(host, realm, i)
2061 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002062 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002063 quote(passwd, safe=''), host)
2064 newurl = 'http://' + host + selector
2065 if data is None:
2066 return self.open(newurl)
2067 else:
2068 return self.open(newurl, data)
2069
2070 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002071 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002072 i = host.find('@') + 1
2073 host = host[i:]
2074 user, passwd = self.get_user_passwd(host, realm, i)
2075 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002076 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002077 quote(passwd, safe=''), host)
2078 newurl = 'https://' + host + selector
2079 if data is None:
2080 return self.open(newurl)
2081 else:
2082 return self.open(newurl, data)
2083
Florent Xicluna757445b2010-05-17 17:24:07 +00002084 def get_user_passwd(self, host, realm, clear_cache=0):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002085 key = realm + '@' + host.lower()
2086 if key in self.auth_cache:
2087 if clear_cache:
2088 del self.auth_cache[key]
2089 else:
2090 return self.auth_cache[key]
2091 user, passwd = self.prompt_user_passwd(host, realm)
2092 if user or passwd: self.auth_cache[key] = (user, passwd)
2093 return user, passwd
2094
2095 def prompt_user_passwd(self, host, realm):
2096 """Override this in a GUI environment!"""
2097 import getpass
2098 try:
2099 user = input("Enter username for %s at %s: " % (realm, host))
2100 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
2101 (user, realm, host))
2102 return user, passwd
2103 except KeyboardInterrupt:
2104 print()
2105 return None, None
2106
2107
2108# Utility functions
2109
2110_localhost = None
2111def localhost():
2112 """Return the IP address of the magic hostname 'localhost'."""
2113 global _localhost
2114 if _localhost is None:
2115 _localhost = socket.gethostbyname('localhost')
2116 return _localhost
2117
2118_thishost = None
2119def thishost():
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00002120 """Return the IP addresses of the current host."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002121 global _thishost
2122 if _thishost is None:
Senthil Kumaran1b7da512011-10-06 00:32:02 +08002123 _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002124 return _thishost
2125
2126_ftperrors = None
2127def ftperrors():
2128 """Return the set of errors raised by the FTP class."""
2129 global _ftperrors
2130 if _ftperrors is None:
2131 import ftplib
2132 _ftperrors = ftplib.all_errors
2133 return _ftperrors
2134
2135_noheaders = None
2136def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002137 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002138 global _noheaders
2139 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002140 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002141 return _noheaders
2142
2143
2144# Utility classes
2145
2146class ftpwrapper:
2147 """Class used by open_ftp() for cache of open FTP connections."""
2148
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002149 def __init__(self, user, passwd, host, port, dirs, timeout=None,
2150 persistent=True):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002151 self.user = user
2152 self.passwd = passwd
2153 self.host = host
2154 self.port = port
2155 self.dirs = dirs
2156 self.timeout = timeout
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002157 self.refcount = 0
2158 self.keepalive = persistent
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002159 self.init()
2160
2161 def init(self):
2162 import ftplib
2163 self.busy = 0
2164 self.ftp = ftplib.FTP()
2165 self.ftp.connect(self.host, self.port, self.timeout)
2166 self.ftp.login(self.user, self.passwd)
2167 for dir in self.dirs:
2168 self.ftp.cwd(dir)
2169
2170 def retrfile(self, file, type):
2171 import ftplib
2172 self.endtransfer()
2173 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2174 else: cmd = 'TYPE ' + type; isdir = 0
2175 try:
2176 self.ftp.voidcmd(cmd)
2177 except ftplib.all_errors:
2178 self.init()
2179 self.ftp.voidcmd(cmd)
2180 conn = None
2181 if file and not isdir:
2182 # Try to retrieve as a file
2183 try:
2184 cmd = 'RETR ' + file
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002185 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002186 except ftplib.error_perm as reason:
2187 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002188 raise URLError('ftp error', reason).with_traceback(
2189 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002190 if not conn:
2191 # Set transfer mode to ASCII!
2192 self.ftp.voidcmd('TYPE A')
2193 # Try a directory listing. Verify that directory exists.
2194 if file:
2195 pwd = self.ftp.pwd()
2196 try:
2197 try:
2198 self.ftp.cwd(file)
2199 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002200 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002201 finally:
2202 self.ftp.cwd(pwd)
2203 cmd = 'LIST ' + file
2204 else:
2205 cmd = 'LIST'
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002206 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002207 self.busy = 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002208
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002209 ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
2210 self.refcount += 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002211 conn.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002212 # Pass back both a suitably decorated object and a retrieval length
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002213 return (ftpobj, retrlen)
2214
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002215 def endtransfer(self):
2216 if not self.busy:
2217 return
2218 self.busy = 0
2219 try:
2220 self.ftp.voidresp()
2221 except ftperrors():
2222 pass
2223
2224 def close(self):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002225 self.keepalive = False
2226 if self.refcount <= 0:
2227 self.real_close()
2228
2229 def file_close(self):
2230 self.endtransfer()
2231 self.refcount -= 1
2232 if self.refcount <= 0 and not self.keepalive:
2233 self.real_close()
2234
2235 def real_close(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002236 self.endtransfer()
2237 try:
2238 self.ftp.close()
2239 except ftperrors():
2240 pass
2241
2242# Proxy handling
2243def getproxies_environment():
2244 """Return a dictionary of scheme -> proxy server URL mappings.
2245
2246 Scan the environment for variables named <scheme>_proxy;
2247 this seems to be the standard convention. If you need a
2248 different way, you can pass a proxies dictionary to the
2249 [Fancy]URLopener constructor.
2250
2251 """
2252 proxies = {}
2253 for name, value in os.environ.items():
2254 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002255 if value and name[-6:] == '_proxy':
2256 proxies[name[:-6]] = value
2257 return proxies
2258
2259def proxy_bypass_environment(host):
2260 """Test if proxies should not be used for a particular host.
2261
2262 Checks the environment for a variable named no_proxy, which should
2263 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2264 """
2265 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2266 # '*' is special case for always bypass
2267 if no_proxy == '*':
2268 return 1
2269 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002270 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002271 # check if the host ends with any of the DNS suffixes
Senthil Kumaran89976f12011-08-06 12:27:40 +08002272 no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
2273 for name in no_proxy_list:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002274 if name and (hostonly.endswith(name) or host.endswith(name)):
2275 return 1
2276 # otherwise, don't bypass
2277 return 0
2278
2279
Ronald Oussorene72e1612011-03-14 18:15:25 -04002280# This code tests an OSX specific data structure but is testable on all
2281# platforms
2282def _proxy_bypass_macosx_sysconf(host, proxy_settings):
2283 """
2284 Return True iff this host shouldn't be accessed using a proxy
2285
2286 This function uses the MacOSX framework SystemConfiguration
2287 to fetch the proxy information.
2288
2289 proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
2290 { 'exclude_simple': bool,
2291 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
2292 }
2293 """
2294 import re
2295 import socket
2296 from fnmatch import fnmatch
2297
2298 hostonly, port = splitport(host)
2299
2300 def ip2num(ipAddr):
2301 parts = ipAddr.split('.')
2302 parts = list(map(int, parts))
2303 if len(parts) != 4:
2304 parts = (parts + [0, 0, 0, 0])[:4]
2305 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2306
2307 # Check for simple host names:
2308 if '.' not in host:
2309 if proxy_settings['exclude_simple']:
2310 return True
2311
2312 hostIP = None
2313
2314 for value in proxy_settings.get('exceptions', ()):
2315 # Items in the list are strings like these: *.local, 169.254/16
2316 if not value: continue
2317
2318 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2319 if m is not None:
2320 if hostIP is None:
2321 try:
2322 hostIP = socket.gethostbyname(hostonly)
2323 hostIP = ip2num(hostIP)
2324 except socket.error:
2325 continue
2326
2327 base = ip2num(m.group(1))
2328 mask = m.group(2)
2329 if mask is None:
2330 mask = 8 * (m.group(1).count('.') + 1)
2331 else:
2332 mask = int(mask[1:])
2333 mask = 32 - mask
2334
2335 if (hostIP >> mask) == (base >> mask):
2336 return True
2337
2338 elif fnmatch(host, value):
2339 return True
2340
2341 return False
2342
2343
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002344if sys.platform == 'darwin':
Ronald Oussoren84151202010-04-18 20:46:11 +00002345 from _scproxy import _get_proxy_settings, _get_proxies
2346
2347 def proxy_bypass_macosx_sysconf(host):
Ronald Oussoren84151202010-04-18 20:46:11 +00002348 proxy_settings = _get_proxy_settings()
Ronald Oussorene72e1612011-03-14 18:15:25 -04002349 return _proxy_bypass_macosx_sysconf(host, proxy_settings)
Ronald Oussoren84151202010-04-18 20:46:11 +00002350
2351 def getproxies_macosx_sysconf():
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002352 """Return a dictionary of scheme -> proxy server URL mappings.
2353
Ronald Oussoren84151202010-04-18 20:46:11 +00002354 This function uses the MacOSX framework SystemConfiguration
2355 to fetch the proxy information.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002356 """
Ronald Oussoren84151202010-04-18 20:46:11 +00002357 return _get_proxies()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002358
Ronald Oussoren84151202010-04-18 20:46:11 +00002359
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002360
2361 def proxy_bypass(host):
2362 if getproxies_environment():
2363 return proxy_bypass_environment(host)
2364 else:
Ronald Oussoren84151202010-04-18 20:46:11 +00002365 return proxy_bypass_macosx_sysconf(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002366
2367 def getproxies():
Ronald Oussoren84151202010-04-18 20:46:11 +00002368 return getproxies_environment() or getproxies_macosx_sysconf()
2369
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002370
2371elif os.name == 'nt':
2372 def getproxies_registry():
2373 """Return a dictionary of scheme -> proxy server URL mappings.
2374
2375 Win32 uses the registry to store proxies.
2376
2377 """
2378 proxies = {}
2379 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002380 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002381 except ImportError:
2382 # Std module, so should be around - but you never know!
2383 return proxies
2384 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002385 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002386 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002387 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002388 'ProxyEnable')[0]
2389 if proxyEnable:
2390 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002391 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002392 'ProxyServer')[0])
2393 if '=' in proxyServer:
2394 # Per-protocol settings
2395 for p in proxyServer.split(';'):
2396 protocol, address = p.split('=', 1)
2397 # See if address has a type:// prefix
2398 import re
2399 if not re.match('^([^/:]+)://', address):
2400 address = '%s://%s' % (protocol, address)
2401 proxies[protocol] = address
2402 else:
2403 # Use one setting for all protocols
2404 if proxyServer[:5] == 'http:':
2405 proxies['http'] = proxyServer
2406 else:
2407 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran04f31b82010-07-14 20:10:52 +00002408 proxies['https'] = 'https://%s' % proxyServer
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002409 proxies['ftp'] = 'ftp://%s' % proxyServer
2410 internetSettings.Close()
2411 except (WindowsError, ValueError, TypeError):
2412 # Either registry key not found etc, or the value in an
2413 # unexpected format.
2414 # proxies already set up to be empty so nothing to do
2415 pass
2416 return proxies
2417
2418 def getproxies():
2419 """Return a dictionary of scheme -> proxy server URL mappings.
2420
2421 Returns settings gathered from the environment, if specified,
2422 or the registry.
2423
2424 """
2425 return getproxies_environment() or getproxies_registry()
2426
2427 def proxy_bypass_registry(host):
2428 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002429 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002430 import re
2431 except ImportError:
2432 # Std modules, so should be around - but you never know!
2433 return 0
2434 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002435 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002436 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002437 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002438 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002439 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002440 'ProxyOverride')[0])
2441 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2442 except WindowsError:
2443 return 0
2444 if not proxyEnable or not proxyOverride:
2445 return 0
2446 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002447 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002448 host = [rawHost]
2449 try:
2450 addr = socket.gethostbyname(rawHost)
2451 if addr != rawHost:
2452 host.append(addr)
2453 except socket.error:
2454 pass
2455 try:
2456 fqdn = socket.getfqdn(rawHost)
2457 if fqdn != rawHost:
2458 host.append(fqdn)
2459 except socket.error:
2460 pass
2461 # make a check value list from the registry entry: replace the
2462 # '<local>' string by the localhost entry and the corresponding
2463 # canonical entry.
2464 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002465 # now check if we match one of the registry values.
2466 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002467 if test == '<local>':
2468 if '.' not in rawHost:
2469 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002470 test = test.replace(".", r"\.") # mask dots
2471 test = test.replace("*", r".*") # change glob sequence
2472 test = test.replace("?", r".") # change glob char
2473 for val in host:
2474 # print "%s <--> %s" %( test, val )
2475 if re.match(test, val, re.I):
2476 return 1
2477 return 0
2478
2479 def proxy_bypass(host):
2480 """Return a dictionary of scheme -> proxy server URL mappings.
2481
2482 Returns settings gathered from the environment, if specified,
2483 or the registry.
2484
2485 """
2486 if getproxies_environment():
2487 return proxy_bypass_environment(host)
2488 else:
2489 return proxy_bypass_registry(host)
2490
2491else:
2492 # By default use environment variables
2493 getproxies = getproxies_environment
2494 proxy_bypass = proxy_bypass_environment