blob: 4ed46ff0b53a5737550378d038d7ae38cfe6aad2 [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 Kumaran04454cd2009-11-15 07:27:02 +000033
34OpenerDirector -- Sets up the User-Agent as the Python-urllib and manages the
35Handler classes while dealing with both 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,
Facundo Batistaf24802c2008-08-17 03:36:03 +0000102 splitattr, splitquery, splitvalue, 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)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000166 self.data = data
167 self.headers = {}
Senthil Kumaran0ac1f832009-07-26 12:39:47 +0000168 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000169 for key, value in headers.items():
170 self.add_header(key, value)
171 self.unredirected_hdrs = {}
172 if origin_req_host is None:
173 origin_req_host = request_host(self)
174 self.origin_req_host = origin_req_host
175 self.unverifiable = unverifiable
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000176 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000177
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000178 def _parse(self):
179 self.type, rest = splittype(self.full_url)
180 if self.type is None:
181 raise ValueError("unknown url type: %s" % self.full_url)
182 self.host, self.selector = splithost(rest)
183 if self.host:
184 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000185
186 def get_method(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000187 if self.data is not None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000188 return "POST"
189 else:
190 return "GET"
191
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000192 # Begin deprecated methods
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000193
194 def add_data(self, data):
195 self.data = data
196
197 def has_data(self):
198 return self.data is not None
199
200 def get_data(self):
201 return self.data
202
203 def get_full_url(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000204 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000205
206 def get_type(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000207 return self.type
208
209 def get_host(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000210 return self.host
211
212 def get_selector(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000213 return self.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000214
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000215 def is_unverifiable(self):
216 return self.unverifiable
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000217
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000218 def get_origin_req_host(self):
219 return self.origin_req_host
220
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000221 # End deprecated methods
222
223 def set_proxy(self, host, type):
Senthil Kumaran0ac1f832009-07-26 12:39:47 +0000224 if self.type == 'https' and not self._tunnel_host:
225 self._tunnel_host = self.host
226 else:
227 self.type= type
228 self.selector = self.full_url
229 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000230
231 def has_proxy(self):
232 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000233
234 def add_header(self, key, val):
235 # useful for something like authentication
236 self.headers[key.capitalize()] = val
237
238 def add_unredirected_header(self, key, val):
239 # will not be added to a redirected request
240 self.unredirected_hdrs[key.capitalize()] = val
241
242 def has_header(self, header_name):
243 return (header_name in self.headers or
244 header_name in self.unredirected_hdrs)
245
246 def get_header(self, header_name, default=None):
247 return self.headers.get(
248 header_name,
249 self.unredirected_hdrs.get(header_name, default))
250
251 def header_items(self):
252 hdrs = self.unredirected_hdrs.copy()
253 hdrs.update(self.headers)
254 return list(hdrs.items())
255
256class OpenerDirector:
257 def __init__(self):
258 client_version = "Python-urllib/%s" % __version__
259 self.addheaders = [('User-agent', client_version)]
260 # manage the individual handlers
261 self.handlers = []
262 self.handle_open = {}
263 self.handle_error = {}
264 self.process_response = {}
265 self.process_request = {}
266
267 def add_handler(self, handler):
268 if not hasattr(handler, "add_parent"):
269 raise TypeError("expected BaseHandler instance, got %r" %
270 type(handler))
271
272 added = False
273 for meth in dir(handler):
274 if meth in ["redirect_request", "do_open", "proxy_open"]:
275 # oops, coincidental match
276 continue
277
278 i = meth.find("_")
279 protocol = meth[:i]
280 condition = meth[i+1:]
281
282 if condition.startswith("error"):
283 j = condition.find("_") + i + 1
284 kind = meth[j+1:]
285 try:
286 kind = int(kind)
287 except ValueError:
288 pass
289 lookup = self.handle_error.get(protocol, {})
290 self.handle_error[protocol] = lookup
291 elif condition == "open":
292 kind = protocol
293 lookup = self.handle_open
294 elif condition == "response":
295 kind = protocol
296 lookup = self.process_response
297 elif condition == "request":
298 kind = protocol
299 lookup = self.process_request
300 else:
301 continue
302
303 handlers = lookup.setdefault(kind, [])
304 if handlers:
305 bisect.insort(handlers, handler)
306 else:
307 handlers.append(handler)
308 added = True
309
310 if added:
311 # the handlers must work in an specific order, the order
312 # is specified in a Handler attribute
313 bisect.insort(self.handlers, handler)
314 handler.add_parent(self)
315
316 def close(self):
317 # Only exists for backwards compatibility.
318 pass
319
320 def _call_chain(self, chain, kind, meth_name, *args):
321 # Handlers raise an exception if no one else should try to handle
322 # the request, or return None if they can't but another handler
323 # could. Otherwise, they return the response.
324 handlers = chain.get(kind, ())
325 for handler in handlers:
326 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000327 result = func(*args)
328 if result is not None:
329 return result
330
331 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
332 # accept a URL or a Request object
333 if isinstance(fullurl, str):
334 req = Request(fullurl, data)
335 else:
336 req = fullurl
337 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000338 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000339
340 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000341 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000342
343 # pre-process request
344 meth_name = protocol+"_request"
345 for processor in self.process_request.get(protocol, []):
346 meth = getattr(processor, meth_name)
347 req = meth(req)
348
349 response = self._open(req, data)
350
351 # post-process response
352 meth_name = protocol+"_response"
353 for processor in self.process_response.get(protocol, []):
354 meth = getattr(processor, meth_name)
355 response = meth(req, response)
356
357 return response
358
359 def _open(self, req, data=None):
360 result = self._call_chain(self.handle_open, 'default',
361 'default_open', req)
362 if result:
363 return result
364
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000365 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000366 result = self._call_chain(self.handle_open, protocol, protocol +
367 '_open', req)
368 if result:
369 return result
370
371 return self._call_chain(self.handle_open, 'unknown',
372 'unknown_open', req)
373
374 def error(self, proto, *args):
375 if proto in ('http', 'https'):
376 # XXX http[s] protocols are special-cased
377 dict = self.handle_error['http'] # https is not different than http
378 proto = args[2] # YUCK!
379 meth_name = 'http_error_%s' % proto
380 http_err = 1
381 orig_args = args
382 else:
383 dict = self.handle_error
384 meth_name = proto + '_error'
385 http_err = 0
386 args = (dict, proto, meth_name) + args
387 result = self._call_chain(*args)
388 if result:
389 return result
390
391 if http_err:
392 args = (dict, 'default', 'http_error_default') + orig_args
393 return self._call_chain(*args)
394
395# XXX probably also want an abstract factory that knows when it makes
396# sense to skip a superclass in favor of a subclass and when it might
397# make sense to include both
398
399def build_opener(*handlers):
400 """Create an opener object from a list of handlers.
401
402 The opener will use several default handlers, including support
Senthil Kumaran04454cd2009-11-15 07:27:02 +0000403 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000404
405 If any of the handlers passed as arguments are subclasses of the
406 default handlers, the default handlers will not be used.
407 """
408 def isclass(obj):
409 return isinstance(obj, type) or hasattr(obj, "__bases__")
410
411 opener = OpenerDirector()
412 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
413 HTTPDefaultErrorHandler, HTTPRedirectHandler,
414 FTPHandler, FileHandler, HTTPErrorProcessor]
415 if hasattr(http.client, "HTTPSConnection"):
416 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000417 skip = set()
418 for klass in default_classes:
419 for check in handlers:
420 if isclass(check):
421 if issubclass(check, klass):
422 skip.add(klass)
423 elif isinstance(check, klass):
424 skip.add(klass)
425 for klass in skip:
426 default_classes.remove(klass)
427
428 for klass in default_classes:
429 opener.add_handler(klass())
430
431 for h in handlers:
432 if isclass(h):
433 h = h()
434 opener.add_handler(h)
435 return opener
436
437class BaseHandler:
438 handler_order = 500
439
440 def add_parent(self, parent):
441 self.parent = parent
442
443 def close(self):
444 # Only exists for backwards compatibility
445 pass
446
447 def __lt__(self, other):
448 if not hasattr(other, "handler_order"):
449 # Try to preserve the old behavior of having custom classes
450 # inserted after default ones (works only for custom user
451 # classes which are not aware of handler_order).
452 return True
453 return self.handler_order < other.handler_order
454
455
456class HTTPErrorProcessor(BaseHandler):
457 """Process HTTP error responses."""
458 handler_order = 1000 # after all other processing
459
460 def http_response(self, request, response):
461 code, msg, hdrs = response.code, response.msg, response.info()
462
463 # According to RFC 2616, "2xx" code indicates that the client's
464 # request was successfully received, understood, and accepted.
465 if not (200 <= code < 300):
466 response = self.parent.error(
467 'http', request, response, code, msg, hdrs)
468
469 return response
470
471 https_response = http_response
472
473class HTTPDefaultErrorHandler(BaseHandler):
474 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000475 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000476
477class HTTPRedirectHandler(BaseHandler):
478 # maximum number of redirections to any single URL
479 # this is needed because of the state that cookies introduce
480 max_repeats = 4
481 # maximum total number of redirections (regardless of URL) before
482 # assuming we're in a loop
483 max_redirections = 10
484
485 def redirect_request(self, req, fp, code, msg, headers, newurl):
486 """Return a Request or None in response to a redirect.
487
488 This is called by the http_error_30x methods when a
489 redirection response is received. If a redirection should
490 take place, return a new Request to allow http_error_30x to
491 perform the redirect. Otherwise, raise HTTPError if no-one
492 else should try to handle this url. Return None if you can't
493 but another Handler might.
494 """
495 m = req.get_method()
496 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
497 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000498 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000499
500 # Strictly (according to RFC 2616), 301 or 302 in response to
501 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000502 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000503 # essentially all clients do redirect in this case, so we do
504 # the same.
505 # be conciliant with URIs containing a space
506 newurl = newurl.replace(' ', '%20')
507 CONTENT_HEADERS = ("content-length", "content-type")
508 newheaders = dict((k, v) for k, v in req.headers.items()
509 if k.lower() not in CONTENT_HEADERS)
510 return Request(newurl,
511 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000512 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000513 unverifiable=True)
514
515 # Implementation note: To avoid the server sending us into an
516 # infinite loop, the request object needs to track what URLs we
517 # have already seen. Do this by adding a handler-specific
518 # attribute to the Request object.
519 def http_error_302(self, req, fp, code, msg, headers):
520 # Some servers (incorrectly) return multiple Location headers
521 # (so probably same goes for URI). Use first header.
522 if "location" in headers:
523 newurl = headers["location"]
524 elif "uri" in headers:
525 newurl = headers["uri"]
526 else:
527 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000528
529 # fix a possible malformed URL
530 urlparts = urlparse(newurl)
531 if not urlparts.path:
532 urlparts = list(urlparts)
533 urlparts[2] = "/"
534 newurl = urlunparse(urlparts)
535
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000536 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000537
538 # XXX Probably want to forget about the state of the current
539 # request, although that might interact poorly with other
540 # handlers that also use handler-specific request attributes
541 new = self.redirect_request(req, fp, code, msg, headers, newurl)
542 if new is None:
543 return
544
545 # loop detection
546 # .redirect_dict has a key url if url was previously visited.
547 if hasattr(req, 'redirect_dict'):
548 visited = new.redirect_dict = req.redirect_dict
549 if (visited.get(newurl, 0) >= self.max_repeats or
550 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000551 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000552 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000553 else:
554 visited = new.redirect_dict = req.redirect_dict = {}
555 visited[newurl] = visited.get(newurl, 0) + 1
556
557 # Don't close the fp until we are sure that we won't use it
558 # with HTTPError.
559 fp.read()
560 fp.close()
561
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000562 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000563
564 http_error_301 = http_error_303 = http_error_307 = http_error_302
565
566 inf_msg = "The HTTP server returned a redirect error that would " \
567 "lead to an infinite loop.\n" \
568 "The last 30x error message was:\n"
569
570
571def _parse_proxy(proxy):
572 """Return (scheme, user, password, host/port) given a URL or an authority.
573
574 If a URL is supplied, it must have an authority (host:port) component.
575 According to RFC 3986, having an authority component means the URL must
576 have two slashes after the scheme:
577
578 >>> _parse_proxy('file:/ftp.example.com/')
579 Traceback (most recent call last):
580 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
581
582 The first three items of the returned tuple may be None.
583
584 Examples of authority parsing:
585
586 >>> _parse_proxy('proxy.example.com')
587 (None, None, None, 'proxy.example.com')
588 >>> _parse_proxy('proxy.example.com:3128')
589 (None, None, None, 'proxy.example.com:3128')
590
591 The authority component may optionally include userinfo (assumed to be
592 username:password):
593
594 >>> _parse_proxy('joe:password@proxy.example.com')
595 (None, 'joe', 'password', 'proxy.example.com')
596 >>> _parse_proxy('joe:password@proxy.example.com:3128')
597 (None, 'joe', 'password', 'proxy.example.com:3128')
598
599 Same examples, but with URLs instead:
600
601 >>> _parse_proxy('http://proxy.example.com/')
602 ('http', None, None, 'proxy.example.com')
603 >>> _parse_proxy('http://proxy.example.com:3128/')
604 ('http', None, None, 'proxy.example.com:3128')
605 >>> _parse_proxy('http://joe:password@proxy.example.com/')
606 ('http', 'joe', 'password', 'proxy.example.com')
607 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
608 ('http', 'joe', 'password', 'proxy.example.com:3128')
609
610 Everything after the authority is ignored:
611
612 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
613 ('ftp', 'joe', 'password', 'proxy.example.com')
614
615 Test for no trailing '/' case:
616
617 >>> _parse_proxy('http://joe:password@proxy.example.com')
618 ('http', 'joe', 'password', 'proxy.example.com')
619
620 """
Georg Brandl13e89462008-07-01 19:56:00 +0000621 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000622 if not r_scheme.startswith("/"):
623 # authority
624 scheme = None
625 authority = proxy
626 else:
627 # URL
628 if not r_scheme.startswith("//"):
629 raise ValueError("proxy URL with no authority: %r" % proxy)
630 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
631 # and 3.3.), path is empty or starts with '/'
632 end = r_scheme.find("/", 2)
633 if end == -1:
634 end = None
635 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000636 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000637 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000638 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000639 else:
640 user = password = None
641 return scheme, user, password, hostport
642
643class ProxyHandler(BaseHandler):
644 # Proxies must be in front
645 handler_order = 100
646
647 def __init__(self, proxies=None):
648 if proxies is None:
649 proxies = getproxies()
650 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
651 self.proxies = proxies
652 for type, url in proxies.items():
653 setattr(self, '%s_open' % type,
654 lambda r, proxy=url, type=type, meth=self.proxy_open: \
655 meth(r, proxy, type))
656
657 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000658 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000659 proxy_type, user, password, hostport = _parse_proxy(proxy)
660 if proxy_type is None:
661 proxy_type = orig_type
Senthil Kumaran11301632009-10-11 06:07:46 +0000662
663 if req.host and proxy_bypass(req.host):
664 return None
665
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000666 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000667 user_pass = '%s:%s' % (unquote(user),
668 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000669 creds = base64.b64encode(user_pass.encode()).decode("ascii")
670 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000671 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000672 req.set_proxy(hostport, proxy_type)
Senthil Kumaran0ac1f832009-07-26 12:39:47 +0000673 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000674 # let other handlers take care of it
675 return None
676 else:
677 # need to start over, because the other handlers don't
678 # grok the proxy's URL type
679 # e.g. if we have a constructor arg proxies like so:
680 # {'http': 'ftp://proxy.example.com'}, we may end up turning
681 # a request for http://acme.example.com/a into one for
682 # ftp://proxy.example.com/a
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000683 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000684
685class HTTPPasswordMgr:
686
687 def __init__(self):
688 self.passwd = {}
689
690 def add_password(self, realm, uri, user, passwd):
691 # uri could be a single URI or a sequence
692 if isinstance(uri, str):
693 uri = [uri]
694 if not realm in self.passwd:
695 self.passwd[realm] = {}
696 for default_port in True, False:
697 reduced_uri = tuple(
698 [self.reduce_uri(u, default_port) for u in uri])
699 self.passwd[realm][reduced_uri] = (user, passwd)
700
701 def find_user_password(self, realm, authuri):
702 domains = self.passwd.get(realm, {})
703 for default_port in True, False:
704 reduced_authuri = self.reduce_uri(authuri, default_port)
705 for uris, authinfo in domains.items():
706 for uri in uris:
707 if self.is_suburi(uri, reduced_authuri):
708 return authinfo
709 return None, None
710
711 def reduce_uri(self, uri, default_port=True):
712 """Accept authority or URI and extract only the authority and path."""
713 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000714 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000715 if parts[1]:
716 # URI
717 scheme = parts[0]
718 authority = parts[1]
719 path = parts[2] or '/'
720 else:
721 # host or host:port
722 scheme = None
723 authority = uri
724 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000725 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000726 if default_port and port is None and scheme is not None:
727 dport = {"http": 80,
728 "https": 443,
729 }.get(scheme)
730 if dport is not None:
731 authority = "%s:%d" % (host, dport)
732 return authority, path
733
734 def is_suburi(self, base, test):
735 """Check if test is below base in a URI tree
736
737 Both args must be URIs in reduced form.
738 """
739 if base == test:
740 return True
741 if base[0] != test[0]:
742 return False
743 common = posixpath.commonprefix((base[1], test[1]))
744 if len(common) == len(base[1]):
745 return True
746 return False
747
748
749class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
750
751 def find_user_password(self, realm, authuri):
752 user, password = HTTPPasswordMgr.find_user_password(self, realm,
753 authuri)
754 if user is not None:
755 return user, password
756 return HTTPPasswordMgr.find_user_password(self, None, authuri)
757
758
759class AbstractBasicAuthHandler:
760
761 # XXX this allows for multiple auth-schemes, but will stupidly pick
762 # the last one with a realm specified.
763
764 # allow for double- and single-quoted realm values
765 # (single quotes are a violation of the RFC, but appear in the wild)
766 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
767 'realm=(["\'])(.*?)\\2', re.I)
768
769 # XXX could pre-emptively send auth info already accepted (RFC 2617,
770 # end of section 2, and section 1.2 immediately after "credentials"
771 # production).
772
773 def __init__(self, password_mgr=None):
774 if password_mgr is None:
775 password_mgr = HTTPPasswordMgr()
776 self.passwd = password_mgr
777 self.add_password = self.passwd.add_password
778
779 def http_error_auth_reqed(self, authreq, host, req, headers):
780 # host may be an authority (without userinfo) or a URL with an
781 # authority
782 # XXX could be multiple headers
783 authreq = headers.get(authreq, None)
784 if authreq:
785 mo = AbstractBasicAuthHandler.rx.search(authreq)
786 if mo:
787 scheme, quote, realm = mo.groups()
788 if scheme.lower() == 'basic':
789 return self.retry_http_basic_auth(host, req, realm)
790
791 def retry_http_basic_auth(self, host, req, realm):
792 user, pw = self.passwd.find_user_password(realm, host)
793 if pw is not None:
794 raw = "%s:%s" % (user, pw)
795 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
796 if req.headers.get(self.auth_header, None) == auth:
797 return None
798 req.add_header(self.auth_header, auth)
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000799 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000800 else:
801 return None
802
803
804class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
805
806 auth_header = 'Authorization'
807
808 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000809 url = req.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000810 return self.http_error_auth_reqed('www-authenticate',
811 url, req, headers)
812
813
814class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
815
816 auth_header = 'Proxy-authorization'
817
818 def http_error_407(self, req, fp, code, msg, headers):
819 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000820 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000821 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
822 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000823 authority = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000824 return self.http_error_auth_reqed('proxy-authenticate',
825 authority, req, headers)
826
827
828def randombytes(n):
829 """Return n random bytes."""
830 return os.urandom(n)
831
832class AbstractDigestAuthHandler:
833 # Digest authentication is specified in RFC 2617.
834
835 # XXX The client does not inspect the Authentication-Info header
836 # in a successful response.
837
838 # XXX It should be possible to test this implementation against
839 # a mock server that just generates a static set of challenges.
840
841 # XXX qop="auth-int" supports is shaky
842
843 def __init__(self, passwd=None):
844 if passwd is None:
845 passwd = HTTPPasswordMgr()
846 self.passwd = passwd
847 self.add_password = self.passwd.add_password
848 self.retried = 0
849 self.nonce_count = 0
850
851 def reset_retry_count(self):
852 self.retried = 0
853
854 def http_error_auth_reqed(self, auth_header, host, req, headers):
855 authreq = headers.get(auth_header, None)
856 if self.retried > 5:
857 # Don't fail endlessly - if we failed once, we'll probably
858 # fail a second time. Hm. Unless the Password Manager is
859 # prompting for the information. Crap. This isn't great
860 # but it's better than the current 'repeat until recursion
861 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000862 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000863 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000864 else:
865 self.retried += 1
866 if authreq:
867 scheme = authreq.split()[0]
868 if scheme.lower() == 'digest':
869 return self.retry_http_digest_auth(req, authreq)
870
871 def retry_http_digest_auth(self, req, auth):
872 token, challenge = auth.split(' ', 1)
873 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
874 auth = self.get_authorization(req, chal)
875 if auth:
876 auth_val = 'Digest %s' % auth
877 if req.headers.get(self.auth_header, None) == auth_val:
878 return None
879 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000880 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000881 return resp
882
883 def get_cnonce(self, nonce):
884 # The cnonce-value is an opaque
885 # quoted string value provided by the client and used by both client
886 # and server to avoid chosen plaintext attacks, to provide mutual
887 # authentication, and to provide some message integrity protection.
888 # This isn't a fabulous effort, but it's probably Good Enough.
889 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
890 b = s.encode("ascii") + randombytes(8)
891 dig = hashlib.sha1(b).hexdigest()
892 return dig[:16]
893
894 def get_authorization(self, req, chal):
895 try:
896 realm = chal['realm']
897 nonce = chal['nonce']
898 qop = chal.get('qop')
899 algorithm = chal.get('algorithm', 'MD5')
900 # mod_digest doesn't send an opaque, even though it isn't
901 # supposed to be optional
902 opaque = chal.get('opaque', None)
903 except KeyError:
904 return None
905
906 H, KD = self.get_algorithm_impls(algorithm)
907 if H is None:
908 return None
909
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000910 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000911 if user is None:
912 return None
913
914 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000915 if req.data is not None:
916 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000917 else:
918 entdig = None
919
920 A1 = "%s:%s:%s" % (user, realm, pw)
921 A2 = "%s:%s" % (req.get_method(),
922 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000923 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000924 if qop == 'auth':
925 self.nonce_count += 1
926 ncvalue = '%08x' % self.nonce_count
927 cnonce = self.get_cnonce(nonce)
928 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
929 respdig = KD(H(A1), noncebit)
930 elif qop is None:
931 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
932 else:
933 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +0000934 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000935
936 # XXX should the partial digests be encoded too?
937
938 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000939 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000940 respdig)
941 if opaque:
942 base += ', opaque="%s"' % opaque
943 if entdig:
944 base += ', digest="%s"' % entdig
945 base += ', algorithm="%s"' % algorithm
946 if qop:
947 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
948 return base
949
950 def get_algorithm_impls(self, algorithm):
951 # lambdas assume digest modules are imported at the top level
952 if algorithm == 'MD5':
953 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
954 elif algorithm == 'SHA':
955 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
956 # XXX MD5-sess
957 KD = lambda s, d: H("%s:%s" % (s, d))
958 return H, KD
959
960 def get_entity_digest(self, data, chal):
961 # XXX not implemented yet
962 return None
963
964
965class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
966 """An authentication protocol defined by RFC 2069
967
968 Digest authentication improves on basic authentication because it
969 does not transmit passwords in the clear.
970 """
971
972 auth_header = 'Authorization'
973 handler_order = 490 # before Basic auth
974
975 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000976 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000977 retry = self.http_error_auth_reqed('www-authenticate',
978 host, req, headers)
979 self.reset_retry_count()
980 return retry
981
982
983class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
984
985 auth_header = 'Proxy-Authorization'
986 handler_order = 490 # before Basic auth
987
988 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000989 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000990 retry = self.http_error_auth_reqed('proxy-authenticate',
991 host, req, headers)
992 self.reset_retry_count()
993 return retry
994
995class AbstractHTTPHandler(BaseHandler):
996
997 def __init__(self, debuglevel=0):
998 self._debuglevel = debuglevel
999
1000 def set_http_debuglevel(self, level):
1001 self._debuglevel = level
1002
1003 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001004 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001005 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001006 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001007
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001008 if request.data is not None: # POST
1009 data = request.data
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001010 if not request.has_header('Content-type'):
1011 request.add_unredirected_header(
1012 'Content-type',
1013 'application/x-www-form-urlencoded')
1014 if not request.has_header('Content-length'):
1015 request.add_unredirected_header(
1016 'Content-length', '%d' % len(data))
1017
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001018 sel_host = host
1019 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001020 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001021 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001022 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001023 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001024 for name, value in self.parent.addheaders:
1025 name = name.capitalize()
1026 if not request.has_header(name):
1027 request.add_unredirected_header(name, value)
1028
1029 return request
1030
1031 def do_open(self, http_class, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001032 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001033
1034 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001035 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001036 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001037 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001038 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001039
1040 h = http_class(host, timeout=req.timeout) # will parse host:port
1041 headers = dict(req.headers)
1042 headers.update(req.unredirected_hdrs)
1043
1044 # TODO(jhylton): Should this be redesigned to handle
1045 # persistent connections?
1046
1047 # We want to make an HTTP/1.1 request, but the addinfourl
1048 # class isn't prepared to deal with a persistent connection.
1049 # It will try to read all remaining data from the socket,
1050 # which will block while the server waits for the next request.
1051 # So make sure the connection gets closed after the (only)
1052 # request.
1053 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001054 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran0ac1f832009-07-26 12:39:47 +00001055
1056 if req._tunnel_host:
1057 h._set_tunnel(req._tunnel_host)
1058
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001059 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001060 h.request(req.get_method(), req.selector, req.data, headers)
1061 r = h.getresponse() # an HTTPResponse instance
1062 except socket.error as err:
Georg Brandl13e89462008-07-01 19:56:00 +00001063 raise URLError(err)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001064
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001065 r.url = req.full_url
1066 # This line replaces the .msg attribute of the HTTPResponse
1067 # with .headers, because urllib clients expect the response to
1068 # have the reason in .msg. It would be good to mark this
1069 # attribute is deprecated and get then to use info() or
1070 # .headers.
1071 r.msg = r.reason
1072 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001073
1074
1075class HTTPHandler(AbstractHTTPHandler):
1076
1077 def http_open(self, req):
1078 return self.do_open(http.client.HTTPConnection, req)
1079
1080 http_request = AbstractHTTPHandler.do_request_
1081
1082if hasattr(http.client, 'HTTPSConnection'):
1083 class HTTPSHandler(AbstractHTTPHandler):
1084
1085 def https_open(self, req):
1086 return self.do_open(http.client.HTTPSConnection, req)
1087
1088 https_request = AbstractHTTPHandler.do_request_
1089
1090class HTTPCookieProcessor(BaseHandler):
1091 def __init__(self, cookiejar=None):
1092 import http.cookiejar
1093 if cookiejar is None:
1094 cookiejar = http.cookiejar.CookieJar()
1095 self.cookiejar = cookiejar
1096
1097 def http_request(self, request):
1098 self.cookiejar.add_cookie_header(request)
1099 return request
1100
1101 def http_response(self, request, response):
1102 self.cookiejar.extract_cookies(response, request)
1103 return response
1104
1105 https_request = http_request
1106 https_response = http_response
1107
1108class UnknownHandler(BaseHandler):
1109 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001110 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001111 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001112
1113def parse_keqv_list(l):
1114 """Parse list of key=value strings where keys are not duplicated."""
1115 parsed = {}
1116 for elt in l:
1117 k, v = elt.split('=', 1)
1118 if v[0] == '"' and v[-1] == '"':
1119 v = v[1:-1]
1120 parsed[k] = v
1121 return parsed
1122
1123def parse_http_list(s):
1124 """Parse lists as described by RFC 2068 Section 2.
1125
1126 In particular, parse comma-separated lists where the elements of
1127 the list may include quoted-strings. A quoted-string could
1128 contain a comma. A non-quoted string could have quotes in the
1129 middle. Neither commas nor quotes count if they are escaped.
1130 Only double-quotes count, not single-quotes.
1131 """
1132 res = []
1133 part = ''
1134
1135 escape = quote = False
1136 for cur in s:
1137 if escape:
1138 part += cur
1139 escape = False
1140 continue
1141 if quote:
1142 if cur == '\\':
1143 escape = True
1144 continue
1145 elif cur == '"':
1146 quote = False
1147 part += cur
1148 continue
1149
1150 if cur == ',':
1151 res.append(part)
1152 part = ''
1153 continue
1154
1155 if cur == '"':
1156 quote = True
1157
1158 part += cur
1159
1160 # append last part
1161 if part:
1162 res.append(part)
1163
1164 return [part.strip() for part in res]
1165
1166class FileHandler(BaseHandler):
1167 # Use local file or FTP depending on form of URL
1168 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001169 url = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001170 if url[:2] == '//' and url[2:3] != '/':
1171 req.type = 'ftp'
1172 return self.parent.open(req)
1173 else:
1174 return self.open_local_file(req)
1175
1176 # names for the localhost
1177 names = None
1178 def get_names(self):
1179 if FileHandler.names is None:
1180 try:
1181 FileHandler.names = (socket.gethostbyname('localhost'),
1182 socket.gethostbyname(socket.gethostname()))
1183 except socket.gaierror:
1184 FileHandler.names = (socket.gethostbyname('localhost'),)
1185 return FileHandler.names
1186
1187 # not entirely sure what the rules are here
1188 def open_local_file(self, req):
1189 import email.utils
1190 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001191 host = req.host
1192 file = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001193 localfile = url2pathname(file)
1194 try:
1195 stats = os.stat(localfile)
1196 size = stats.st_size
1197 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1198 mtype = mimetypes.guess_type(file)[0]
1199 headers = email.message_from_string(
1200 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1201 (mtype or 'text/plain', size, modified))
1202 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001203 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001204 if not host or \
1205 (not port and _safe_gethostbyname(host) in self.get_names()):
Georg Brandl13e89462008-07-01 19:56:00 +00001206 return addinfourl(open(localfile, 'rb'), headers, 'file:'+file)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001207 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001208 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001209 raise URLError(msg)
1210 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001211
1212def _safe_gethostbyname(host):
1213 try:
1214 return socket.gethostbyname(host)
1215 except socket.gaierror:
1216 return None
1217
1218class FTPHandler(BaseHandler):
1219 def ftp_open(self, req):
1220 import ftplib
1221 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001222 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001223 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001224 raise URLError('ftp error: no host given')
1225 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001226 if port is None:
1227 port = ftplib.FTP_PORT
1228 else:
1229 port = int(port)
1230
1231 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001232 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001233 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001234 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001235 else:
1236 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001237 host = unquote(host)
1238 user = unquote(user or '')
1239 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001240
1241 try:
1242 host = socket.gethostbyname(host)
1243 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001244 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001245 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001246 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001247 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001248 dirs, file = dirs[:-1], dirs[-1]
1249 if dirs and not dirs[0]:
1250 dirs = dirs[1:]
1251 try:
1252 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1253 type = file and 'I' or 'D'
1254 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001255 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001256 if attr.lower() == 'type' and \
1257 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1258 type = value.upper()
1259 fp, retrlen = fw.retrfile(file, type)
1260 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001261 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001262 if mtype:
1263 headers += "Content-type: %s\n" % mtype
1264 if retrlen is not None and retrlen >= 0:
1265 headers += "Content-length: %d\n" % retrlen
1266 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001267 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001268 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001269 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001270 raise exc.with_traceback(sys.exc_info()[2])
1271
1272 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1273 fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
1274 return fw
1275
1276class CacheFTPHandler(FTPHandler):
1277 # XXX would be nice to have pluggable cache strategies
1278 # XXX this stuff is definitely not thread safe
1279 def __init__(self):
1280 self.cache = {}
1281 self.timeout = {}
1282 self.soonest = 0
1283 self.delay = 60
1284 self.max_conns = 16
1285
1286 def setTimeout(self, t):
1287 self.delay = t
1288
1289 def setMaxConns(self, m):
1290 self.max_conns = m
1291
1292 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1293 key = user, host, port, '/'.join(dirs), timeout
1294 if key in self.cache:
1295 self.timeout[key] = time.time() + self.delay
1296 else:
1297 self.cache[key] = ftpwrapper(user, passwd, host, port,
1298 dirs, timeout)
1299 self.timeout[key] = time.time() + self.delay
1300 self.check_cache()
1301 return self.cache[key]
1302
1303 def check_cache(self):
1304 # first check for old ones
1305 t = time.time()
1306 if self.soonest <= t:
1307 for k, v in list(self.timeout.items()):
1308 if v < t:
1309 self.cache[k].close()
1310 del self.cache[k]
1311 del self.timeout[k]
1312 self.soonest = min(list(self.timeout.values()))
1313
1314 # then check the size
1315 if len(self.cache) == self.max_conns:
1316 for k, v in list(self.timeout.items()):
1317 if v == self.soonest:
1318 del self.cache[k]
1319 del self.timeout[k]
1320 break
1321 self.soonest = min(list(self.timeout.values()))
1322
1323# Code move from the old urllib module
1324
1325MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1326
1327# Helper for non-unix systems
1328if os.name == 'mac':
1329 from macurl2path import url2pathname, pathname2url
1330elif os.name == 'nt':
1331 from nturl2path import url2pathname, pathname2url
1332else:
1333 def url2pathname(pathname):
1334 """OS-specific conversion from a relative URL of the 'file' scheme
1335 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001336 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001337
1338 def pathname2url(pathname):
1339 """OS-specific conversion from a file system path to a relative URL
1340 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001341 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001342
1343# This really consists of two pieces:
1344# (1) a class which handles opening of all sorts of URLs
1345# (plus assorted utilities etc.)
1346# (2) a set of functions for parsing URLs
1347# XXX Should these be separated out into different modules?
1348
1349
1350ftpcache = {}
1351class URLopener:
1352 """Class to open URLs.
1353 This is a class rather than just a subroutine because we may need
1354 more than one set of global protocol-specific options.
1355 Note -- this is a base class for those who don't want the
1356 automatic handling of errors type 302 (relocated) and 401
1357 (authorization needed)."""
1358
1359 __tempfiles = None
1360
1361 version = "Python-urllib/%s" % __version__
1362
1363 # Constructor
1364 def __init__(self, proxies=None, **x509):
1365 if proxies is None:
1366 proxies = getproxies()
1367 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1368 self.proxies = proxies
1369 self.key_file = x509.get('key_file')
1370 self.cert_file = x509.get('cert_file')
1371 self.addheaders = [('User-Agent', self.version)]
1372 self.__tempfiles = []
1373 self.__unlink = os.unlink # See cleanup()
1374 self.tempcache = None
1375 # Undocumented feature: if you assign {} to tempcache,
1376 # it is used to cache files retrieved with
1377 # self.retrieve(). This is not enabled by default
1378 # since it does not work for changing documents (and I
1379 # haven't got the logic to check expiration headers
1380 # yet).
1381 self.ftpcache = ftpcache
1382 # Undocumented feature: you can use a different
1383 # ftp cache by assigning to the .ftpcache member;
1384 # in case you want logically independent URL openers
1385 # XXX This is not threadsafe. Bah.
1386
1387 def __del__(self):
1388 self.close()
1389
1390 def close(self):
1391 self.cleanup()
1392
1393 def cleanup(self):
1394 # This code sometimes runs when the rest of this module
1395 # has already been deleted, so it can't use any globals
1396 # or import anything.
1397 if self.__tempfiles:
1398 for file in self.__tempfiles:
1399 try:
1400 self.__unlink(file)
1401 except OSError:
1402 pass
1403 del self.__tempfiles[:]
1404 if self.tempcache:
1405 self.tempcache.clear()
1406
1407 def addheader(self, *args):
1408 """Add a header to be used by the HTTP interface only
1409 e.g. u.addheader('Accept', 'sound/basic')"""
1410 self.addheaders.append(args)
1411
1412 # External interface
1413 def open(self, fullurl, data=None):
1414 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001415 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001416 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001417 if self.tempcache and fullurl in self.tempcache:
1418 filename, headers = self.tempcache[fullurl]
1419 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001420 return addinfourl(fp, headers, fullurl)
1421 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001422 if not urltype:
1423 urltype = 'file'
1424 if urltype in self.proxies:
1425 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001426 urltype, proxyhost = splittype(proxy)
1427 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001428 url = (host, fullurl) # Signal special case to open_*()
1429 else:
1430 proxy = None
1431 name = 'open_' + urltype
1432 self.type = urltype
1433 name = name.replace('-', '_')
1434 if not hasattr(self, name):
1435 if proxy:
1436 return self.open_unknown_proxy(proxy, fullurl, data)
1437 else:
1438 return self.open_unknown(fullurl, data)
1439 try:
1440 if data is None:
1441 return getattr(self, name)(url)
1442 else:
1443 return getattr(self, name)(url, data)
1444 except socket.error as msg:
1445 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1446
1447 def open_unknown(self, fullurl, data=None):
1448 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001449 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001450 raise IOError('url error', 'unknown url type', type)
1451
1452 def open_unknown_proxy(self, proxy, fullurl, data=None):
1453 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001454 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001455 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1456
1457 # External interface
1458 def retrieve(self, url, filename=None, reporthook=None, data=None):
1459 """retrieve(url) returns (filename, headers) for a local object
1460 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001461 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001462 if self.tempcache and url in self.tempcache:
1463 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001464 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001465 if filename is None and (not type or type == 'file'):
1466 try:
1467 fp = self.open_local_file(url1)
1468 hdrs = fp.info()
1469 del fp
Georg Brandl13e89462008-07-01 19:56:00 +00001470 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001471 except IOError as msg:
1472 pass
1473 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001474 try:
1475 headers = fp.info()
1476 if filename:
1477 tfp = open(filename, 'wb')
1478 else:
1479 import tempfile
1480 garbage, path = splittype(url)
1481 garbage, path = splithost(path or "")
1482 path, garbage = splitquery(path or "")
1483 path, garbage = splitattr(path or "")
1484 suffix = os.path.splitext(path)[1]
1485 (fd, filename) = tempfile.mkstemp(suffix)
1486 self.__tempfiles.append(filename)
1487 tfp = os.fdopen(fd, 'wb')
1488 try:
1489 result = filename, headers
1490 if self.tempcache is not None:
1491 self.tempcache[url] = result
1492 bs = 1024*8
1493 size = -1
1494 read = 0
1495 blocknum = 0
1496 if reporthook:
1497 if "content-length" in headers:
1498 size = int(headers["Content-Length"])
1499 reporthook(blocknum, bs, size)
1500 while 1:
1501 block = fp.read(bs)
1502 if not block:
1503 break
1504 read += len(block)
1505 tfp.write(block)
1506 blocknum += 1
1507 if reporthook:
1508 reporthook(blocknum, bs, size)
1509 finally:
1510 tfp.close()
1511 finally:
1512 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001513 del fp
1514 del tfp
1515
1516 # raise exception if actual size does not match content-length header
1517 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001518 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001519 "retrieval incomplete: got only %i out of %i bytes"
1520 % (read, size), result)
1521
1522 return result
1523
1524 # Each method named open_<type> knows how to open that type of URL
1525
1526 def _open_generic_http(self, connection_factory, url, data):
1527 """Make an HTTP connection using connection_class.
1528
1529 This is an internal method that should be called from
1530 open_http() or open_https().
1531
1532 Arguments:
1533 - connection_factory should take a host name and return an
1534 HTTPConnection instance.
1535 - url is the url to retrieval or a host, relative-path pair.
1536 - data is payload for a POST request or None.
1537 """
1538
1539 user_passwd = None
1540 proxy_passwd= None
1541 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001542 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001543 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001544 user_passwd, host = splituser(host)
1545 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001546 realhost = host
1547 else:
1548 host, selector = url
1549 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001550 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001551 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001552 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001553 url = rest
1554 user_passwd = None
1555 if urltype.lower() != 'http':
1556 realhost = None
1557 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001558 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001559 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001560 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001561 if user_passwd:
1562 selector = "%s://%s%s" % (urltype, realhost, rest)
1563 if proxy_bypass(realhost):
1564 host = realhost
1565
1566 #print "proxy via http:", host, selector
1567 if not host: raise IOError('http error', 'no host given')
1568
1569 if proxy_passwd:
1570 import base64
1571 proxy_auth = base64.b64encode(proxy_passwd).strip()
1572 else:
1573 proxy_auth = None
1574
1575 if user_passwd:
1576 import base64
1577 auth = base64.b64encode(user_passwd).strip()
1578 else:
1579 auth = None
1580 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001581 headers = {}
1582 if proxy_auth:
1583 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1584 if auth:
1585 headers["Authorization"] = "Basic %s" % auth
1586 if realhost:
1587 headers["Host"] = realhost
1588 for header, value in self.addheaders:
1589 headers[header] = value
1590
1591 if data is not None:
1592 headers["Content-Type"] = "application/x-www-form-urlencoded"
1593 http_conn.request("POST", selector, data, headers)
1594 else:
1595 http_conn.request("GET", selector, headers=headers)
1596
1597 try:
1598 response = http_conn.getresponse()
1599 except http.client.BadStatusLine:
1600 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001601 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001602
1603 # According to RFC 2616, "2xx" code indicates that the client's
1604 # request was successfully received, understood, and accepted.
1605 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001606 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001607 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001608 else:
1609 return self.http_error(
1610 url, response.fp,
1611 response.status, response.reason, response.msg, data)
1612
1613 def open_http(self, url, data=None):
1614 """Use HTTP protocol."""
1615 return self._open_generic_http(http.client.HTTPConnection, url, data)
1616
1617 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1618 """Handle http errors.
1619
1620 Derived class can override this, or provide specific handlers
1621 named http_error_DDD where DDD is the 3-digit error code."""
1622 # First check if there's a specific handler for this error
1623 name = 'http_error_%d' % errcode
1624 if hasattr(self, name):
1625 method = getattr(self, name)
1626 if data is None:
1627 result = method(url, fp, errcode, errmsg, headers)
1628 else:
1629 result = method(url, fp, errcode, errmsg, headers, data)
1630 if result: return result
1631 return self.http_error_default(url, fp, errcode, errmsg, headers)
1632
1633 def http_error_default(self, url, fp, errcode, errmsg, headers):
1634 """Default error handler: close the connection and raise IOError."""
1635 void = fp.read()
1636 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001637 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001638
1639 if _have_ssl:
1640 def _https_connection(self, host):
1641 return http.client.HTTPSConnection(host,
1642 key_file=self.key_file,
1643 cert_file=self.cert_file)
1644
1645 def open_https(self, url, data=None):
1646 """Use HTTPS protocol."""
1647 return self._open_generic_http(self._https_connection, url, data)
1648
1649 def open_file(self, url):
1650 """Use local file or FTP depending on form of URL."""
1651 if not isinstance(url, str):
1652 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1653 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
1654 return self.open_ftp(url)
1655 else:
1656 return self.open_local_file(url)
1657
1658 def open_local_file(self, url):
1659 """Use local file."""
1660 import mimetypes, email.utils
1661 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001662 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001663 localname = url2pathname(file)
1664 try:
1665 stats = os.stat(localname)
1666 except OSError as e:
1667 raise URLError(e.errno, e.strerror, e.filename)
1668 size = stats.st_size
1669 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1670 mtype = mimetypes.guess_type(url)[0]
1671 headers = email.message_from_string(
1672 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1673 (mtype or 'text/plain', size, modified))
1674 if not host:
1675 urlfile = file
1676 if file[:1] == '/':
1677 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001678 return addinfourl(open(localname, 'rb'), headers, urlfile)
1679 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001680 if (not port
1681 and socket.gethostbyname(host) in (localhost(), thishost())):
1682 urlfile = file
1683 if file[:1] == '/':
1684 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001685 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001686 raise URLError('local file error', 'not on local host')
1687
1688 def open_ftp(self, url):
1689 """Use FTP protocol."""
1690 if not isinstance(url, str):
1691 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1692 import mimetypes
1693 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001694 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001695 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001696 host, port = splitport(host)
1697 user, host = splituser(host)
1698 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001699 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001700 host = unquote(host)
1701 user = unquote(user or '')
1702 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001703 host = socket.gethostbyname(host)
1704 if not port:
1705 import ftplib
1706 port = ftplib.FTP_PORT
1707 else:
1708 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001709 path, attrs = splitattr(path)
1710 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001711 dirs = path.split('/')
1712 dirs, file = dirs[:-1], dirs[-1]
1713 if dirs and not dirs[0]: dirs = dirs[1:]
1714 if dirs and not dirs[0]: dirs[0] = '/'
1715 key = user, host, port, '/'.join(dirs)
1716 # XXX thread unsafe!
1717 if len(self.ftpcache) > MAXFTPCACHE:
1718 # Prune the cache, rather arbitrarily
1719 for k in self.ftpcache.keys():
1720 if k != key:
1721 v = self.ftpcache[k]
1722 del self.ftpcache[k]
1723 v.close()
1724 try:
1725 if not key in self.ftpcache:
1726 self.ftpcache[key] = \
1727 ftpwrapper(user, passwd, host, port, dirs)
1728 if not file: type = 'D'
1729 else: type = 'I'
1730 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001731 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001732 if attr.lower() == 'type' and \
1733 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1734 type = value.upper()
1735 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1736 mtype = mimetypes.guess_type("ftp:" + url)[0]
1737 headers = ""
1738 if mtype:
1739 headers += "Content-Type: %s\n" % mtype
1740 if retrlen is not None and retrlen >= 0:
1741 headers += "Content-Length: %d\n" % retrlen
1742 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001743 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001744 except ftperrors() as msg:
1745 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1746
1747 def open_data(self, url, data=None):
1748 """Use "data" URL."""
1749 if not isinstance(url, str):
1750 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1751 # ignore POSTed data
1752 #
1753 # syntax of data URLs:
1754 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1755 # mediatype := [ type "/" subtype ] *( ";" parameter )
1756 # data := *urlchar
1757 # parameter := attribute "=" value
1758 try:
1759 [type, data] = url.split(',', 1)
1760 except ValueError:
1761 raise IOError('data error', 'bad data URL')
1762 if not type:
1763 type = 'text/plain;charset=US-ASCII'
1764 semi = type.rfind(';')
1765 if semi >= 0 and '=' not in type[semi:]:
1766 encoding = type[semi+1:]
1767 type = type[:semi]
1768 else:
1769 encoding = ''
1770 msg = []
1771 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
1772 time.gmtime(time.time())))
1773 msg.append('Content-type: %s' % type)
1774 if encoding == 'base64':
1775 import base64
Georg Brandl706824f2009-06-04 09:42:55 +00001776 # XXX is this encoding/decoding ok?
1777 data = base64.decodebytes(data.encode('ascii')).decode('latin1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001778 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001779 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001780 msg.append('Content-Length: %d' % len(data))
1781 msg.append('')
1782 msg.append(data)
1783 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001784 headers = email.message_from_string(msg)
1785 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001786 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001787 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001788
1789
1790class FancyURLopener(URLopener):
1791 """Derived class with handlers for errors we can handle (perhaps)."""
1792
1793 def __init__(self, *args, **kwargs):
1794 URLopener.__init__(self, *args, **kwargs)
1795 self.auth_cache = {}
1796 self.tries = 0
1797 self.maxtries = 10
1798
1799 def http_error_default(self, url, fp, errcode, errmsg, headers):
1800 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001801 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001802
1803 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1804 """Error 302 -- relocated (temporarily)."""
1805 self.tries += 1
1806 if self.maxtries and self.tries >= self.maxtries:
1807 if hasattr(self, "http_error_500"):
1808 meth = self.http_error_500
1809 else:
1810 meth = self.http_error_default
1811 self.tries = 0
1812 return meth(url, fp, 500,
1813 "Internal Server Error: Redirect Recursion", headers)
1814 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
1815 data)
1816 self.tries = 0
1817 return result
1818
1819 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
1820 if 'location' in headers:
1821 newurl = headers['location']
1822 elif 'uri' in headers:
1823 newurl = headers['uri']
1824 else:
1825 return
1826 void = fp.read()
1827 fp.close()
1828 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00001829 newurl = urljoin(self.type + ":" + url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001830 return self.open(newurl)
1831
1832 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
1833 """Error 301 -- also relocated (permanently)."""
1834 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1835
1836 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
1837 """Error 303 -- also relocated (essentially identical to 302)."""
1838 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1839
1840 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
1841 """Error 307 -- relocated, but turn POST into error."""
1842 if data is None:
1843 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1844 else:
1845 return self.http_error_default(url, fp, errcode, errmsg, headers)
1846
1847 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
1848 """Error 401 -- authentication required.
1849 This function supports Basic authentication only."""
1850 if not 'www-authenticate' in headers:
1851 URLopener.http_error_default(self, url, fp,
1852 errcode, errmsg, headers)
1853 stuff = headers['www-authenticate']
1854 import re
1855 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1856 if not match:
1857 URLopener.http_error_default(self, url, fp,
1858 errcode, errmsg, headers)
1859 scheme, realm = match.groups()
1860 if scheme.lower() != 'basic':
1861 URLopener.http_error_default(self, url, fp,
1862 errcode, errmsg, headers)
1863 name = 'retry_' + self.type + '_basic_auth'
1864 if data is None:
1865 return getattr(self,name)(url, realm)
1866 else:
1867 return getattr(self,name)(url, realm, data)
1868
1869 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
1870 """Error 407 -- proxy authentication required.
1871 This function supports Basic authentication only."""
1872 if not 'proxy-authenticate' in headers:
1873 URLopener.http_error_default(self, url, fp,
1874 errcode, errmsg, headers)
1875 stuff = headers['proxy-authenticate']
1876 import re
1877 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1878 if not match:
1879 URLopener.http_error_default(self, url, fp,
1880 errcode, errmsg, headers)
1881 scheme, realm = match.groups()
1882 if scheme.lower() != 'basic':
1883 URLopener.http_error_default(self, url, fp,
1884 errcode, errmsg, headers)
1885 name = 'retry_proxy_' + self.type + '_basic_auth'
1886 if data is None:
1887 return getattr(self,name)(url, realm)
1888 else:
1889 return getattr(self,name)(url, realm, data)
1890
1891 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001892 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001893 newurl = 'http://' + host + selector
1894 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00001895 urltype, proxyhost = splittype(proxy)
1896 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001897 i = proxyhost.find('@') + 1
1898 proxyhost = proxyhost[i:]
1899 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1900 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001901 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001902 quote(passwd, safe=''), proxyhost)
1903 self.proxies['http'] = 'http://' + proxyhost + proxyselector
1904 if data is None:
1905 return self.open(newurl)
1906 else:
1907 return self.open(newurl, data)
1908
1909 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001910 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001911 newurl = 'https://' + host + selector
1912 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00001913 urltype, proxyhost = splittype(proxy)
1914 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001915 i = proxyhost.find('@') + 1
1916 proxyhost = proxyhost[i:]
1917 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1918 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001919 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001920 quote(passwd, safe=''), proxyhost)
1921 self.proxies['https'] = 'https://' + proxyhost + proxyselector
1922 if data is None:
1923 return self.open(newurl)
1924 else:
1925 return self.open(newurl, data)
1926
1927 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001928 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001929 i = host.find('@') + 1
1930 host = host[i:]
1931 user, passwd = self.get_user_passwd(host, realm, i)
1932 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001933 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001934 quote(passwd, safe=''), host)
1935 newurl = 'http://' + host + selector
1936 if data is None:
1937 return self.open(newurl)
1938 else:
1939 return self.open(newurl, data)
1940
1941 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001942 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001943 i = host.find('@') + 1
1944 host = host[i:]
1945 user, passwd = self.get_user_passwd(host, realm, i)
1946 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001947 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001948 quote(passwd, safe=''), host)
1949 newurl = 'https://' + host + selector
1950 if data is None:
1951 return self.open(newurl)
1952 else:
1953 return self.open(newurl, data)
1954
1955 def get_user_passwd(self, host, realm, clear_cache = 0):
1956 key = realm + '@' + host.lower()
1957 if key in self.auth_cache:
1958 if clear_cache:
1959 del self.auth_cache[key]
1960 else:
1961 return self.auth_cache[key]
1962 user, passwd = self.prompt_user_passwd(host, realm)
1963 if user or passwd: self.auth_cache[key] = (user, passwd)
1964 return user, passwd
1965
1966 def prompt_user_passwd(self, host, realm):
1967 """Override this in a GUI environment!"""
1968 import getpass
1969 try:
1970 user = input("Enter username for %s at %s: " % (realm, host))
1971 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
1972 (user, realm, host))
1973 return user, passwd
1974 except KeyboardInterrupt:
1975 print()
1976 return None, None
1977
1978
1979# Utility functions
1980
1981_localhost = None
1982def localhost():
1983 """Return the IP address of the magic hostname 'localhost'."""
1984 global _localhost
1985 if _localhost is None:
1986 _localhost = socket.gethostbyname('localhost')
1987 return _localhost
1988
1989_thishost = None
1990def thishost():
1991 """Return the IP address of the current host."""
1992 global _thishost
1993 if _thishost is None:
1994 _thishost = socket.gethostbyname(socket.gethostname())
1995 return _thishost
1996
1997_ftperrors = None
1998def ftperrors():
1999 """Return the set of errors raised by the FTP class."""
2000 global _ftperrors
2001 if _ftperrors is None:
2002 import ftplib
2003 _ftperrors = ftplib.all_errors
2004 return _ftperrors
2005
2006_noheaders = None
2007def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002008 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002009 global _noheaders
2010 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002011 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002012 return _noheaders
2013
2014
2015# Utility classes
2016
2017class ftpwrapper:
2018 """Class used by open_ftp() for cache of open FTP connections."""
2019
2020 def __init__(self, user, passwd, host, port, dirs, timeout=None):
2021 self.user = user
2022 self.passwd = passwd
2023 self.host = host
2024 self.port = port
2025 self.dirs = dirs
2026 self.timeout = timeout
2027 self.init()
2028
2029 def init(self):
2030 import ftplib
2031 self.busy = 0
2032 self.ftp = ftplib.FTP()
2033 self.ftp.connect(self.host, self.port, self.timeout)
2034 self.ftp.login(self.user, self.passwd)
2035 for dir in self.dirs:
2036 self.ftp.cwd(dir)
2037
2038 def retrfile(self, file, type):
2039 import ftplib
2040 self.endtransfer()
2041 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2042 else: cmd = 'TYPE ' + type; isdir = 0
2043 try:
2044 self.ftp.voidcmd(cmd)
2045 except ftplib.all_errors:
2046 self.init()
2047 self.ftp.voidcmd(cmd)
2048 conn = None
2049 if file and not isdir:
2050 # Try to retrieve as a file
2051 try:
2052 cmd = 'RETR ' + file
2053 conn = self.ftp.ntransfercmd(cmd)
2054 except ftplib.error_perm as reason:
2055 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002056 raise URLError('ftp error', reason).with_traceback(
2057 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002058 if not conn:
2059 # Set transfer mode to ASCII!
2060 self.ftp.voidcmd('TYPE A')
2061 # Try a directory listing. Verify that directory exists.
2062 if file:
2063 pwd = self.ftp.pwd()
2064 try:
2065 try:
2066 self.ftp.cwd(file)
2067 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002068 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002069 finally:
2070 self.ftp.cwd(pwd)
2071 cmd = 'LIST ' + file
2072 else:
2073 cmd = 'LIST'
2074 conn = self.ftp.ntransfercmd(cmd)
2075 self.busy = 1
2076 # Pass back both a suitably decorated object and a retrieval length
Georg Brandl13e89462008-07-01 19:56:00 +00002077 return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002078 def endtransfer(self):
2079 if not self.busy:
2080 return
2081 self.busy = 0
2082 try:
2083 self.ftp.voidresp()
2084 except ftperrors():
2085 pass
2086
2087 def close(self):
2088 self.endtransfer()
2089 try:
2090 self.ftp.close()
2091 except ftperrors():
2092 pass
2093
2094# Proxy handling
2095def getproxies_environment():
2096 """Return a dictionary of scheme -> proxy server URL mappings.
2097
2098 Scan the environment for variables named <scheme>_proxy;
2099 this seems to be the standard convention. If you need a
2100 different way, you can pass a proxies dictionary to the
2101 [Fancy]URLopener constructor.
2102
2103 """
2104 proxies = {}
2105 for name, value in os.environ.items():
2106 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002107 if value and name[-6:] == '_proxy':
2108 proxies[name[:-6]] = value
2109 return proxies
2110
2111def proxy_bypass_environment(host):
2112 """Test if proxies should not be used for a particular host.
2113
2114 Checks the environment for a variable named no_proxy, which should
2115 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2116 """
2117 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2118 # '*' is special case for always bypass
2119 if no_proxy == '*':
2120 return 1
2121 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002122 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002123 # check if the host ends with any of the DNS suffixes
2124 for name in no_proxy.split(','):
2125 if name and (hostonly.endswith(name) or host.endswith(name)):
2126 return 1
2127 # otherwise, don't bypass
2128 return 0
2129
2130
2131if sys.platform == 'darwin':
2132 def getproxies_internetconfig():
2133 """Return a dictionary of scheme -> proxy server URL mappings.
2134
2135 By convention the mac uses Internet Config to store
2136 proxies. An HTTP proxy, for instance, is stored under
2137 the HttpProxy key.
2138
2139 """
2140 try:
2141 import ic
2142 except ImportError:
2143 return {}
2144
2145 try:
2146 config = ic.IC()
2147 except ic.error:
2148 return {}
2149 proxies = {}
2150 # HTTP:
2151 if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
2152 try:
2153 value = config['HTTPProxyHost']
2154 except ic.error:
2155 pass
2156 else:
2157 proxies['http'] = 'http://%s' % value
2158 # FTP: XXX To be done.
2159 # Gopher: XXX To be done.
2160 return proxies
2161
2162 def proxy_bypass(host):
2163 if getproxies_environment():
2164 return proxy_bypass_environment(host)
2165 else:
2166 return 0
2167
2168 def getproxies():
2169 return getproxies_environment() or getproxies_internetconfig()
2170
2171elif os.name == 'nt':
2172 def getproxies_registry():
2173 """Return a dictionary of scheme -> proxy server URL mappings.
2174
2175 Win32 uses the registry to store proxies.
2176
2177 """
2178 proxies = {}
2179 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002180 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002181 except ImportError:
2182 # Std module, so should be around - but you never know!
2183 return proxies
2184 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002185 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002186 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002187 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002188 'ProxyEnable')[0]
2189 if proxyEnable:
2190 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002191 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002192 'ProxyServer')[0])
2193 if '=' in proxyServer:
2194 # Per-protocol settings
2195 for p in proxyServer.split(';'):
2196 protocol, address = p.split('=', 1)
2197 # See if address has a type:// prefix
2198 import re
2199 if not re.match('^([^/:]+)://', address):
2200 address = '%s://%s' % (protocol, address)
2201 proxies[protocol] = address
2202 else:
2203 # Use one setting for all protocols
2204 if proxyServer[:5] == 'http:':
2205 proxies['http'] = proxyServer
2206 else:
2207 proxies['http'] = 'http://%s' % proxyServer
2208 proxies['ftp'] = 'ftp://%s' % proxyServer
2209 internetSettings.Close()
2210 except (WindowsError, ValueError, TypeError):
2211 # Either registry key not found etc, or the value in an
2212 # unexpected format.
2213 # proxies already set up to be empty so nothing to do
2214 pass
2215 return proxies
2216
2217 def getproxies():
2218 """Return a dictionary of scheme -> proxy server URL mappings.
2219
2220 Returns settings gathered from the environment, if specified,
2221 or the registry.
2222
2223 """
2224 return getproxies_environment() or getproxies_registry()
2225
2226 def proxy_bypass_registry(host):
2227 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002228 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002229 import re
2230 except ImportError:
2231 # Std modules, so should be around - but you never know!
2232 return 0
2233 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002234 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002235 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002236 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002237 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002238 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002239 'ProxyOverride')[0])
2240 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2241 except WindowsError:
2242 return 0
2243 if not proxyEnable or not proxyOverride:
2244 return 0
2245 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002246 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002247 host = [rawHost]
2248 try:
2249 addr = socket.gethostbyname(rawHost)
2250 if addr != rawHost:
2251 host.append(addr)
2252 except socket.error:
2253 pass
2254 try:
2255 fqdn = socket.getfqdn(rawHost)
2256 if fqdn != rawHost:
2257 host.append(fqdn)
2258 except socket.error:
2259 pass
2260 # make a check value list from the registry entry: replace the
2261 # '<local>' string by the localhost entry and the corresponding
2262 # canonical entry.
2263 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002264 # now check if we match one of the registry values.
2265 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002266 if test == '<local>':
2267 if '.' not in rawHost:
2268 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002269 test = test.replace(".", r"\.") # mask dots
2270 test = test.replace("*", r".*") # change glob sequence
2271 test = test.replace("?", r".") # change glob char
2272 for val in host:
2273 # print "%s <--> %s" %( test, val )
2274 if re.match(test, val, re.I):
2275 return 1
2276 return 0
2277
2278 def proxy_bypass(host):
2279 """Return a dictionary of scheme -> proxy server URL mappings.
2280
2281 Returns settings gathered from the environment, if specified,
2282 or the registry.
2283
2284 """
2285 if getproxies_environment():
2286 return proxy_bypass_environment(host)
2287 else:
2288 return proxy_bypass_registry(host)
2289
2290else:
2291 # By default use environment variables
2292 getproxies = getproxies_environment
2293 proxy_bypass = proxy_bypass_environment