blob: 65ce287588ffb13b45eae848c607ae39925adbbe [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
Jeremy Hylton1afc1692008-06-18 20:49:58 +000098
Georg Brandl13e89462008-07-01 19:56:00 +000099from urllib.error import URLError, HTTPError, ContentTooShortError
100from urllib.parse import (
101 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
102 splittype, splithost, splitport, splituser, splitpasswd,
Senthil Kumarand95cc752010-08-08 11:27:53 +0000103 splitattr, splitquery, splitvalue, splittag, to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000104from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000105
106# check for SSL
107try:
108 import ssl
Senthil Kumaranc2958622010-11-22 04:48:26 +0000109except ImportError:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000110 _have_ssl = False
111else:
112 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000113
114# used in User-Agent header sent
115__version__ = sys.version[:3]
116
117_opener = None
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000118def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
119 *, cafile=None, capath=None):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000120 global _opener
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000121 if cafile or capath:
122 if not _have_ssl:
123 raise ValueError('SSL support not available')
124 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
125 context.options |= ssl.OP_NO_SSLv2
126 if cafile or capath:
127 context.verify_mode = ssl.CERT_REQUIRED
128 context.load_verify_locations(cafile, capath)
129 check_hostname = True
130 else:
131 check_hostname = False
132 https_handler = HTTPSHandler(context=context, check_hostname=check_hostname)
133 opener = build_opener(https_handler)
134 elif _opener is None:
135 _opener = opener = build_opener()
136 else:
137 opener = _opener
138 return opener.open(url, data, timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000139
140def install_opener(opener):
141 global _opener
142 _opener = opener
143
144# TODO(jhylton): Make this work with the same global opener.
145_urlopener = None
146def urlretrieve(url, filename=None, reporthook=None, data=None):
147 global _urlopener
148 if not _urlopener:
149 _urlopener = FancyURLopener()
150 return _urlopener.retrieve(url, filename, reporthook, data)
151
152def urlcleanup():
153 if _urlopener:
154 _urlopener.cleanup()
155 global _opener
156 if _opener:
157 _opener = None
158
159# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000160_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000161def request_host(request):
162 """Return request-host, as defined by RFC 2965.
163
164 Variation from RFC: returned value is lowercased, for convenient
165 comparison.
166
167 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000168 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000169 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000170 if host == "":
171 host = request.get_header("Host", "")
172
173 # remove port, if present
174 host = _cut_port_re.sub("", host, 1)
175 return host.lower()
176
177class Request:
178
179 def __init__(self, url, data=None, headers={},
Senthil Kumarande49d642011-10-16 23:54:44 +0800180 origin_req_host=None, unverifiable=False,
181 method=None):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000182 # unwrap('<URL:type://host/path>') --> 'type://host/path'
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000183 self.full_url = unwrap(url)
Senthil Kumaran26430412011-04-13 07:01:19 +0800184 self.full_url, self.fragment = splittag(self.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000185 self.data = data
186 self.headers = {}
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000187 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000188 for key, value in headers.items():
189 self.add_header(key, value)
190 self.unredirected_hdrs = {}
191 if origin_req_host is None:
192 origin_req_host = request_host(self)
193 self.origin_req_host = origin_req_host
194 self.unverifiable = unverifiable
Senthil Kumarande49d642011-10-16 23:54:44 +0800195 self.method = method
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):
Senthil Kumarande49d642011-10-16 23:54:44 +0800207 """Return a string indicating the HTTP request method."""
208 if self.method is not None:
209 return self.method
210 elif self.data is not None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000211 return "POST"
212 else:
213 return "GET"
214
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000215 # Begin deprecated methods
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000216
217 def add_data(self, data):
218 self.data = data
219
220 def has_data(self):
221 return self.data is not None
222
223 def get_data(self):
224 return self.data
225
226 def get_full_url(self):
Senthil Kumaran26430412011-04-13 07:01:19 +0800227 if self.fragment:
228 return '%s#%s' % (self.full_url, self.fragment)
229 else:
230 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000231
232 def get_type(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000233 return self.type
234
235 def get_host(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000236 return self.host
237
238 def get_selector(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000239 return self.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000240
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000241 def is_unverifiable(self):
242 return self.unverifiable
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000243
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000244 def get_origin_req_host(self):
245 return self.origin_req_host
246
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000247 # End deprecated methods
248
249 def set_proxy(self, host, type):
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000250 if self.type == 'https' and not self._tunnel_host:
251 self._tunnel_host = self.host
252 else:
253 self.type= type
254 self.selector = self.full_url
255 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000256
257 def has_proxy(self):
258 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000259
260 def add_header(self, key, val):
261 # useful for something like authentication
262 self.headers[key.capitalize()] = val
263
264 def add_unredirected_header(self, key, val):
265 # will not be added to a redirected request
266 self.unredirected_hdrs[key.capitalize()] = val
267
268 def has_header(self, header_name):
269 return (header_name in self.headers or
270 header_name in self.unredirected_hdrs)
271
272 def get_header(self, header_name, default=None):
273 return self.headers.get(
274 header_name,
275 self.unredirected_hdrs.get(header_name, default))
276
277 def header_items(self):
278 hdrs = self.unredirected_hdrs.copy()
279 hdrs.update(self.headers)
280 return list(hdrs.items())
281
282class OpenerDirector:
283 def __init__(self):
284 client_version = "Python-urllib/%s" % __version__
285 self.addheaders = [('User-agent', client_version)]
R. David Murray25b8cca2010-12-23 19:44:49 +0000286 # self.handlers is retained only for backward compatibility
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000287 self.handlers = []
R. David Murray25b8cca2010-12-23 19:44:49 +0000288 # manage the individual handlers
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000289 self.handle_open = {}
290 self.handle_error = {}
291 self.process_response = {}
292 self.process_request = {}
293
294 def add_handler(self, handler):
295 if not hasattr(handler, "add_parent"):
296 raise TypeError("expected BaseHandler instance, got %r" %
297 type(handler))
298
299 added = False
300 for meth in dir(handler):
301 if meth in ["redirect_request", "do_open", "proxy_open"]:
302 # oops, coincidental match
303 continue
304
305 i = meth.find("_")
306 protocol = meth[:i]
307 condition = meth[i+1:]
308
309 if condition.startswith("error"):
310 j = condition.find("_") + i + 1
311 kind = meth[j+1:]
312 try:
313 kind = int(kind)
314 except ValueError:
315 pass
316 lookup = self.handle_error.get(protocol, {})
317 self.handle_error[protocol] = lookup
318 elif condition == "open":
319 kind = protocol
320 lookup = self.handle_open
321 elif condition == "response":
322 kind = protocol
323 lookup = self.process_response
324 elif condition == "request":
325 kind = protocol
326 lookup = self.process_request
327 else:
328 continue
329
330 handlers = lookup.setdefault(kind, [])
331 if handlers:
332 bisect.insort(handlers, handler)
333 else:
334 handlers.append(handler)
335 added = True
336
337 if added:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000338 bisect.insort(self.handlers, handler)
339 handler.add_parent(self)
340
341 def close(self):
342 # Only exists for backwards compatibility.
343 pass
344
345 def _call_chain(self, chain, kind, meth_name, *args):
346 # Handlers raise an exception if no one else should try to handle
347 # the request, or return None if they can't but another handler
348 # could. Otherwise, they return the response.
349 handlers = chain.get(kind, ())
350 for handler in handlers:
351 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000352 result = func(*args)
353 if result is not None:
354 return result
355
356 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
357 # accept a URL or a Request object
358 if isinstance(fullurl, str):
359 req = Request(fullurl, data)
360 else:
361 req = fullurl
362 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000363 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000364
365 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000366 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000367
368 # pre-process request
369 meth_name = protocol+"_request"
370 for processor in self.process_request.get(protocol, []):
371 meth = getattr(processor, meth_name)
372 req = meth(req)
373
374 response = self._open(req, data)
375
376 # post-process response
377 meth_name = protocol+"_response"
378 for processor in self.process_response.get(protocol, []):
379 meth = getattr(processor, meth_name)
380 response = meth(req, response)
381
382 return response
383
384 def _open(self, req, data=None):
385 result = self._call_chain(self.handle_open, 'default',
386 'default_open', req)
387 if result:
388 return result
389
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000390 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000391 result = self._call_chain(self.handle_open, protocol, protocol +
392 '_open', req)
393 if result:
394 return result
395
396 return self._call_chain(self.handle_open, 'unknown',
397 'unknown_open', req)
398
399 def error(self, proto, *args):
400 if proto in ('http', 'https'):
401 # XXX http[s] protocols are special-cased
402 dict = self.handle_error['http'] # https is not different than http
403 proto = args[2] # YUCK!
404 meth_name = 'http_error_%s' % proto
405 http_err = 1
406 orig_args = args
407 else:
408 dict = self.handle_error
409 meth_name = proto + '_error'
410 http_err = 0
411 args = (dict, proto, meth_name) + args
412 result = self._call_chain(*args)
413 if result:
414 return result
415
416 if http_err:
417 args = (dict, 'default', 'http_error_default') + orig_args
418 return self._call_chain(*args)
419
420# XXX probably also want an abstract factory that knows when it makes
421# sense to skip a superclass in favor of a subclass and when it might
422# make sense to include both
423
424def build_opener(*handlers):
425 """Create an opener object from a list of handlers.
426
427 The opener will use several default handlers, including support
Senthil Kumaran1107c5d2009-11-15 06:20:55 +0000428 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000429
430 If any of the handlers passed as arguments are subclasses of the
431 default handlers, the default handlers will not be used.
432 """
433 def isclass(obj):
434 return isinstance(obj, type) or hasattr(obj, "__bases__")
435
436 opener = OpenerDirector()
437 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
438 HTTPDefaultErrorHandler, HTTPRedirectHandler,
439 FTPHandler, FileHandler, HTTPErrorProcessor]
440 if hasattr(http.client, "HTTPSConnection"):
441 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000442 skip = set()
443 for klass in default_classes:
444 for check in handlers:
445 if isclass(check):
446 if issubclass(check, klass):
447 skip.add(klass)
448 elif isinstance(check, klass):
449 skip.add(klass)
450 for klass in skip:
451 default_classes.remove(klass)
452
453 for klass in default_classes:
454 opener.add_handler(klass())
455
456 for h in handlers:
457 if isclass(h):
458 h = h()
459 opener.add_handler(h)
460 return opener
461
462class BaseHandler:
463 handler_order = 500
464
465 def add_parent(self, parent):
466 self.parent = parent
467
468 def close(self):
469 # Only exists for backwards compatibility
470 pass
471
472 def __lt__(self, other):
473 if not hasattr(other, "handler_order"):
474 # Try to preserve the old behavior of having custom classes
475 # inserted after default ones (works only for custom user
476 # classes which are not aware of handler_order).
477 return True
478 return self.handler_order < other.handler_order
479
480
481class HTTPErrorProcessor(BaseHandler):
482 """Process HTTP error responses."""
483 handler_order = 1000 # after all other processing
484
485 def http_response(self, request, response):
486 code, msg, hdrs = response.code, response.msg, response.info()
487
488 # According to RFC 2616, "2xx" code indicates that the client's
489 # request was successfully received, understood, and accepted.
490 if not (200 <= code < 300):
491 response = self.parent.error(
492 'http', request, response, code, msg, hdrs)
493
494 return response
495
496 https_response = http_response
497
498class HTTPDefaultErrorHandler(BaseHandler):
499 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000500 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000501
502class HTTPRedirectHandler(BaseHandler):
503 # maximum number of redirections to any single URL
504 # this is needed because of the state that cookies introduce
505 max_repeats = 4
506 # maximum total number of redirections (regardless of URL) before
507 # assuming we're in a loop
508 max_redirections = 10
509
510 def redirect_request(self, req, fp, code, msg, headers, newurl):
511 """Return a Request or None in response to a redirect.
512
513 This is called by the http_error_30x methods when a
514 redirection response is received. If a redirection should
515 take place, return a new Request to allow http_error_30x to
516 perform the redirect. Otherwise, raise HTTPError if no-one
517 else should try to handle this url. Return None if you can't
518 but another Handler might.
519 """
520 m = req.get_method()
521 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
522 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000523 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000524
525 # Strictly (according to RFC 2616), 301 or 302 in response to
526 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000527 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000528 # essentially all clients do redirect in this case, so we do
529 # the same.
530 # be conciliant with URIs containing a space
531 newurl = newurl.replace(' ', '%20')
532 CONTENT_HEADERS = ("content-length", "content-type")
533 newheaders = dict((k, v) for k, v in req.headers.items()
534 if k.lower() not in CONTENT_HEADERS)
535 return Request(newurl,
536 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000537 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000538 unverifiable=True)
539
540 # Implementation note: To avoid the server sending us into an
541 # infinite loop, the request object needs to track what URLs we
542 # have already seen. Do this by adding a handler-specific
543 # attribute to the Request object.
544 def http_error_302(self, req, fp, code, msg, headers):
545 # Some servers (incorrectly) return multiple Location headers
546 # (so probably same goes for URI). Use first header.
547 if "location" in headers:
548 newurl = headers["location"]
549 elif "uri" in headers:
550 newurl = headers["uri"]
551 else:
552 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000553
554 # fix a possible malformed URL
555 urlparts = urlparse(newurl)
guido@google.coma119df92011-03-29 11:41:02 -0700556
557 # For security reasons we don't allow redirection to anything other
558 # than http, https or ftp.
559
560 if not urlparts.scheme in ('http', 'https', 'ftp'):
561 raise HTTPError(newurl, code,
562 msg +
563 " - Redirection to url '%s' is not allowed" %
564 newurl,
565 headers, fp)
566
Facundo Batistaf24802c2008-08-17 03:36:03 +0000567 if not urlparts.path:
568 urlparts = list(urlparts)
569 urlparts[2] = "/"
570 newurl = urlunparse(urlparts)
571
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000572 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000573
574 # XXX Probably want to forget about the state of the current
575 # request, although that might interact poorly with other
576 # handlers that also use handler-specific request attributes
577 new = self.redirect_request(req, fp, code, msg, headers, newurl)
578 if new is None:
579 return
580
581 # loop detection
582 # .redirect_dict has a key url if url was previously visited.
583 if hasattr(req, 'redirect_dict'):
584 visited = new.redirect_dict = req.redirect_dict
585 if (visited.get(newurl, 0) >= self.max_repeats or
586 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000587 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000588 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000589 else:
590 visited = new.redirect_dict = req.redirect_dict = {}
591 visited[newurl] = visited.get(newurl, 0) + 1
592
593 # Don't close the fp until we are sure that we won't use it
594 # with HTTPError.
595 fp.read()
596 fp.close()
597
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000598 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000599
600 http_error_301 = http_error_303 = http_error_307 = http_error_302
601
602 inf_msg = "The HTTP server returned a redirect error that would " \
603 "lead to an infinite loop.\n" \
604 "The last 30x error message was:\n"
605
606
607def _parse_proxy(proxy):
608 """Return (scheme, user, password, host/port) given a URL or an authority.
609
610 If a URL is supplied, it must have an authority (host:port) component.
611 According to RFC 3986, having an authority component means the URL must
612 have two slashes after the scheme:
613
614 >>> _parse_proxy('file:/ftp.example.com/')
615 Traceback (most recent call last):
616 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
617
618 The first three items of the returned tuple may be None.
619
620 Examples of authority parsing:
621
622 >>> _parse_proxy('proxy.example.com')
623 (None, None, None, 'proxy.example.com')
624 >>> _parse_proxy('proxy.example.com:3128')
625 (None, None, None, 'proxy.example.com:3128')
626
627 The authority component may optionally include userinfo (assumed to be
628 username:password):
629
630 >>> _parse_proxy('joe:password@proxy.example.com')
631 (None, 'joe', 'password', 'proxy.example.com')
632 >>> _parse_proxy('joe:password@proxy.example.com:3128')
633 (None, 'joe', 'password', 'proxy.example.com:3128')
634
635 Same examples, but with URLs instead:
636
637 >>> _parse_proxy('http://proxy.example.com/')
638 ('http', None, None, 'proxy.example.com')
639 >>> _parse_proxy('http://proxy.example.com:3128/')
640 ('http', None, None, 'proxy.example.com:3128')
641 >>> _parse_proxy('http://joe:password@proxy.example.com/')
642 ('http', 'joe', 'password', 'proxy.example.com')
643 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
644 ('http', 'joe', 'password', 'proxy.example.com:3128')
645
646 Everything after the authority is ignored:
647
648 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
649 ('ftp', 'joe', 'password', 'proxy.example.com')
650
651 Test for no trailing '/' case:
652
653 >>> _parse_proxy('http://joe:password@proxy.example.com')
654 ('http', 'joe', 'password', 'proxy.example.com')
655
656 """
Georg Brandl13e89462008-07-01 19:56:00 +0000657 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000658 if not r_scheme.startswith("/"):
659 # authority
660 scheme = None
661 authority = proxy
662 else:
663 # URL
664 if not r_scheme.startswith("//"):
665 raise ValueError("proxy URL with no authority: %r" % proxy)
666 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
667 # and 3.3.), path is empty or starts with '/'
668 end = r_scheme.find("/", 2)
669 if end == -1:
670 end = None
671 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000672 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000673 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000674 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000675 else:
676 user = password = None
677 return scheme, user, password, hostport
678
679class ProxyHandler(BaseHandler):
680 # Proxies must be in front
681 handler_order = 100
682
683 def __init__(self, proxies=None):
684 if proxies is None:
685 proxies = getproxies()
686 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
687 self.proxies = proxies
688 for type, url in proxies.items():
689 setattr(self, '%s_open' % type,
690 lambda r, proxy=url, type=type, meth=self.proxy_open: \
691 meth(r, proxy, type))
692
693 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000694 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000695 proxy_type, user, password, hostport = _parse_proxy(proxy)
696 if proxy_type is None:
697 proxy_type = orig_type
Senthil Kumaran7bb04972009-10-11 04:58:55 +0000698
699 if req.host and proxy_bypass(req.host):
700 return None
701
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000702 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000703 user_pass = '%s:%s' % (unquote(user),
704 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000705 creds = base64.b64encode(user_pass.encode()).decode("ascii")
706 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000707 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000708 req.set_proxy(hostport, proxy_type)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000709 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000710 # let other handlers take care of it
711 return None
712 else:
713 # need to start over, because the other handlers don't
714 # grok the proxy's URL type
715 # e.g. if we have a constructor arg proxies like so:
716 # {'http': 'ftp://proxy.example.com'}, we may end up turning
717 # a request for http://acme.example.com/a into one for
718 # ftp://proxy.example.com/a
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000719 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000720
721class HTTPPasswordMgr:
722
723 def __init__(self):
724 self.passwd = {}
725
726 def add_password(self, realm, uri, user, passwd):
727 # uri could be a single URI or a sequence
728 if isinstance(uri, str):
729 uri = [uri]
730 if not realm in self.passwd:
731 self.passwd[realm] = {}
732 for default_port in True, False:
733 reduced_uri = tuple(
734 [self.reduce_uri(u, default_port) for u in uri])
735 self.passwd[realm][reduced_uri] = (user, passwd)
736
737 def find_user_password(self, realm, authuri):
738 domains = self.passwd.get(realm, {})
739 for default_port in True, False:
740 reduced_authuri = self.reduce_uri(authuri, default_port)
741 for uris, authinfo in domains.items():
742 for uri in uris:
743 if self.is_suburi(uri, reduced_authuri):
744 return authinfo
745 return None, None
746
747 def reduce_uri(self, uri, default_port=True):
748 """Accept authority or URI and extract only the authority and path."""
749 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000750 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000751 if parts[1]:
752 # URI
753 scheme = parts[0]
754 authority = parts[1]
755 path = parts[2] or '/'
756 else:
757 # host or host:port
758 scheme = None
759 authority = uri
760 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000761 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000762 if default_port and port is None and scheme is not None:
763 dport = {"http": 80,
764 "https": 443,
765 }.get(scheme)
766 if dport is not None:
767 authority = "%s:%d" % (host, dport)
768 return authority, path
769
770 def is_suburi(self, base, test):
771 """Check if test is below base in a URI tree
772
773 Both args must be URIs in reduced form.
774 """
775 if base == test:
776 return True
777 if base[0] != test[0]:
778 return False
779 common = posixpath.commonprefix((base[1], test[1]))
780 if len(common) == len(base[1]):
781 return True
782 return False
783
784
785class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
786
787 def find_user_password(self, realm, authuri):
788 user, password = HTTPPasswordMgr.find_user_password(self, realm,
789 authuri)
790 if user is not None:
791 return user, password
792 return HTTPPasswordMgr.find_user_password(self, None, authuri)
793
794
795class AbstractBasicAuthHandler:
796
797 # XXX this allows for multiple auth-schemes, but will stupidly pick
798 # the last one with a realm specified.
799
800 # allow for double- and single-quoted realm values
801 # (single quotes are a violation of the RFC, but appear in the wild)
802 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
803 'realm=(["\'])(.*?)\\2', re.I)
804
805 # XXX could pre-emptively send auth info already accepted (RFC 2617,
806 # end of section 2, and section 1.2 immediately after "credentials"
807 # production).
808
809 def __init__(self, password_mgr=None):
810 if password_mgr is None:
811 password_mgr = HTTPPasswordMgr()
812 self.passwd = password_mgr
813 self.add_password = self.passwd.add_password
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000814 self.retried = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000815
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000816 def reset_retry_count(self):
817 self.retried = 0
818
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000819 def http_error_auth_reqed(self, authreq, host, req, headers):
820 # host may be an authority (without userinfo) or a URL with an
821 # authority
822 # XXX could be multiple headers
823 authreq = headers.get(authreq, None)
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000824
825 if self.retried > 5:
826 # retry sending the username:password 5 times before failing.
827 raise HTTPError(req.get_full_url(), 401, "basic auth failed",
828 headers, None)
829 else:
830 self.retried += 1
831
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000832 if authreq:
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800833 scheme = authreq.split()[0]
834 if not scheme.lower() == 'basic':
835 raise ValueError("AbstractBasicAuthHandler does not"
836 " support the following scheme: '%s'" %
837 scheme)
838 else:
839 mo = AbstractBasicAuthHandler.rx.search(authreq)
840 if mo:
841 scheme, quote, realm = mo.groups()
842 if scheme.lower() == 'basic':
843 response = self.retry_http_basic_auth(host, req, realm)
844 if response and response.code != 401:
845 self.retried = 0
846 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000847
848 def retry_http_basic_auth(self, host, req, realm):
849 user, pw = self.passwd.find_user_password(realm, host)
850 if pw is not None:
851 raw = "%s:%s" % (user, pw)
852 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
853 if req.headers.get(self.auth_header, None) == auth:
854 return None
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +0000855 req.add_unredirected_header(self.auth_header, auth)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000856 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000857 else:
858 return None
859
860
861class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
862
863 auth_header = 'Authorization'
864
865 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000866 url = req.full_url
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000867 response = self.http_error_auth_reqed('www-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000868 url, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000869 self.reset_retry_count()
870 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000871
872
873class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
874
875 auth_header = 'Proxy-authorization'
876
877 def http_error_407(self, req, fp, code, msg, headers):
878 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000879 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000880 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
881 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000882 authority = req.host
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000883 response = self.http_error_auth_reqed('proxy-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000884 authority, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000885 self.reset_retry_count()
886 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000887
888
889def randombytes(n):
890 """Return n random bytes."""
891 return os.urandom(n)
892
893class AbstractDigestAuthHandler:
894 # Digest authentication is specified in RFC 2617.
895
896 # XXX The client does not inspect the Authentication-Info header
897 # in a successful response.
898
899 # XXX It should be possible to test this implementation against
900 # a mock server that just generates a static set of challenges.
901
902 # XXX qop="auth-int" supports is shaky
903
904 def __init__(self, passwd=None):
905 if passwd is None:
906 passwd = HTTPPasswordMgr()
907 self.passwd = passwd
908 self.add_password = self.passwd.add_password
909 self.retried = 0
910 self.nonce_count = 0
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000911 self.last_nonce = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000912
913 def reset_retry_count(self):
914 self.retried = 0
915
916 def http_error_auth_reqed(self, auth_header, host, req, headers):
917 authreq = headers.get(auth_header, None)
918 if self.retried > 5:
919 # Don't fail endlessly - if we failed once, we'll probably
920 # fail a second time. Hm. Unless the Password Manager is
921 # prompting for the information. Crap. This isn't great
922 # but it's better than the current 'repeat until recursion
923 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000924 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000925 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000926 else:
927 self.retried += 1
928 if authreq:
929 scheme = authreq.split()[0]
930 if scheme.lower() == 'digest':
931 return self.retry_http_digest_auth(req, authreq)
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800932 elif not scheme.lower() == 'basic':
933 raise ValueError("AbstractDigestAuthHandler does not support"
934 " the following scheme: '%s'" % scheme)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000935
936 def retry_http_digest_auth(self, req, auth):
937 token, challenge = auth.split(' ', 1)
938 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
939 auth = self.get_authorization(req, chal)
940 if auth:
941 auth_val = 'Digest %s' % auth
942 if req.headers.get(self.auth_header, None) == auth_val:
943 return None
944 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000945 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000946 return resp
947
948 def get_cnonce(self, nonce):
949 # The cnonce-value is an opaque
950 # quoted string value provided by the client and used by both client
951 # and server to avoid chosen plaintext attacks, to provide mutual
952 # authentication, and to provide some message integrity protection.
953 # This isn't a fabulous effort, but it's probably Good Enough.
954 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
955 b = s.encode("ascii") + randombytes(8)
956 dig = hashlib.sha1(b).hexdigest()
957 return dig[:16]
958
959 def get_authorization(self, req, chal):
960 try:
961 realm = chal['realm']
962 nonce = chal['nonce']
963 qop = chal.get('qop')
964 algorithm = chal.get('algorithm', 'MD5')
965 # mod_digest doesn't send an opaque, even though it isn't
966 # supposed to be optional
967 opaque = chal.get('opaque', None)
968 except KeyError:
969 return None
970
971 H, KD = self.get_algorithm_impls(algorithm)
972 if H is None:
973 return None
974
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000975 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000976 if user is None:
977 return None
978
979 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000980 if req.data is not None:
981 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000982 else:
983 entdig = None
984
985 A1 = "%s:%s:%s" % (user, realm, pw)
986 A2 = "%s:%s" % (req.get_method(),
987 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000988 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000989 if qop == 'auth':
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000990 if nonce == self.last_nonce:
991 self.nonce_count += 1
992 else:
993 self.nonce_count = 1
994 self.last_nonce = nonce
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000995 ncvalue = '%08x' % self.nonce_count
996 cnonce = self.get_cnonce(nonce)
997 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
998 respdig = KD(H(A1), noncebit)
999 elif qop is None:
1000 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
1001 else:
1002 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +00001003 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001004
1005 # XXX should the partial digests be encoded too?
1006
1007 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001008 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001009 respdig)
1010 if opaque:
1011 base += ', opaque="%s"' % opaque
1012 if entdig:
1013 base += ', digest="%s"' % entdig
1014 base += ', algorithm="%s"' % algorithm
1015 if qop:
1016 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
1017 return base
1018
1019 def get_algorithm_impls(self, algorithm):
1020 # lambdas assume digest modules are imported at the top level
1021 if algorithm == 'MD5':
1022 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
1023 elif algorithm == 'SHA':
1024 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
1025 # XXX MD5-sess
1026 KD = lambda s, d: H("%s:%s" % (s, d))
1027 return H, KD
1028
1029 def get_entity_digest(self, data, chal):
1030 # XXX not implemented yet
1031 return None
1032
1033
1034class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1035 """An authentication protocol defined by RFC 2069
1036
1037 Digest authentication improves on basic authentication because it
1038 does not transmit passwords in the clear.
1039 """
1040
1041 auth_header = 'Authorization'
1042 handler_order = 490 # before Basic auth
1043
1044 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001045 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001046 retry = self.http_error_auth_reqed('www-authenticate',
1047 host, req, headers)
1048 self.reset_retry_count()
1049 return retry
1050
1051
1052class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1053
1054 auth_header = 'Proxy-Authorization'
1055 handler_order = 490 # before Basic auth
1056
1057 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001058 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001059 retry = self.http_error_auth_reqed('proxy-authenticate',
1060 host, req, headers)
1061 self.reset_retry_count()
1062 return retry
1063
1064class AbstractHTTPHandler(BaseHandler):
1065
1066 def __init__(self, debuglevel=0):
1067 self._debuglevel = debuglevel
1068
1069 def set_http_debuglevel(self, level):
1070 self._debuglevel = level
1071
1072 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001073 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001074 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001075 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001076
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001077 if request.data is not None: # POST
1078 data = request.data
Senthil Kumaran29333122011-02-11 11:25:47 +00001079 if isinstance(data, str):
1080 raise TypeError("POST data should be bytes"
1081 " or an iterable of bytes. It cannot be str.")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001082 if not request.has_header('Content-type'):
1083 request.add_unredirected_header(
1084 'Content-type',
1085 'application/x-www-form-urlencoded')
1086 if not request.has_header('Content-length'):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001087 try:
1088 mv = memoryview(data)
1089 except TypeError:
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001090 if isinstance(data, collections.Iterable):
Georg Brandl61536042011-02-03 07:46:41 +00001091 raise ValueError("Content-Length should be specified "
1092 "for iterable data of type %r %r" % (type(data),
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001093 data))
1094 else:
1095 request.add_unredirected_header(
Senthil Kumaran1e991f22010-12-24 04:03:59 +00001096 'Content-length', '%d' % (len(mv) * mv.itemsize))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001097
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001098 sel_host = host
1099 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001100 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001101 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001102 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001103 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001104 for name, value in self.parent.addheaders:
1105 name = name.capitalize()
1106 if not request.has_header(name):
1107 request.add_unredirected_header(name, value)
1108
1109 return request
1110
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001111 def do_open(self, http_class, req, **http_conn_args):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001112 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001113
1114 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001115 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001116 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001117 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001118 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001119
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001120 # will parse host:port
1121 h = http_class(host, timeout=req.timeout, **http_conn_args)
Senthil Kumaran42ef4b12010-09-27 01:26:03 +00001122
1123 headers = dict(req.unredirected_hdrs)
1124 headers.update(dict((k, v) for k, v in req.headers.items()
1125 if k not in headers))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001126
1127 # TODO(jhylton): Should this be redesigned to handle
1128 # persistent connections?
1129
1130 # We want to make an HTTP/1.1 request, but the addinfourl
1131 # class isn't prepared to deal with a persistent connection.
1132 # It will try to read all remaining data from the socket,
1133 # which will block while the server waits for the next request.
1134 # So make sure the connection gets closed after the (only)
1135 # request.
1136 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001137 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001138
1139 if req._tunnel_host:
Senthil Kumaran47fff872009-12-20 07:10:31 +00001140 tunnel_headers = {}
1141 proxy_auth_hdr = "Proxy-Authorization"
1142 if proxy_auth_hdr in headers:
1143 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1144 # Proxy-Authorization should not be sent to origin
1145 # server.
1146 del headers[proxy_auth_hdr]
1147 h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001148
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001149 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001150 h.request(req.get_method(), req.selector, req.data, headers)
Senthil Kumaran1299a8f2011-07-27 08:05:58 +08001151 except socket.error as err: # timeout error
Senthil Kumaran45686b42011-07-27 09:31:03 +08001152 h.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001153 raise URLError(err)
Senthil Kumaran45686b42011-07-27 09:31:03 +08001154 else:
1155 r = h.getresponse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001156
Senthil Kumaran26430412011-04-13 07:01:19 +08001157 r.url = req.get_full_url()
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001158 # This line replaces the .msg attribute of the HTTPResponse
1159 # with .headers, because urllib clients expect the response to
1160 # have the reason in .msg. It would be good to mark this
1161 # attribute is deprecated and get then to use info() or
1162 # .headers.
1163 r.msg = r.reason
1164 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001165
1166
1167class HTTPHandler(AbstractHTTPHandler):
1168
1169 def http_open(self, req):
1170 return self.do_open(http.client.HTTPConnection, req)
1171
1172 http_request = AbstractHTTPHandler.do_request_
1173
1174if hasattr(http.client, 'HTTPSConnection'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001175 import ssl
1176
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001177 class HTTPSHandler(AbstractHTTPHandler):
1178
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001179 def __init__(self, debuglevel=0, context=None, check_hostname=None):
1180 AbstractHTTPHandler.__init__(self, debuglevel)
1181 self._context = context
1182 self._check_hostname = check_hostname
1183
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001184 def https_open(self, req):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001185 return self.do_open(http.client.HTTPSConnection, req,
1186 context=self._context, check_hostname=self._check_hostname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001187
1188 https_request = AbstractHTTPHandler.do_request_
1189
1190class HTTPCookieProcessor(BaseHandler):
1191 def __init__(self, cookiejar=None):
1192 import http.cookiejar
1193 if cookiejar is None:
1194 cookiejar = http.cookiejar.CookieJar()
1195 self.cookiejar = cookiejar
1196
1197 def http_request(self, request):
1198 self.cookiejar.add_cookie_header(request)
1199 return request
1200
1201 def http_response(self, request, response):
1202 self.cookiejar.extract_cookies(response, request)
1203 return response
1204
1205 https_request = http_request
1206 https_response = http_response
1207
1208class UnknownHandler(BaseHandler):
1209 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001210 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001211 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001212
1213def parse_keqv_list(l):
1214 """Parse list of key=value strings where keys are not duplicated."""
1215 parsed = {}
1216 for elt in l:
1217 k, v = elt.split('=', 1)
1218 if v[0] == '"' and v[-1] == '"':
1219 v = v[1:-1]
1220 parsed[k] = v
1221 return parsed
1222
1223def parse_http_list(s):
1224 """Parse lists as described by RFC 2068 Section 2.
1225
1226 In particular, parse comma-separated lists where the elements of
1227 the list may include quoted-strings. A quoted-string could
1228 contain a comma. A non-quoted string could have quotes in the
1229 middle. Neither commas nor quotes count if they are escaped.
1230 Only double-quotes count, not single-quotes.
1231 """
1232 res = []
1233 part = ''
1234
1235 escape = quote = False
1236 for cur in s:
1237 if escape:
1238 part += cur
1239 escape = False
1240 continue
1241 if quote:
1242 if cur == '\\':
1243 escape = True
1244 continue
1245 elif cur == '"':
1246 quote = False
1247 part += cur
1248 continue
1249
1250 if cur == ',':
1251 res.append(part)
1252 part = ''
1253 continue
1254
1255 if cur == '"':
1256 quote = True
1257
1258 part += cur
1259
1260 # append last part
1261 if part:
1262 res.append(part)
1263
1264 return [part.strip() for part in res]
1265
1266class FileHandler(BaseHandler):
1267 # Use local file or FTP depending on form of URL
1268 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001269 url = req.selector
Senthil Kumaran2ef16322010-07-11 03:12:43 +00001270 if url[:2] == '//' and url[2:3] != '/' and (req.host and
1271 req.host != 'localhost'):
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001272 if not req.host is self.get_names():
1273 raise URLError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001274 else:
1275 return self.open_local_file(req)
1276
1277 # names for the localhost
1278 names = None
1279 def get_names(self):
1280 if FileHandler.names is None:
1281 try:
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001282 FileHandler.names = tuple(
1283 socket.gethostbyname_ex('localhost')[2] +
1284 socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001285 except socket.gaierror:
1286 FileHandler.names = (socket.gethostbyname('localhost'),)
1287 return FileHandler.names
1288
1289 # not entirely sure what the rules are here
1290 def open_local_file(self, req):
1291 import email.utils
1292 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001293 host = req.host
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001294 filename = req.selector
1295 localfile = url2pathname(filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001296 try:
1297 stats = os.stat(localfile)
1298 size = stats.st_size
1299 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001300 mtype = mimetypes.guess_type(filename)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001301 headers = email.message_from_string(
1302 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1303 (mtype or 'text/plain', size, modified))
1304 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001305 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001306 if not host or \
1307 (not port and _safe_gethostbyname(host) in self.get_names()):
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001308 if host:
1309 origurl = 'file://' + host + filename
1310 else:
1311 origurl = 'file://' + filename
1312 return addinfourl(open(localfile, 'rb'), headers, origurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001313 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001314 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001315 raise URLError(msg)
1316 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001317
1318def _safe_gethostbyname(host):
1319 try:
1320 return socket.gethostbyname(host)
1321 except socket.gaierror:
1322 return None
1323
1324class FTPHandler(BaseHandler):
1325 def ftp_open(self, req):
1326 import ftplib
1327 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001328 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001329 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001330 raise URLError('ftp error: no host given')
1331 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001332 if port is None:
1333 port = ftplib.FTP_PORT
1334 else:
1335 port = int(port)
1336
1337 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001338 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001339 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001340 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001341 else:
1342 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001343 host = unquote(host)
Senthil Kumarandaa29d02010-11-18 15:36:41 +00001344 user = user or ''
1345 passwd = passwd or ''
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001346
1347 try:
1348 host = socket.gethostbyname(host)
1349 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001350 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001351 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001352 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001353 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001354 dirs, file = dirs[:-1], dirs[-1]
1355 if dirs and not dirs[0]:
1356 dirs = dirs[1:]
1357 try:
1358 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1359 type = file and 'I' or 'D'
1360 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001361 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001362 if attr.lower() == 'type' and \
1363 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1364 type = value.upper()
1365 fp, retrlen = fw.retrfile(file, type)
1366 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001367 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001368 if mtype:
1369 headers += "Content-type: %s\n" % mtype
1370 if retrlen is not None and retrlen >= 0:
1371 headers += "Content-length: %d\n" % retrlen
1372 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001373 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001374 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001375 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001376 raise exc.with_traceback(sys.exc_info()[2])
1377
1378 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001379 return ftpwrapper(user, passwd, host, port, dirs, timeout,
1380 persistent=False)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001381
1382class CacheFTPHandler(FTPHandler):
1383 # XXX would be nice to have pluggable cache strategies
1384 # XXX this stuff is definitely not thread safe
1385 def __init__(self):
1386 self.cache = {}
1387 self.timeout = {}
1388 self.soonest = 0
1389 self.delay = 60
1390 self.max_conns = 16
1391
1392 def setTimeout(self, t):
1393 self.delay = t
1394
1395 def setMaxConns(self, m):
1396 self.max_conns = m
1397
1398 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1399 key = user, host, port, '/'.join(dirs), timeout
1400 if key in self.cache:
1401 self.timeout[key] = time.time() + self.delay
1402 else:
1403 self.cache[key] = ftpwrapper(user, passwd, host, port,
1404 dirs, timeout)
1405 self.timeout[key] = time.time() + self.delay
1406 self.check_cache()
1407 return self.cache[key]
1408
1409 def check_cache(self):
1410 # first check for old ones
1411 t = time.time()
1412 if self.soonest <= t:
1413 for k, v in list(self.timeout.items()):
1414 if v < t:
1415 self.cache[k].close()
1416 del self.cache[k]
1417 del self.timeout[k]
1418 self.soonest = min(list(self.timeout.values()))
1419
1420 # then check the size
1421 if len(self.cache) == self.max_conns:
1422 for k, v in list(self.timeout.items()):
1423 if v == self.soonest:
1424 del self.cache[k]
1425 del self.timeout[k]
1426 break
1427 self.soonest = min(list(self.timeout.values()))
1428
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02001429 def clear_cache(self):
1430 for conn in self.cache.values():
1431 conn.close()
1432 self.cache.clear()
1433 self.timeout.clear()
1434
1435
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001436# Code move from the old urllib module
1437
1438MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1439
1440# Helper for non-unix systems
Ronald Oussoren94f25282010-05-05 19:11:21 +00001441if os.name == 'nt':
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001442 from nturl2path import url2pathname, pathname2url
1443else:
1444 def url2pathname(pathname):
1445 """OS-specific conversion from a relative URL of the 'file' scheme
1446 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001447 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001448
1449 def pathname2url(pathname):
1450 """OS-specific conversion from a file system path to a relative URL
1451 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001452 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001453
1454# This really consists of two pieces:
1455# (1) a class which handles opening of all sorts of URLs
1456# (plus assorted utilities etc.)
1457# (2) a set of functions for parsing URLs
1458# XXX Should these be separated out into different modules?
1459
1460
1461ftpcache = {}
1462class URLopener:
1463 """Class to open URLs.
1464 This is a class rather than just a subroutine because we may need
1465 more than one set of global protocol-specific options.
1466 Note -- this is a base class for those who don't want the
1467 automatic handling of errors type 302 (relocated) and 401
1468 (authorization needed)."""
1469
1470 __tempfiles = None
1471
1472 version = "Python-urllib/%s" % __version__
1473
1474 # Constructor
1475 def __init__(self, proxies=None, **x509):
1476 if proxies is None:
1477 proxies = getproxies()
1478 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1479 self.proxies = proxies
1480 self.key_file = x509.get('key_file')
1481 self.cert_file = x509.get('cert_file')
1482 self.addheaders = [('User-Agent', self.version)]
1483 self.__tempfiles = []
1484 self.__unlink = os.unlink # See cleanup()
1485 self.tempcache = None
1486 # Undocumented feature: if you assign {} to tempcache,
1487 # it is used to cache files retrieved with
1488 # self.retrieve(). This is not enabled by default
1489 # since it does not work for changing documents (and I
1490 # haven't got the logic to check expiration headers
1491 # yet).
1492 self.ftpcache = ftpcache
1493 # Undocumented feature: you can use a different
1494 # ftp cache by assigning to the .ftpcache member;
1495 # in case you want logically independent URL openers
1496 # XXX This is not threadsafe. Bah.
1497
1498 def __del__(self):
1499 self.close()
1500
1501 def close(self):
1502 self.cleanup()
1503
1504 def cleanup(self):
1505 # This code sometimes runs when the rest of this module
1506 # has already been deleted, so it can't use any globals
1507 # or import anything.
1508 if self.__tempfiles:
1509 for file in self.__tempfiles:
1510 try:
1511 self.__unlink(file)
1512 except OSError:
1513 pass
1514 del self.__tempfiles[:]
1515 if self.tempcache:
1516 self.tempcache.clear()
1517
1518 def addheader(self, *args):
1519 """Add a header to be used by the HTTP interface only
1520 e.g. u.addheader('Accept', 'sound/basic')"""
1521 self.addheaders.append(args)
1522
1523 # External interface
1524 def open(self, fullurl, data=None):
1525 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001526 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran734f0592010-02-20 22:19:04 +00001527 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001528 if self.tempcache and fullurl in self.tempcache:
1529 filename, headers = self.tempcache[fullurl]
1530 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001531 return addinfourl(fp, headers, fullurl)
1532 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001533 if not urltype:
1534 urltype = 'file'
1535 if urltype in self.proxies:
1536 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001537 urltype, proxyhost = splittype(proxy)
1538 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001539 url = (host, fullurl) # Signal special case to open_*()
1540 else:
1541 proxy = None
1542 name = 'open_' + urltype
1543 self.type = urltype
1544 name = name.replace('-', '_')
1545 if not hasattr(self, name):
1546 if proxy:
1547 return self.open_unknown_proxy(proxy, fullurl, data)
1548 else:
1549 return self.open_unknown(fullurl, data)
1550 try:
1551 if data is None:
1552 return getattr(self, name)(url)
1553 else:
1554 return getattr(self, name)(url, data)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001555 except HTTPError:
1556 raise
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001557 except socket.error as msg:
1558 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1559
1560 def open_unknown(self, fullurl, data=None):
1561 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001562 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001563 raise IOError('url error', 'unknown url type', type)
1564
1565 def open_unknown_proxy(self, proxy, fullurl, data=None):
1566 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001567 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001568 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1569
1570 # External interface
1571 def retrieve(self, url, filename=None, reporthook=None, data=None):
1572 """retrieve(url) returns (filename, headers) for a local object
1573 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001574 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001575 if self.tempcache and url in self.tempcache:
1576 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001577 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001578 if filename is None and (not type or type == 'file'):
1579 try:
1580 fp = self.open_local_file(url1)
1581 hdrs = fp.info()
Philip Jenveycb134d72009-12-03 02:45:01 +00001582 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001583 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001584 except IOError as msg:
1585 pass
1586 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001587 try:
1588 headers = fp.info()
1589 if filename:
1590 tfp = open(filename, 'wb')
1591 else:
1592 import tempfile
1593 garbage, path = splittype(url)
1594 garbage, path = splithost(path or "")
1595 path, garbage = splitquery(path or "")
1596 path, garbage = splitattr(path or "")
1597 suffix = os.path.splitext(path)[1]
1598 (fd, filename) = tempfile.mkstemp(suffix)
1599 self.__tempfiles.append(filename)
1600 tfp = os.fdopen(fd, 'wb')
1601 try:
1602 result = filename, headers
1603 if self.tempcache is not None:
1604 self.tempcache[url] = result
1605 bs = 1024*8
1606 size = -1
1607 read = 0
1608 blocknum = 0
1609 if reporthook:
1610 if "content-length" in headers:
1611 size = int(headers["Content-Length"])
1612 reporthook(blocknum, bs, size)
1613 while 1:
1614 block = fp.read(bs)
1615 if not block:
1616 break
1617 read += len(block)
1618 tfp.write(block)
1619 blocknum += 1
1620 if reporthook:
1621 reporthook(blocknum, bs, size)
1622 finally:
1623 tfp.close()
1624 finally:
1625 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001626
1627 # raise exception if actual size does not match content-length header
1628 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001629 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001630 "retrieval incomplete: got only %i out of %i bytes"
1631 % (read, size), result)
1632
1633 return result
1634
1635 # Each method named open_<type> knows how to open that type of URL
1636
1637 def _open_generic_http(self, connection_factory, url, data):
1638 """Make an HTTP connection using connection_class.
1639
1640 This is an internal method that should be called from
1641 open_http() or open_https().
1642
1643 Arguments:
1644 - connection_factory should take a host name and return an
1645 HTTPConnection instance.
1646 - url is the url to retrieval or a host, relative-path pair.
1647 - data is payload for a POST request or None.
1648 """
1649
1650 user_passwd = None
1651 proxy_passwd= None
1652 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001653 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001654 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001655 user_passwd, host = splituser(host)
1656 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001657 realhost = host
1658 else:
1659 host, selector = url
1660 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001661 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001662 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001663 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001664 url = rest
1665 user_passwd = None
1666 if urltype.lower() != 'http':
1667 realhost = None
1668 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001669 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001670 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001671 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001672 if user_passwd:
1673 selector = "%s://%s%s" % (urltype, realhost, rest)
1674 if proxy_bypass(realhost):
1675 host = realhost
1676
1677 #print "proxy via http:", host, selector
1678 if not host: raise IOError('http error', 'no host given')
1679
1680 if proxy_passwd:
1681 import base64
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001682 proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001683 else:
1684 proxy_auth = None
1685
1686 if user_passwd:
1687 import base64
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001688 auth = base64.b64encode(user_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001689 else:
1690 auth = None
1691 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001692 headers = {}
1693 if proxy_auth:
1694 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1695 if auth:
1696 headers["Authorization"] = "Basic %s" % auth
1697 if realhost:
1698 headers["Host"] = realhost
Senthil Kumarand91ffca2011-03-19 17:25:27 +08001699
1700 # Add Connection:close as we don't support persistent connections yet.
1701 # This helps in closing the socket and avoiding ResourceWarning
1702
1703 headers["Connection"] = "close"
1704
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001705 for header, value in self.addheaders:
1706 headers[header] = value
1707
1708 if data is not None:
1709 headers["Content-Type"] = "application/x-www-form-urlencoded"
1710 http_conn.request("POST", selector, data, headers)
1711 else:
1712 http_conn.request("GET", selector, headers=headers)
1713
1714 try:
1715 response = http_conn.getresponse()
1716 except http.client.BadStatusLine:
1717 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001718 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001719
1720 # According to RFC 2616, "2xx" code indicates that the client's
1721 # request was successfully received, understood, and accepted.
1722 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001723 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001724 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001725 else:
1726 return self.http_error(
1727 url, response.fp,
1728 response.status, response.reason, response.msg, data)
1729
1730 def open_http(self, url, data=None):
1731 """Use HTTP protocol."""
1732 return self._open_generic_http(http.client.HTTPConnection, url, data)
1733
1734 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1735 """Handle http errors.
1736
1737 Derived class can override this, or provide specific handlers
1738 named http_error_DDD where DDD is the 3-digit error code."""
1739 # First check if there's a specific handler for this error
1740 name = 'http_error_%d' % errcode
1741 if hasattr(self, name):
1742 method = getattr(self, name)
1743 if data is None:
1744 result = method(url, fp, errcode, errmsg, headers)
1745 else:
1746 result = method(url, fp, errcode, errmsg, headers, data)
1747 if result: return result
1748 return self.http_error_default(url, fp, errcode, errmsg, headers)
1749
1750 def http_error_default(self, url, fp, errcode, errmsg, headers):
1751 """Default error handler: close the connection and raise IOError."""
1752 void = fp.read()
1753 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001754 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001755
1756 if _have_ssl:
1757 def _https_connection(self, host):
1758 return http.client.HTTPSConnection(host,
1759 key_file=self.key_file,
1760 cert_file=self.cert_file)
1761
1762 def open_https(self, url, data=None):
1763 """Use HTTPS protocol."""
1764 return self._open_generic_http(self._https_connection, url, data)
1765
1766 def open_file(self, url):
1767 """Use local file or FTP depending on form of URL."""
1768 if not isinstance(url, str):
1769 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1770 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Senthil Kumaran383c32d2010-10-14 11:57:35 +00001771 raise ValueError("file:// scheme is supported only on localhost")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001772 else:
1773 return self.open_local_file(url)
1774
1775 def open_local_file(self, url):
1776 """Use local file."""
1777 import mimetypes, email.utils
1778 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001779 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001780 localname = url2pathname(file)
1781 try:
1782 stats = os.stat(localname)
1783 except OSError as e:
1784 raise URLError(e.errno, e.strerror, e.filename)
1785 size = stats.st_size
1786 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1787 mtype = mimetypes.guess_type(url)[0]
1788 headers = email.message_from_string(
1789 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1790 (mtype or 'text/plain', size, modified))
1791 if not host:
1792 urlfile = file
1793 if file[:1] == '/':
1794 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001795 return addinfourl(open(localname, 'rb'), headers, urlfile)
1796 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001797 if (not port
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001798 and socket.gethostbyname(host) in (localhost() + thishost())):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001799 urlfile = file
1800 if file[:1] == '/':
1801 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001802 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001803 raise URLError('local file error', 'not on local host')
1804
1805 def open_ftp(self, url):
1806 """Use FTP protocol."""
1807 if not isinstance(url, str):
1808 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1809 import mimetypes
1810 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001811 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001812 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001813 host, port = splitport(host)
1814 user, host = splituser(host)
1815 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001816 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001817 host = unquote(host)
1818 user = unquote(user or '')
1819 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001820 host = socket.gethostbyname(host)
1821 if not port:
1822 import ftplib
1823 port = ftplib.FTP_PORT
1824 else:
1825 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001826 path, attrs = splitattr(path)
1827 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001828 dirs = path.split('/')
1829 dirs, file = dirs[:-1], dirs[-1]
1830 if dirs and not dirs[0]: dirs = dirs[1:]
1831 if dirs and not dirs[0]: dirs[0] = '/'
1832 key = user, host, port, '/'.join(dirs)
1833 # XXX thread unsafe!
1834 if len(self.ftpcache) > MAXFTPCACHE:
1835 # Prune the cache, rather arbitrarily
1836 for k in self.ftpcache.keys():
1837 if k != key:
1838 v = self.ftpcache[k]
1839 del self.ftpcache[k]
1840 v.close()
1841 try:
1842 if not key in self.ftpcache:
1843 self.ftpcache[key] = \
1844 ftpwrapper(user, passwd, host, port, dirs)
1845 if not file: type = 'D'
1846 else: type = 'I'
1847 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001848 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001849 if attr.lower() == 'type' and \
1850 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1851 type = value.upper()
1852 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1853 mtype = mimetypes.guess_type("ftp:" + url)[0]
1854 headers = ""
1855 if mtype:
1856 headers += "Content-Type: %s\n" % mtype
1857 if retrlen is not None and retrlen >= 0:
1858 headers += "Content-Length: %d\n" % retrlen
1859 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001860 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001861 except ftperrors() as msg:
1862 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1863
1864 def open_data(self, url, data=None):
1865 """Use "data" URL."""
1866 if not isinstance(url, str):
1867 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1868 # ignore POSTed data
1869 #
1870 # syntax of data URLs:
1871 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1872 # mediatype := [ type "/" subtype ] *( ";" parameter )
1873 # data := *urlchar
1874 # parameter := attribute "=" value
1875 try:
1876 [type, data] = url.split(',', 1)
1877 except ValueError:
1878 raise IOError('data error', 'bad data URL')
1879 if not type:
1880 type = 'text/plain;charset=US-ASCII'
1881 semi = type.rfind(';')
1882 if semi >= 0 and '=' not in type[semi:]:
1883 encoding = type[semi+1:]
1884 type = type[:semi]
1885 else:
1886 encoding = ''
1887 msg = []
Senthil Kumaranf6c456d2010-05-01 08:29:18 +00001888 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001889 time.gmtime(time.time())))
1890 msg.append('Content-type: %s' % type)
1891 if encoding == 'base64':
1892 import base64
Georg Brandl706824f2009-06-04 09:42:55 +00001893 # XXX is this encoding/decoding ok?
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001894 data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001895 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001896 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001897 msg.append('Content-Length: %d' % len(data))
1898 msg.append('')
1899 msg.append(data)
1900 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001901 headers = email.message_from_string(msg)
1902 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001903 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001904 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001905
1906
1907class FancyURLopener(URLopener):
1908 """Derived class with handlers for errors we can handle (perhaps)."""
1909
1910 def __init__(self, *args, **kwargs):
1911 URLopener.__init__(self, *args, **kwargs)
1912 self.auth_cache = {}
1913 self.tries = 0
1914 self.maxtries = 10
1915
1916 def http_error_default(self, url, fp, errcode, errmsg, headers):
1917 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001918 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001919
1920 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1921 """Error 302 -- relocated (temporarily)."""
1922 self.tries += 1
1923 if self.maxtries and self.tries >= self.maxtries:
1924 if hasattr(self, "http_error_500"):
1925 meth = self.http_error_500
1926 else:
1927 meth = self.http_error_default
1928 self.tries = 0
1929 return meth(url, fp, 500,
1930 "Internal Server Error: Redirect Recursion", headers)
1931 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
1932 data)
1933 self.tries = 0
1934 return result
1935
1936 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
1937 if 'location' in headers:
1938 newurl = headers['location']
1939 elif 'uri' in headers:
1940 newurl = headers['uri']
1941 else:
1942 return
1943 void = fp.read()
1944 fp.close()
guido@google.coma119df92011-03-29 11:41:02 -07001945
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001946 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00001947 newurl = urljoin(self.type + ":" + url, newurl)
guido@google.coma119df92011-03-29 11:41:02 -07001948
1949 urlparts = urlparse(newurl)
1950
1951 # For security reasons, we don't allow redirection to anything other
1952 # than http, https and ftp.
1953
1954 # We are using newer HTTPError with older redirect_internal method
1955 # This older method will get deprecated in 3.3
1956
1957 if not urlparts.scheme in ('http', 'https', 'ftp'):
1958 raise HTTPError(newurl, errcode,
1959 errmsg +
1960 " Redirection to url '%s' is not allowed." % newurl,
1961 headers, fp)
1962
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001963 return self.open(newurl)
1964
1965 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
1966 """Error 301 -- also relocated (permanently)."""
1967 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1968
1969 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
1970 """Error 303 -- also relocated (essentially identical to 302)."""
1971 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1972
1973 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
1974 """Error 307 -- relocated, but turn POST into error."""
1975 if data is None:
1976 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1977 else:
1978 return self.http_error_default(url, fp, errcode, errmsg, headers)
1979
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001980 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
1981 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001982 """Error 401 -- authentication required.
1983 This function supports Basic authentication only."""
1984 if not 'www-authenticate' in headers:
1985 URLopener.http_error_default(self, url, fp,
1986 errcode, errmsg, headers)
1987 stuff = headers['www-authenticate']
1988 import re
1989 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1990 if not match:
1991 URLopener.http_error_default(self, url, fp,
1992 errcode, errmsg, headers)
1993 scheme, realm = match.groups()
1994 if scheme.lower() != 'basic':
1995 URLopener.http_error_default(self, url, fp,
1996 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001997 if not retry:
1998 URLopener.http_error_default(self, url, fp, errcode, errmsg,
1999 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002000 name = 'retry_' + self.type + '_basic_auth'
2001 if data is None:
2002 return getattr(self,name)(url, realm)
2003 else:
2004 return getattr(self,name)(url, realm, data)
2005
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002006 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
2007 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002008 """Error 407 -- proxy authentication required.
2009 This function supports Basic authentication only."""
2010 if not 'proxy-authenticate' in headers:
2011 URLopener.http_error_default(self, url, fp,
2012 errcode, errmsg, headers)
2013 stuff = headers['proxy-authenticate']
2014 import re
2015 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2016 if not match:
2017 URLopener.http_error_default(self, url, fp,
2018 errcode, errmsg, headers)
2019 scheme, realm = match.groups()
2020 if scheme.lower() != 'basic':
2021 URLopener.http_error_default(self, url, fp,
2022 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00002023 if not retry:
2024 URLopener.http_error_default(self, url, fp, errcode, errmsg,
2025 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002026 name = 'retry_proxy_' + self.type + '_basic_auth'
2027 if data is None:
2028 return getattr(self,name)(url, realm)
2029 else:
2030 return getattr(self,name)(url, realm, data)
2031
2032 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002033 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002034 newurl = 'http://' + host + selector
2035 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00002036 urltype, proxyhost = splittype(proxy)
2037 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002038 i = proxyhost.find('@') + 1
2039 proxyhost = proxyhost[i:]
2040 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2041 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002042 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002043 quote(passwd, safe=''), proxyhost)
2044 self.proxies['http'] = 'http://' + proxyhost + proxyselector
2045 if data is None:
2046 return self.open(newurl)
2047 else:
2048 return self.open(newurl, data)
2049
2050 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002051 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002052 newurl = 'https://' + host + selector
2053 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00002054 urltype, proxyhost = splittype(proxy)
2055 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002056 i = proxyhost.find('@') + 1
2057 proxyhost = proxyhost[i:]
2058 user, passwd = self.get_user_passwd(proxyhost, realm, i)
2059 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002060 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002061 quote(passwd, safe=''), proxyhost)
2062 self.proxies['https'] = 'https://' + proxyhost + proxyselector
2063 if data is None:
2064 return self.open(newurl)
2065 else:
2066 return self.open(newurl, data)
2067
2068 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002069 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002070 i = host.find('@') + 1
2071 host = host[i:]
2072 user, passwd = self.get_user_passwd(host, realm, i)
2073 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002074 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002075 quote(passwd, safe=''), host)
2076 newurl = 'http://' + host + selector
2077 if data is None:
2078 return self.open(newurl)
2079 else:
2080 return self.open(newurl, data)
2081
2082 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00002083 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002084 i = host.find('@') + 1
2085 host = host[i:]
2086 user, passwd = self.get_user_passwd(host, realm, i)
2087 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00002088 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002089 quote(passwd, safe=''), host)
2090 newurl = 'https://' + host + selector
2091 if data is None:
2092 return self.open(newurl)
2093 else:
2094 return self.open(newurl, data)
2095
Florent Xicluna757445b2010-05-17 17:24:07 +00002096 def get_user_passwd(self, host, realm, clear_cache=0):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002097 key = realm + '@' + host.lower()
2098 if key in self.auth_cache:
2099 if clear_cache:
2100 del self.auth_cache[key]
2101 else:
2102 return self.auth_cache[key]
2103 user, passwd = self.prompt_user_passwd(host, realm)
2104 if user or passwd: self.auth_cache[key] = (user, passwd)
2105 return user, passwd
2106
2107 def prompt_user_passwd(self, host, realm):
2108 """Override this in a GUI environment!"""
2109 import getpass
2110 try:
2111 user = input("Enter username for %s at %s: " % (realm, host))
2112 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
2113 (user, realm, host))
2114 return user, passwd
2115 except KeyboardInterrupt:
2116 print()
2117 return None, None
2118
2119
2120# Utility functions
2121
2122_localhost = None
2123def localhost():
2124 """Return the IP address of the magic hostname 'localhost'."""
2125 global _localhost
2126 if _localhost is None:
2127 _localhost = socket.gethostbyname('localhost')
2128 return _localhost
2129
2130_thishost = None
2131def thishost():
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00002132 """Return the IP addresses of the current host."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002133 global _thishost
2134 if _thishost is None:
Senthil Kumaran1b7da512011-10-06 00:32:02 +08002135 _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002136 return _thishost
2137
2138_ftperrors = None
2139def ftperrors():
2140 """Return the set of errors raised by the FTP class."""
2141 global _ftperrors
2142 if _ftperrors is None:
2143 import ftplib
2144 _ftperrors = ftplib.all_errors
2145 return _ftperrors
2146
2147_noheaders = None
2148def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002149 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002150 global _noheaders
2151 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002152 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002153 return _noheaders
2154
2155
2156# Utility classes
2157
2158class ftpwrapper:
2159 """Class used by open_ftp() for cache of open FTP connections."""
2160
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002161 def __init__(self, user, passwd, host, port, dirs, timeout=None,
2162 persistent=True):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002163 self.user = user
2164 self.passwd = passwd
2165 self.host = host
2166 self.port = port
2167 self.dirs = dirs
2168 self.timeout = timeout
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002169 self.refcount = 0
2170 self.keepalive = persistent
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002171 self.init()
2172
2173 def init(self):
2174 import ftplib
2175 self.busy = 0
2176 self.ftp = ftplib.FTP()
2177 self.ftp.connect(self.host, self.port, self.timeout)
2178 self.ftp.login(self.user, self.passwd)
2179 for dir in self.dirs:
2180 self.ftp.cwd(dir)
2181
2182 def retrfile(self, file, type):
2183 import ftplib
2184 self.endtransfer()
2185 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2186 else: cmd = 'TYPE ' + type; isdir = 0
2187 try:
2188 self.ftp.voidcmd(cmd)
2189 except ftplib.all_errors:
2190 self.init()
2191 self.ftp.voidcmd(cmd)
2192 conn = None
2193 if file and not isdir:
2194 # Try to retrieve as a file
2195 try:
2196 cmd = 'RETR ' + file
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002197 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002198 except ftplib.error_perm as reason:
2199 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002200 raise URLError('ftp error', reason).with_traceback(
2201 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002202 if not conn:
2203 # Set transfer mode to ASCII!
2204 self.ftp.voidcmd('TYPE A')
2205 # Try a directory listing. Verify that directory exists.
2206 if file:
2207 pwd = self.ftp.pwd()
2208 try:
2209 try:
2210 self.ftp.cwd(file)
2211 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002212 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002213 finally:
2214 self.ftp.cwd(pwd)
2215 cmd = 'LIST ' + file
2216 else:
2217 cmd = 'LIST'
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002218 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002219 self.busy = 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002220
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002221 ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
2222 self.refcount += 1
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002223 conn.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002224 # Pass back both a suitably decorated object and a retrieval length
Senthil Kumaran2024acd2011-03-24 11:46:19 +08002225 return (ftpobj, retrlen)
2226
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002227 def endtransfer(self):
2228 if not self.busy:
2229 return
2230 self.busy = 0
2231 try:
2232 self.ftp.voidresp()
2233 except ftperrors():
2234 pass
2235
2236 def close(self):
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +02002237 self.keepalive = False
2238 if self.refcount <= 0:
2239 self.real_close()
2240
2241 def file_close(self):
2242 self.endtransfer()
2243 self.refcount -= 1
2244 if self.refcount <= 0 and not self.keepalive:
2245 self.real_close()
2246
2247 def real_close(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002248 self.endtransfer()
2249 try:
2250 self.ftp.close()
2251 except ftperrors():
2252 pass
2253
2254# Proxy handling
2255def getproxies_environment():
2256 """Return a dictionary of scheme -> proxy server URL mappings.
2257
2258 Scan the environment for variables named <scheme>_proxy;
2259 this seems to be the standard convention. If you need a
2260 different way, you can pass a proxies dictionary to the
2261 [Fancy]URLopener constructor.
2262
2263 """
2264 proxies = {}
2265 for name, value in os.environ.items():
2266 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002267 if value and name[-6:] == '_proxy':
2268 proxies[name[:-6]] = value
2269 return proxies
2270
2271def proxy_bypass_environment(host):
2272 """Test if proxies should not be used for a particular host.
2273
2274 Checks the environment for a variable named no_proxy, which should
2275 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2276 """
2277 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2278 # '*' is special case for always bypass
2279 if no_proxy == '*':
2280 return 1
2281 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002282 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002283 # check if the host ends with any of the DNS suffixes
Senthil Kumaran89976f12011-08-06 12:27:40 +08002284 no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
2285 for name in no_proxy_list:
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002286 if name and (hostonly.endswith(name) or host.endswith(name)):
2287 return 1
2288 # otherwise, don't bypass
2289 return 0
2290
2291
Ronald Oussorene72e1612011-03-14 18:15:25 -04002292# This code tests an OSX specific data structure but is testable on all
2293# platforms
2294def _proxy_bypass_macosx_sysconf(host, proxy_settings):
2295 """
2296 Return True iff this host shouldn't be accessed using a proxy
2297
2298 This function uses the MacOSX framework SystemConfiguration
2299 to fetch the proxy information.
2300
2301 proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
2302 { 'exclude_simple': bool,
2303 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
2304 }
2305 """
2306 import re
2307 import socket
2308 from fnmatch import fnmatch
2309
2310 hostonly, port = splitport(host)
2311
2312 def ip2num(ipAddr):
2313 parts = ipAddr.split('.')
2314 parts = list(map(int, parts))
2315 if len(parts) != 4:
2316 parts = (parts + [0, 0, 0, 0])[:4]
2317 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2318
2319 # Check for simple host names:
2320 if '.' not in host:
2321 if proxy_settings['exclude_simple']:
2322 return True
2323
2324 hostIP = None
2325
2326 for value in proxy_settings.get('exceptions', ()):
2327 # Items in the list are strings like these: *.local, 169.254/16
2328 if not value: continue
2329
2330 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2331 if m is not None:
2332 if hostIP is None:
2333 try:
2334 hostIP = socket.gethostbyname(hostonly)
2335 hostIP = ip2num(hostIP)
2336 except socket.error:
2337 continue
2338
2339 base = ip2num(m.group(1))
2340 mask = m.group(2)
2341 if mask is None:
2342 mask = 8 * (m.group(1).count('.') + 1)
2343 else:
2344 mask = int(mask[1:])
2345 mask = 32 - mask
2346
2347 if (hostIP >> mask) == (base >> mask):
2348 return True
2349
2350 elif fnmatch(host, value):
2351 return True
2352
2353 return False
2354
2355
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002356if sys.platform == 'darwin':
Ronald Oussoren84151202010-04-18 20:46:11 +00002357 from _scproxy import _get_proxy_settings, _get_proxies
2358
2359 def proxy_bypass_macosx_sysconf(host):
Ronald Oussoren84151202010-04-18 20:46:11 +00002360 proxy_settings = _get_proxy_settings()
Ronald Oussorene72e1612011-03-14 18:15:25 -04002361 return _proxy_bypass_macosx_sysconf(host, proxy_settings)
Ronald Oussoren84151202010-04-18 20:46:11 +00002362
2363 def getproxies_macosx_sysconf():
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002364 """Return a dictionary of scheme -> proxy server URL mappings.
2365
Ronald Oussoren84151202010-04-18 20:46:11 +00002366 This function uses the MacOSX framework SystemConfiguration
2367 to fetch the proxy information.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002368 """
Ronald Oussoren84151202010-04-18 20:46:11 +00002369 return _get_proxies()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002370
Ronald Oussoren84151202010-04-18 20:46:11 +00002371
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002372
2373 def proxy_bypass(host):
2374 if getproxies_environment():
2375 return proxy_bypass_environment(host)
2376 else:
Ronald Oussoren84151202010-04-18 20:46:11 +00002377 return proxy_bypass_macosx_sysconf(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002378
2379 def getproxies():
Ronald Oussoren84151202010-04-18 20:46:11 +00002380 return getproxies_environment() or getproxies_macosx_sysconf()
2381
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002382
2383elif os.name == 'nt':
2384 def getproxies_registry():
2385 """Return a dictionary of scheme -> proxy server URL mappings.
2386
2387 Win32 uses the registry to store proxies.
2388
2389 """
2390 proxies = {}
2391 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002392 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002393 except ImportError:
2394 # Std module, so should be around - but you never know!
2395 return proxies
2396 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002397 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002398 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002399 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002400 'ProxyEnable')[0]
2401 if proxyEnable:
2402 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002403 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002404 'ProxyServer')[0])
2405 if '=' in proxyServer:
2406 # Per-protocol settings
2407 for p in proxyServer.split(';'):
2408 protocol, address = p.split('=', 1)
2409 # See if address has a type:// prefix
2410 import re
2411 if not re.match('^([^/:]+)://', address):
2412 address = '%s://%s' % (protocol, address)
2413 proxies[protocol] = address
2414 else:
2415 # Use one setting for all protocols
2416 if proxyServer[:5] == 'http:':
2417 proxies['http'] = proxyServer
2418 else:
2419 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran04f31b82010-07-14 20:10:52 +00002420 proxies['https'] = 'https://%s' % proxyServer
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002421 proxies['ftp'] = 'ftp://%s' % proxyServer
2422 internetSettings.Close()
2423 except (WindowsError, ValueError, TypeError):
2424 # Either registry key not found etc, or the value in an
2425 # unexpected format.
2426 # proxies already set up to be empty so nothing to do
2427 pass
2428 return proxies
2429
2430 def getproxies():
2431 """Return a dictionary of scheme -> proxy server URL mappings.
2432
2433 Returns settings gathered from the environment, if specified,
2434 or the registry.
2435
2436 """
2437 return getproxies_environment() or getproxies_registry()
2438
2439 def proxy_bypass_registry(host):
2440 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002441 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002442 import re
2443 except ImportError:
2444 # Std modules, so should be around - but you never know!
2445 return 0
2446 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002447 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002448 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002449 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002450 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002451 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002452 'ProxyOverride')[0])
2453 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2454 except WindowsError:
2455 return 0
2456 if not proxyEnable or not proxyOverride:
2457 return 0
2458 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002459 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002460 host = [rawHost]
2461 try:
2462 addr = socket.gethostbyname(rawHost)
2463 if addr != rawHost:
2464 host.append(addr)
2465 except socket.error:
2466 pass
2467 try:
2468 fqdn = socket.getfqdn(rawHost)
2469 if fqdn != rawHost:
2470 host.append(fqdn)
2471 except socket.error:
2472 pass
2473 # make a check value list from the registry entry: replace the
2474 # '<local>' string by the localhost entry and the corresponding
2475 # canonical entry.
2476 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002477 # now check if we match one of the registry values.
2478 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002479 if test == '<local>':
2480 if '.' not in rawHost:
2481 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002482 test = test.replace(".", r"\.") # mask dots
2483 test = test.replace("*", r".*") # change glob sequence
2484 test = test.replace("?", r".") # change glob char
2485 for val in host:
2486 # print "%s <--> %s" %( test, val )
2487 if re.match(test, val, re.I):
2488 return 1
2489 return 0
2490
2491 def proxy_bypass(host):
2492 """Return a dictionary of scheme -> proxy server URL mappings.
2493
2494 Returns settings gathered from the environment, if specified,
2495 or the registry.
2496
2497 """
2498 if getproxies_environment():
2499 return proxy_bypass_environment(host)
2500 else:
2501 return proxy_bypass_registry(host)
2502
2503else:
2504 # By default use environment variables
2505 getproxies = getproxies_environment
2506 proxy_bypass = proxy_bypass_environment