blob: 68a8cabda1bea202efd3cfcff2a2abea255c10fa [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
Jeremy Hylton1afc1692008-06-18 20:49:58 +000097
Georg Brandl13e89462008-07-01 19:56:00 +000098from urllib.error import URLError, HTTPError, ContentTooShortError
99from urllib.parse import (
100 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
101 splittype, splithost, splitport, splituser, splitpasswd,
Senthil Kumarand95cc752010-08-08 11:27:53 +0000102 splitattr, splitquery, splitvalue, splittag, to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000103from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000104
105# check for SSL
106try:
107 import ssl
108except:
109 _have_ssl = False
110else:
111 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000112
113# used in User-Agent header sent
114__version__ = sys.version[:3]
115
116_opener = None
117def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
118 global _opener
119 if _opener is None:
120 _opener = build_opener()
121 return _opener.open(url, data, timeout)
122
123def install_opener(opener):
124 global _opener
125 _opener = opener
126
127# TODO(jhylton): Make this work with the same global opener.
128_urlopener = None
129def urlretrieve(url, filename=None, reporthook=None, data=None):
130 global _urlopener
131 if not _urlopener:
132 _urlopener = FancyURLopener()
133 return _urlopener.retrieve(url, filename, reporthook, data)
134
135def urlcleanup():
136 if _urlopener:
137 _urlopener.cleanup()
138 global _opener
139 if _opener:
140 _opener = None
141
142# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000143_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000144def request_host(request):
145 """Return request-host, as defined by RFC 2965.
146
147 Variation from RFC: returned value is lowercased, for convenient
148 comparison.
149
150 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000151 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000152 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000153 if host == "":
154 host = request.get_header("Host", "")
155
156 # remove port, if present
157 host = _cut_port_re.sub("", host, 1)
158 return host.lower()
159
160class Request:
161
162 def __init__(self, url, data=None, headers={},
163 origin_req_host=None, unverifiable=False):
164 # unwrap('<URL:type://host/path>') --> 'type://host/path'
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000165 self.full_url = unwrap(url)
Senthil Kumarand95cc752010-08-08 11:27:53 +0000166 self.full_url, fragment = splittag(self.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000167 self.data = data
168 self.headers = {}
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000169 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000170 for key, value in headers.items():
171 self.add_header(key, value)
172 self.unredirected_hdrs = {}
173 if origin_req_host is None:
174 origin_req_host = request_host(self)
175 self.origin_req_host = origin_req_host
176 self.unverifiable = unverifiable
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000177 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000178
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000179 def _parse(self):
180 self.type, rest = splittype(self.full_url)
181 if self.type is None:
182 raise ValueError("unknown url type: %s" % self.full_url)
183 self.host, self.selector = splithost(rest)
184 if self.host:
185 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000186
187 def get_method(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000188 if self.data is not None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000189 return "POST"
190 else:
191 return "GET"
192
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000193 # Begin deprecated methods
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000194
195 def add_data(self, data):
196 self.data = data
197
198 def has_data(self):
199 return self.data is not None
200
201 def get_data(self):
202 return self.data
203
204 def get_full_url(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000205 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000206
207 def get_type(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000208 return self.type
209
210 def get_host(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000211 return self.host
212
213 def get_selector(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000214 return self.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000215
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000216 def is_unverifiable(self):
217 return self.unverifiable
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000218
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000219 def get_origin_req_host(self):
220 return self.origin_req_host
221
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000222 # End deprecated methods
223
224 def set_proxy(self, host, type):
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000225 if self.type == 'https' and not self._tunnel_host:
226 self._tunnel_host = self.host
227 else:
228 self.type= type
229 self.selector = self.full_url
230 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000231
232 def has_proxy(self):
233 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000234
235 def add_header(self, key, val):
236 # useful for something like authentication
237 self.headers[key.capitalize()] = val
238
239 def add_unredirected_header(self, key, val):
240 # will not be added to a redirected request
241 self.unredirected_hdrs[key.capitalize()] = val
242
243 def has_header(self, header_name):
244 return (header_name in self.headers or
245 header_name in self.unredirected_hdrs)
246
247 def get_header(self, header_name, default=None):
248 return self.headers.get(
249 header_name,
250 self.unredirected_hdrs.get(header_name, default))
251
252 def header_items(self):
253 hdrs = self.unredirected_hdrs.copy()
254 hdrs.update(self.headers)
255 return list(hdrs.items())
256
257class OpenerDirector:
258 def __init__(self):
259 client_version = "Python-urllib/%s" % __version__
260 self.addheaders = [('User-agent', client_version)]
261 # manage the individual handlers
262 self.handlers = []
263 self.handle_open = {}
264 self.handle_error = {}
265 self.process_response = {}
266 self.process_request = {}
267
268 def add_handler(self, handler):
269 if not hasattr(handler, "add_parent"):
270 raise TypeError("expected BaseHandler instance, got %r" %
271 type(handler))
272
273 added = False
274 for meth in dir(handler):
275 if meth in ["redirect_request", "do_open", "proxy_open"]:
276 # oops, coincidental match
277 continue
278
279 i = meth.find("_")
280 protocol = meth[:i]
281 condition = meth[i+1:]
282
283 if condition.startswith("error"):
284 j = condition.find("_") + i + 1
285 kind = meth[j+1:]
286 try:
287 kind = int(kind)
288 except ValueError:
289 pass
290 lookup = self.handle_error.get(protocol, {})
291 self.handle_error[protocol] = lookup
292 elif condition == "open":
293 kind = protocol
294 lookup = self.handle_open
295 elif condition == "response":
296 kind = protocol
297 lookup = self.process_response
298 elif condition == "request":
299 kind = protocol
300 lookup = self.process_request
301 else:
302 continue
303
304 handlers = lookup.setdefault(kind, [])
305 if handlers:
306 bisect.insort(handlers, handler)
307 else:
308 handlers.append(handler)
309 added = True
310
311 if added:
312 # the handlers must work in an specific order, the order
313 # is specified in a Handler attribute
314 bisect.insort(self.handlers, handler)
315 handler.add_parent(self)
316
317 def close(self):
318 # Only exists for backwards compatibility.
319 pass
320
321 def _call_chain(self, chain, kind, meth_name, *args):
322 # Handlers raise an exception if no one else should try to handle
323 # the request, or return None if they can't but another handler
324 # could. Otherwise, they return the response.
325 handlers = chain.get(kind, ())
326 for handler in handlers:
327 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000328 result = func(*args)
329 if result is not None:
330 return result
331
332 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
333 # accept a URL or a Request object
334 if isinstance(fullurl, str):
335 req = Request(fullurl, data)
336 else:
337 req = fullurl
338 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000339 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000340
341 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000342 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000343
344 # pre-process request
345 meth_name = protocol+"_request"
346 for processor in self.process_request.get(protocol, []):
347 meth = getattr(processor, meth_name)
348 req = meth(req)
349
350 response = self._open(req, data)
351
352 # post-process response
353 meth_name = protocol+"_response"
354 for processor in self.process_response.get(protocol, []):
355 meth = getattr(processor, meth_name)
356 response = meth(req, response)
357
358 return response
359
360 def _open(self, req, data=None):
361 result = self._call_chain(self.handle_open, 'default',
362 'default_open', req)
363 if result:
364 return result
365
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000366 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000367 result = self._call_chain(self.handle_open, protocol, protocol +
368 '_open', req)
369 if result:
370 return result
371
372 return self._call_chain(self.handle_open, 'unknown',
373 'unknown_open', req)
374
375 def error(self, proto, *args):
376 if proto in ('http', 'https'):
377 # XXX http[s] protocols are special-cased
378 dict = self.handle_error['http'] # https is not different than http
379 proto = args[2] # YUCK!
380 meth_name = 'http_error_%s' % proto
381 http_err = 1
382 orig_args = args
383 else:
384 dict = self.handle_error
385 meth_name = proto + '_error'
386 http_err = 0
387 args = (dict, proto, meth_name) + args
388 result = self._call_chain(*args)
389 if result:
390 return result
391
392 if http_err:
393 args = (dict, 'default', 'http_error_default') + orig_args
394 return self._call_chain(*args)
395
396# XXX probably also want an abstract factory that knows when it makes
397# sense to skip a superclass in favor of a subclass and when it might
398# make sense to include both
399
400def build_opener(*handlers):
401 """Create an opener object from a list of handlers.
402
403 The opener will use several default handlers, including support
Senthil Kumaran1107c5d2009-11-15 06:20:55 +0000404 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000405
406 If any of the handlers passed as arguments are subclasses of the
407 default handlers, the default handlers will not be used.
408 """
409 def isclass(obj):
410 return isinstance(obj, type) or hasattr(obj, "__bases__")
411
412 opener = OpenerDirector()
413 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
414 HTTPDefaultErrorHandler, HTTPRedirectHandler,
415 FTPHandler, FileHandler, HTTPErrorProcessor]
416 if hasattr(http.client, "HTTPSConnection"):
417 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000418 skip = set()
419 for klass in default_classes:
420 for check in handlers:
421 if isclass(check):
422 if issubclass(check, klass):
423 skip.add(klass)
424 elif isinstance(check, klass):
425 skip.add(klass)
426 for klass in skip:
427 default_classes.remove(klass)
428
429 for klass in default_classes:
430 opener.add_handler(klass())
431
432 for h in handlers:
433 if isclass(h):
434 h = h()
435 opener.add_handler(h)
436 return opener
437
438class BaseHandler:
439 handler_order = 500
440
441 def add_parent(self, parent):
442 self.parent = parent
443
444 def close(self):
445 # Only exists for backwards compatibility
446 pass
447
448 def __lt__(self, other):
449 if not hasattr(other, "handler_order"):
450 # Try to preserve the old behavior of having custom classes
451 # inserted after default ones (works only for custom user
452 # classes which are not aware of handler_order).
453 return True
454 return self.handler_order < other.handler_order
455
456
457class HTTPErrorProcessor(BaseHandler):
458 """Process HTTP error responses."""
459 handler_order = 1000 # after all other processing
460
461 def http_response(self, request, response):
462 code, msg, hdrs = response.code, response.msg, response.info()
463
464 # According to RFC 2616, "2xx" code indicates that the client's
465 # request was successfully received, understood, and accepted.
466 if not (200 <= code < 300):
467 response = self.parent.error(
468 'http', request, response, code, msg, hdrs)
469
470 return response
471
472 https_response = http_response
473
474class HTTPDefaultErrorHandler(BaseHandler):
475 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000476 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000477
478class HTTPRedirectHandler(BaseHandler):
479 # maximum number of redirections to any single URL
480 # this is needed because of the state that cookies introduce
481 max_repeats = 4
482 # maximum total number of redirections (regardless of URL) before
483 # assuming we're in a loop
484 max_redirections = 10
485
486 def redirect_request(self, req, fp, code, msg, headers, newurl):
487 """Return a Request or None in response to a redirect.
488
489 This is called by the http_error_30x methods when a
490 redirection response is received. If a redirection should
491 take place, return a new Request to allow http_error_30x to
492 perform the redirect. Otherwise, raise HTTPError if no-one
493 else should try to handle this url. Return None if you can't
494 but another Handler might.
495 """
496 m = req.get_method()
497 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
498 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000499 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000500
501 # Strictly (according to RFC 2616), 301 or 302 in response to
502 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000503 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000504 # essentially all clients do redirect in this case, so we do
505 # the same.
506 # be conciliant with URIs containing a space
507 newurl = newurl.replace(' ', '%20')
508 CONTENT_HEADERS = ("content-length", "content-type")
509 newheaders = dict((k, v) for k, v in req.headers.items()
510 if k.lower() not in CONTENT_HEADERS)
511 return Request(newurl,
512 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000513 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000514 unverifiable=True)
515
516 # Implementation note: To avoid the server sending us into an
517 # infinite loop, the request object needs to track what URLs we
518 # have already seen. Do this by adding a handler-specific
519 # attribute to the Request object.
520 def http_error_302(self, req, fp, code, msg, headers):
521 # Some servers (incorrectly) return multiple Location headers
522 # (so probably same goes for URI). Use first header.
523 if "location" in headers:
524 newurl = headers["location"]
525 elif "uri" in headers:
526 newurl = headers["uri"]
527 else:
528 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000529
530 # fix a possible malformed URL
531 urlparts = urlparse(newurl)
532 if not urlparts.path:
533 urlparts = list(urlparts)
534 urlparts[2] = "/"
535 newurl = urlunparse(urlparts)
536
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000537 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000538
539 # XXX Probably want to forget about the state of the current
540 # request, although that might interact poorly with other
541 # handlers that also use handler-specific request attributes
542 new = self.redirect_request(req, fp, code, msg, headers, newurl)
543 if new is None:
544 return
545
546 # loop detection
547 # .redirect_dict has a key url if url was previously visited.
548 if hasattr(req, 'redirect_dict'):
549 visited = new.redirect_dict = req.redirect_dict
550 if (visited.get(newurl, 0) >= self.max_repeats or
551 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000552 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000553 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000554 else:
555 visited = new.redirect_dict = req.redirect_dict = {}
556 visited[newurl] = visited.get(newurl, 0) + 1
557
558 # Don't close the fp until we are sure that we won't use it
559 # with HTTPError.
560 fp.read()
561 fp.close()
562
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000563 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000564
565 http_error_301 = http_error_303 = http_error_307 = http_error_302
566
567 inf_msg = "The HTTP server returned a redirect error that would " \
568 "lead to an infinite loop.\n" \
569 "The last 30x error message was:\n"
570
571
572def _parse_proxy(proxy):
573 """Return (scheme, user, password, host/port) given a URL or an authority.
574
575 If a URL is supplied, it must have an authority (host:port) component.
576 According to RFC 3986, having an authority component means the URL must
577 have two slashes after the scheme:
578
579 >>> _parse_proxy('file:/ftp.example.com/')
580 Traceback (most recent call last):
581 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
582
583 The first three items of the returned tuple may be None.
584
585 Examples of authority parsing:
586
587 >>> _parse_proxy('proxy.example.com')
588 (None, None, None, 'proxy.example.com')
589 >>> _parse_proxy('proxy.example.com:3128')
590 (None, None, None, 'proxy.example.com:3128')
591
592 The authority component may optionally include userinfo (assumed to be
593 username:password):
594
595 >>> _parse_proxy('joe:password@proxy.example.com')
596 (None, 'joe', 'password', 'proxy.example.com')
597 >>> _parse_proxy('joe:password@proxy.example.com:3128')
598 (None, 'joe', 'password', 'proxy.example.com:3128')
599
600 Same examples, but with URLs instead:
601
602 >>> _parse_proxy('http://proxy.example.com/')
603 ('http', None, None, 'proxy.example.com')
604 >>> _parse_proxy('http://proxy.example.com:3128/')
605 ('http', None, None, 'proxy.example.com:3128')
606 >>> _parse_proxy('http://joe:password@proxy.example.com/')
607 ('http', 'joe', 'password', 'proxy.example.com')
608 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
609 ('http', 'joe', 'password', 'proxy.example.com:3128')
610
611 Everything after the authority is ignored:
612
613 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
614 ('ftp', 'joe', 'password', 'proxy.example.com')
615
616 Test for no trailing '/' case:
617
618 >>> _parse_proxy('http://joe:password@proxy.example.com')
619 ('http', 'joe', 'password', 'proxy.example.com')
620
621 """
Georg Brandl13e89462008-07-01 19:56:00 +0000622 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000623 if not r_scheme.startswith("/"):
624 # authority
625 scheme = None
626 authority = proxy
627 else:
628 # URL
629 if not r_scheme.startswith("//"):
630 raise ValueError("proxy URL with no authority: %r" % proxy)
631 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
632 # and 3.3.), path is empty or starts with '/'
633 end = r_scheme.find("/", 2)
634 if end == -1:
635 end = None
636 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000637 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000638 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000639 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000640 else:
641 user = password = None
642 return scheme, user, password, hostport
643
644class ProxyHandler(BaseHandler):
645 # Proxies must be in front
646 handler_order = 100
647
648 def __init__(self, proxies=None):
649 if proxies is None:
650 proxies = getproxies()
651 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
652 self.proxies = proxies
653 for type, url in proxies.items():
654 setattr(self, '%s_open' % type,
655 lambda r, proxy=url, type=type, meth=self.proxy_open: \
656 meth(r, proxy, type))
657
658 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000659 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000660 proxy_type, user, password, hostport = _parse_proxy(proxy)
661 if proxy_type is None:
662 proxy_type = orig_type
Senthil Kumaran7bb04972009-10-11 04:58:55 +0000663
664 if req.host and proxy_bypass(req.host):
665 return None
666
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000667 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000668 user_pass = '%s:%s' % (unquote(user),
669 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000670 creds = base64.b64encode(user_pass.encode()).decode("ascii")
671 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000672 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000673 req.set_proxy(hostport, proxy_type)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000674 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000675 # let other handlers take care of it
676 return None
677 else:
678 # need to start over, because the other handlers don't
679 # grok the proxy's URL type
680 # e.g. if we have a constructor arg proxies like so:
681 # {'http': 'ftp://proxy.example.com'}, we may end up turning
682 # a request for http://acme.example.com/a into one for
683 # ftp://proxy.example.com/a
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000684 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000685
686class HTTPPasswordMgr:
687
688 def __init__(self):
689 self.passwd = {}
690
691 def add_password(self, realm, uri, user, passwd):
692 # uri could be a single URI or a sequence
693 if isinstance(uri, str):
694 uri = [uri]
695 if not realm in self.passwd:
696 self.passwd[realm] = {}
697 for default_port in True, False:
698 reduced_uri = tuple(
699 [self.reduce_uri(u, default_port) for u in uri])
700 self.passwd[realm][reduced_uri] = (user, passwd)
701
702 def find_user_password(self, realm, authuri):
703 domains = self.passwd.get(realm, {})
704 for default_port in True, False:
705 reduced_authuri = self.reduce_uri(authuri, default_port)
706 for uris, authinfo in domains.items():
707 for uri in uris:
708 if self.is_suburi(uri, reduced_authuri):
709 return authinfo
710 return None, None
711
712 def reduce_uri(self, uri, default_port=True):
713 """Accept authority or URI and extract only the authority and path."""
714 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000715 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000716 if parts[1]:
717 # URI
718 scheme = parts[0]
719 authority = parts[1]
720 path = parts[2] or '/'
721 else:
722 # host or host:port
723 scheme = None
724 authority = uri
725 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000726 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000727 if default_port and port is None and scheme is not None:
728 dport = {"http": 80,
729 "https": 443,
730 }.get(scheme)
731 if dport is not None:
732 authority = "%s:%d" % (host, dport)
733 return authority, path
734
735 def is_suburi(self, base, test):
736 """Check if test is below base in a URI tree
737
738 Both args must be URIs in reduced form.
739 """
740 if base == test:
741 return True
742 if base[0] != test[0]:
743 return False
744 common = posixpath.commonprefix((base[1], test[1]))
745 if len(common) == len(base[1]):
746 return True
747 return False
748
749
750class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
751
752 def find_user_password(self, realm, authuri):
753 user, password = HTTPPasswordMgr.find_user_password(self, realm,
754 authuri)
755 if user is not None:
756 return user, password
757 return HTTPPasswordMgr.find_user_password(self, None, authuri)
758
759
760class AbstractBasicAuthHandler:
761
762 # XXX this allows for multiple auth-schemes, but will stupidly pick
763 # the last one with a realm specified.
764
765 # allow for double- and single-quoted realm values
766 # (single quotes are a violation of the RFC, but appear in the wild)
767 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
768 'realm=(["\'])(.*?)\\2', re.I)
769
770 # XXX could pre-emptively send auth info already accepted (RFC 2617,
771 # end of section 2, and section 1.2 immediately after "credentials"
772 # production).
773
774 def __init__(self, password_mgr=None):
775 if password_mgr is None:
776 password_mgr = HTTPPasswordMgr()
777 self.passwd = password_mgr
778 self.add_password = self.passwd.add_password
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000779 self.retried = 0
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000780
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000781 def reset_retry_count(self):
782 self.retried = 0
783
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000784 def http_error_auth_reqed(self, authreq, host, req, headers):
785 # host may be an authority (without userinfo) or a URL with an
786 # authority
787 # XXX could be multiple headers
788 authreq = headers.get(authreq, None)
Senthil Kumaranf4998ac2010-06-01 12:53:48 +0000789
790 if self.retried > 5:
791 # retry sending the username:password 5 times before failing.
792 raise HTTPError(req.get_full_url(), 401, "basic auth failed",
793 headers, None)
794 else:
795 self.retried += 1
796
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000797 if authreq:
798 mo = AbstractBasicAuthHandler.rx.search(authreq)
799 if mo:
800 scheme, quote, realm = mo.groups()
801 if scheme.lower() == 'basic':
802 return self.retry_http_basic_auth(host, req, realm)
803
804 def retry_http_basic_auth(self, host, req, realm):
805 user, pw = self.passwd.find_user_password(realm, host)
806 if pw is not None:
807 raw = "%s:%s" % (user, pw)
808 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
809 if req.headers.get(self.auth_header, None) == auth:
810 return None
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +0000811 req.add_unredirected_header(self.auth_header, auth)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000812 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000813 else:
814 return None
815
816
817class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
818
819 auth_header = 'Authorization'
820
821 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000822 url = req.full_url
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000823 response = self.http_error_auth_reqed('www-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000824 url, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000825 self.reset_retry_count()
826 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000827
828
829class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
830
831 auth_header = 'Proxy-authorization'
832
833 def http_error_407(self, req, fp, code, msg, headers):
834 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000835 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000836 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
837 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000838 authority = req.host
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000839 response = self.http_error_auth_reqed('proxy-authenticate',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000840 authority, req, headers)
Senthil Kumaran67a62a42010-08-19 17:50:31 +0000841 self.reset_retry_count()
842 return response
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000843
844
845def randombytes(n):
846 """Return n random bytes."""
847 return os.urandom(n)
848
849class AbstractDigestAuthHandler:
850 # Digest authentication is specified in RFC 2617.
851
852 # XXX The client does not inspect the Authentication-Info header
853 # in a successful response.
854
855 # XXX It should be possible to test this implementation against
856 # a mock server that just generates a static set of challenges.
857
858 # XXX qop="auth-int" supports is shaky
859
860 def __init__(self, passwd=None):
861 if passwd is None:
862 passwd = HTTPPasswordMgr()
863 self.passwd = passwd
864 self.add_password = self.passwd.add_password
865 self.retried = 0
866 self.nonce_count = 0
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000867 self.last_nonce = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000868
869 def reset_retry_count(self):
870 self.retried = 0
871
872 def http_error_auth_reqed(self, auth_header, host, req, headers):
873 authreq = headers.get(auth_header, None)
874 if self.retried > 5:
875 # Don't fail endlessly - if we failed once, we'll probably
876 # fail a second time. Hm. Unless the Password Manager is
877 # prompting for the information. Crap. This isn't great
878 # but it's better than the current 'repeat until recursion
879 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000880 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000881 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000882 else:
883 self.retried += 1
884 if authreq:
885 scheme = authreq.split()[0]
886 if scheme.lower() == 'digest':
887 return self.retry_http_digest_auth(req, authreq)
888
889 def retry_http_digest_auth(self, req, auth):
890 token, challenge = auth.split(' ', 1)
891 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
892 auth = self.get_authorization(req, chal)
893 if auth:
894 auth_val = 'Digest %s' % auth
895 if req.headers.get(self.auth_header, None) == auth_val:
896 return None
897 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000898 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000899 return resp
900
901 def get_cnonce(self, nonce):
902 # The cnonce-value is an opaque
903 # quoted string value provided by the client and used by both client
904 # and server to avoid chosen plaintext attacks, to provide mutual
905 # authentication, and to provide some message integrity protection.
906 # This isn't a fabulous effort, but it's probably Good Enough.
907 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
908 b = s.encode("ascii") + randombytes(8)
909 dig = hashlib.sha1(b).hexdigest()
910 return dig[:16]
911
912 def get_authorization(self, req, chal):
913 try:
914 realm = chal['realm']
915 nonce = chal['nonce']
916 qop = chal.get('qop')
917 algorithm = chal.get('algorithm', 'MD5')
918 # mod_digest doesn't send an opaque, even though it isn't
919 # supposed to be optional
920 opaque = chal.get('opaque', None)
921 except KeyError:
922 return None
923
924 H, KD = self.get_algorithm_impls(algorithm)
925 if H is None:
926 return None
927
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000928 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000929 if user is None:
930 return None
931
932 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000933 if req.data is not None:
934 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000935 else:
936 entdig = None
937
938 A1 = "%s:%s:%s" % (user, realm, pw)
939 A2 = "%s:%s" % (req.get_method(),
940 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000941 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000942 if qop == 'auth':
Senthil Kumaran4c7eaee2009-11-15 08:43:45 +0000943 if nonce == self.last_nonce:
944 self.nonce_count += 1
945 else:
946 self.nonce_count = 1
947 self.last_nonce = nonce
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000948 ncvalue = '%08x' % self.nonce_count
949 cnonce = self.get_cnonce(nonce)
950 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
951 respdig = KD(H(A1), noncebit)
952 elif qop is None:
953 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
954 else:
955 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +0000956 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000957
958 # XXX should the partial digests be encoded too?
959
960 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000961 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000962 respdig)
963 if opaque:
964 base += ', opaque="%s"' % opaque
965 if entdig:
966 base += ', digest="%s"' % entdig
967 base += ', algorithm="%s"' % algorithm
968 if qop:
969 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
970 return base
971
972 def get_algorithm_impls(self, algorithm):
973 # lambdas assume digest modules are imported at the top level
974 if algorithm == 'MD5':
975 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
976 elif algorithm == 'SHA':
977 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
978 # XXX MD5-sess
979 KD = lambda s, d: H("%s:%s" % (s, d))
980 return H, KD
981
982 def get_entity_digest(self, data, chal):
983 # XXX not implemented yet
984 return None
985
986
987class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
988 """An authentication protocol defined by RFC 2069
989
990 Digest authentication improves on basic authentication because it
991 does not transmit passwords in the clear.
992 """
993
994 auth_header = 'Authorization'
995 handler_order = 490 # before Basic auth
996
997 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000998 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000999 retry = self.http_error_auth_reqed('www-authenticate',
1000 host, req, headers)
1001 self.reset_retry_count()
1002 return retry
1003
1004
1005class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1006
1007 auth_header = 'Proxy-Authorization'
1008 handler_order = 490 # before Basic auth
1009
1010 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001011 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001012 retry = self.http_error_auth_reqed('proxy-authenticate',
1013 host, req, headers)
1014 self.reset_retry_count()
1015 return retry
1016
1017class AbstractHTTPHandler(BaseHandler):
1018
1019 def __init__(self, debuglevel=0):
1020 self._debuglevel = debuglevel
1021
1022 def set_http_debuglevel(self, level):
1023 self._debuglevel = level
1024
1025 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001026 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001027 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001028 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001029
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001030 if request.data is not None: # POST
1031 data = request.data
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001032 if not request.has_header('Content-type'):
1033 request.add_unredirected_header(
1034 'Content-type',
1035 'application/x-www-form-urlencoded')
1036 if not request.has_header('Content-length'):
1037 request.add_unredirected_header(
1038 'Content-length', '%d' % len(data))
1039
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001040 sel_host = host
1041 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001042 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001043 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001044 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001045 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001046 for name, value in self.parent.addheaders:
1047 name = name.capitalize()
1048 if not request.has_header(name):
1049 request.add_unredirected_header(name, value)
1050
1051 return request
1052
1053 def do_open(self, http_class, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001054 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001055
1056 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001057 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001058 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001059 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001060 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001061
1062 h = http_class(host, timeout=req.timeout) # will parse host:port
1063 headers = dict(req.headers)
1064 headers.update(req.unredirected_hdrs)
1065
1066 # TODO(jhylton): Should this be redesigned to handle
1067 # persistent connections?
1068
1069 # We want to make an HTTP/1.1 request, but the addinfourl
1070 # class isn't prepared to deal with a persistent connection.
1071 # It will try to read all remaining data from the socket,
1072 # which will block while the server waits for the next request.
1073 # So make sure the connection gets closed after the (only)
1074 # request.
1075 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001076 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001077
1078 if req._tunnel_host:
Senthil Kumaran47fff872009-12-20 07:10:31 +00001079 tunnel_headers = {}
1080 proxy_auth_hdr = "Proxy-Authorization"
1081 if proxy_auth_hdr in headers:
1082 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1083 # Proxy-Authorization should not be sent to origin
1084 # server.
1085 del headers[proxy_auth_hdr]
1086 h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001087
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001088 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001089 h.request(req.get_method(), req.selector, req.data, headers)
1090 r = h.getresponse() # an HTTPResponse instance
1091 except socket.error as err:
Georg Brandl13e89462008-07-01 19:56:00 +00001092 raise URLError(err)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001093
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001094 r.url = req.full_url
1095 # This line replaces the .msg attribute of the HTTPResponse
1096 # with .headers, because urllib clients expect the response to
1097 # have the reason in .msg. It would be good to mark this
1098 # attribute is deprecated and get then to use info() or
1099 # .headers.
1100 r.msg = r.reason
1101 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001102
1103
1104class HTTPHandler(AbstractHTTPHandler):
1105
1106 def http_open(self, req):
1107 return self.do_open(http.client.HTTPConnection, req)
1108
1109 http_request = AbstractHTTPHandler.do_request_
1110
1111if hasattr(http.client, 'HTTPSConnection'):
1112 class HTTPSHandler(AbstractHTTPHandler):
1113
1114 def https_open(self, req):
1115 return self.do_open(http.client.HTTPSConnection, req)
1116
1117 https_request = AbstractHTTPHandler.do_request_
1118
1119class HTTPCookieProcessor(BaseHandler):
1120 def __init__(self, cookiejar=None):
1121 import http.cookiejar
1122 if cookiejar is None:
1123 cookiejar = http.cookiejar.CookieJar()
1124 self.cookiejar = cookiejar
1125
1126 def http_request(self, request):
1127 self.cookiejar.add_cookie_header(request)
1128 return request
1129
1130 def http_response(self, request, response):
1131 self.cookiejar.extract_cookies(response, request)
1132 return response
1133
1134 https_request = http_request
1135 https_response = http_response
1136
1137class UnknownHandler(BaseHandler):
1138 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001139 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001140 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001141
1142def parse_keqv_list(l):
1143 """Parse list of key=value strings where keys are not duplicated."""
1144 parsed = {}
1145 for elt in l:
1146 k, v = elt.split('=', 1)
1147 if v[0] == '"' and v[-1] == '"':
1148 v = v[1:-1]
1149 parsed[k] = v
1150 return parsed
1151
1152def parse_http_list(s):
1153 """Parse lists as described by RFC 2068 Section 2.
1154
1155 In particular, parse comma-separated lists where the elements of
1156 the list may include quoted-strings. A quoted-string could
1157 contain a comma. A non-quoted string could have quotes in the
1158 middle. Neither commas nor quotes count if they are escaped.
1159 Only double-quotes count, not single-quotes.
1160 """
1161 res = []
1162 part = ''
1163
1164 escape = quote = False
1165 for cur in s:
1166 if escape:
1167 part += cur
1168 escape = False
1169 continue
1170 if quote:
1171 if cur == '\\':
1172 escape = True
1173 continue
1174 elif cur == '"':
1175 quote = False
1176 part += cur
1177 continue
1178
1179 if cur == ',':
1180 res.append(part)
1181 part = ''
1182 continue
1183
1184 if cur == '"':
1185 quote = True
1186
1187 part += cur
1188
1189 # append last part
1190 if part:
1191 res.append(part)
1192
1193 return [part.strip() for part in res]
1194
1195class FileHandler(BaseHandler):
1196 # Use local file or FTP depending on form of URL
1197 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001198 url = req.selector
Senthil Kumaran2ef16322010-07-11 03:12:43 +00001199 if url[:2] == '//' and url[2:3] != '/' and (req.host and
1200 req.host != 'localhost'):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001201 req.type = 'ftp'
1202 return self.parent.open(req)
1203 else:
1204 return self.open_local_file(req)
1205
1206 # names for the localhost
1207 names = None
1208 def get_names(self):
1209 if FileHandler.names is None:
1210 try:
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001211 FileHandler.names = tuple(
1212 socket.gethostbyname_ex('localhost')[2] +
1213 socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001214 except socket.gaierror:
1215 FileHandler.names = (socket.gethostbyname('localhost'),)
1216 return FileHandler.names
1217
1218 # not entirely sure what the rules are here
1219 def open_local_file(self, req):
1220 import email.utils
1221 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001222 host = req.host
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001223 filename = req.selector
1224 localfile = url2pathname(filename)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001225 try:
1226 stats = os.stat(localfile)
1227 size = stats.st_size
1228 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001229 mtype = mimetypes.guess_type(filename)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001230 headers = email.message_from_string(
1231 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1232 (mtype or 'text/plain', size, modified))
1233 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001234 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001235 if not host or \
1236 (not port and _safe_gethostbyname(host) in self.get_names()):
Senthil Kumaran06f5a532010-05-08 05:12:05 +00001237 if host:
1238 origurl = 'file://' + host + filename
1239 else:
1240 origurl = 'file://' + filename
1241 return addinfourl(open(localfile, 'rb'), headers, origurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001242 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001243 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001244 raise URLError(msg)
1245 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001246
1247def _safe_gethostbyname(host):
1248 try:
1249 return socket.gethostbyname(host)
1250 except socket.gaierror:
1251 return None
1252
1253class FTPHandler(BaseHandler):
1254 def ftp_open(self, req):
1255 import ftplib
1256 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001257 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001258 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001259 raise URLError('ftp error: no host given')
1260 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001261 if port is None:
1262 port = ftplib.FTP_PORT
1263 else:
1264 port = int(port)
1265
1266 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001267 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001268 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001269 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001270 else:
1271 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001272 host = unquote(host)
1273 user = unquote(user or '')
1274 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001275
1276 try:
1277 host = socket.gethostbyname(host)
1278 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001279 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001280 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001281 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001282 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001283 dirs, file = dirs[:-1], dirs[-1]
1284 if dirs and not dirs[0]:
1285 dirs = dirs[1:]
1286 try:
1287 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1288 type = file and 'I' or 'D'
1289 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001290 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001291 if attr.lower() == 'type' and \
1292 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1293 type = value.upper()
1294 fp, retrlen = fw.retrfile(file, type)
1295 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001296 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001297 if mtype:
1298 headers += "Content-type: %s\n" % mtype
1299 if retrlen is not None and retrlen >= 0:
1300 headers += "Content-length: %d\n" % retrlen
1301 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001302 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001303 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001304 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001305 raise exc.with_traceback(sys.exc_info()[2])
1306
1307 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1308 fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
1309 return fw
1310
1311class CacheFTPHandler(FTPHandler):
1312 # XXX would be nice to have pluggable cache strategies
1313 # XXX this stuff is definitely not thread safe
1314 def __init__(self):
1315 self.cache = {}
1316 self.timeout = {}
1317 self.soonest = 0
1318 self.delay = 60
1319 self.max_conns = 16
1320
1321 def setTimeout(self, t):
1322 self.delay = t
1323
1324 def setMaxConns(self, m):
1325 self.max_conns = m
1326
1327 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1328 key = user, host, port, '/'.join(dirs), timeout
1329 if key in self.cache:
1330 self.timeout[key] = time.time() + self.delay
1331 else:
1332 self.cache[key] = ftpwrapper(user, passwd, host, port,
1333 dirs, timeout)
1334 self.timeout[key] = time.time() + self.delay
1335 self.check_cache()
1336 return self.cache[key]
1337
1338 def check_cache(self):
1339 # first check for old ones
1340 t = time.time()
1341 if self.soonest <= t:
1342 for k, v in list(self.timeout.items()):
1343 if v < t:
1344 self.cache[k].close()
1345 del self.cache[k]
1346 del self.timeout[k]
1347 self.soonest = min(list(self.timeout.values()))
1348
1349 # then check the size
1350 if len(self.cache) == self.max_conns:
1351 for k, v in list(self.timeout.items()):
1352 if v == self.soonest:
1353 del self.cache[k]
1354 del self.timeout[k]
1355 break
1356 self.soonest = min(list(self.timeout.values()))
1357
1358# Code move from the old urllib module
1359
1360MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1361
1362# Helper for non-unix systems
Ronald Oussoren94f25282010-05-05 19:11:21 +00001363if os.name == 'nt':
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001364 from nturl2path import url2pathname, pathname2url
1365else:
1366 def url2pathname(pathname):
1367 """OS-specific conversion from a relative URL of the 'file' scheme
1368 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001369 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001370
1371 def pathname2url(pathname):
1372 """OS-specific conversion from a file system path to a relative URL
1373 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001374 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001375
1376# This really consists of two pieces:
1377# (1) a class which handles opening of all sorts of URLs
1378# (plus assorted utilities etc.)
1379# (2) a set of functions for parsing URLs
1380# XXX Should these be separated out into different modules?
1381
1382
1383ftpcache = {}
1384class URLopener:
1385 """Class to open URLs.
1386 This is a class rather than just a subroutine because we may need
1387 more than one set of global protocol-specific options.
1388 Note -- this is a base class for those who don't want the
1389 automatic handling of errors type 302 (relocated) and 401
1390 (authorization needed)."""
1391
1392 __tempfiles = None
1393
1394 version = "Python-urllib/%s" % __version__
1395
1396 # Constructor
1397 def __init__(self, proxies=None, **x509):
1398 if proxies is None:
1399 proxies = getproxies()
1400 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1401 self.proxies = proxies
1402 self.key_file = x509.get('key_file')
1403 self.cert_file = x509.get('cert_file')
1404 self.addheaders = [('User-Agent', self.version)]
1405 self.__tempfiles = []
1406 self.__unlink = os.unlink # See cleanup()
1407 self.tempcache = None
1408 # Undocumented feature: if you assign {} to tempcache,
1409 # it is used to cache files retrieved with
1410 # self.retrieve(). This is not enabled by default
1411 # since it does not work for changing documents (and I
1412 # haven't got the logic to check expiration headers
1413 # yet).
1414 self.ftpcache = ftpcache
1415 # Undocumented feature: you can use a different
1416 # ftp cache by assigning to the .ftpcache member;
1417 # in case you want logically independent URL openers
1418 # XXX This is not threadsafe. Bah.
1419
1420 def __del__(self):
1421 self.close()
1422
1423 def close(self):
1424 self.cleanup()
1425
1426 def cleanup(self):
1427 # This code sometimes runs when the rest of this module
1428 # has already been deleted, so it can't use any globals
1429 # or import anything.
1430 if self.__tempfiles:
1431 for file in self.__tempfiles:
1432 try:
1433 self.__unlink(file)
1434 except OSError:
1435 pass
1436 del self.__tempfiles[:]
1437 if self.tempcache:
1438 self.tempcache.clear()
1439
1440 def addheader(self, *args):
1441 """Add a header to be used by the HTTP interface only
1442 e.g. u.addheader('Accept', 'sound/basic')"""
1443 self.addheaders.append(args)
1444
1445 # External interface
1446 def open(self, fullurl, data=None):
1447 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001448 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran734f0592010-02-20 22:19:04 +00001449 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001450 if self.tempcache and fullurl in self.tempcache:
1451 filename, headers = self.tempcache[fullurl]
1452 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001453 return addinfourl(fp, headers, fullurl)
1454 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001455 if not urltype:
1456 urltype = 'file'
1457 if urltype in self.proxies:
1458 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001459 urltype, proxyhost = splittype(proxy)
1460 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001461 url = (host, fullurl) # Signal special case to open_*()
1462 else:
1463 proxy = None
1464 name = 'open_' + urltype
1465 self.type = urltype
1466 name = name.replace('-', '_')
1467 if not hasattr(self, name):
1468 if proxy:
1469 return self.open_unknown_proxy(proxy, fullurl, data)
1470 else:
1471 return self.open_unknown(fullurl, data)
1472 try:
1473 if data is None:
1474 return getattr(self, name)(url)
1475 else:
1476 return getattr(self, name)(url, data)
1477 except socket.error as msg:
1478 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1479
1480 def open_unknown(self, fullurl, data=None):
1481 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001482 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001483 raise IOError('url error', 'unknown url type', type)
1484
1485 def open_unknown_proxy(self, proxy, fullurl, data=None):
1486 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001487 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001488 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1489
1490 # External interface
1491 def retrieve(self, url, filename=None, reporthook=None, data=None):
1492 """retrieve(url) returns (filename, headers) for a local object
1493 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001494 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001495 if self.tempcache and url in self.tempcache:
1496 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001497 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001498 if filename is None and (not type or type == 'file'):
1499 try:
1500 fp = self.open_local_file(url1)
1501 hdrs = fp.info()
Philip Jenveycb134d72009-12-03 02:45:01 +00001502 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001503 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001504 except IOError as msg:
1505 pass
1506 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001507 try:
1508 headers = fp.info()
1509 if filename:
1510 tfp = open(filename, 'wb')
1511 else:
1512 import tempfile
1513 garbage, path = splittype(url)
1514 garbage, path = splithost(path or "")
1515 path, garbage = splitquery(path or "")
1516 path, garbage = splitattr(path or "")
1517 suffix = os.path.splitext(path)[1]
1518 (fd, filename) = tempfile.mkstemp(suffix)
1519 self.__tempfiles.append(filename)
1520 tfp = os.fdopen(fd, 'wb')
1521 try:
1522 result = filename, headers
1523 if self.tempcache is not None:
1524 self.tempcache[url] = result
1525 bs = 1024*8
1526 size = -1
1527 read = 0
1528 blocknum = 0
1529 if reporthook:
1530 if "content-length" in headers:
1531 size = int(headers["Content-Length"])
1532 reporthook(blocknum, bs, size)
1533 while 1:
1534 block = fp.read(bs)
1535 if not block:
1536 break
1537 read += len(block)
1538 tfp.write(block)
1539 blocknum += 1
1540 if reporthook:
1541 reporthook(blocknum, bs, size)
1542 finally:
1543 tfp.close()
1544 finally:
1545 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001546
1547 # raise exception if actual size does not match content-length header
1548 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001549 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001550 "retrieval incomplete: got only %i out of %i bytes"
1551 % (read, size), result)
1552
1553 return result
1554
1555 # Each method named open_<type> knows how to open that type of URL
1556
1557 def _open_generic_http(self, connection_factory, url, data):
1558 """Make an HTTP connection using connection_class.
1559
1560 This is an internal method that should be called from
1561 open_http() or open_https().
1562
1563 Arguments:
1564 - connection_factory should take a host name and return an
1565 HTTPConnection instance.
1566 - url is the url to retrieval or a host, relative-path pair.
1567 - data is payload for a POST request or None.
1568 """
1569
1570 user_passwd = None
1571 proxy_passwd= None
1572 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001573 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001574 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001575 user_passwd, host = splituser(host)
1576 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001577 realhost = host
1578 else:
1579 host, selector = url
1580 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001581 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001582 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001583 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001584 url = rest
1585 user_passwd = None
1586 if urltype.lower() != 'http':
1587 realhost = None
1588 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001589 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001590 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001591 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001592 if user_passwd:
1593 selector = "%s://%s%s" % (urltype, realhost, rest)
1594 if proxy_bypass(realhost):
1595 host = realhost
1596
1597 #print "proxy via http:", host, selector
1598 if not host: raise IOError('http error', 'no host given')
1599
1600 if proxy_passwd:
1601 import base64
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001602 proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001603 else:
1604 proxy_auth = None
1605
1606 if user_passwd:
1607 import base64
Senthil Kumaran5626eec2010-08-04 17:46:23 +00001608 auth = base64.b64encode(user_passwd.encode()).decode('ascii')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001609 else:
1610 auth = None
1611 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001612 headers = {}
1613 if proxy_auth:
1614 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1615 if auth:
1616 headers["Authorization"] = "Basic %s" % auth
1617 if realhost:
1618 headers["Host"] = realhost
1619 for header, value in self.addheaders:
1620 headers[header] = value
1621
1622 if data is not None:
1623 headers["Content-Type"] = "application/x-www-form-urlencoded"
1624 http_conn.request("POST", selector, data, headers)
1625 else:
1626 http_conn.request("GET", selector, headers=headers)
1627
1628 try:
1629 response = http_conn.getresponse()
1630 except http.client.BadStatusLine:
1631 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001632 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001633
1634 # According to RFC 2616, "2xx" code indicates that the client's
1635 # request was successfully received, understood, and accepted.
1636 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001637 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001638 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001639 else:
1640 return self.http_error(
1641 url, response.fp,
1642 response.status, response.reason, response.msg, data)
1643
1644 def open_http(self, url, data=None):
1645 """Use HTTP protocol."""
1646 return self._open_generic_http(http.client.HTTPConnection, url, data)
1647
1648 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1649 """Handle http errors.
1650
1651 Derived class can override this, or provide specific handlers
1652 named http_error_DDD where DDD is the 3-digit error code."""
1653 # First check if there's a specific handler for this error
1654 name = 'http_error_%d' % errcode
1655 if hasattr(self, name):
1656 method = getattr(self, name)
1657 if data is None:
1658 result = method(url, fp, errcode, errmsg, headers)
1659 else:
1660 result = method(url, fp, errcode, errmsg, headers, data)
1661 if result: return result
1662 return self.http_error_default(url, fp, errcode, errmsg, headers)
1663
1664 def http_error_default(self, url, fp, errcode, errmsg, headers):
1665 """Default error handler: close the connection and raise IOError."""
1666 void = fp.read()
1667 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001668 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001669
1670 if _have_ssl:
1671 def _https_connection(self, host):
1672 return http.client.HTTPSConnection(host,
1673 key_file=self.key_file,
1674 cert_file=self.cert_file)
1675
1676 def open_https(self, url, data=None):
1677 """Use HTTPS protocol."""
1678 return self._open_generic_http(self._https_connection, url, data)
1679
1680 def open_file(self, url):
1681 """Use local file or FTP depending on form of URL."""
1682 if not isinstance(url, str):
1683 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1684 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
1685 return self.open_ftp(url)
1686 else:
1687 return self.open_local_file(url)
1688
1689 def open_local_file(self, url):
1690 """Use local file."""
1691 import mimetypes, email.utils
1692 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001693 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001694 localname = url2pathname(file)
1695 try:
1696 stats = os.stat(localname)
1697 except OSError as e:
1698 raise URLError(e.errno, e.strerror, e.filename)
1699 size = stats.st_size
1700 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1701 mtype = mimetypes.guess_type(url)[0]
1702 headers = email.message_from_string(
1703 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1704 (mtype or 'text/plain', size, modified))
1705 if not host:
1706 urlfile = file
1707 if file[:1] == '/':
1708 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001709 return addinfourl(open(localname, 'rb'), headers, urlfile)
1710 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001711 if (not port
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00001712 and socket.gethostbyname(host) in (localhost() + thishost())):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001713 urlfile = file
1714 if file[:1] == '/':
1715 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001716 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001717 raise URLError('local file error', 'not on local host')
1718
1719 def open_ftp(self, url):
1720 """Use FTP protocol."""
1721 if not isinstance(url, str):
1722 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1723 import mimetypes
1724 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001725 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001726 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001727 host, port = splitport(host)
1728 user, host = splituser(host)
1729 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001730 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001731 host = unquote(host)
1732 user = unquote(user or '')
1733 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001734 host = socket.gethostbyname(host)
1735 if not port:
1736 import ftplib
1737 port = ftplib.FTP_PORT
1738 else:
1739 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001740 path, attrs = splitattr(path)
1741 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001742 dirs = path.split('/')
1743 dirs, file = dirs[:-1], dirs[-1]
1744 if dirs and not dirs[0]: dirs = dirs[1:]
1745 if dirs and not dirs[0]: dirs[0] = '/'
1746 key = user, host, port, '/'.join(dirs)
1747 # XXX thread unsafe!
1748 if len(self.ftpcache) > MAXFTPCACHE:
1749 # Prune the cache, rather arbitrarily
1750 for k in self.ftpcache.keys():
1751 if k != key:
1752 v = self.ftpcache[k]
1753 del self.ftpcache[k]
1754 v.close()
1755 try:
1756 if not key in self.ftpcache:
1757 self.ftpcache[key] = \
1758 ftpwrapper(user, passwd, host, port, dirs)
1759 if not file: type = 'D'
1760 else: type = 'I'
1761 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001762 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001763 if attr.lower() == 'type' and \
1764 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1765 type = value.upper()
1766 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1767 mtype = mimetypes.guess_type("ftp:" + url)[0]
1768 headers = ""
1769 if mtype:
1770 headers += "Content-Type: %s\n" % mtype
1771 if retrlen is not None and retrlen >= 0:
1772 headers += "Content-Length: %d\n" % retrlen
1773 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001774 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001775 except ftperrors() as msg:
1776 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1777
1778 def open_data(self, url, data=None):
1779 """Use "data" URL."""
1780 if not isinstance(url, str):
1781 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1782 # ignore POSTed data
1783 #
1784 # syntax of data URLs:
1785 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1786 # mediatype := [ type "/" subtype ] *( ";" parameter )
1787 # data := *urlchar
1788 # parameter := attribute "=" value
1789 try:
1790 [type, data] = url.split(',', 1)
1791 except ValueError:
1792 raise IOError('data error', 'bad data URL')
1793 if not type:
1794 type = 'text/plain;charset=US-ASCII'
1795 semi = type.rfind(';')
1796 if semi >= 0 and '=' not in type[semi:]:
1797 encoding = type[semi+1:]
1798 type = type[:semi]
1799 else:
1800 encoding = ''
1801 msg = []
Senthil Kumaranf6c456d2010-05-01 08:29:18 +00001802 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001803 time.gmtime(time.time())))
1804 msg.append('Content-type: %s' % type)
1805 if encoding == 'base64':
1806 import base64
Georg Brandl706824f2009-06-04 09:42:55 +00001807 # XXX is this encoding/decoding ok?
1808 data = base64.decodebytes(data.encode('ascii')).decode('latin1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001809 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001810 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001811 msg.append('Content-Length: %d' % len(data))
1812 msg.append('')
1813 msg.append(data)
1814 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001815 headers = email.message_from_string(msg)
1816 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001817 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001818 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001819
1820
1821class FancyURLopener(URLopener):
1822 """Derived class with handlers for errors we can handle (perhaps)."""
1823
1824 def __init__(self, *args, **kwargs):
1825 URLopener.__init__(self, *args, **kwargs)
1826 self.auth_cache = {}
1827 self.tries = 0
1828 self.maxtries = 10
1829
1830 def http_error_default(self, url, fp, errcode, errmsg, headers):
1831 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001832 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001833
1834 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1835 """Error 302 -- relocated (temporarily)."""
1836 self.tries += 1
1837 if self.maxtries and self.tries >= self.maxtries:
1838 if hasattr(self, "http_error_500"):
1839 meth = self.http_error_500
1840 else:
1841 meth = self.http_error_default
1842 self.tries = 0
1843 return meth(url, fp, 500,
1844 "Internal Server Error: Redirect Recursion", headers)
1845 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
1846 data)
1847 self.tries = 0
1848 return result
1849
1850 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
1851 if 'location' in headers:
1852 newurl = headers['location']
1853 elif 'uri' in headers:
1854 newurl = headers['uri']
1855 else:
1856 return
1857 void = fp.read()
1858 fp.close()
1859 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00001860 newurl = urljoin(self.type + ":" + url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001861 return self.open(newurl)
1862
1863 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
1864 """Error 301 -- also relocated (permanently)."""
1865 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1866
1867 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
1868 """Error 303 -- also relocated (essentially identical to 302)."""
1869 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1870
1871 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
1872 """Error 307 -- relocated, but turn POST into error."""
1873 if data is None:
1874 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1875 else:
1876 return self.http_error_default(url, fp, errcode, errmsg, headers)
1877
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001878 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
1879 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001880 """Error 401 -- authentication required.
1881 This function supports Basic authentication only."""
1882 if not 'www-authenticate' in headers:
1883 URLopener.http_error_default(self, url, fp,
1884 errcode, errmsg, headers)
1885 stuff = headers['www-authenticate']
1886 import re
1887 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1888 if not match:
1889 URLopener.http_error_default(self, url, fp,
1890 errcode, errmsg, headers)
1891 scheme, realm = match.groups()
1892 if scheme.lower() != 'basic':
1893 URLopener.http_error_default(self, url, fp,
1894 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001895 if not retry:
1896 URLopener.http_error_default(self, url, fp, errcode, errmsg,
1897 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001898 name = 'retry_' + self.type + '_basic_auth'
1899 if data is None:
1900 return getattr(self,name)(url, realm)
1901 else:
1902 return getattr(self,name)(url, realm, data)
1903
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001904 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
1905 retry=False):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001906 """Error 407 -- proxy authentication required.
1907 This function supports Basic authentication only."""
1908 if not 'proxy-authenticate' in headers:
1909 URLopener.http_error_default(self, url, fp,
1910 errcode, errmsg, headers)
1911 stuff = headers['proxy-authenticate']
1912 import re
1913 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1914 if not match:
1915 URLopener.http_error_default(self, url, fp,
1916 errcode, errmsg, headers)
1917 scheme, realm = match.groups()
1918 if scheme.lower() != 'basic':
1919 URLopener.http_error_default(self, url, fp,
1920 errcode, errmsg, headers)
Senthil Kumaran80f1b052010-06-18 15:08:18 +00001921 if not retry:
1922 URLopener.http_error_default(self, url, fp, errcode, errmsg,
1923 headers)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001924 name = 'retry_proxy_' + self.type + '_basic_auth'
1925 if data is None:
1926 return getattr(self,name)(url, realm)
1927 else:
1928 return getattr(self,name)(url, realm, data)
1929
1930 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001931 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001932 newurl = 'http://' + host + selector
1933 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00001934 urltype, proxyhost = splittype(proxy)
1935 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001936 i = proxyhost.find('@') + 1
1937 proxyhost = proxyhost[i:]
1938 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1939 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001940 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001941 quote(passwd, safe=''), proxyhost)
1942 self.proxies['http'] = 'http://' + proxyhost + proxyselector
1943 if data is None:
1944 return self.open(newurl)
1945 else:
1946 return self.open(newurl, data)
1947
1948 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001949 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001950 newurl = 'https://' + host + selector
1951 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00001952 urltype, proxyhost = splittype(proxy)
1953 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001954 i = proxyhost.find('@') + 1
1955 proxyhost = proxyhost[i:]
1956 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1957 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001958 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001959 quote(passwd, safe=''), proxyhost)
1960 self.proxies['https'] = 'https://' + proxyhost + proxyselector
1961 if data is None:
1962 return self.open(newurl)
1963 else:
1964 return self.open(newurl, data)
1965
1966 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001967 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001968 i = host.find('@') + 1
1969 host = host[i:]
1970 user, passwd = self.get_user_passwd(host, realm, i)
1971 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001972 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001973 quote(passwd, safe=''), host)
1974 newurl = 'http://' + host + selector
1975 if data is None:
1976 return self.open(newurl)
1977 else:
1978 return self.open(newurl, data)
1979
1980 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001981 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001982 i = host.find('@') + 1
1983 host = host[i:]
1984 user, passwd = self.get_user_passwd(host, realm, i)
1985 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001986 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001987 quote(passwd, safe=''), host)
1988 newurl = 'https://' + host + selector
1989 if data is None:
1990 return self.open(newurl)
1991 else:
1992 return self.open(newurl, data)
1993
Florent Xicluna757445b2010-05-17 17:24:07 +00001994 def get_user_passwd(self, host, realm, clear_cache=0):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001995 key = realm + '@' + host.lower()
1996 if key in self.auth_cache:
1997 if clear_cache:
1998 del self.auth_cache[key]
1999 else:
2000 return self.auth_cache[key]
2001 user, passwd = self.prompt_user_passwd(host, realm)
2002 if user or passwd: self.auth_cache[key] = (user, passwd)
2003 return user, passwd
2004
2005 def prompt_user_passwd(self, host, realm):
2006 """Override this in a GUI environment!"""
2007 import getpass
2008 try:
2009 user = input("Enter username for %s at %s: " % (realm, host))
2010 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
2011 (user, realm, host))
2012 return user, passwd
2013 except KeyboardInterrupt:
2014 print()
2015 return None, None
2016
2017
2018# Utility functions
2019
2020_localhost = None
2021def localhost():
2022 """Return the IP address of the magic hostname 'localhost'."""
2023 global _localhost
2024 if _localhost is None:
2025 _localhost = socket.gethostbyname('localhost')
2026 return _localhost
2027
2028_thishost = None
2029def thishost():
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00002030 """Return the IP addresses of the current host."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002031 global _thishost
2032 if _thishost is None:
Senthil Kumaran99b2c8f2009-12-27 10:13:39 +00002033 _thishost = tuple(socket.gethostbyname_ex(socket.gethostname()[2]))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002034 return _thishost
2035
2036_ftperrors = None
2037def ftperrors():
2038 """Return the set of errors raised by the FTP class."""
2039 global _ftperrors
2040 if _ftperrors is None:
2041 import ftplib
2042 _ftperrors = ftplib.all_errors
2043 return _ftperrors
2044
2045_noheaders = None
2046def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002047 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002048 global _noheaders
2049 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002050 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002051 return _noheaders
2052
2053
2054# Utility classes
2055
2056class ftpwrapper:
2057 """Class used by open_ftp() for cache of open FTP connections."""
2058
2059 def __init__(self, user, passwd, host, port, dirs, timeout=None):
2060 self.user = user
2061 self.passwd = passwd
2062 self.host = host
2063 self.port = port
2064 self.dirs = dirs
2065 self.timeout = timeout
2066 self.init()
2067
2068 def init(self):
2069 import ftplib
2070 self.busy = 0
2071 self.ftp = ftplib.FTP()
2072 self.ftp.connect(self.host, self.port, self.timeout)
2073 self.ftp.login(self.user, self.passwd)
2074 for dir in self.dirs:
2075 self.ftp.cwd(dir)
2076
2077 def retrfile(self, file, type):
2078 import ftplib
2079 self.endtransfer()
2080 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2081 else: cmd = 'TYPE ' + type; isdir = 0
2082 try:
2083 self.ftp.voidcmd(cmd)
2084 except ftplib.all_errors:
2085 self.init()
2086 self.ftp.voidcmd(cmd)
2087 conn = None
2088 if file and not isdir:
2089 # Try to retrieve as a file
2090 try:
2091 cmd = 'RETR ' + file
2092 conn = self.ftp.ntransfercmd(cmd)
2093 except ftplib.error_perm as reason:
2094 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002095 raise URLError('ftp error', reason).with_traceback(
2096 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002097 if not conn:
2098 # Set transfer mode to ASCII!
2099 self.ftp.voidcmd('TYPE A')
2100 # Try a directory listing. Verify that directory exists.
2101 if file:
2102 pwd = self.ftp.pwd()
2103 try:
2104 try:
2105 self.ftp.cwd(file)
2106 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002107 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002108 finally:
2109 self.ftp.cwd(pwd)
2110 cmd = 'LIST ' + file
2111 else:
2112 cmd = 'LIST'
2113 conn = self.ftp.ntransfercmd(cmd)
2114 self.busy = 1
2115 # Pass back both a suitably decorated object and a retrieval length
Georg Brandl13e89462008-07-01 19:56:00 +00002116 return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002117 def endtransfer(self):
2118 if not self.busy:
2119 return
2120 self.busy = 0
2121 try:
2122 self.ftp.voidresp()
2123 except ftperrors():
2124 pass
2125
2126 def close(self):
2127 self.endtransfer()
2128 try:
2129 self.ftp.close()
2130 except ftperrors():
2131 pass
2132
2133# Proxy handling
2134def getproxies_environment():
2135 """Return a dictionary of scheme -> proxy server URL mappings.
2136
2137 Scan the environment for variables named <scheme>_proxy;
2138 this seems to be the standard convention. If you need a
2139 different way, you can pass a proxies dictionary to the
2140 [Fancy]URLopener constructor.
2141
2142 """
2143 proxies = {}
2144 for name, value in os.environ.items():
2145 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002146 if value and name[-6:] == '_proxy':
2147 proxies[name[:-6]] = value
2148 return proxies
2149
2150def proxy_bypass_environment(host):
2151 """Test if proxies should not be used for a particular host.
2152
2153 Checks the environment for a variable named no_proxy, which should
2154 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2155 """
2156 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2157 # '*' is special case for always bypass
2158 if no_proxy == '*':
2159 return 1
2160 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002161 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002162 # check if the host ends with any of the DNS suffixes
2163 for name in no_proxy.split(','):
2164 if name and (hostonly.endswith(name) or host.endswith(name)):
2165 return 1
2166 # otherwise, don't bypass
2167 return 0
2168
2169
2170if sys.platform == 'darwin':
Ronald Oussoren84151202010-04-18 20:46:11 +00002171 from _scproxy import _get_proxy_settings, _get_proxies
2172
2173 def proxy_bypass_macosx_sysconf(host):
2174 """
2175 Return True iff this host shouldn't be accessed using a proxy
2176
2177 This function uses the MacOSX framework SystemConfiguration
2178 to fetch the proxy information.
2179 """
2180 import re
2181 import socket
2182 from fnmatch import fnmatch
2183
2184 hostonly, port = splitport(host)
2185
2186 def ip2num(ipAddr):
2187 parts = ipAddr.split('.')
Mark Dickinsonc3f45c22010-05-09 12:16:29 +00002188 parts = list(map(int, parts))
Ronald Oussoren84151202010-04-18 20:46:11 +00002189 if len(parts) != 4:
2190 parts = (parts + [0, 0, 0, 0])[:4]
2191 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2192
2193 proxy_settings = _get_proxy_settings()
2194
2195 # Check for simple host names:
2196 if '.' not in host:
2197 if proxy_settings['exclude_simple']:
2198 return True
2199
2200 hostIP = None
2201
2202 for value in proxy_settings.get('exceptions', ()):
2203 # Items in the list are strings like these: *.local, 169.254/16
2204 if not value: continue
2205
2206 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2207 if m is not None:
2208 if hostIP is None:
2209 try:
2210 hostIP = socket.gethostbyname(hostonly)
2211 hostIP = ip2num(hostIP)
2212 except socket.error:
2213 continue
2214
2215 base = ip2num(m.group(1))
Ronald Oussorenab90f8e2010-06-27 14:26:30 +00002216 mask = m.group(2)
2217 if mask is None:
2218 mask = 8 * (m.group(1).count('.') + 1)
2219
2220 else:
2221 mask = int(mask[1:])
2222 mask = 32 - mask
Ronald Oussoren84151202010-04-18 20:46:11 +00002223
2224 if (hostIP >> mask) == (base >> mask):
2225 return True
2226
2227 elif fnmatch(host, value):
2228 return True
2229
2230 return False
2231
2232
2233 def getproxies_macosx_sysconf():
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002234 """Return a dictionary of scheme -> proxy server URL mappings.
2235
Ronald Oussoren84151202010-04-18 20:46:11 +00002236 This function uses the MacOSX framework SystemConfiguration
2237 to fetch the proxy information.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002238 """
Ronald Oussoren84151202010-04-18 20:46:11 +00002239 return _get_proxies()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002240
Ronald Oussoren84151202010-04-18 20:46:11 +00002241
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002242
2243 def proxy_bypass(host):
2244 if getproxies_environment():
2245 return proxy_bypass_environment(host)
2246 else:
Ronald Oussoren84151202010-04-18 20:46:11 +00002247 return proxy_bypass_macosx_sysconf(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002248
2249 def getproxies():
Ronald Oussoren84151202010-04-18 20:46:11 +00002250 return getproxies_environment() or getproxies_macosx_sysconf()
2251
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002252
2253elif os.name == 'nt':
2254 def getproxies_registry():
2255 """Return a dictionary of scheme -> proxy server URL mappings.
2256
2257 Win32 uses the registry to store proxies.
2258
2259 """
2260 proxies = {}
2261 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002262 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002263 except ImportError:
2264 # Std module, so should be around - but you never know!
2265 return proxies
2266 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002267 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002268 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002269 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002270 'ProxyEnable')[0]
2271 if proxyEnable:
2272 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002273 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002274 'ProxyServer')[0])
2275 if '=' in proxyServer:
2276 # Per-protocol settings
2277 for p in proxyServer.split(';'):
2278 protocol, address = p.split('=', 1)
2279 # See if address has a type:// prefix
2280 import re
2281 if not re.match('^([^/:]+)://', address):
2282 address = '%s://%s' % (protocol, address)
2283 proxies[protocol] = address
2284 else:
2285 # Use one setting for all protocols
2286 if proxyServer[:5] == 'http:':
2287 proxies['http'] = proxyServer
2288 else:
2289 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran04f31b82010-07-14 20:10:52 +00002290 proxies['https'] = 'https://%s' % proxyServer
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002291 proxies['ftp'] = 'ftp://%s' % proxyServer
2292 internetSettings.Close()
2293 except (WindowsError, ValueError, TypeError):
2294 # Either registry key not found etc, or the value in an
2295 # unexpected format.
2296 # proxies already set up to be empty so nothing to do
2297 pass
2298 return proxies
2299
2300 def getproxies():
2301 """Return a dictionary of scheme -> proxy server URL mappings.
2302
2303 Returns settings gathered from the environment, if specified,
2304 or the registry.
2305
2306 """
2307 return getproxies_environment() or getproxies_registry()
2308
2309 def proxy_bypass_registry(host):
2310 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002311 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002312 import re
2313 except ImportError:
2314 # Std modules, so should be around - but you never know!
2315 return 0
2316 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002317 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002318 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002319 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002320 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002321 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002322 'ProxyOverride')[0])
2323 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2324 except WindowsError:
2325 return 0
2326 if not proxyEnable or not proxyOverride:
2327 return 0
2328 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002329 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002330 host = [rawHost]
2331 try:
2332 addr = socket.gethostbyname(rawHost)
2333 if addr != rawHost:
2334 host.append(addr)
2335 except socket.error:
2336 pass
2337 try:
2338 fqdn = socket.getfqdn(rawHost)
2339 if fqdn != rawHost:
2340 host.append(fqdn)
2341 except socket.error:
2342 pass
2343 # make a check value list from the registry entry: replace the
2344 # '<local>' string by the localhost entry and the corresponding
2345 # canonical entry.
2346 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002347 # now check if we match one of the registry values.
2348 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002349 if test == '<local>':
2350 if '.' not in rawHost:
2351 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002352 test = test.replace(".", r"\.") # mask dots
2353 test = test.replace("*", r".*") # change glob sequence
2354 test = test.replace("?", r".") # change glob char
2355 for val in host:
2356 # print "%s <--> %s" %( test, val )
2357 if re.match(test, val, re.I):
2358 return 1
2359 return 0
2360
2361 def proxy_bypass(host):
2362 """Return a dictionary of scheme -> proxy server URL mappings.
2363
2364 Returns settings gathered from the environment, if specified,
2365 or the registry.
2366
2367 """
2368 if getproxies_environment():
2369 return proxy_bypass_environment(host)
2370 else:
2371 return proxy_bypass_registry(host)
2372
2373else:
2374 # By default use environment variables
2375 getproxies = getproxies_environment
2376 proxy_bypass = proxy_bypass_environment