blob: 9f7ebd7afce774a05a7e1273fa8fbb7a08dd9faa [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 Kumaran0ac1f832009-07-26 12:39:47 +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 Kumaran0ac1f832009-07-26 12:39:47 +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 Kumarane9da06f2009-07-19 04:20:12 +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
Senthil Kumaran11301632009-10-11 06:07:46 +0000660
661 if req.host and proxy_bypass(req.host):
662 return None
663
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000664 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000665 user_pass = '%s:%s' % (unquote(user),
666 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000667 creds = base64.b64encode(user_pass.encode()).decode("ascii")
668 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000669 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000670 req.set_proxy(hostport, proxy_type)
Senthil Kumaran0ac1f832009-07-26 12:39:47 +0000671 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000672 # let other handlers take care of it
673 return None
674 else:
675 # need to start over, because the other handlers don't
676 # grok the proxy's URL type
677 # e.g. if we have a constructor arg proxies like so:
678 # {'http': 'ftp://proxy.example.com'}, we may end up turning
679 # a request for http://acme.example.com/a into one for
680 # ftp://proxy.example.com/a
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000681 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000682
683class HTTPPasswordMgr:
684
685 def __init__(self):
686 self.passwd = {}
687
688 def add_password(self, realm, uri, user, passwd):
689 # uri could be a single URI or a sequence
690 if isinstance(uri, str):
691 uri = [uri]
692 if not realm in self.passwd:
693 self.passwd[realm] = {}
694 for default_port in True, False:
695 reduced_uri = tuple(
696 [self.reduce_uri(u, default_port) for u in uri])
697 self.passwd[realm][reduced_uri] = (user, passwd)
698
699 def find_user_password(self, realm, authuri):
700 domains = self.passwd.get(realm, {})
701 for default_port in True, False:
702 reduced_authuri = self.reduce_uri(authuri, default_port)
703 for uris, authinfo in domains.items():
704 for uri in uris:
705 if self.is_suburi(uri, reduced_authuri):
706 return authinfo
707 return None, None
708
709 def reduce_uri(self, uri, default_port=True):
710 """Accept authority or URI and extract only the authority and path."""
711 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000712 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000713 if parts[1]:
714 # URI
715 scheme = parts[0]
716 authority = parts[1]
717 path = parts[2] or '/'
718 else:
719 # host or host:port
720 scheme = None
721 authority = uri
722 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000723 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000724 if default_port and port is None and scheme is not None:
725 dport = {"http": 80,
726 "https": 443,
727 }.get(scheme)
728 if dport is not None:
729 authority = "%s:%d" % (host, dport)
730 return authority, path
731
732 def is_suburi(self, base, test):
733 """Check if test is below base in a URI tree
734
735 Both args must be URIs in reduced form.
736 """
737 if base == test:
738 return True
739 if base[0] != test[0]:
740 return False
741 common = posixpath.commonprefix((base[1], test[1]))
742 if len(common) == len(base[1]):
743 return True
744 return False
745
746
747class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
748
749 def find_user_password(self, realm, authuri):
750 user, password = HTTPPasswordMgr.find_user_password(self, realm,
751 authuri)
752 if user is not None:
753 return user, password
754 return HTTPPasswordMgr.find_user_password(self, None, authuri)
755
756
757class AbstractBasicAuthHandler:
758
759 # XXX this allows for multiple auth-schemes, but will stupidly pick
760 # the last one with a realm specified.
761
762 # allow for double- and single-quoted realm values
763 # (single quotes are a violation of the RFC, but appear in the wild)
764 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
765 'realm=(["\'])(.*?)\\2', re.I)
766
767 # XXX could pre-emptively send auth info already accepted (RFC 2617,
768 # end of section 2, and section 1.2 immediately after "credentials"
769 # production).
770
771 def __init__(self, password_mgr=None):
772 if password_mgr is None:
773 password_mgr = HTTPPasswordMgr()
774 self.passwd = password_mgr
775 self.add_password = self.passwd.add_password
776
777 def http_error_auth_reqed(self, authreq, host, req, headers):
778 # host may be an authority (without userinfo) or a URL with an
779 # authority
780 # XXX could be multiple headers
781 authreq = headers.get(authreq, None)
782 if authreq:
783 mo = AbstractBasicAuthHandler.rx.search(authreq)
784 if mo:
785 scheme, quote, realm = mo.groups()
786 if scheme.lower() == 'basic':
787 return self.retry_http_basic_auth(host, req, realm)
788
789 def retry_http_basic_auth(self, host, req, realm):
790 user, pw = self.passwd.find_user_password(realm, host)
791 if pw is not None:
792 raw = "%s:%s" % (user, pw)
793 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
794 if req.headers.get(self.auth_header, None) == auth:
795 return None
796 req.add_header(self.auth_header, auth)
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000797 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000798 else:
799 return None
800
801
802class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
803
804 auth_header = 'Authorization'
805
806 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000807 url = req.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000808 return self.http_error_auth_reqed('www-authenticate',
809 url, req, headers)
810
811
812class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
813
814 auth_header = 'Proxy-authorization'
815
816 def http_error_407(self, req, fp, code, msg, headers):
817 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000818 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000819 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
820 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000821 authority = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000822 return self.http_error_auth_reqed('proxy-authenticate',
823 authority, req, headers)
824
825
826def randombytes(n):
827 """Return n random bytes."""
828 return os.urandom(n)
829
830class AbstractDigestAuthHandler:
831 # Digest authentication is specified in RFC 2617.
832
833 # XXX The client does not inspect the Authentication-Info header
834 # in a successful response.
835
836 # XXX It should be possible to test this implementation against
837 # a mock server that just generates a static set of challenges.
838
839 # XXX qop="auth-int" supports is shaky
840
841 def __init__(self, passwd=None):
842 if passwd is None:
843 passwd = HTTPPasswordMgr()
844 self.passwd = passwd
845 self.add_password = self.passwd.add_password
846 self.retried = 0
847 self.nonce_count = 0
848
849 def reset_retry_count(self):
850 self.retried = 0
851
852 def http_error_auth_reqed(self, auth_header, host, req, headers):
853 authreq = headers.get(auth_header, None)
854 if self.retried > 5:
855 # Don't fail endlessly - if we failed once, we'll probably
856 # fail a second time. Hm. Unless the Password Manager is
857 # prompting for the information. Crap. This isn't great
858 # but it's better than the current 'repeat until recursion
859 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000860 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000861 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000862 else:
863 self.retried += 1
864 if authreq:
865 scheme = authreq.split()[0]
866 if scheme.lower() == 'digest':
867 return self.retry_http_digest_auth(req, authreq)
868
869 def retry_http_digest_auth(self, req, auth):
870 token, challenge = auth.split(' ', 1)
871 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
872 auth = self.get_authorization(req, chal)
873 if auth:
874 auth_val = 'Digest %s' % auth
875 if req.headers.get(self.auth_header, None) == auth_val:
876 return None
877 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000878 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000879 return resp
880
881 def get_cnonce(self, nonce):
882 # The cnonce-value is an opaque
883 # quoted string value provided by the client and used by both client
884 # and server to avoid chosen plaintext attacks, to provide mutual
885 # authentication, and to provide some message integrity protection.
886 # This isn't a fabulous effort, but it's probably Good Enough.
887 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
888 b = s.encode("ascii") + randombytes(8)
889 dig = hashlib.sha1(b).hexdigest()
890 return dig[:16]
891
892 def get_authorization(self, req, chal):
893 try:
894 realm = chal['realm']
895 nonce = chal['nonce']
896 qop = chal.get('qop')
897 algorithm = chal.get('algorithm', 'MD5')
898 # mod_digest doesn't send an opaque, even though it isn't
899 # supposed to be optional
900 opaque = chal.get('opaque', None)
901 except KeyError:
902 return None
903
904 H, KD = self.get_algorithm_impls(algorithm)
905 if H is None:
906 return None
907
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000908 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000909 if user is None:
910 return None
911
912 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000913 if req.data is not None:
914 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000915 else:
916 entdig = None
917
918 A1 = "%s:%s:%s" % (user, realm, pw)
919 A2 = "%s:%s" % (req.get_method(),
920 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000921 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000922 if qop == 'auth':
923 self.nonce_count += 1
924 ncvalue = '%08x' % self.nonce_count
925 cnonce = self.get_cnonce(nonce)
926 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
927 respdig = KD(H(A1), noncebit)
928 elif qop is None:
929 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
930 else:
931 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +0000932 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000933
934 # XXX should the partial digests be encoded too?
935
936 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000937 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000938 respdig)
939 if opaque:
940 base += ', opaque="%s"' % opaque
941 if entdig:
942 base += ', digest="%s"' % entdig
943 base += ', algorithm="%s"' % algorithm
944 if qop:
945 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
946 return base
947
948 def get_algorithm_impls(self, algorithm):
949 # lambdas assume digest modules are imported at the top level
950 if algorithm == 'MD5':
951 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
952 elif algorithm == 'SHA':
953 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
954 # XXX MD5-sess
955 KD = lambda s, d: H("%s:%s" % (s, d))
956 return H, KD
957
958 def get_entity_digest(self, data, chal):
959 # XXX not implemented yet
960 return None
961
962
963class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
964 """An authentication protocol defined by RFC 2069
965
966 Digest authentication improves on basic authentication because it
967 does not transmit passwords in the clear.
968 """
969
970 auth_header = 'Authorization'
971 handler_order = 490 # before Basic auth
972
973 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000974 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000975 retry = self.http_error_auth_reqed('www-authenticate',
976 host, req, headers)
977 self.reset_retry_count()
978 return retry
979
980
981class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
982
983 auth_header = 'Proxy-Authorization'
984 handler_order = 490 # before Basic auth
985
986 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000987 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000988 retry = self.http_error_auth_reqed('proxy-authenticate',
989 host, req, headers)
990 self.reset_retry_count()
991 return retry
992
993class AbstractHTTPHandler(BaseHandler):
994
995 def __init__(self, debuglevel=0):
996 self._debuglevel = debuglevel
997
998 def set_http_debuglevel(self, level):
999 self._debuglevel = level
1000
1001 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001002 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001003 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001004 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001005
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001006 if request.data is not None: # POST
1007 data = request.data
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001008 if not request.has_header('Content-type'):
1009 request.add_unredirected_header(
1010 'Content-type',
1011 'application/x-www-form-urlencoded')
1012 if not request.has_header('Content-length'):
1013 request.add_unredirected_header(
1014 'Content-length', '%d' % len(data))
1015
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001016 sel_host = host
1017 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001018 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001019 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001020 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001021 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001022 for name, value in self.parent.addheaders:
1023 name = name.capitalize()
1024 if not request.has_header(name):
1025 request.add_unredirected_header(name, value)
1026
1027 return request
1028
1029 def do_open(self, http_class, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001030 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001031
1032 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001033 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001034 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001035 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001036 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001037
1038 h = http_class(host, timeout=req.timeout) # will parse host:port
1039 headers = dict(req.headers)
1040 headers.update(req.unredirected_hdrs)
1041
1042 # TODO(jhylton): Should this be redesigned to handle
1043 # persistent connections?
1044
1045 # We want to make an HTTP/1.1 request, but the addinfourl
1046 # class isn't prepared to deal with a persistent connection.
1047 # It will try to read all remaining data from the socket,
1048 # which will block while the server waits for the next request.
1049 # So make sure the connection gets closed after the (only)
1050 # request.
1051 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001052 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran0ac1f832009-07-26 12:39:47 +00001053
1054 if req._tunnel_host:
1055 h._set_tunnel(req._tunnel_host)
1056
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001057 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001058 h.request(req.get_method(), req.selector, req.data, headers)
1059 r = h.getresponse() # an HTTPResponse instance
1060 except socket.error as err:
Georg Brandl13e89462008-07-01 19:56:00 +00001061 raise URLError(err)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001062
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001063 r.url = req.full_url
1064 # This line replaces the .msg attribute of the HTTPResponse
1065 # with .headers, because urllib clients expect the response to
1066 # have the reason in .msg. It would be good to mark this
1067 # attribute is deprecated and get then to use info() or
1068 # .headers.
1069 r.msg = r.reason
1070 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001071
1072
1073class HTTPHandler(AbstractHTTPHandler):
1074
1075 def http_open(self, req):
1076 return self.do_open(http.client.HTTPConnection, req)
1077
1078 http_request = AbstractHTTPHandler.do_request_
1079
1080if hasattr(http.client, 'HTTPSConnection'):
1081 class HTTPSHandler(AbstractHTTPHandler):
1082
1083 def https_open(self, req):
1084 return self.do_open(http.client.HTTPSConnection, req)
1085
1086 https_request = AbstractHTTPHandler.do_request_
1087
1088class HTTPCookieProcessor(BaseHandler):
1089 def __init__(self, cookiejar=None):
1090 import http.cookiejar
1091 if cookiejar is None:
1092 cookiejar = http.cookiejar.CookieJar()
1093 self.cookiejar = cookiejar
1094
1095 def http_request(self, request):
1096 self.cookiejar.add_cookie_header(request)
1097 return request
1098
1099 def http_response(self, request, response):
1100 self.cookiejar.extract_cookies(response, request)
1101 return response
1102
1103 https_request = http_request
1104 https_response = http_response
1105
1106class UnknownHandler(BaseHandler):
1107 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001108 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001109 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001110
1111def parse_keqv_list(l):
1112 """Parse list of key=value strings where keys are not duplicated."""
1113 parsed = {}
1114 for elt in l:
1115 k, v = elt.split('=', 1)
1116 if v[0] == '"' and v[-1] == '"':
1117 v = v[1:-1]
1118 parsed[k] = v
1119 return parsed
1120
1121def parse_http_list(s):
1122 """Parse lists as described by RFC 2068 Section 2.
1123
1124 In particular, parse comma-separated lists where the elements of
1125 the list may include quoted-strings. A quoted-string could
1126 contain a comma. A non-quoted string could have quotes in the
1127 middle. Neither commas nor quotes count if they are escaped.
1128 Only double-quotes count, not single-quotes.
1129 """
1130 res = []
1131 part = ''
1132
1133 escape = quote = False
1134 for cur in s:
1135 if escape:
1136 part += cur
1137 escape = False
1138 continue
1139 if quote:
1140 if cur == '\\':
1141 escape = True
1142 continue
1143 elif cur == '"':
1144 quote = False
1145 part += cur
1146 continue
1147
1148 if cur == ',':
1149 res.append(part)
1150 part = ''
1151 continue
1152
1153 if cur == '"':
1154 quote = True
1155
1156 part += cur
1157
1158 # append last part
1159 if part:
1160 res.append(part)
1161
1162 return [part.strip() for part in res]
1163
1164class FileHandler(BaseHandler):
1165 # Use local file or FTP depending on form of URL
1166 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001167 url = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001168 if url[:2] == '//' and url[2:3] != '/':
1169 req.type = 'ftp'
1170 return self.parent.open(req)
1171 else:
1172 return self.open_local_file(req)
1173
1174 # names for the localhost
1175 names = None
1176 def get_names(self):
1177 if FileHandler.names is None:
1178 try:
1179 FileHandler.names = (socket.gethostbyname('localhost'),
1180 socket.gethostbyname(socket.gethostname()))
1181 except socket.gaierror:
1182 FileHandler.names = (socket.gethostbyname('localhost'),)
1183 return FileHandler.names
1184
1185 # not entirely sure what the rules are here
1186 def open_local_file(self, req):
1187 import email.utils
1188 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001189 host = req.host
1190 file = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001191 localfile = url2pathname(file)
1192 try:
1193 stats = os.stat(localfile)
1194 size = stats.st_size
1195 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1196 mtype = mimetypes.guess_type(file)[0]
1197 headers = email.message_from_string(
1198 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1199 (mtype or 'text/plain', size, modified))
1200 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001201 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001202 if not host or \
1203 (not port and _safe_gethostbyname(host) in self.get_names()):
Georg Brandl13e89462008-07-01 19:56:00 +00001204 return addinfourl(open(localfile, 'rb'), headers, 'file:'+file)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001205 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001206 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001207 raise URLError(msg)
1208 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001209
1210def _safe_gethostbyname(host):
1211 try:
1212 return socket.gethostbyname(host)
1213 except socket.gaierror:
1214 return None
1215
1216class FTPHandler(BaseHandler):
1217 def ftp_open(self, req):
1218 import ftplib
1219 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001220 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001221 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001222 raise URLError('ftp error: no host given')
1223 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001224 if port is None:
1225 port = ftplib.FTP_PORT
1226 else:
1227 port = int(port)
1228
1229 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001230 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001231 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001232 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001233 else:
1234 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001235 host = unquote(host)
1236 user = unquote(user or '')
1237 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001238
1239 try:
1240 host = socket.gethostbyname(host)
1241 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001242 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001243 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001244 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001245 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001246 dirs, file = dirs[:-1], dirs[-1]
1247 if dirs and not dirs[0]:
1248 dirs = dirs[1:]
1249 try:
1250 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1251 type = file and 'I' or 'D'
1252 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001253 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001254 if attr.lower() == 'type' and \
1255 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1256 type = value.upper()
1257 fp, retrlen = fw.retrfile(file, type)
1258 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001259 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001260 if mtype:
1261 headers += "Content-type: %s\n" % mtype
1262 if retrlen is not None and retrlen >= 0:
1263 headers += "Content-length: %d\n" % retrlen
1264 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001265 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001266 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001267 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001268 raise exc.with_traceback(sys.exc_info()[2])
1269
1270 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1271 fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
1272 return fw
1273
1274class CacheFTPHandler(FTPHandler):
1275 # XXX would be nice to have pluggable cache strategies
1276 # XXX this stuff is definitely not thread safe
1277 def __init__(self):
1278 self.cache = {}
1279 self.timeout = {}
1280 self.soonest = 0
1281 self.delay = 60
1282 self.max_conns = 16
1283
1284 def setTimeout(self, t):
1285 self.delay = t
1286
1287 def setMaxConns(self, m):
1288 self.max_conns = m
1289
1290 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1291 key = user, host, port, '/'.join(dirs), timeout
1292 if key in self.cache:
1293 self.timeout[key] = time.time() + self.delay
1294 else:
1295 self.cache[key] = ftpwrapper(user, passwd, host, port,
1296 dirs, timeout)
1297 self.timeout[key] = time.time() + self.delay
1298 self.check_cache()
1299 return self.cache[key]
1300
1301 def check_cache(self):
1302 # first check for old ones
1303 t = time.time()
1304 if self.soonest <= t:
1305 for k, v in list(self.timeout.items()):
1306 if v < t:
1307 self.cache[k].close()
1308 del self.cache[k]
1309 del self.timeout[k]
1310 self.soonest = min(list(self.timeout.values()))
1311
1312 # then check the size
1313 if len(self.cache) == self.max_conns:
1314 for k, v in list(self.timeout.items()):
1315 if v == self.soonest:
1316 del self.cache[k]
1317 del self.timeout[k]
1318 break
1319 self.soonest = min(list(self.timeout.values()))
1320
1321# Code move from the old urllib module
1322
1323MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1324
1325# Helper for non-unix systems
1326if os.name == 'mac':
1327 from macurl2path import url2pathname, pathname2url
1328elif os.name == 'nt':
1329 from nturl2path import url2pathname, pathname2url
1330else:
1331 def url2pathname(pathname):
1332 """OS-specific conversion from a relative URL of the 'file' scheme
1333 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001334 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001335
1336 def pathname2url(pathname):
1337 """OS-specific conversion from a file system path to a relative URL
1338 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001339 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001340
1341# This really consists of two pieces:
1342# (1) a class which handles opening of all sorts of URLs
1343# (plus assorted utilities etc.)
1344# (2) a set of functions for parsing URLs
1345# XXX Should these be separated out into different modules?
1346
1347
1348ftpcache = {}
1349class URLopener:
1350 """Class to open URLs.
1351 This is a class rather than just a subroutine because we may need
1352 more than one set of global protocol-specific options.
1353 Note -- this is a base class for those who don't want the
1354 automatic handling of errors type 302 (relocated) and 401
1355 (authorization needed)."""
1356
1357 __tempfiles = None
1358
1359 version = "Python-urllib/%s" % __version__
1360
1361 # Constructor
1362 def __init__(self, proxies=None, **x509):
1363 if proxies is None:
1364 proxies = getproxies()
1365 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1366 self.proxies = proxies
1367 self.key_file = x509.get('key_file')
1368 self.cert_file = x509.get('cert_file')
1369 self.addheaders = [('User-Agent', self.version)]
1370 self.__tempfiles = []
1371 self.__unlink = os.unlink # See cleanup()
1372 self.tempcache = None
1373 # Undocumented feature: if you assign {} to tempcache,
1374 # it is used to cache files retrieved with
1375 # self.retrieve(). This is not enabled by default
1376 # since it does not work for changing documents (and I
1377 # haven't got the logic to check expiration headers
1378 # yet).
1379 self.ftpcache = ftpcache
1380 # Undocumented feature: you can use a different
1381 # ftp cache by assigning to the .ftpcache member;
1382 # in case you want logically independent URL openers
1383 # XXX This is not threadsafe. Bah.
1384
1385 def __del__(self):
1386 self.close()
1387
1388 def close(self):
1389 self.cleanup()
1390
1391 def cleanup(self):
1392 # This code sometimes runs when the rest of this module
1393 # has already been deleted, so it can't use any globals
1394 # or import anything.
1395 if self.__tempfiles:
1396 for file in self.__tempfiles:
1397 try:
1398 self.__unlink(file)
1399 except OSError:
1400 pass
1401 del self.__tempfiles[:]
1402 if self.tempcache:
1403 self.tempcache.clear()
1404
1405 def addheader(self, *args):
1406 """Add a header to be used by the HTTP interface only
1407 e.g. u.addheader('Accept', 'sound/basic')"""
1408 self.addheaders.append(args)
1409
1410 # External interface
1411 def open(self, fullurl, data=None):
1412 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001413 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001414 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001415 if self.tempcache and fullurl in self.tempcache:
1416 filename, headers = self.tempcache[fullurl]
1417 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001418 return addinfourl(fp, headers, fullurl)
1419 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001420 if not urltype:
1421 urltype = 'file'
1422 if urltype in self.proxies:
1423 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001424 urltype, proxyhost = splittype(proxy)
1425 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001426 url = (host, fullurl) # Signal special case to open_*()
1427 else:
1428 proxy = None
1429 name = 'open_' + urltype
1430 self.type = urltype
1431 name = name.replace('-', '_')
1432 if not hasattr(self, name):
1433 if proxy:
1434 return self.open_unknown_proxy(proxy, fullurl, data)
1435 else:
1436 return self.open_unknown(fullurl, data)
1437 try:
1438 if data is None:
1439 return getattr(self, name)(url)
1440 else:
1441 return getattr(self, name)(url, data)
1442 except socket.error as msg:
1443 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1444
1445 def open_unknown(self, fullurl, data=None):
1446 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001447 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001448 raise IOError('url error', 'unknown url type', type)
1449
1450 def open_unknown_proxy(self, proxy, fullurl, data=None):
1451 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001452 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001453 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1454
1455 # External interface
1456 def retrieve(self, url, filename=None, reporthook=None, data=None):
1457 """retrieve(url) returns (filename, headers) for a local object
1458 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001459 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001460 if self.tempcache and url in self.tempcache:
1461 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001462 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001463 if filename is None and (not type or type == 'file'):
1464 try:
1465 fp = self.open_local_file(url1)
1466 hdrs = fp.info()
1467 del fp
Georg Brandl13e89462008-07-01 19:56:00 +00001468 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001469 except IOError as msg:
1470 pass
1471 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001472 try:
1473 headers = fp.info()
1474 if filename:
1475 tfp = open(filename, 'wb')
1476 else:
1477 import tempfile
1478 garbage, path = splittype(url)
1479 garbage, path = splithost(path or "")
1480 path, garbage = splitquery(path or "")
1481 path, garbage = splitattr(path or "")
1482 suffix = os.path.splitext(path)[1]
1483 (fd, filename) = tempfile.mkstemp(suffix)
1484 self.__tempfiles.append(filename)
1485 tfp = os.fdopen(fd, 'wb')
1486 try:
1487 result = filename, headers
1488 if self.tempcache is not None:
1489 self.tempcache[url] = result
1490 bs = 1024*8
1491 size = -1
1492 read = 0
1493 blocknum = 0
1494 if reporthook:
1495 if "content-length" in headers:
1496 size = int(headers["Content-Length"])
1497 reporthook(blocknum, bs, size)
1498 while 1:
1499 block = fp.read(bs)
1500 if not block:
1501 break
1502 read += len(block)
1503 tfp.write(block)
1504 blocknum += 1
1505 if reporthook:
1506 reporthook(blocknum, bs, size)
1507 finally:
1508 tfp.close()
1509 finally:
1510 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001511 del fp
1512 del tfp
1513
1514 # raise exception if actual size does not match content-length header
1515 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001516 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001517 "retrieval incomplete: got only %i out of %i bytes"
1518 % (read, size), result)
1519
1520 return result
1521
1522 # Each method named open_<type> knows how to open that type of URL
1523
1524 def _open_generic_http(self, connection_factory, url, data):
1525 """Make an HTTP connection using connection_class.
1526
1527 This is an internal method that should be called from
1528 open_http() or open_https().
1529
1530 Arguments:
1531 - connection_factory should take a host name and return an
1532 HTTPConnection instance.
1533 - url is the url to retrieval or a host, relative-path pair.
1534 - data is payload for a POST request or None.
1535 """
1536
1537 user_passwd = None
1538 proxy_passwd= None
1539 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001540 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001541 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001542 user_passwd, host = splituser(host)
1543 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001544 realhost = host
1545 else:
1546 host, selector = url
1547 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001548 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001549 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001550 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001551 url = rest
1552 user_passwd = None
1553 if urltype.lower() != 'http':
1554 realhost = None
1555 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001556 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001557 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001558 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001559 if user_passwd:
1560 selector = "%s://%s%s" % (urltype, realhost, rest)
1561 if proxy_bypass(realhost):
1562 host = realhost
1563
1564 #print "proxy via http:", host, selector
1565 if not host: raise IOError('http error', 'no host given')
1566
1567 if proxy_passwd:
1568 import base64
1569 proxy_auth = base64.b64encode(proxy_passwd).strip()
1570 else:
1571 proxy_auth = None
1572
1573 if user_passwd:
1574 import base64
1575 auth = base64.b64encode(user_passwd).strip()
1576 else:
1577 auth = None
1578 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001579 headers = {}
1580 if proxy_auth:
1581 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1582 if auth:
1583 headers["Authorization"] = "Basic %s" % auth
1584 if realhost:
1585 headers["Host"] = realhost
1586 for header, value in self.addheaders:
1587 headers[header] = value
1588
1589 if data is not None:
1590 headers["Content-Type"] = "application/x-www-form-urlencoded"
1591 http_conn.request("POST", selector, data, headers)
1592 else:
1593 http_conn.request("GET", selector, headers=headers)
1594
1595 try:
1596 response = http_conn.getresponse()
1597 except http.client.BadStatusLine:
1598 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001599 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001600
1601 # According to RFC 2616, "2xx" code indicates that the client's
1602 # request was successfully received, understood, and accepted.
1603 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001604 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001605 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001606 else:
1607 return self.http_error(
1608 url, response.fp,
1609 response.status, response.reason, response.msg, data)
1610
1611 def open_http(self, url, data=None):
1612 """Use HTTP protocol."""
1613 return self._open_generic_http(http.client.HTTPConnection, url, data)
1614
1615 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1616 """Handle http errors.
1617
1618 Derived class can override this, or provide specific handlers
1619 named http_error_DDD where DDD is the 3-digit error code."""
1620 # First check if there's a specific handler for this error
1621 name = 'http_error_%d' % errcode
1622 if hasattr(self, name):
1623 method = getattr(self, name)
1624 if data is None:
1625 result = method(url, fp, errcode, errmsg, headers)
1626 else:
1627 result = method(url, fp, errcode, errmsg, headers, data)
1628 if result: return result
1629 return self.http_error_default(url, fp, errcode, errmsg, headers)
1630
1631 def http_error_default(self, url, fp, errcode, errmsg, headers):
1632 """Default error handler: close the connection and raise IOError."""
1633 void = fp.read()
1634 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001635 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001636
1637 if _have_ssl:
1638 def _https_connection(self, host):
1639 return http.client.HTTPSConnection(host,
1640 key_file=self.key_file,
1641 cert_file=self.cert_file)
1642
1643 def open_https(self, url, data=None):
1644 """Use HTTPS protocol."""
1645 return self._open_generic_http(self._https_connection, url, data)
1646
1647 def open_file(self, url):
1648 """Use local file or FTP depending on form of URL."""
1649 if not isinstance(url, str):
1650 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1651 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
1652 return self.open_ftp(url)
1653 else:
1654 return self.open_local_file(url)
1655
1656 def open_local_file(self, url):
1657 """Use local file."""
1658 import mimetypes, email.utils
1659 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001660 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001661 localname = url2pathname(file)
1662 try:
1663 stats = os.stat(localname)
1664 except OSError as e:
1665 raise URLError(e.errno, e.strerror, e.filename)
1666 size = stats.st_size
1667 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1668 mtype = mimetypes.guess_type(url)[0]
1669 headers = email.message_from_string(
1670 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1671 (mtype or 'text/plain', size, modified))
1672 if not host:
1673 urlfile = file
1674 if file[:1] == '/':
1675 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001676 return addinfourl(open(localname, 'rb'), headers, urlfile)
1677 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001678 if (not port
1679 and socket.gethostbyname(host) in (localhost(), thishost())):
1680 urlfile = file
1681 if file[:1] == '/':
1682 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001683 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001684 raise URLError('local file error', 'not on local host')
1685
1686 def open_ftp(self, url):
1687 """Use FTP protocol."""
1688 if not isinstance(url, str):
1689 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1690 import mimetypes
1691 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001692 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001693 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001694 host, port = splitport(host)
1695 user, host = splituser(host)
1696 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001697 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001698 host = unquote(host)
1699 user = unquote(user or '')
1700 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001701 host = socket.gethostbyname(host)
1702 if not port:
1703 import ftplib
1704 port = ftplib.FTP_PORT
1705 else:
1706 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001707 path, attrs = splitattr(path)
1708 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001709 dirs = path.split('/')
1710 dirs, file = dirs[:-1], dirs[-1]
1711 if dirs and not dirs[0]: dirs = dirs[1:]
1712 if dirs and not dirs[0]: dirs[0] = '/'
1713 key = user, host, port, '/'.join(dirs)
1714 # XXX thread unsafe!
1715 if len(self.ftpcache) > MAXFTPCACHE:
1716 # Prune the cache, rather arbitrarily
1717 for k in self.ftpcache.keys():
1718 if k != key:
1719 v = self.ftpcache[k]
1720 del self.ftpcache[k]
1721 v.close()
1722 try:
1723 if not key in self.ftpcache:
1724 self.ftpcache[key] = \
1725 ftpwrapper(user, passwd, host, port, dirs)
1726 if not file: type = 'D'
1727 else: type = 'I'
1728 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001729 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001730 if attr.lower() == 'type' and \
1731 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1732 type = value.upper()
1733 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1734 mtype = mimetypes.guess_type("ftp:" + url)[0]
1735 headers = ""
1736 if mtype:
1737 headers += "Content-Type: %s\n" % mtype
1738 if retrlen is not None and retrlen >= 0:
1739 headers += "Content-Length: %d\n" % retrlen
1740 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001741 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001742 except ftperrors() as msg:
1743 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1744
1745 def open_data(self, url, data=None):
1746 """Use "data" URL."""
1747 if not isinstance(url, str):
1748 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1749 # ignore POSTed data
1750 #
1751 # syntax of data URLs:
1752 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1753 # mediatype := [ type "/" subtype ] *( ";" parameter )
1754 # data := *urlchar
1755 # parameter := attribute "=" value
1756 try:
1757 [type, data] = url.split(',', 1)
1758 except ValueError:
1759 raise IOError('data error', 'bad data URL')
1760 if not type:
1761 type = 'text/plain;charset=US-ASCII'
1762 semi = type.rfind(';')
1763 if semi >= 0 and '=' not in type[semi:]:
1764 encoding = type[semi+1:]
1765 type = type[:semi]
1766 else:
1767 encoding = ''
1768 msg = []
1769 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
1770 time.gmtime(time.time())))
1771 msg.append('Content-type: %s' % type)
1772 if encoding == 'base64':
1773 import base64
Georg Brandl706824f2009-06-04 09:42:55 +00001774 # XXX is this encoding/decoding ok?
1775 data = base64.decodebytes(data.encode('ascii')).decode('latin1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001776 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001777 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001778 msg.append('Content-Length: %d' % len(data))
1779 msg.append('')
1780 msg.append(data)
1781 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001782 headers = email.message_from_string(msg)
1783 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001784 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001785 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001786
1787
1788class FancyURLopener(URLopener):
1789 """Derived class with handlers for errors we can handle (perhaps)."""
1790
1791 def __init__(self, *args, **kwargs):
1792 URLopener.__init__(self, *args, **kwargs)
1793 self.auth_cache = {}
1794 self.tries = 0
1795 self.maxtries = 10
1796
1797 def http_error_default(self, url, fp, errcode, errmsg, headers):
1798 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001799 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001800
1801 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1802 """Error 302 -- relocated (temporarily)."""
1803 self.tries += 1
1804 if self.maxtries and self.tries >= self.maxtries:
1805 if hasattr(self, "http_error_500"):
1806 meth = self.http_error_500
1807 else:
1808 meth = self.http_error_default
1809 self.tries = 0
1810 return meth(url, fp, 500,
1811 "Internal Server Error: Redirect Recursion", headers)
1812 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
1813 data)
1814 self.tries = 0
1815 return result
1816
1817 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
1818 if 'location' in headers:
1819 newurl = headers['location']
1820 elif 'uri' in headers:
1821 newurl = headers['uri']
1822 else:
1823 return
1824 void = fp.read()
1825 fp.close()
1826 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00001827 newurl = urljoin(self.type + ":" + url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001828 return self.open(newurl)
1829
1830 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
1831 """Error 301 -- also relocated (permanently)."""
1832 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1833
1834 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
1835 """Error 303 -- also relocated (essentially identical to 302)."""
1836 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1837
1838 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
1839 """Error 307 -- relocated, but turn POST into error."""
1840 if data is None:
1841 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1842 else:
1843 return self.http_error_default(url, fp, errcode, errmsg, headers)
1844
1845 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
1846 """Error 401 -- authentication required.
1847 This function supports Basic authentication only."""
1848 if not 'www-authenticate' in headers:
1849 URLopener.http_error_default(self, url, fp,
1850 errcode, errmsg, headers)
1851 stuff = headers['www-authenticate']
1852 import re
1853 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1854 if not match:
1855 URLopener.http_error_default(self, url, fp,
1856 errcode, errmsg, headers)
1857 scheme, realm = match.groups()
1858 if scheme.lower() != 'basic':
1859 URLopener.http_error_default(self, url, fp,
1860 errcode, errmsg, headers)
1861 name = 'retry_' + self.type + '_basic_auth'
1862 if data is None:
1863 return getattr(self,name)(url, realm)
1864 else:
1865 return getattr(self,name)(url, realm, data)
1866
1867 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
1868 """Error 407 -- proxy authentication required.
1869 This function supports Basic authentication only."""
1870 if not 'proxy-authenticate' in headers:
1871 URLopener.http_error_default(self, url, fp,
1872 errcode, errmsg, headers)
1873 stuff = headers['proxy-authenticate']
1874 import re
1875 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1876 if not match:
1877 URLopener.http_error_default(self, url, fp,
1878 errcode, errmsg, headers)
1879 scheme, realm = match.groups()
1880 if scheme.lower() != 'basic':
1881 URLopener.http_error_default(self, url, fp,
1882 errcode, errmsg, headers)
1883 name = 'retry_proxy_' + self.type + '_basic_auth'
1884 if data is None:
1885 return getattr(self,name)(url, realm)
1886 else:
1887 return getattr(self,name)(url, realm, data)
1888
1889 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001890 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001891 newurl = 'http://' + host + selector
1892 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00001893 urltype, proxyhost = splittype(proxy)
1894 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001895 i = proxyhost.find('@') + 1
1896 proxyhost = proxyhost[i:]
1897 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1898 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001899 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001900 quote(passwd, safe=''), proxyhost)
1901 self.proxies['http'] = 'http://' + proxyhost + proxyselector
1902 if data is None:
1903 return self.open(newurl)
1904 else:
1905 return self.open(newurl, data)
1906
1907 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001908 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001909 newurl = 'https://' + host + selector
1910 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00001911 urltype, proxyhost = splittype(proxy)
1912 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001913 i = proxyhost.find('@') + 1
1914 proxyhost = proxyhost[i:]
1915 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1916 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001917 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001918 quote(passwd, safe=''), proxyhost)
1919 self.proxies['https'] = 'https://' + proxyhost + proxyselector
1920 if data is None:
1921 return self.open(newurl)
1922 else:
1923 return self.open(newurl, data)
1924
1925 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001926 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001927 i = host.find('@') + 1
1928 host = host[i:]
1929 user, passwd = self.get_user_passwd(host, realm, i)
1930 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001931 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001932 quote(passwd, safe=''), host)
1933 newurl = 'http://' + host + selector
1934 if data is None:
1935 return self.open(newurl)
1936 else:
1937 return self.open(newurl, data)
1938
1939 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001940 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001941 i = host.find('@') + 1
1942 host = host[i:]
1943 user, passwd = self.get_user_passwd(host, realm, i)
1944 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001945 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001946 quote(passwd, safe=''), host)
1947 newurl = 'https://' + host + selector
1948 if data is None:
1949 return self.open(newurl)
1950 else:
1951 return self.open(newurl, data)
1952
1953 def get_user_passwd(self, host, realm, clear_cache = 0):
1954 key = realm + '@' + host.lower()
1955 if key in self.auth_cache:
1956 if clear_cache:
1957 del self.auth_cache[key]
1958 else:
1959 return self.auth_cache[key]
1960 user, passwd = self.prompt_user_passwd(host, realm)
1961 if user or passwd: self.auth_cache[key] = (user, passwd)
1962 return user, passwd
1963
1964 def prompt_user_passwd(self, host, realm):
1965 """Override this in a GUI environment!"""
1966 import getpass
1967 try:
1968 user = input("Enter username for %s at %s: " % (realm, host))
1969 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
1970 (user, realm, host))
1971 return user, passwd
1972 except KeyboardInterrupt:
1973 print()
1974 return None, None
1975
1976
1977# Utility functions
1978
1979_localhost = None
1980def localhost():
1981 """Return the IP address of the magic hostname 'localhost'."""
1982 global _localhost
1983 if _localhost is None:
1984 _localhost = socket.gethostbyname('localhost')
1985 return _localhost
1986
1987_thishost = None
1988def thishost():
1989 """Return the IP address of the current host."""
1990 global _thishost
1991 if _thishost is None:
1992 _thishost = socket.gethostbyname(socket.gethostname())
1993 return _thishost
1994
1995_ftperrors = None
1996def ftperrors():
1997 """Return the set of errors raised by the FTP class."""
1998 global _ftperrors
1999 if _ftperrors is None:
2000 import ftplib
2001 _ftperrors = ftplib.all_errors
2002 return _ftperrors
2003
2004_noheaders = None
2005def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002006 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002007 global _noheaders
2008 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002009 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002010 return _noheaders
2011
2012
2013# Utility classes
2014
2015class ftpwrapper:
2016 """Class used by open_ftp() for cache of open FTP connections."""
2017
2018 def __init__(self, user, passwd, host, port, dirs, timeout=None):
2019 self.user = user
2020 self.passwd = passwd
2021 self.host = host
2022 self.port = port
2023 self.dirs = dirs
2024 self.timeout = timeout
2025 self.init()
2026
2027 def init(self):
2028 import ftplib
2029 self.busy = 0
2030 self.ftp = ftplib.FTP()
2031 self.ftp.connect(self.host, self.port, self.timeout)
2032 self.ftp.login(self.user, self.passwd)
2033 for dir in self.dirs:
2034 self.ftp.cwd(dir)
2035
2036 def retrfile(self, file, type):
2037 import ftplib
2038 self.endtransfer()
2039 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2040 else: cmd = 'TYPE ' + type; isdir = 0
2041 try:
2042 self.ftp.voidcmd(cmd)
2043 except ftplib.all_errors:
2044 self.init()
2045 self.ftp.voidcmd(cmd)
2046 conn = None
2047 if file and not isdir:
2048 # Try to retrieve as a file
2049 try:
2050 cmd = 'RETR ' + file
2051 conn = self.ftp.ntransfercmd(cmd)
2052 except ftplib.error_perm as reason:
2053 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002054 raise URLError('ftp error', reason).with_traceback(
2055 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002056 if not conn:
2057 # Set transfer mode to ASCII!
2058 self.ftp.voidcmd('TYPE A')
2059 # Try a directory listing. Verify that directory exists.
2060 if file:
2061 pwd = self.ftp.pwd()
2062 try:
2063 try:
2064 self.ftp.cwd(file)
2065 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002066 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002067 finally:
2068 self.ftp.cwd(pwd)
2069 cmd = 'LIST ' + file
2070 else:
2071 cmd = 'LIST'
2072 conn = self.ftp.ntransfercmd(cmd)
2073 self.busy = 1
2074 # Pass back both a suitably decorated object and a retrieval length
Georg Brandl13e89462008-07-01 19:56:00 +00002075 return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002076 def endtransfer(self):
2077 if not self.busy:
2078 return
2079 self.busy = 0
2080 try:
2081 self.ftp.voidresp()
2082 except ftperrors():
2083 pass
2084
2085 def close(self):
2086 self.endtransfer()
2087 try:
2088 self.ftp.close()
2089 except ftperrors():
2090 pass
2091
2092# Proxy handling
2093def getproxies_environment():
2094 """Return a dictionary of scheme -> proxy server URL mappings.
2095
2096 Scan the environment for variables named <scheme>_proxy;
2097 this seems to be the standard convention. If you need a
2098 different way, you can pass a proxies dictionary to the
2099 [Fancy]URLopener constructor.
2100
2101 """
2102 proxies = {}
2103 for name, value in os.environ.items():
2104 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002105 if value and name[-6:] == '_proxy':
2106 proxies[name[:-6]] = value
2107 return proxies
2108
2109def proxy_bypass_environment(host):
2110 """Test if proxies should not be used for a particular host.
2111
2112 Checks the environment for a variable named no_proxy, which should
2113 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2114 """
2115 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2116 # '*' is special case for always bypass
2117 if no_proxy == '*':
2118 return 1
2119 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002120 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002121 # check if the host ends with any of the DNS suffixes
2122 for name in no_proxy.split(','):
2123 if name and (hostonly.endswith(name) or host.endswith(name)):
2124 return 1
2125 # otherwise, don't bypass
2126 return 0
2127
2128
2129if sys.platform == 'darwin':
2130 def getproxies_internetconfig():
2131 """Return a dictionary of scheme -> proxy server URL mappings.
2132
2133 By convention the mac uses Internet Config to store
2134 proxies. An HTTP proxy, for instance, is stored under
2135 the HttpProxy key.
2136
2137 """
2138 try:
2139 import ic
2140 except ImportError:
2141 return {}
2142
2143 try:
2144 config = ic.IC()
2145 except ic.error:
2146 return {}
2147 proxies = {}
2148 # HTTP:
2149 if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
2150 try:
2151 value = config['HTTPProxyHost']
2152 except ic.error:
2153 pass
2154 else:
2155 proxies['http'] = 'http://%s' % value
2156 # FTP: XXX To be done.
2157 # Gopher: XXX To be done.
2158 return proxies
2159
2160 def proxy_bypass(host):
2161 if getproxies_environment():
2162 return proxy_bypass_environment(host)
2163 else:
2164 return 0
2165
2166 def getproxies():
2167 return getproxies_environment() or getproxies_internetconfig()
2168
2169elif os.name == 'nt':
2170 def getproxies_registry():
2171 """Return a dictionary of scheme -> proxy server URL mappings.
2172
2173 Win32 uses the registry to store proxies.
2174
2175 """
2176 proxies = {}
2177 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002178 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002179 except ImportError:
2180 # Std module, so should be around - but you never know!
2181 return proxies
2182 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002183 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002184 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002185 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002186 'ProxyEnable')[0]
2187 if proxyEnable:
2188 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002189 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002190 'ProxyServer')[0])
2191 if '=' in proxyServer:
2192 # Per-protocol settings
2193 for p in proxyServer.split(';'):
2194 protocol, address = p.split('=', 1)
2195 # See if address has a type:// prefix
2196 import re
2197 if not re.match('^([^/:]+)://', address):
2198 address = '%s://%s' % (protocol, address)
2199 proxies[protocol] = address
2200 else:
2201 # Use one setting for all protocols
2202 if proxyServer[:5] == 'http:':
2203 proxies['http'] = proxyServer
2204 else:
2205 proxies['http'] = 'http://%s' % proxyServer
2206 proxies['ftp'] = 'ftp://%s' % proxyServer
2207 internetSettings.Close()
2208 except (WindowsError, ValueError, TypeError):
2209 # Either registry key not found etc, or the value in an
2210 # unexpected format.
2211 # proxies already set up to be empty so nothing to do
2212 pass
2213 return proxies
2214
2215 def getproxies():
2216 """Return a dictionary of scheme -> proxy server URL mappings.
2217
2218 Returns settings gathered from the environment, if specified,
2219 or the registry.
2220
2221 """
2222 return getproxies_environment() or getproxies_registry()
2223
2224 def proxy_bypass_registry(host):
2225 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002226 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002227 import re
2228 except ImportError:
2229 # Std modules, so should be around - but you never know!
2230 return 0
2231 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002232 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002233 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002234 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002235 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002236 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002237 'ProxyOverride')[0])
2238 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2239 except WindowsError:
2240 return 0
2241 if not proxyEnable or not proxyOverride:
2242 return 0
2243 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002244 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002245 host = [rawHost]
2246 try:
2247 addr = socket.gethostbyname(rawHost)
2248 if addr != rawHost:
2249 host.append(addr)
2250 except socket.error:
2251 pass
2252 try:
2253 fqdn = socket.getfqdn(rawHost)
2254 if fqdn != rawHost:
2255 host.append(fqdn)
2256 except socket.error:
2257 pass
2258 # make a check value list from the registry entry: replace the
2259 # '<local>' string by the localhost entry and the corresponding
2260 # canonical entry.
2261 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002262 # now check if we match one of the registry values.
2263 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002264 if test == '<local>':
2265 if '.' not in rawHost:
2266 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002267 test = test.replace(".", r"\.") # mask dots
2268 test = test.replace("*", r".*") # change glob sequence
2269 test = test.replace("?", r".") # change glob char
2270 for val in host:
2271 # print "%s <--> %s" %( test, val )
2272 if re.match(test, val, re.I):
2273 return 1
2274 return 0
2275
2276 def proxy_bypass(host):
2277 """Return a dictionary of scheme -> proxy server URL mappings.
2278
2279 Returns settings gathered from the environment, if specified,
2280 or the registry.
2281
2282 """
2283 if getproxies_environment():
2284 return proxy_bypass_environment(host)
2285 else:
2286 return proxy_bypass_registry(host)
2287
2288else:
2289 # By default use environment variables
2290 getproxies = getproxies_environment
2291 proxy_bypass = proxy_bypass_environment