blob: 6bc386ba843ca58e1bd64827239c92ddbd4867c7 [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:
33OpenerDirector --
34
35Request -- An object that encapsulates the state of a request. The
36state can be as simple as the URL. It can also include extra HTTP
37headers, e.g. a User-Agent.
38
39BaseHandler --
40
41internals:
42BaseHandler and parent
43_call_chain conventions
44
45Example usage:
46
Georg Brandl029986a2008-06-23 11:44:14 +000047import urllib.request
Jeremy Hylton1afc1692008-06-18 20:49:58 +000048
49# set up authentication info
Georg Brandl029986a2008-06-23 11:44:14 +000050authinfo = urllib.request.HTTPBasicAuthHandler()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000051authinfo.add_password(realm='PDQ Application',
52 uri='https://mahler:8092/site-updates.py',
53 user='klem',
54 passwd='geheim$parole')
55
Georg Brandl029986a2008-06-23 11:44:14 +000056proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
Jeremy Hylton1afc1692008-06-18 20:49:58 +000057
58# build a new opener that adds authentication and caching FTP handlers
Georg Brandl029986a2008-06-23 11:44:14 +000059opener = urllib.request.build_opener(proxy_support, authinfo,
60 urllib.request.CacheFTPHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000061
62# install it
Georg Brandl029986a2008-06-23 11:44:14 +000063urllib.request.install_opener(opener)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000064
Georg Brandl029986a2008-06-23 11:44:14 +000065f = urllib.request.urlopen('http://www.python.org/')
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066"""
67
68# XXX issues:
69# If an authentication error handler that tries to perform
70# authentication for some reason but fails, how should the error be
71# signalled? The client needs to know the HTTP error code. But if
72# the handler knows that the problem was, e.g., that it didn't know
73# that hash algo that requested in the challenge, it would be good to
74# pass that information along to the client, too.
75# ftp errors aren't handled cleanly
76# check digest against correct (i.e. non-apache) implementation
77
78# Possible extensions:
79# complex proxies XXX not sure what exactly was meant by this
80# abstract factory for opener
81
82import base64
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +000083import bisect
Jeremy Hylton1afc1692008-06-18 20:49:58 +000084import email
85import hashlib
86import http.client
87import io
88import os
89import posixpath
90import random
91import re
92import socket
93import sys
94import time
Jeremy Hylton1afc1692008-06-18 20:49:58 +000095
Georg Brandl13e89462008-07-01 19:56:00 +000096from urllib.error import URLError, HTTPError, ContentTooShortError
97from urllib.parse import (
98 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
99 splittype, splithost, splitport, splituser, splitpasswd,
Facundo Batistaf24802c2008-08-17 03:36:03 +0000100 splitattr, splitquery, splitvalue, to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000101from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000102
103# check for SSL
104try:
105 import ssl
106except:
107 _have_ssl = False
108else:
109 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000110
111# used in User-Agent header sent
112__version__ = sys.version[:3]
113
114_opener = None
115def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
116 global _opener
117 if _opener is None:
118 _opener = build_opener()
119 return _opener.open(url, data, timeout)
120
121def install_opener(opener):
122 global _opener
123 _opener = opener
124
125# TODO(jhylton): Make this work with the same global opener.
126_urlopener = None
127def urlretrieve(url, filename=None, reporthook=None, data=None):
128 global _urlopener
129 if not _urlopener:
130 _urlopener = FancyURLopener()
131 return _urlopener.retrieve(url, filename, reporthook, data)
132
133def urlcleanup():
134 if _urlopener:
135 _urlopener.cleanup()
136 global _opener
137 if _opener:
138 _opener = None
139
140# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000141_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000142def request_host(request):
143 """Return request-host, as defined by RFC 2965.
144
145 Variation from RFC: returned value is lowercased, for convenient
146 comparison.
147
148 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000149 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000150 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000151 if host == "":
152 host = request.get_header("Host", "")
153
154 # remove port, if present
155 host = _cut_port_re.sub("", host, 1)
156 return host.lower()
157
158class Request:
159
160 def __init__(self, url, data=None, headers={},
161 origin_req_host=None, unverifiable=False):
162 # unwrap('<URL:type://host/path>') --> 'type://host/path'
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000163 self.full_url = unwrap(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000164 self.data = data
165 self.headers = {}
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000166 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000167 for key, value in headers.items():
168 self.add_header(key, value)
169 self.unredirected_hdrs = {}
170 if origin_req_host is None:
171 origin_req_host = request_host(self)
172 self.origin_req_host = origin_req_host
173 self.unverifiable = unverifiable
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000174 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000175
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000176 def _parse(self):
177 self.type, rest = splittype(self.full_url)
178 if self.type is None:
179 raise ValueError("unknown url type: %s" % self.full_url)
180 self.host, self.selector = splithost(rest)
181 if self.host:
182 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000183
184 def get_method(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000185 if self.data is not None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000186 return "POST"
187 else:
188 return "GET"
189
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000190 # Begin deprecated methods
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000191
192 def add_data(self, data):
193 self.data = data
194
195 def has_data(self):
196 return self.data is not None
197
198 def get_data(self):
199 return self.data
200
201 def get_full_url(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000202 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000203
204 def get_type(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000205 return self.type
206
207 def get_host(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000208 return self.host
209
210 def get_selector(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000211 return self.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000212
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000213 def is_unverifiable(self):
214 return self.unverifiable
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000215
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000216 def get_origin_req_host(self):
217 return self.origin_req_host
218
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000219 # End deprecated methods
220
221 def set_proxy(self, host, type):
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000222 if self.type == 'https' and not self._tunnel_host:
223 self._tunnel_host = self.host
224 else:
225 self.type= type
226 self.selector = self.full_url
227 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000228
229 def has_proxy(self):
230 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000231
232 def add_header(self, key, val):
233 # useful for something like authentication
234 self.headers[key.capitalize()] = val
235
236 def add_unredirected_header(self, key, val):
237 # will not be added to a redirected request
238 self.unredirected_hdrs[key.capitalize()] = val
239
240 def has_header(self, header_name):
241 return (header_name in self.headers or
242 header_name in self.unredirected_hdrs)
243
244 def get_header(self, header_name, default=None):
245 return self.headers.get(
246 header_name,
247 self.unredirected_hdrs.get(header_name, default))
248
249 def header_items(self):
250 hdrs = self.unredirected_hdrs.copy()
251 hdrs.update(self.headers)
252 return list(hdrs.items())
253
254class OpenerDirector:
255 def __init__(self):
256 client_version = "Python-urllib/%s" % __version__
257 self.addheaders = [('User-agent', client_version)]
258 # manage the individual handlers
259 self.handlers = []
260 self.handle_open = {}
261 self.handle_error = {}
262 self.process_response = {}
263 self.process_request = {}
264
265 def add_handler(self, handler):
266 if not hasattr(handler, "add_parent"):
267 raise TypeError("expected BaseHandler instance, got %r" %
268 type(handler))
269
270 added = False
271 for meth in dir(handler):
272 if meth in ["redirect_request", "do_open", "proxy_open"]:
273 # oops, coincidental match
274 continue
275
276 i = meth.find("_")
277 protocol = meth[:i]
278 condition = meth[i+1:]
279
280 if condition.startswith("error"):
281 j = condition.find("_") + i + 1
282 kind = meth[j+1:]
283 try:
284 kind = int(kind)
285 except ValueError:
286 pass
287 lookup = self.handle_error.get(protocol, {})
288 self.handle_error[protocol] = lookup
289 elif condition == "open":
290 kind = protocol
291 lookup = self.handle_open
292 elif condition == "response":
293 kind = protocol
294 lookup = self.process_response
295 elif condition == "request":
296 kind = protocol
297 lookup = self.process_request
298 else:
299 continue
300
301 handlers = lookup.setdefault(kind, [])
302 if handlers:
303 bisect.insort(handlers, handler)
304 else:
305 handlers.append(handler)
306 added = True
307
308 if added:
309 # the handlers must work in an specific order, the order
310 # is specified in a Handler attribute
311 bisect.insort(self.handlers, handler)
312 handler.add_parent(self)
313
314 def close(self):
315 # Only exists for backwards compatibility.
316 pass
317
318 def _call_chain(self, chain, kind, meth_name, *args):
319 # Handlers raise an exception if no one else should try to handle
320 # the request, or return None if they can't but another handler
321 # could. Otherwise, they return the response.
322 handlers = chain.get(kind, ())
323 for handler in handlers:
324 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000325 result = func(*args)
326 if result is not None:
327 return result
328
329 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
330 # accept a URL or a Request object
331 if isinstance(fullurl, str):
332 req = Request(fullurl, data)
333 else:
334 req = fullurl
335 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000336 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000337
338 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000339 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000340
341 # pre-process request
342 meth_name = protocol+"_request"
343 for processor in self.process_request.get(protocol, []):
344 meth = getattr(processor, meth_name)
345 req = meth(req)
346
347 response = self._open(req, data)
348
349 # post-process response
350 meth_name = protocol+"_response"
351 for processor in self.process_response.get(protocol, []):
352 meth = getattr(processor, meth_name)
353 response = meth(req, response)
354
355 return response
356
357 def _open(self, req, data=None):
358 result = self._call_chain(self.handle_open, 'default',
359 'default_open', req)
360 if result:
361 return result
362
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000363 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000364 result = self._call_chain(self.handle_open, protocol, protocol +
365 '_open', req)
366 if result:
367 return result
368
369 return self._call_chain(self.handle_open, 'unknown',
370 'unknown_open', req)
371
372 def error(self, proto, *args):
373 if proto in ('http', 'https'):
374 # XXX http[s] protocols are special-cased
375 dict = self.handle_error['http'] # https is not different than http
376 proto = args[2] # YUCK!
377 meth_name = 'http_error_%s' % proto
378 http_err = 1
379 orig_args = args
380 else:
381 dict = self.handle_error
382 meth_name = proto + '_error'
383 http_err = 0
384 args = (dict, proto, meth_name) + args
385 result = self._call_chain(*args)
386 if result:
387 return result
388
389 if http_err:
390 args = (dict, 'default', 'http_error_default') + orig_args
391 return self._call_chain(*args)
392
393# XXX probably also want an abstract factory that knows when it makes
394# sense to skip a superclass in favor of a subclass and when it might
395# make sense to include both
396
397def build_opener(*handlers):
398 """Create an opener object from a list of handlers.
399
400 The opener will use several default handlers, including support
401 for HTTP and FTP.
402
403 If any of the handlers passed as arguments are subclasses of the
404 default handlers, the default handlers will not be used.
405 """
406 def isclass(obj):
407 return isinstance(obj, type) or hasattr(obj, "__bases__")
408
409 opener = OpenerDirector()
410 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
411 HTTPDefaultErrorHandler, HTTPRedirectHandler,
412 FTPHandler, FileHandler, HTTPErrorProcessor]
413 if hasattr(http.client, "HTTPSConnection"):
414 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000415 skip = set()
416 for klass in default_classes:
417 for check in handlers:
418 if isclass(check):
419 if issubclass(check, klass):
420 skip.add(klass)
421 elif isinstance(check, klass):
422 skip.add(klass)
423 for klass in skip:
424 default_classes.remove(klass)
425
426 for klass in default_classes:
427 opener.add_handler(klass())
428
429 for h in handlers:
430 if isclass(h):
431 h = h()
432 opener.add_handler(h)
433 return opener
434
435class BaseHandler:
436 handler_order = 500
437
438 def add_parent(self, parent):
439 self.parent = parent
440
441 def close(self):
442 # Only exists for backwards compatibility
443 pass
444
445 def __lt__(self, other):
446 if not hasattr(other, "handler_order"):
447 # Try to preserve the old behavior of having custom classes
448 # inserted after default ones (works only for custom user
449 # classes which are not aware of handler_order).
450 return True
451 return self.handler_order < other.handler_order
452
453
454class HTTPErrorProcessor(BaseHandler):
455 """Process HTTP error responses."""
456 handler_order = 1000 # after all other processing
457
458 def http_response(self, request, response):
459 code, msg, hdrs = response.code, response.msg, response.info()
460
461 # According to RFC 2616, "2xx" code indicates that the client's
462 # request was successfully received, understood, and accepted.
463 if not (200 <= code < 300):
464 response = self.parent.error(
465 'http', request, response, code, msg, hdrs)
466
467 return response
468
469 https_response = http_response
470
471class HTTPDefaultErrorHandler(BaseHandler):
472 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000473 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000474
475class HTTPRedirectHandler(BaseHandler):
476 # maximum number of redirections to any single URL
477 # this is needed because of the state that cookies introduce
478 max_repeats = 4
479 # maximum total number of redirections (regardless of URL) before
480 # assuming we're in a loop
481 max_redirections = 10
482
483 def redirect_request(self, req, fp, code, msg, headers, newurl):
484 """Return a Request or None in response to a redirect.
485
486 This is called by the http_error_30x methods when a
487 redirection response is received. If a redirection should
488 take place, return a new Request to allow http_error_30x to
489 perform the redirect. Otherwise, raise HTTPError if no-one
490 else should try to handle this url. Return None if you can't
491 but another Handler might.
492 """
493 m = req.get_method()
494 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
495 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000496 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000497
498 # Strictly (according to RFC 2616), 301 or 302 in response to
499 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000500 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000501 # essentially all clients do redirect in this case, so we do
502 # the same.
503 # be conciliant with URIs containing a space
504 newurl = newurl.replace(' ', '%20')
505 CONTENT_HEADERS = ("content-length", "content-type")
506 newheaders = dict((k, v) for k, v in req.headers.items()
507 if k.lower() not in CONTENT_HEADERS)
508 return Request(newurl,
509 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000510 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000511 unverifiable=True)
512
513 # Implementation note: To avoid the server sending us into an
514 # infinite loop, the request object needs to track what URLs we
515 # have already seen. Do this by adding a handler-specific
516 # attribute to the Request object.
517 def http_error_302(self, req, fp, code, msg, headers):
518 # Some servers (incorrectly) return multiple Location headers
519 # (so probably same goes for URI). Use first header.
520 if "location" in headers:
521 newurl = headers["location"]
522 elif "uri" in headers:
523 newurl = headers["uri"]
524 else:
525 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000526
527 # fix a possible malformed URL
528 urlparts = urlparse(newurl)
529 if not urlparts.path:
530 urlparts = list(urlparts)
531 urlparts[2] = "/"
532 newurl = urlunparse(urlparts)
533
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000534 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000535
536 # XXX Probably want to forget about the state of the current
537 # request, although that might interact poorly with other
538 # handlers that also use handler-specific request attributes
539 new = self.redirect_request(req, fp, code, msg, headers, newurl)
540 if new is None:
541 return
542
543 # loop detection
544 # .redirect_dict has a key url if url was previously visited.
545 if hasattr(req, 'redirect_dict'):
546 visited = new.redirect_dict = req.redirect_dict
547 if (visited.get(newurl, 0) >= self.max_repeats or
548 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000549 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000550 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000551 else:
552 visited = new.redirect_dict = req.redirect_dict = {}
553 visited[newurl] = visited.get(newurl, 0) + 1
554
555 # Don't close the fp until we are sure that we won't use it
556 # with HTTPError.
557 fp.read()
558 fp.close()
559
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000560 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000561
562 http_error_301 = http_error_303 = http_error_307 = http_error_302
563
564 inf_msg = "The HTTP server returned a redirect error that would " \
565 "lead to an infinite loop.\n" \
566 "The last 30x error message was:\n"
567
568
569def _parse_proxy(proxy):
570 """Return (scheme, user, password, host/port) given a URL or an authority.
571
572 If a URL is supplied, it must have an authority (host:port) component.
573 According to RFC 3986, having an authority component means the URL must
574 have two slashes after the scheme:
575
576 >>> _parse_proxy('file:/ftp.example.com/')
577 Traceback (most recent call last):
578 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
579
580 The first three items of the returned tuple may be None.
581
582 Examples of authority parsing:
583
584 >>> _parse_proxy('proxy.example.com')
585 (None, None, None, 'proxy.example.com')
586 >>> _parse_proxy('proxy.example.com:3128')
587 (None, None, None, 'proxy.example.com:3128')
588
589 The authority component may optionally include userinfo (assumed to be
590 username:password):
591
592 >>> _parse_proxy('joe:password@proxy.example.com')
593 (None, 'joe', 'password', 'proxy.example.com')
594 >>> _parse_proxy('joe:password@proxy.example.com:3128')
595 (None, 'joe', 'password', 'proxy.example.com:3128')
596
597 Same examples, but with URLs instead:
598
599 >>> _parse_proxy('http://proxy.example.com/')
600 ('http', None, None, 'proxy.example.com')
601 >>> _parse_proxy('http://proxy.example.com:3128/')
602 ('http', None, None, 'proxy.example.com:3128')
603 >>> _parse_proxy('http://joe:password@proxy.example.com/')
604 ('http', 'joe', 'password', 'proxy.example.com')
605 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
606 ('http', 'joe', 'password', 'proxy.example.com:3128')
607
608 Everything after the authority is ignored:
609
610 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
611 ('ftp', 'joe', 'password', 'proxy.example.com')
612
613 Test for no trailing '/' case:
614
615 >>> _parse_proxy('http://joe:password@proxy.example.com')
616 ('http', 'joe', 'password', 'proxy.example.com')
617
618 """
Georg Brandl13e89462008-07-01 19:56:00 +0000619 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000620 if not r_scheme.startswith("/"):
621 # authority
622 scheme = None
623 authority = proxy
624 else:
625 # URL
626 if not r_scheme.startswith("//"):
627 raise ValueError("proxy URL with no authority: %r" % proxy)
628 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
629 # and 3.3.), path is empty or starts with '/'
630 end = r_scheme.find("/", 2)
631 if end == -1:
632 end = None
633 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000634 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000635 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000636 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000637 else:
638 user = password = None
639 return scheme, user, password, hostport
640
641class ProxyHandler(BaseHandler):
642 # Proxies must be in front
643 handler_order = 100
644
645 def __init__(self, proxies=None):
646 if proxies is None:
647 proxies = getproxies()
648 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
649 self.proxies = proxies
650 for type, url in proxies.items():
651 setattr(self, '%s_open' % type,
652 lambda r, proxy=url, type=type, meth=self.proxy_open: \
653 meth(r, proxy, type))
654
655 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000656 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000657 proxy_type, user, password, hostport = _parse_proxy(proxy)
658 if proxy_type is None:
659 proxy_type = orig_type
660 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000661 user_pass = '%s:%s' % (unquote(user),
662 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000663 creds = base64.b64encode(user_pass.encode()).decode("ascii")
664 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000665 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000666 req.set_proxy(hostport, proxy_type)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000667 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000668 # let other handlers take care of it
669 return None
670 else:
671 # need to start over, because the other handlers don't
672 # grok the proxy's URL type
673 # e.g. if we have a constructor arg proxies like so:
674 # {'http': 'ftp://proxy.example.com'}, we may end up turning
675 # a request for http://acme.example.com/a into one for
676 # ftp://proxy.example.com/a
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000677 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000678
679class HTTPPasswordMgr:
680
681 def __init__(self):
682 self.passwd = {}
683
684 def add_password(self, realm, uri, user, passwd):
685 # uri could be a single URI or a sequence
686 if isinstance(uri, str):
687 uri = [uri]
688 if not realm in self.passwd:
689 self.passwd[realm] = {}
690 for default_port in True, False:
691 reduced_uri = tuple(
692 [self.reduce_uri(u, default_port) for u in uri])
693 self.passwd[realm][reduced_uri] = (user, passwd)
694
695 def find_user_password(self, realm, authuri):
696 domains = self.passwd.get(realm, {})
697 for default_port in True, False:
698 reduced_authuri = self.reduce_uri(authuri, default_port)
699 for uris, authinfo in domains.items():
700 for uri in uris:
701 if self.is_suburi(uri, reduced_authuri):
702 return authinfo
703 return None, None
704
705 def reduce_uri(self, uri, default_port=True):
706 """Accept authority or URI and extract only the authority and path."""
707 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000708 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000709 if parts[1]:
710 # URI
711 scheme = parts[0]
712 authority = parts[1]
713 path = parts[2] or '/'
714 else:
715 # host or host:port
716 scheme = None
717 authority = uri
718 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000719 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000720 if default_port and port is None and scheme is not None:
721 dport = {"http": 80,
722 "https": 443,
723 }.get(scheme)
724 if dport is not None:
725 authority = "%s:%d" % (host, dport)
726 return authority, path
727
728 def is_suburi(self, base, test):
729 """Check if test is below base in a URI tree
730
731 Both args must be URIs in reduced form.
732 """
733 if base == test:
734 return True
735 if base[0] != test[0]:
736 return False
737 common = posixpath.commonprefix((base[1], test[1]))
738 if len(common) == len(base[1]):
739 return True
740 return False
741
742
743class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
744
745 def find_user_password(self, realm, authuri):
746 user, password = HTTPPasswordMgr.find_user_password(self, realm,
747 authuri)
748 if user is not None:
749 return user, password
750 return HTTPPasswordMgr.find_user_password(self, None, authuri)
751
752
753class AbstractBasicAuthHandler:
754
755 # XXX this allows for multiple auth-schemes, but will stupidly pick
756 # the last one with a realm specified.
757
758 # allow for double- and single-quoted realm values
759 # (single quotes are a violation of the RFC, but appear in the wild)
760 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
761 'realm=(["\'])(.*?)\\2', re.I)
762
763 # XXX could pre-emptively send auth info already accepted (RFC 2617,
764 # end of section 2, and section 1.2 immediately after "credentials"
765 # production).
766
767 def __init__(self, password_mgr=None):
768 if password_mgr is None:
769 password_mgr = HTTPPasswordMgr()
770 self.passwd = password_mgr
771 self.add_password = self.passwd.add_password
772
773 def http_error_auth_reqed(self, authreq, host, req, headers):
774 # host may be an authority (without userinfo) or a URL with an
775 # authority
776 # XXX could be multiple headers
777 authreq = headers.get(authreq, None)
778 if authreq:
779 mo = AbstractBasicAuthHandler.rx.search(authreq)
780 if mo:
781 scheme, quote, realm = mo.groups()
782 if scheme.lower() == 'basic':
783 return self.retry_http_basic_auth(host, req, realm)
784
785 def retry_http_basic_auth(self, host, req, realm):
786 user, pw = self.passwd.find_user_password(realm, host)
787 if pw is not None:
788 raw = "%s:%s" % (user, pw)
789 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
790 if req.headers.get(self.auth_header, None) == auth:
791 return None
792 req.add_header(self.auth_header, auth)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000793 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000794 else:
795 return None
796
797
798class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
799
800 auth_header = 'Authorization'
801
802 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000803 url = req.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000804 return self.http_error_auth_reqed('www-authenticate',
805 url, req, headers)
806
807
808class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
809
810 auth_header = 'Proxy-authorization'
811
812 def http_error_407(self, req, fp, code, msg, headers):
813 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000814 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000815 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
816 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000817 authority = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000818 return self.http_error_auth_reqed('proxy-authenticate',
819 authority, req, headers)
820
821
822def randombytes(n):
823 """Return n random bytes."""
824 return os.urandom(n)
825
826class AbstractDigestAuthHandler:
827 # Digest authentication is specified in RFC 2617.
828
829 # XXX The client does not inspect the Authentication-Info header
830 # in a successful response.
831
832 # XXX It should be possible to test this implementation against
833 # a mock server that just generates a static set of challenges.
834
835 # XXX qop="auth-int" supports is shaky
836
837 def __init__(self, passwd=None):
838 if passwd is None:
839 passwd = HTTPPasswordMgr()
840 self.passwd = passwd
841 self.add_password = self.passwd.add_password
842 self.retried = 0
843 self.nonce_count = 0
844
845 def reset_retry_count(self):
846 self.retried = 0
847
848 def http_error_auth_reqed(self, auth_header, host, req, headers):
849 authreq = headers.get(auth_header, None)
850 if self.retried > 5:
851 # Don't fail endlessly - if we failed once, we'll probably
852 # fail a second time. Hm. Unless the Password Manager is
853 # prompting for the information. Crap. This isn't great
854 # but it's better than the current 'repeat until recursion
855 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000856 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000857 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000858 else:
859 self.retried += 1
860 if authreq:
861 scheme = authreq.split()[0]
862 if scheme.lower() == 'digest':
863 return self.retry_http_digest_auth(req, authreq)
864
865 def retry_http_digest_auth(self, req, auth):
866 token, challenge = auth.split(' ', 1)
867 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
868 auth = self.get_authorization(req, chal)
869 if auth:
870 auth_val = 'Digest %s' % auth
871 if req.headers.get(self.auth_header, None) == auth_val:
872 return None
873 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000874 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000875 return resp
876
877 def get_cnonce(self, nonce):
878 # The cnonce-value is an opaque
879 # quoted string value provided by the client and used by both client
880 # and server to avoid chosen plaintext attacks, to provide mutual
881 # authentication, and to provide some message integrity protection.
882 # This isn't a fabulous effort, but it's probably Good Enough.
883 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
884 b = s.encode("ascii") + randombytes(8)
885 dig = hashlib.sha1(b).hexdigest()
886 return dig[:16]
887
888 def get_authorization(self, req, chal):
889 try:
890 realm = chal['realm']
891 nonce = chal['nonce']
892 qop = chal.get('qop')
893 algorithm = chal.get('algorithm', 'MD5')
894 # mod_digest doesn't send an opaque, even though it isn't
895 # supposed to be optional
896 opaque = chal.get('opaque', None)
897 except KeyError:
898 return None
899
900 H, KD = self.get_algorithm_impls(algorithm)
901 if H is None:
902 return None
903
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000904 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000905 if user is None:
906 return None
907
908 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000909 if req.data is not None:
910 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000911 else:
912 entdig = None
913
914 A1 = "%s:%s:%s" % (user, realm, pw)
915 A2 = "%s:%s" % (req.get_method(),
916 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000917 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000918 if qop == 'auth':
919 self.nonce_count += 1
920 ncvalue = '%08x' % self.nonce_count
921 cnonce = self.get_cnonce(nonce)
922 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
923 respdig = KD(H(A1), noncebit)
924 elif qop is None:
925 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
926 else:
927 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +0000928 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000929
930 # XXX should the partial digests be encoded too?
931
932 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000933 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000934 respdig)
935 if opaque:
936 base += ', opaque="%s"' % opaque
937 if entdig:
938 base += ', digest="%s"' % entdig
939 base += ', algorithm="%s"' % algorithm
940 if qop:
941 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
942 return base
943
944 def get_algorithm_impls(self, algorithm):
945 # lambdas assume digest modules are imported at the top level
946 if algorithm == 'MD5':
947 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
948 elif algorithm == 'SHA':
949 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
950 # XXX MD5-sess
951 KD = lambda s, d: H("%s:%s" % (s, d))
952 return H, KD
953
954 def get_entity_digest(self, data, chal):
955 # XXX not implemented yet
956 return None
957
958
959class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
960 """An authentication protocol defined by RFC 2069
961
962 Digest authentication improves on basic authentication because it
963 does not transmit passwords in the clear.
964 """
965
966 auth_header = 'Authorization'
967 handler_order = 490 # before Basic auth
968
969 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000970 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000971 retry = self.http_error_auth_reqed('www-authenticate',
972 host, req, headers)
973 self.reset_retry_count()
974 return retry
975
976
977class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
978
979 auth_header = 'Proxy-Authorization'
980 handler_order = 490 # before Basic auth
981
982 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000983 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000984 retry = self.http_error_auth_reqed('proxy-authenticate',
985 host, req, headers)
986 self.reset_retry_count()
987 return retry
988
989class AbstractHTTPHandler(BaseHandler):
990
991 def __init__(self, debuglevel=0):
992 self._debuglevel = debuglevel
993
994 def set_http_debuglevel(self, level):
995 self._debuglevel = level
996
997 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000998 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000999 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001000 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001001
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001002 if request.data is not None: # POST
1003 data = request.data
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001004 if not request.has_header('Content-type'):
1005 request.add_unredirected_header(
1006 'Content-type',
1007 'application/x-www-form-urlencoded')
1008 if not request.has_header('Content-length'):
1009 request.add_unredirected_header(
1010 'Content-length', '%d' % len(data))
1011
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001012 sel_host = host
1013 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001014 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001015 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001016 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001017 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001018 for name, value in self.parent.addheaders:
1019 name = name.capitalize()
1020 if not request.has_header(name):
1021 request.add_unredirected_header(name, value)
1022
1023 return request
1024
1025 def do_open(self, http_class, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001026 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001027
1028 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001029 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001030 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001031 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001032 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001033
1034 h = http_class(host, timeout=req.timeout) # will parse host:port
1035 headers = dict(req.headers)
1036 headers.update(req.unredirected_hdrs)
1037
1038 # TODO(jhylton): Should this be redesigned to handle
1039 # persistent connections?
1040
1041 # We want to make an HTTP/1.1 request, but the addinfourl
1042 # class isn't prepared to deal with a persistent connection.
1043 # It will try to read all remaining data from the socket,
1044 # which will block while the server waits for the next request.
1045 # So make sure the connection gets closed after the (only)
1046 # request.
1047 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001048 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001049
1050 if req._tunnel_host:
1051 h.set_tunnel(req._tunnel_host)
1052
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001053 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001054 h.request(req.get_method(), req.selector, req.data, headers)
1055 r = h.getresponse() # an HTTPResponse instance
1056 except socket.error as err:
Georg Brandl13e89462008-07-01 19:56:00 +00001057 raise URLError(err)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001058
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001059 r.url = req.full_url
1060 # This line replaces the .msg attribute of the HTTPResponse
1061 # with .headers, because urllib clients expect the response to
1062 # have the reason in .msg. It would be good to mark this
1063 # attribute is deprecated and get then to use info() or
1064 # .headers.
1065 r.msg = r.reason
1066 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001067
1068
1069class HTTPHandler(AbstractHTTPHandler):
1070
1071 def http_open(self, req):
1072 return self.do_open(http.client.HTTPConnection, req)
1073
1074 http_request = AbstractHTTPHandler.do_request_
1075
1076if hasattr(http.client, 'HTTPSConnection'):
1077 class HTTPSHandler(AbstractHTTPHandler):
1078
1079 def https_open(self, req):
1080 return self.do_open(http.client.HTTPSConnection, req)
1081
1082 https_request = AbstractHTTPHandler.do_request_
1083
1084class HTTPCookieProcessor(BaseHandler):
1085 def __init__(self, cookiejar=None):
1086 import http.cookiejar
1087 if cookiejar is None:
1088 cookiejar = http.cookiejar.CookieJar()
1089 self.cookiejar = cookiejar
1090
1091 def http_request(self, request):
1092 self.cookiejar.add_cookie_header(request)
1093 return request
1094
1095 def http_response(self, request, response):
1096 self.cookiejar.extract_cookies(response, request)
1097 return response
1098
1099 https_request = http_request
1100 https_response = http_response
1101
1102class UnknownHandler(BaseHandler):
1103 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001104 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001105 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001106
1107def parse_keqv_list(l):
1108 """Parse list of key=value strings where keys are not duplicated."""
1109 parsed = {}
1110 for elt in l:
1111 k, v = elt.split('=', 1)
1112 if v[0] == '"' and v[-1] == '"':
1113 v = v[1:-1]
1114 parsed[k] = v
1115 return parsed
1116
1117def parse_http_list(s):
1118 """Parse lists as described by RFC 2068 Section 2.
1119
1120 In particular, parse comma-separated lists where the elements of
1121 the list may include quoted-strings. A quoted-string could
1122 contain a comma. A non-quoted string could have quotes in the
1123 middle. Neither commas nor quotes count if they are escaped.
1124 Only double-quotes count, not single-quotes.
1125 """
1126 res = []
1127 part = ''
1128
1129 escape = quote = False
1130 for cur in s:
1131 if escape:
1132 part += cur
1133 escape = False
1134 continue
1135 if quote:
1136 if cur == '\\':
1137 escape = True
1138 continue
1139 elif cur == '"':
1140 quote = False
1141 part += cur
1142 continue
1143
1144 if cur == ',':
1145 res.append(part)
1146 part = ''
1147 continue
1148
1149 if cur == '"':
1150 quote = True
1151
1152 part += cur
1153
1154 # append last part
1155 if part:
1156 res.append(part)
1157
1158 return [part.strip() for part in res]
1159
1160class FileHandler(BaseHandler):
1161 # Use local file or FTP depending on form of URL
1162 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001163 url = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001164 if url[:2] == '//' and url[2:3] != '/':
1165 req.type = 'ftp'
1166 return self.parent.open(req)
1167 else:
1168 return self.open_local_file(req)
1169
1170 # names for the localhost
1171 names = None
1172 def get_names(self):
1173 if FileHandler.names is None:
1174 try:
1175 FileHandler.names = (socket.gethostbyname('localhost'),
1176 socket.gethostbyname(socket.gethostname()))
1177 except socket.gaierror:
1178 FileHandler.names = (socket.gethostbyname('localhost'),)
1179 return FileHandler.names
1180
1181 # not entirely sure what the rules are here
1182 def open_local_file(self, req):
1183 import email.utils
1184 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001185 host = req.host
1186 file = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001187 localfile = url2pathname(file)
1188 try:
1189 stats = os.stat(localfile)
1190 size = stats.st_size
1191 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1192 mtype = mimetypes.guess_type(file)[0]
1193 headers = email.message_from_string(
1194 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1195 (mtype or 'text/plain', size, modified))
1196 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001197 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001198 if not host or \
1199 (not port and _safe_gethostbyname(host) in self.get_names()):
Georg Brandl13e89462008-07-01 19:56:00 +00001200 return addinfourl(open(localfile, 'rb'), headers, 'file:'+file)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001201 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001202 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001203 raise URLError(msg)
1204 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001205
1206def _safe_gethostbyname(host):
1207 try:
1208 return socket.gethostbyname(host)
1209 except socket.gaierror:
1210 return None
1211
1212class FTPHandler(BaseHandler):
1213 def ftp_open(self, req):
1214 import ftplib
1215 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001216 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001217 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001218 raise URLError('ftp error: no host given')
1219 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001220 if port is None:
1221 port = ftplib.FTP_PORT
1222 else:
1223 port = int(port)
1224
1225 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001226 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001227 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001228 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001229 else:
1230 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001231 host = unquote(host)
1232 user = unquote(user or '')
1233 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001234
1235 try:
1236 host = socket.gethostbyname(host)
1237 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001238 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001239 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001240 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001241 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001242 dirs, file = dirs[:-1], dirs[-1]
1243 if dirs and not dirs[0]:
1244 dirs = dirs[1:]
1245 try:
1246 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1247 type = file and 'I' or 'D'
1248 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001249 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001250 if attr.lower() == 'type' and \
1251 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1252 type = value.upper()
1253 fp, retrlen = fw.retrfile(file, type)
1254 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001255 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001256 if mtype:
1257 headers += "Content-type: %s\n" % mtype
1258 if retrlen is not None and retrlen >= 0:
1259 headers += "Content-length: %d\n" % retrlen
1260 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001261 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001262 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001263 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001264 raise exc.with_traceback(sys.exc_info()[2])
1265
1266 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1267 fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
1268 return fw
1269
1270class CacheFTPHandler(FTPHandler):
1271 # XXX would be nice to have pluggable cache strategies
1272 # XXX this stuff is definitely not thread safe
1273 def __init__(self):
1274 self.cache = {}
1275 self.timeout = {}
1276 self.soonest = 0
1277 self.delay = 60
1278 self.max_conns = 16
1279
1280 def setTimeout(self, t):
1281 self.delay = t
1282
1283 def setMaxConns(self, m):
1284 self.max_conns = m
1285
1286 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1287 key = user, host, port, '/'.join(dirs), timeout
1288 if key in self.cache:
1289 self.timeout[key] = time.time() + self.delay
1290 else:
1291 self.cache[key] = ftpwrapper(user, passwd, host, port,
1292 dirs, timeout)
1293 self.timeout[key] = time.time() + self.delay
1294 self.check_cache()
1295 return self.cache[key]
1296
1297 def check_cache(self):
1298 # first check for old ones
1299 t = time.time()
1300 if self.soonest <= t:
1301 for k, v in list(self.timeout.items()):
1302 if v < t:
1303 self.cache[k].close()
1304 del self.cache[k]
1305 del self.timeout[k]
1306 self.soonest = min(list(self.timeout.values()))
1307
1308 # then check the size
1309 if len(self.cache) == self.max_conns:
1310 for k, v in list(self.timeout.items()):
1311 if v == self.soonest:
1312 del self.cache[k]
1313 del self.timeout[k]
1314 break
1315 self.soonest = min(list(self.timeout.values()))
1316
1317# Code move from the old urllib module
1318
1319MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1320
1321# Helper for non-unix systems
1322if os.name == 'mac':
1323 from macurl2path import url2pathname, pathname2url
1324elif os.name == 'nt':
1325 from nturl2path import url2pathname, pathname2url
1326else:
1327 def url2pathname(pathname):
1328 """OS-specific conversion from a relative URL of the 'file' scheme
1329 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001330 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001331
1332 def pathname2url(pathname):
1333 """OS-specific conversion from a file system path to a relative URL
1334 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001335 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001336
1337# This really consists of two pieces:
1338# (1) a class which handles opening of all sorts of URLs
1339# (plus assorted utilities etc.)
1340# (2) a set of functions for parsing URLs
1341# XXX Should these be separated out into different modules?
1342
1343
1344ftpcache = {}
1345class URLopener:
1346 """Class to open URLs.
1347 This is a class rather than just a subroutine because we may need
1348 more than one set of global protocol-specific options.
1349 Note -- this is a base class for those who don't want the
1350 automatic handling of errors type 302 (relocated) and 401
1351 (authorization needed)."""
1352
1353 __tempfiles = None
1354
1355 version = "Python-urllib/%s" % __version__
1356
1357 # Constructor
1358 def __init__(self, proxies=None, **x509):
1359 if proxies is None:
1360 proxies = getproxies()
1361 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1362 self.proxies = proxies
1363 self.key_file = x509.get('key_file')
1364 self.cert_file = x509.get('cert_file')
1365 self.addheaders = [('User-Agent', self.version)]
1366 self.__tempfiles = []
1367 self.__unlink = os.unlink # See cleanup()
1368 self.tempcache = None
1369 # Undocumented feature: if you assign {} to tempcache,
1370 # it is used to cache files retrieved with
1371 # self.retrieve(). This is not enabled by default
1372 # since it does not work for changing documents (and I
1373 # haven't got the logic to check expiration headers
1374 # yet).
1375 self.ftpcache = ftpcache
1376 # Undocumented feature: you can use a different
1377 # ftp cache by assigning to the .ftpcache member;
1378 # in case you want logically independent URL openers
1379 # XXX This is not threadsafe. Bah.
1380
1381 def __del__(self):
1382 self.close()
1383
1384 def close(self):
1385 self.cleanup()
1386
1387 def cleanup(self):
1388 # This code sometimes runs when the rest of this module
1389 # has already been deleted, so it can't use any globals
1390 # or import anything.
1391 if self.__tempfiles:
1392 for file in self.__tempfiles:
1393 try:
1394 self.__unlink(file)
1395 except OSError:
1396 pass
1397 del self.__tempfiles[:]
1398 if self.tempcache:
1399 self.tempcache.clear()
1400
1401 def addheader(self, *args):
1402 """Add a header to be used by the HTTP interface only
1403 e.g. u.addheader('Accept', 'sound/basic')"""
1404 self.addheaders.append(args)
1405
1406 # External interface
1407 def open(self, fullurl, data=None):
1408 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001409 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001410 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001411 if self.tempcache and fullurl in self.tempcache:
1412 filename, headers = self.tempcache[fullurl]
1413 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001414 return addinfourl(fp, headers, fullurl)
1415 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001416 if not urltype:
1417 urltype = 'file'
1418 if urltype in self.proxies:
1419 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001420 urltype, proxyhost = splittype(proxy)
1421 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001422 url = (host, fullurl) # Signal special case to open_*()
1423 else:
1424 proxy = None
1425 name = 'open_' + urltype
1426 self.type = urltype
1427 name = name.replace('-', '_')
1428 if not hasattr(self, name):
1429 if proxy:
1430 return self.open_unknown_proxy(proxy, fullurl, data)
1431 else:
1432 return self.open_unknown(fullurl, data)
1433 try:
1434 if data is None:
1435 return getattr(self, name)(url)
1436 else:
1437 return getattr(self, name)(url, data)
1438 except socket.error as msg:
1439 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1440
1441 def open_unknown(self, fullurl, data=None):
1442 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001443 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001444 raise IOError('url error', 'unknown url type', type)
1445
1446 def open_unknown_proxy(self, proxy, fullurl, data=None):
1447 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001448 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001449 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1450
1451 # External interface
1452 def retrieve(self, url, filename=None, reporthook=None, data=None):
1453 """retrieve(url) returns (filename, headers) for a local object
1454 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001455 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001456 if self.tempcache and url in self.tempcache:
1457 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001458 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001459 if filename is None and (not type or type == 'file'):
1460 try:
1461 fp = self.open_local_file(url1)
1462 hdrs = fp.info()
1463 del fp
Georg Brandl13e89462008-07-01 19:56:00 +00001464 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001465 except IOError as msg:
1466 pass
1467 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001468 try:
1469 headers = fp.info()
1470 if filename:
1471 tfp = open(filename, 'wb')
1472 else:
1473 import tempfile
1474 garbage, path = splittype(url)
1475 garbage, path = splithost(path or "")
1476 path, garbage = splitquery(path or "")
1477 path, garbage = splitattr(path or "")
1478 suffix = os.path.splitext(path)[1]
1479 (fd, filename) = tempfile.mkstemp(suffix)
1480 self.__tempfiles.append(filename)
1481 tfp = os.fdopen(fd, 'wb')
1482 try:
1483 result = filename, headers
1484 if self.tempcache is not None:
1485 self.tempcache[url] = result
1486 bs = 1024*8
1487 size = -1
1488 read = 0
1489 blocknum = 0
1490 if reporthook:
1491 if "content-length" in headers:
1492 size = int(headers["Content-Length"])
1493 reporthook(blocknum, bs, size)
1494 while 1:
1495 block = fp.read(bs)
1496 if not block:
1497 break
1498 read += len(block)
1499 tfp.write(block)
1500 blocknum += 1
1501 if reporthook:
1502 reporthook(blocknum, bs, size)
1503 finally:
1504 tfp.close()
1505 finally:
1506 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001507 del fp
1508 del tfp
1509
1510 # raise exception if actual size does not match content-length header
1511 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001512 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001513 "retrieval incomplete: got only %i out of %i bytes"
1514 % (read, size), result)
1515
1516 return result
1517
1518 # Each method named open_<type> knows how to open that type of URL
1519
1520 def _open_generic_http(self, connection_factory, url, data):
1521 """Make an HTTP connection using connection_class.
1522
1523 This is an internal method that should be called from
1524 open_http() or open_https().
1525
1526 Arguments:
1527 - connection_factory should take a host name and return an
1528 HTTPConnection instance.
1529 - url is the url to retrieval or a host, relative-path pair.
1530 - data is payload for a POST request or None.
1531 """
1532
1533 user_passwd = None
1534 proxy_passwd= None
1535 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001536 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001537 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001538 user_passwd, host = splituser(host)
1539 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001540 realhost = host
1541 else:
1542 host, selector = url
1543 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001544 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001545 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001546 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001547 url = rest
1548 user_passwd = None
1549 if urltype.lower() != 'http':
1550 realhost = None
1551 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001552 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001553 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001554 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001555 if user_passwd:
1556 selector = "%s://%s%s" % (urltype, realhost, rest)
1557 if proxy_bypass(realhost):
1558 host = realhost
1559
1560 #print "proxy via http:", host, selector
1561 if not host: raise IOError('http error', 'no host given')
1562
1563 if proxy_passwd:
1564 import base64
1565 proxy_auth = base64.b64encode(proxy_passwd).strip()
1566 else:
1567 proxy_auth = None
1568
1569 if user_passwd:
1570 import base64
1571 auth = base64.b64encode(user_passwd).strip()
1572 else:
1573 auth = None
1574 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001575 headers = {}
1576 if proxy_auth:
1577 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1578 if auth:
1579 headers["Authorization"] = "Basic %s" % auth
1580 if realhost:
1581 headers["Host"] = realhost
1582 for header, value in self.addheaders:
1583 headers[header] = value
1584
1585 if data is not None:
1586 headers["Content-Type"] = "application/x-www-form-urlencoded"
1587 http_conn.request("POST", selector, data, headers)
1588 else:
1589 http_conn.request("GET", selector, headers=headers)
1590
1591 try:
1592 response = http_conn.getresponse()
1593 except http.client.BadStatusLine:
1594 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001595 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001596
1597 # According to RFC 2616, "2xx" code indicates that the client's
1598 # request was successfully received, understood, and accepted.
1599 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001600 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001601 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001602 else:
1603 return self.http_error(
1604 url, response.fp,
1605 response.status, response.reason, response.msg, data)
1606
1607 def open_http(self, url, data=None):
1608 """Use HTTP protocol."""
1609 return self._open_generic_http(http.client.HTTPConnection, url, data)
1610
1611 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1612 """Handle http errors.
1613
1614 Derived class can override this, or provide specific handlers
1615 named http_error_DDD where DDD is the 3-digit error code."""
1616 # First check if there's a specific handler for this error
1617 name = 'http_error_%d' % errcode
1618 if hasattr(self, name):
1619 method = getattr(self, name)
1620 if data is None:
1621 result = method(url, fp, errcode, errmsg, headers)
1622 else:
1623 result = method(url, fp, errcode, errmsg, headers, data)
1624 if result: return result
1625 return self.http_error_default(url, fp, errcode, errmsg, headers)
1626
1627 def http_error_default(self, url, fp, errcode, errmsg, headers):
1628 """Default error handler: close the connection and raise IOError."""
1629 void = fp.read()
1630 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001631 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001632
1633 if _have_ssl:
1634 def _https_connection(self, host):
1635 return http.client.HTTPSConnection(host,
1636 key_file=self.key_file,
1637 cert_file=self.cert_file)
1638
1639 def open_https(self, url, data=None):
1640 """Use HTTPS protocol."""
1641 return self._open_generic_http(self._https_connection, url, data)
1642
1643 def open_file(self, url):
1644 """Use local file or FTP depending on form of URL."""
1645 if not isinstance(url, str):
1646 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1647 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
1648 return self.open_ftp(url)
1649 else:
1650 return self.open_local_file(url)
1651
1652 def open_local_file(self, url):
1653 """Use local file."""
1654 import mimetypes, email.utils
1655 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001656 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001657 localname = url2pathname(file)
1658 try:
1659 stats = os.stat(localname)
1660 except OSError as e:
1661 raise URLError(e.errno, e.strerror, e.filename)
1662 size = stats.st_size
1663 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1664 mtype = mimetypes.guess_type(url)[0]
1665 headers = email.message_from_string(
1666 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1667 (mtype or 'text/plain', size, modified))
1668 if not host:
1669 urlfile = file
1670 if file[:1] == '/':
1671 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001672 return addinfourl(open(localname, 'rb'), headers, urlfile)
1673 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001674 if (not port
1675 and socket.gethostbyname(host) in (localhost(), thishost())):
1676 urlfile = file
1677 if file[:1] == '/':
1678 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001679 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001680 raise URLError('local file error', 'not on local host')
1681
1682 def open_ftp(self, url):
1683 """Use FTP protocol."""
1684 if not isinstance(url, str):
1685 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1686 import mimetypes
1687 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001688 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001689 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001690 host, port = splitport(host)
1691 user, host = splituser(host)
1692 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001693 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001694 host = unquote(host)
1695 user = unquote(user or '')
1696 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001697 host = socket.gethostbyname(host)
1698 if not port:
1699 import ftplib
1700 port = ftplib.FTP_PORT
1701 else:
1702 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001703 path, attrs = splitattr(path)
1704 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001705 dirs = path.split('/')
1706 dirs, file = dirs[:-1], dirs[-1]
1707 if dirs and not dirs[0]: dirs = dirs[1:]
1708 if dirs and not dirs[0]: dirs[0] = '/'
1709 key = user, host, port, '/'.join(dirs)
1710 # XXX thread unsafe!
1711 if len(self.ftpcache) > MAXFTPCACHE:
1712 # Prune the cache, rather arbitrarily
1713 for k in self.ftpcache.keys():
1714 if k != key:
1715 v = self.ftpcache[k]
1716 del self.ftpcache[k]
1717 v.close()
1718 try:
1719 if not key in self.ftpcache:
1720 self.ftpcache[key] = \
1721 ftpwrapper(user, passwd, host, port, dirs)
1722 if not file: type = 'D'
1723 else: type = 'I'
1724 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001725 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001726 if attr.lower() == 'type' and \
1727 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1728 type = value.upper()
1729 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1730 mtype = mimetypes.guess_type("ftp:" + url)[0]
1731 headers = ""
1732 if mtype:
1733 headers += "Content-Type: %s\n" % mtype
1734 if retrlen is not None and retrlen >= 0:
1735 headers += "Content-Length: %d\n" % retrlen
1736 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001737 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001738 except ftperrors() as msg:
1739 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1740
1741 def open_data(self, url, data=None):
1742 """Use "data" URL."""
1743 if not isinstance(url, str):
1744 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1745 # ignore POSTed data
1746 #
1747 # syntax of data URLs:
1748 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1749 # mediatype := [ type "/" subtype ] *( ";" parameter )
1750 # data := *urlchar
1751 # parameter := attribute "=" value
1752 try:
1753 [type, data] = url.split(',', 1)
1754 except ValueError:
1755 raise IOError('data error', 'bad data URL')
1756 if not type:
1757 type = 'text/plain;charset=US-ASCII'
1758 semi = type.rfind(';')
1759 if semi >= 0 and '=' not in type[semi:]:
1760 encoding = type[semi+1:]
1761 type = type[:semi]
1762 else:
1763 encoding = ''
1764 msg = []
1765 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
1766 time.gmtime(time.time())))
1767 msg.append('Content-type: %s' % type)
1768 if encoding == 'base64':
1769 import base64
Georg Brandl706824f2009-06-04 09:42:55 +00001770 # XXX is this encoding/decoding ok?
1771 data = base64.decodebytes(data.encode('ascii')).decode('latin1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001772 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001773 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001774 msg.append('Content-Length: %d' % len(data))
1775 msg.append('')
1776 msg.append(data)
1777 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001778 headers = email.message_from_string(msg)
1779 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001780 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001781 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001782
1783
1784class FancyURLopener(URLopener):
1785 """Derived class with handlers for errors we can handle (perhaps)."""
1786
1787 def __init__(self, *args, **kwargs):
1788 URLopener.__init__(self, *args, **kwargs)
1789 self.auth_cache = {}
1790 self.tries = 0
1791 self.maxtries = 10
1792
1793 def http_error_default(self, url, fp, errcode, errmsg, headers):
1794 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001795 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001796
1797 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1798 """Error 302 -- relocated (temporarily)."""
1799 self.tries += 1
1800 if self.maxtries and self.tries >= self.maxtries:
1801 if hasattr(self, "http_error_500"):
1802 meth = self.http_error_500
1803 else:
1804 meth = self.http_error_default
1805 self.tries = 0
1806 return meth(url, fp, 500,
1807 "Internal Server Error: Redirect Recursion", headers)
1808 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
1809 data)
1810 self.tries = 0
1811 return result
1812
1813 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
1814 if 'location' in headers:
1815 newurl = headers['location']
1816 elif 'uri' in headers:
1817 newurl = headers['uri']
1818 else:
1819 return
1820 void = fp.read()
1821 fp.close()
1822 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00001823 newurl = urljoin(self.type + ":" + url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001824 return self.open(newurl)
1825
1826 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
1827 """Error 301 -- also relocated (permanently)."""
1828 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1829
1830 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
1831 """Error 303 -- also relocated (essentially identical to 302)."""
1832 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1833
1834 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
1835 """Error 307 -- relocated, but turn POST into error."""
1836 if data is None:
1837 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1838 else:
1839 return self.http_error_default(url, fp, errcode, errmsg, headers)
1840
1841 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
1842 """Error 401 -- authentication required.
1843 This function supports Basic authentication only."""
1844 if not 'www-authenticate' in headers:
1845 URLopener.http_error_default(self, url, fp,
1846 errcode, errmsg, headers)
1847 stuff = headers['www-authenticate']
1848 import re
1849 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1850 if not match:
1851 URLopener.http_error_default(self, url, fp,
1852 errcode, errmsg, headers)
1853 scheme, realm = match.groups()
1854 if scheme.lower() != 'basic':
1855 URLopener.http_error_default(self, url, fp,
1856 errcode, errmsg, headers)
1857 name = 'retry_' + self.type + '_basic_auth'
1858 if data is None:
1859 return getattr(self,name)(url, realm)
1860 else:
1861 return getattr(self,name)(url, realm, data)
1862
1863 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
1864 """Error 407 -- proxy authentication required.
1865 This function supports Basic authentication only."""
1866 if not 'proxy-authenticate' in headers:
1867 URLopener.http_error_default(self, url, fp,
1868 errcode, errmsg, headers)
1869 stuff = headers['proxy-authenticate']
1870 import re
1871 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1872 if not match:
1873 URLopener.http_error_default(self, url, fp,
1874 errcode, errmsg, headers)
1875 scheme, realm = match.groups()
1876 if scheme.lower() != 'basic':
1877 URLopener.http_error_default(self, url, fp,
1878 errcode, errmsg, headers)
1879 name = 'retry_proxy_' + self.type + '_basic_auth'
1880 if data is None:
1881 return getattr(self,name)(url, realm)
1882 else:
1883 return getattr(self,name)(url, realm, data)
1884
1885 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001886 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001887 newurl = 'http://' + host + selector
1888 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00001889 urltype, proxyhost = splittype(proxy)
1890 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001891 i = proxyhost.find('@') + 1
1892 proxyhost = proxyhost[i:]
1893 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1894 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001895 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001896 quote(passwd, safe=''), proxyhost)
1897 self.proxies['http'] = 'http://' + proxyhost + proxyselector
1898 if data is None:
1899 return self.open(newurl)
1900 else:
1901 return self.open(newurl, data)
1902
1903 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001904 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001905 newurl = 'https://' + host + selector
1906 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00001907 urltype, proxyhost = splittype(proxy)
1908 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001909 i = proxyhost.find('@') + 1
1910 proxyhost = proxyhost[i:]
1911 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1912 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001913 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001914 quote(passwd, safe=''), proxyhost)
1915 self.proxies['https'] = 'https://' + proxyhost + proxyselector
1916 if data is None:
1917 return self.open(newurl)
1918 else:
1919 return self.open(newurl, data)
1920
1921 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001922 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001923 i = host.find('@') + 1
1924 host = host[i:]
1925 user, passwd = self.get_user_passwd(host, realm, i)
1926 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001927 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001928 quote(passwd, safe=''), host)
1929 newurl = 'http://' + host + selector
1930 if data is None:
1931 return self.open(newurl)
1932 else:
1933 return self.open(newurl, data)
1934
1935 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001936 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001937 i = host.find('@') + 1
1938 host = host[i:]
1939 user, passwd = self.get_user_passwd(host, realm, i)
1940 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001941 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001942 quote(passwd, safe=''), host)
1943 newurl = 'https://' + host + selector
1944 if data is None:
1945 return self.open(newurl)
1946 else:
1947 return self.open(newurl, data)
1948
1949 def get_user_passwd(self, host, realm, clear_cache = 0):
1950 key = realm + '@' + host.lower()
1951 if key in self.auth_cache:
1952 if clear_cache:
1953 del self.auth_cache[key]
1954 else:
1955 return self.auth_cache[key]
1956 user, passwd = self.prompt_user_passwd(host, realm)
1957 if user or passwd: self.auth_cache[key] = (user, passwd)
1958 return user, passwd
1959
1960 def prompt_user_passwd(self, host, realm):
1961 """Override this in a GUI environment!"""
1962 import getpass
1963 try:
1964 user = input("Enter username for %s at %s: " % (realm, host))
1965 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
1966 (user, realm, host))
1967 return user, passwd
1968 except KeyboardInterrupt:
1969 print()
1970 return None, None
1971
1972
1973# Utility functions
1974
1975_localhost = None
1976def localhost():
1977 """Return the IP address of the magic hostname 'localhost'."""
1978 global _localhost
1979 if _localhost is None:
1980 _localhost = socket.gethostbyname('localhost')
1981 return _localhost
1982
1983_thishost = None
1984def thishost():
1985 """Return the IP address of the current host."""
1986 global _thishost
1987 if _thishost is None:
1988 _thishost = socket.gethostbyname(socket.gethostname())
1989 return _thishost
1990
1991_ftperrors = None
1992def ftperrors():
1993 """Return the set of errors raised by the FTP class."""
1994 global _ftperrors
1995 if _ftperrors is None:
1996 import ftplib
1997 _ftperrors = ftplib.all_errors
1998 return _ftperrors
1999
2000_noheaders = None
2001def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002002 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002003 global _noheaders
2004 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002005 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002006 return _noheaders
2007
2008
2009# Utility classes
2010
2011class ftpwrapper:
2012 """Class used by open_ftp() for cache of open FTP connections."""
2013
2014 def __init__(self, user, passwd, host, port, dirs, timeout=None):
2015 self.user = user
2016 self.passwd = passwd
2017 self.host = host
2018 self.port = port
2019 self.dirs = dirs
2020 self.timeout = timeout
2021 self.init()
2022
2023 def init(self):
2024 import ftplib
2025 self.busy = 0
2026 self.ftp = ftplib.FTP()
2027 self.ftp.connect(self.host, self.port, self.timeout)
2028 self.ftp.login(self.user, self.passwd)
2029 for dir in self.dirs:
2030 self.ftp.cwd(dir)
2031
2032 def retrfile(self, file, type):
2033 import ftplib
2034 self.endtransfer()
2035 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2036 else: cmd = 'TYPE ' + type; isdir = 0
2037 try:
2038 self.ftp.voidcmd(cmd)
2039 except ftplib.all_errors:
2040 self.init()
2041 self.ftp.voidcmd(cmd)
2042 conn = None
2043 if file and not isdir:
2044 # Try to retrieve as a file
2045 try:
2046 cmd = 'RETR ' + file
2047 conn = self.ftp.ntransfercmd(cmd)
2048 except ftplib.error_perm as reason:
2049 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002050 raise URLError('ftp error', reason).with_traceback(
2051 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002052 if not conn:
2053 # Set transfer mode to ASCII!
2054 self.ftp.voidcmd('TYPE A')
2055 # Try a directory listing. Verify that directory exists.
2056 if file:
2057 pwd = self.ftp.pwd()
2058 try:
2059 try:
2060 self.ftp.cwd(file)
2061 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002062 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002063 finally:
2064 self.ftp.cwd(pwd)
2065 cmd = 'LIST ' + file
2066 else:
2067 cmd = 'LIST'
2068 conn = self.ftp.ntransfercmd(cmd)
2069 self.busy = 1
2070 # Pass back both a suitably decorated object and a retrieval length
Georg Brandl13e89462008-07-01 19:56:00 +00002071 return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002072 def endtransfer(self):
2073 if not self.busy:
2074 return
2075 self.busy = 0
2076 try:
2077 self.ftp.voidresp()
2078 except ftperrors():
2079 pass
2080
2081 def close(self):
2082 self.endtransfer()
2083 try:
2084 self.ftp.close()
2085 except ftperrors():
2086 pass
2087
2088# Proxy handling
2089def getproxies_environment():
2090 """Return a dictionary of scheme -> proxy server URL mappings.
2091
2092 Scan the environment for variables named <scheme>_proxy;
2093 this seems to be the standard convention. If you need a
2094 different way, you can pass a proxies dictionary to the
2095 [Fancy]URLopener constructor.
2096
2097 """
2098 proxies = {}
2099 for name, value in os.environ.items():
2100 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002101 if value and name[-6:] == '_proxy':
2102 proxies[name[:-6]] = value
2103 return proxies
2104
2105def proxy_bypass_environment(host):
2106 """Test if proxies should not be used for a particular host.
2107
2108 Checks the environment for a variable named no_proxy, which should
2109 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2110 """
2111 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2112 # '*' is special case for always bypass
2113 if no_proxy == '*':
2114 return 1
2115 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002116 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002117 # check if the host ends with any of the DNS suffixes
2118 for name in no_proxy.split(','):
2119 if name and (hostonly.endswith(name) or host.endswith(name)):
2120 return 1
2121 # otherwise, don't bypass
2122 return 0
2123
2124
2125if sys.platform == 'darwin':
2126 def getproxies_internetconfig():
2127 """Return a dictionary of scheme -> proxy server URL mappings.
2128
2129 By convention the mac uses Internet Config to store
2130 proxies. An HTTP proxy, for instance, is stored under
2131 the HttpProxy key.
2132
2133 """
2134 try:
2135 import ic
2136 except ImportError:
2137 return {}
2138
2139 try:
2140 config = ic.IC()
2141 except ic.error:
2142 return {}
2143 proxies = {}
2144 # HTTP:
2145 if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
2146 try:
2147 value = config['HTTPProxyHost']
2148 except ic.error:
2149 pass
2150 else:
2151 proxies['http'] = 'http://%s' % value
2152 # FTP: XXX To be done.
2153 # Gopher: XXX To be done.
2154 return proxies
2155
2156 def proxy_bypass(host):
2157 if getproxies_environment():
2158 return proxy_bypass_environment(host)
2159 else:
2160 return 0
2161
2162 def getproxies():
2163 return getproxies_environment() or getproxies_internetconfig()
2164
2165elif os.name == 'nt':
2166 def getproxies_registry():
2167 """Return a dictionary of scheme -> proxy server URL mappings.
2168
2169 Win32 uses the registry to store proxies.
2170
2171 """
2172 proxies = {}
2173 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002174 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002175 except ImportError:
2176 # Std module, so should be around - but you never know!
2177 return proxies
2178 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002179 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002180 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002181 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002182 'ProxyEnable')[0]
2183 if proxyEnable:
2184 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002185 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002186 'ProxyServer')[0])
2187 if '=' in proxyServer:
2188 # Per-protocol settings
2189 for p in proxyServer.split(';'):
2190 protocol, address = p.split('=', 1)
2191 # See if address has a type:// prefix
2192 import re
2193 if not re.match('^([^/:]+)://', address):
2194 address = '%s://%s' % (protocol, address)
2195 proxies[protocol] = address
2196 else:
2197 # Use one setting for all protocols
2198 if proxyServer[:5] == 'http:':
2199 proxies['http'] = proxyServer
2200 else:
2201 proxies['http'] = 'http://%s' % proxyServer
2202 proxies['ftp'] = 'ftp://%s' % proxyServer
2203 internetSettings.Close()
2204 except (WindowsError, ValueError, TypeError):
2205 # Either registry key not found etc, or the value in an
2206 # unexpected format.
2207 # proxies already set up to be empty so nothing to do
2208 pass
2209 return proxies
2210
2211 def getproxies():
2212 """Return a dictionary of scheme -> proxy server URL mappings.
2213
2214 Returns settings gathered from the environment, if specified,
2215 or the registry.
2216
2217 """
2218 return getproxies_environment() or getproxies_registry()
2219
2220 def proxy_bypass_registry(host):
2221 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002222 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002223 import re
2224 except ImportError:
2225 # Std modules, so should be around - but you never know!
2226 return 0
2227 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002228 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002229 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002230 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002231 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002232 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002233 'ProxyOverride')[0])
2234 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2235 except WindowsError:
2236 return 0
2237 if not proxyEnable or not proxyOverride:
2238 return 0
2239 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002240 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002241 host = [rawHost]
2242 try:
2243 addr = socket.gethostbyname(rawHost)
2244 if addr != rawHost:
2245 host.append(addr)
2246 except socket.error:
2247 pass
2248 try:
2249 fqdn = socket.getfqdn(rawHost)
2250 if fqdn != rawHost:
2251 host.append(fqdn)
2252 except socket.error:
2253 pass
2254 # make a check value list from the registry entry: replace the
2255 # '<local>' string by the localhost entry and the corresponding
2256 # canonical entry.
2257 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002258 # now check if we match one of the registry values.
2259 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002260 if test == '<local>':
2261 if '.' not in rawHost:
2262 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002263 test = test.replace(".", r"\.") # mask dots
2264 test = test.replace("*", r".*") # change glob sequence
2265 test = test.replace("?", r".") # change glob char
2266 for val in host:
2267 # print "%s <--> %s" %( test, val )
2268 if re.match(test, val, re.I):
2269 return 1
2270 return 0
2271
2272 def proxy_bypass(host):
2273 """Return a dictionary of scheme -> proxy server URL mappings.
2274
2275 Returns settings gathered from the environment, if specified,
2276 or the registry.
2277
2278 """
2279 if getproxies_environment():
2280 return proxy_bypass_environment(host)
2281 else:
2282 return proxy_bypass_registry(host)
2283
2284else:
2285 # By default use environment variables
2286 getproxies = getproxies_environment
2287 proxy_bypass = proxy_bypass_environment