blob: 6e892e43e0d1d6ecc88167d3b1dfb38ae470a7c6 [file] [log] [blame]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001"""An extensible library for opening URLs using a variety of protocols
2
3The simplest way to use this module is to call the urlopen function,
4which accepts a string containing a URL or a Request object (described
5below). It opens the URL and returns the results as file-like
6object; the returned object has some extra methods described below.
7
8The OpenerDirector manages a collection of Handler objects that do
9all the actual work. Each Handler implements a particular protocol or
10option. The OpenerDirector is a composite object that invokes the
11Handlers needed to open the requested URL. For example, the
12HTTPHandler performs HTTP GET and POST requests and deals with
13non-error returns. The HTTPRedirectHandler automatically deals with
14HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15deals with digest authentication.
16
17urlopen(url, data=None) -- Basic usage is the same as original
18urllib. pass the url and optionally data to post to an HTTP URL, and
19get a file-like object back. One difference is that you can also pass
20a Request instance instead of URL. Raises a URLError (subclass of
21IOError); for HTTP errors, raises an HTTPError, which can also be
22treated as a valid response.
23
24build_opener -- Function that creates a new OpenerDirector instance.
25Will install the default handlers. Accepts one or more Handlers as
26arguments, either instances or Handler classes that it will
27instantiate. If one of the argument is a subclass of the default
28handler, the argument will be installed instead of the default.
29
30install_opener -- Installs a new opener as the default opener.
31
32objects of interest:
Senthil Kumaran04454cd2009-11-15 07:27:02 +000033
Senthil Kumaran4b9fbeb2009-12-20 07:18:22 +000034OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
35the Handler classes, while dealing with requests and responses.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000036
37Request -- An object that encapsulates the state of a request. The
38state can be as simple as the URL. It can also include extra HTTP
39headers, e.g. a User-Agent.
40
41BaseHandler --
42
43internals:
44BaseHandler and parent
45_call_chain conventions
46
47Example usage:
48
Georg Brandl029986a2008-06-23 11:44:14 +000049import urllib.request
Jeremy Hylton1afc1692008-06-18 20:49:58 +000050
51# set up authentication info
Georg Brandl029986a2008-06-23 11:44:14 +000052authinfo = urllib.request.HTTPBasicAuthHandler()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000053authinfo.add_password(realm='PDQ Application',
54 uri='https://mahler:8092/site-updates.py',
55 user='klem',
56 passwd='geheim$parole')
57
Georg Brandl029986a2008-06-23 11:44:14 +000058proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
Jeremy Hylton1afc1692008-06-18 20:49:58 +000059
60# build a new opener that adds authentication and caching FTP handlers
Georg Brandl029986a2008-06-23 11:44:14 +000061opener = urllib.request.build_opener(proxy_support, authinfo,
62 urllib.request.CacheFTPHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000063
64# install it
Georg Brandl029986a2008-06-23 11:44:14 +000065urllib.request.install_opener(opener)
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066
Georg Brandl029986a2008-06-23 11:44:14 +000067f = urllib.request.urlopen('http://www.python.org/')
Jeremy Hylton1afc1692008-06-18 20:49:58 +000068"""
69
70# XXX issues:
71# If an authentication error handler that tries to perform
72# authentication for some reason but fails, how should the error be
73# signalled? The client needs to know the HTTP error code. But if
74# the handler knows that the problem was, e.g., that it didn't know
75# that hash algo that requested in the challenge, it would be good to
76# pass that information along to the client, too.
77# ftp errors aren't handled cleanly
78# check digest against correct (i.e. non-apache) implementation
79
80# Possible extensions:
81# complex proxies XXX not sure what exactly was meant by this
82# abstract factory for opener
83
84import base64
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +000085import bisect
Jeremy Hylton1afc1692008-06-18 20:49:58 +000086import email
87import hashlib
88import http.client
89import io
90import os
91import posixpath
92import random
93import re
94import socket
95import sys
96import time
Jeremy Hylton1afc1692008-06-18 20:49:58 +000097
Georg Brandl13e89462008-07-01 19:56:00 +000098from urllib.error import URLError, HTTPError, ContentTooShortError
99from urllib.parse import (
100 urlparse, urlsplit, urljoin, unwrap, quote, unquote,
101 splittype, splithost, splitport, splituser, splitpasswd,
Facundo Batistaf24802c2008-08-17 03:36:03 +0000102 splitattr, splitquery, splitvalue, to_bytes, urlunparse)
Georg Brandl13e89462008-07-01 19:56:00 +0000103from urllib.response import addinfourl, addclosehook
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000104
105# check for SSL
106try:
107 import ssl
108except:
109 _have_ssl = False
110else:
111 _have_ssl = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000112
113# used in User-Agent header sent
114__version__ = sys.version[:3]
115
116_opener = None
117def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
118 global _opener
119 if _opener is None:
120 _opener = build_opener()
121 return _opener.open(url, data, timeout)
122
123def install_opener(opener):
124 global _opener
125 _opener = opener
126
127# TODO(jhylton): Make this work with the same global opener.
128_urlopener = None
129def urlretrieve(url, filename=None, reporthook=None, data=None):
130 global _urlopener
131 if not _urlopener:
132 _urlopener = FancyURLopener()
133 return _urlopener.retrieve(url, filename, reporthook, data)
134
135def urlcleanup():
136 if _urlopener:
137 _urlopener.cleanup()
138 global _opener
139 if _opener:
140 _opener = None
141
142# copied from cookielib.py
Antoine Pitroufd036452008-08-19 17:56:33 +0000143_cut_port_re = re.compile(r":\d+$", re.ASCII)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000144def request_host(request):
145 """Return request-host, as defined by RFC 2965.
146
147 Variation from RFC: returned value is lowercased, for convenient
148 comparison.
149
150 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000151 url = request.full_url
Georg Brandl13e89462008-07-01 19:56:00 +0000152 host = urlparse(url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000153 if host == "":
154 host = request.get_header("Host", "")
155
156 # remove port, if present
157 host = _cut_port_re.sub("", host, 1)
158 return host.lower()
159
160class Request:
161
162 def __init__(self, url, data=None, headers={},
163 origin_req_host=None, unverifiable=False):
164 # unwrap('<URL:type://host/path>') --> 'type://host/path'
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000165 self.full_url = unwrap(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000166 self.data = data
167 self.headers = {}
Senthil Kumaran0ac1f832009-07-26 12:39:47 +0000168 self._tunnel_host = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000169 for key, value in headers.items():
170 self.add_header(key, value)
171 self.unredirected_hdrs = {}
172 if origin_req_host is None:
173 origin_req_host = request_host(self)
174 self.origin_req_host = origin_req_host
175 self.unverifiable = unverifiable
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000176 self._parse()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000177
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000178 def _parse(self):
179 self.type, rest = splittype(self.full_url)
180 if self.type is None:
181 raise ValueError("unknown url type: %s" % self.full_url)
182 self.host, self.selector = splithost(rest)
183 if self.host:
184 self.host = unquote(self.host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000185
186 def get_method(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000187 if self.data is not None:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000188 return "POST"
189 else:
190 return "GET"
191
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000192 # Begin deprecated methods
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000193
194 def add_data(self, data):
195 self.data = data
196
197 def has_data(self):
198 return self.data is not None
199
200 def get_data(self):
201 return self.data
202
203 def get_full_url(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000204 return self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000205
206 def get_type(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000207 return self.type
208
209 def get_host(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000210 return self.host
211
212 def get_selector(self):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000213 return self.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000214
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000215 def is_unverifiable(self):
216 return self.unverifiable
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000217
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000218 def get_origin_req_host(self):
219 return self.origin_req_host
220
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000221 # End deprecated methods
222
223 def set_proxy(self, host, type):
Senthil Kumaran0ac1f832009-07-26 12:39:47 +0000224 if self.type == 'https' and not self._tunnel_host:
225 self._tunnel_host = self.host
226 else:
227 self.type= type
228 self.selector = self.full_url
229 self.host = host
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000230
231 def has_proxy(self):
232 return self.selector == self.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000233
234 def add_header(self, key, val):
235 # useful for something like authentication
236 self.headers[key.capitalize()] = val
237
238 def add_unredirected_header(self, key, val):
239 # will not be added to a redirected request
240 self.unredirected_hdrs[key.capitalize()] = val
241
242 def has_header(self, header_name):
243 return (header_name in self.headers or
244 header_name in self.unredirected_hdrs)
245
246 def get_header(self, header_name, default=None):
247 return self.headers.get(
248 header_name,
249 self.unredirected_hdrs.get(header_name, default))
250
251 def header_items(self):
252 hdrs = self.unredirected_hdrs.copy()
253 hdrs.update(self.headers)
254 return list(hdrs.items())
255
256class OpenerDirector:
257 def __init__(self):
258 client_version = "Python-urllib/%s" % __version__
259 self.addheaders = [('User-agent', client_version)]
260 # manage the individual handlers
261 self.handlers = []
262 self.handle_open = {}
263 self.handle_error = {}
264 self.process_response = {}
265 self.process_request = {}
266
267 def add_handler(self, handler):
268 if not hasattr(handler, "add_parent"):
269 raise TypeError("expected BaseHandler instance, got %r" %
270 type(handler))
271
272 added = False
273 for meth in dir(handler):
274 if meth in ["redirect_request", "do_open", "proxy_open"]:
275 # oops, coincidental match
276 continue
277
278 i = meth.find("_")
279 protocol = meth[:i]
280 condition = meth[i+1:]
281
282 if condition.startswith("error"):
283 j = condition.find("_") + i + 1
284 kind = meth[j+1:]
285 try:
286 kind = int(kind)
287 except ValueError:
288 pass
289 lookup = self.handle_error.get(protocol, {})
290 self.handle_error[protocol] = lookup
291 elif condition == "open":
292 kind = protocol
293 lookup = self.handle_open
294 elif condition == "response":
295 kind = protocol
296 lookup = self.process_response
297 elif condition == "request":
298 kind = protocol
299 lookup = self.process_request
300 else:
301 continue
302
303 handlers = lookup.setdefault(kind, [])
304 if handlers:
305 bisect.insort(handlers, handler)
306 else:
307 handlers.append(handler)
308 added = True
309
310 if added:
311 # the handlers must work in an specific order, the order
312 # is specified in a Handler attribute
313 bisect.insort(self.handlers, handler)
314 handler.add_parent(self)
315
316 def close(self):
317 # Only exists for backwards compatibility.
318 pass
319
320 def _call_chain(self, chain, kind, meth_name, *args):
321 # Handlers raise an exception if no one else should try to handle
322 # the request, or return None if they can't but another handler
323 # could. Otherwise, they return the response.
324 handlers = chain.get(kind, ())
325 for handler in handlers:
326 func = getattr(handler, meth_name)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000327 result = func(*args)
328 if result is not None:
329 return result
330
331 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
332 # accept a URL or a Request object
333 if isinstance(fullurl, str):
334 req = Request(fullurl, data)
335 else:
336 req = fullurl
337 if data is not None:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000338 req.data = data
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000339
340 req.timeout = timeout
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000341 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000342
343 # pre-process request
344 meth_name = protocol+"_request"
345 for processor in self.process_request.get(protocol, []):
346 meth = getattr(processor, meth_name)
347 req = meth(req)
348
349 response = self._open(req, data)
350
351 # post-process response
352 meth_name = protocol+"_response"
353 for processor in self.process_response.get(protocol, []):
354 meth = getattr(processor, meth_name)
355 response = meth(req, response)
356
357 return response
358
359 def _open(self, req, data=None):
360 result = self._call_chain(self.handle_open, 'default',
361 'default_open', req)
362 if result:
363 return result
364
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000365 protocol = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000366 result = self._call_chain(self.handle_open, protocol, protocol +
367 '_open', req)
368 if result:
369 return result
370
371 return self._call_chain(self.handle_open, 'unknown',
372 'unknown_open', req)
373
374 def error(self, proto, *args):
375 if proto in ('http', 'https'):
376 # XXX http[s] protocols are special-cased
377 dict = self.handle_error['http'] # https is not different than http
378 proto = args[2] # YUCK!
379 meth_name = 'http_error_%s' % proto
380 http_err = 1
381 orig_args = args
382 else:
383 dict = self.handle_error
384 meth_name = proto + '_error'
385 http_err = 0
386 args = (dict, proto, meth_name) + args
387 result = self._call_chain(*args)
388 if result:
389 return result
390
391 if http_err:
392 args = (dict, 'default', 'http_error_default') + orig_args
393 return self._call_chain(*args)
394
395# XXX probably also want an abstract factory that knows when it makes
396# sense to skip a superclass in favor of a subclass and when it might
397# make sense to include both
398
399def build_opener(*handlers):
400 """Create an opener object from a list of handlers.
401
402 The opener will use several default handlers, including support
Senthil Kumaran04454cd2009-11-15 07:27:02 +0000403 for HTTP, FTP and when applicable HTTPS.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000404
405 If any of the handlers passed as arguments are subclasses of the
406 default handlers, the default handlers will not be used.
407 """
408 def isclass(obj):
409 return isinstance(obj, type) or hasattr(obj, "__bases__")
410
411 opener = OpenerDirector()
412 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
413 HTTPDefaultErrorHandler, HTTPRedirectHandler,
414 FTPHandler, FileHandler, HTTPErrorProcessor]
415 if hasattr(http.client, "HTTPSConnection"):
416 default_classes.append(HTTPSHandler)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000417 skip = set()
418 for klass in default_classes:
419 for check in handlers:
420 if isclass(check):
421 if issubclass(check, klass):
422 skip.add(klass)
423 elif isinstance(check, klass):
424 skip.add(klass)
425 for klass in skip:
426 default_classes.remove(klass)
427
428 for klass in default_classes:
429 opener.add_handler(klass())
430
431 for h in handlers:
432 if isclass(h):
433 h = h()
434 opener.add_handler(h)
435 return opener
436
437class BaseHandler:
438 handler_order = 500
439
440 def add_parent(self, parent):
441 self.parent = parent
442
443 def close(self):
444 # Only exists for backwards compatibility
445 pass
446
447 def __lt__(self, other):
448 if not hasattr(other, "handler_order"):
449 # Try to preserve the old behavior of having custom classes
450 # inserted after default ones (works only for custom user
451 # classes which are not aware of handler_order).
452 return True
453 return self.handler_order < other.handler_order
454
455
456class HTTPErrorProcessor(BaseHandler):
457 """Process HTTP error responses."""
458 handler_order = 1000 # after all other processing
459
460 def http_response(self, request, response):
461 code, msg, hdrs = response.code, response.msg, response.info()
462
463 # According to RFC 2616, "2xx" code indicates that the client's
464 # request was successfully received, understood, and accepted.
465 if not (200 <= code < 300):
466 response = self.parent.error(
467 'http', request, response, code, msg, hdrs)
468
469 return response
470
471 https_response = http_response
472
473class HTTPDefaultErrorHandler(BaseHandler):
474 def http_error_default(self, req, fp, code, msg, hdrs):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000475 raise HTTPError(req.full_url, code, msg, hdrs, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000476
477class HTTPRedirectHandler(BaseHandler):
478 # maximum number of redirections to any single URL
479 # this is needed because of the state that cookies introduce
480 max_repeats = 4
481 # maximum total number of redirections (regardless of URL) before
482 # assuming we're in a loop
483 max_redirections = 10
484
485 def redirect_request(self, req, fp, code, msg, headers, newurl):
486 """Return a Request or None in response to a redirect.
487
488 This is called by the http_error_30x methods when a
489 redirection response is received. If a redirection should
490 take place, return a new Request to allow http_error_30x to
491 perform the redirect. Otherwise, raise HTTPError if no-one
492 else should try to handle this url. Return None if you can't
493 but another Handler might.
494 """
495 m = req.get_method()
496 if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
497 or code in (301, 302, 303) and m == "POST")):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000498 raise HTTPError(req.full_url, code, msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000499
500 # Strictly (according to RFC 2616), 301 or 302 in response to
501 # a POST MUST NOT cause a redirection without confirmation
Georg Brandl029986a2008-06-23 11:44:14 +0000502 # from the user (of urllib.request, in this case). In practice,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000503 # essentially all clients do redirect in this case, so we do
504 # the same.
505 # be conciliant with URIs containing a space
506 newurl = newurl.replace(' ', '%20')
507 CONTENT_HEADERS = ("content-length", "content-type")
508 newheaders = dict((k, v) for k, v in req.headers.items()
509 if k.lower() not in CONTENT_HEADERS)
510 return Request(newurl,
511 headers=newheaders,
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000512 origin_req_host=req.origin_req_host,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000513 unverifiable=True)
514
515 # Implementation note: To avoid the server sending us into an
516 # infinite loop, the request object needs to track what URLs we
517 # have already seen. Do this by adding a handler-specific
518 # attribute to the Request object.
519 def http_error_302(self, req, fp, code, msg, headers):
520 # Some servers (incorrectly) return multiple Location headers
521 # (so probably same goes for URI). Use first header.
522 if "location" in headers:
523 newurl = headers["location"]
524 elif "uri" in headers:
525 newurl = headers["uri"]
526 else:
527 return
Facundo Batistaf24802c2008-08-17 03:36:03 +0000528
529 # fix a possible malformed URL
530 urlparts = urlparse(newurl)
531 if not urlparts.path:
532 urlparts = list(urlparts)
533 urlparts[2] = "/"
534 newurl = urlunparse(urlparts)
535
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000536 newurl = urljoin(req.full_url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000537
538 # XXX Probably want to forget about the state of the current
539 # request, although that might interact poorly with other
540 # handlers that also use handler-specific request attributes
541 new = self.redirect_request(req, fp, code, msg, headers, newurl)
542 if new is None:
543 return
544
545 # loop detection
546 # .redirect_dict has a key url if url was previously visited.
547 if hasattr(req, 'redirect_dict'):
548 visited = new.redirect_dict = req.redirect_dict
549 if (visited.get(newurl, 0) >= self.max_repeats or
550 len(visited) >= self.max_redirections):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000551 raise HTTPError(req.full_url, code,
Georg Brandl13e89462008-07-01 19:56:00 +0000552 self.inf_msg + msg, headers, fp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000553 else:
554 visited = new.redirect_dict = req.redirect_dict = {}
555 visited[newurl] = visited.get(newurl, 0) + 1
556
557 # Don't close the fp until we are sure that we won't use it
558 # with HTTPError.
559 fp.read()
560 fp.close()
561
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000562 return self.parent.open(new, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000563
564 http_error_301 = http_error_303 = http_error_307 = http_error_302
565
566 inf_msg = "The HTTP server returned a redirect error that would " \
567 "lead to an infinite loop.\n" \
568 "The last 30x error message was:\n"
569
570
571def _parse_proxy(proxy):
572 """Return (scheme, user, password, host/port) given a URL or an authority.
573
574 If a URL is supplied, it must have an authority (host:port) component.
575 According to RFC 3986, having an authority component means the URL must
576 have two slashes after the scheme:
577
578 >>> _parse_proxy('file:/ftp.example.com/')
579 Traceback (most recent call last):
580 ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
581
582 The first three items of the returned tuple may be None.
583
584 Examples of authority parsing:
585
586 >>> _parse_proxy('proxy.example.com')
587 (None, None, None, 'proxy.example.com')
588 >>> _parse_proxy('proxy.example.com:3128')
589 (None, None, None, 'proxy.example.com:3128')
590
591 The authority component may optionally include userinfo (assumed to be
592 username:password):
593
594 >>> _parse_proxy('joe:password@proxy.example.com')
595 (None, 'joe', 'password', 'proxy.example.com')
596 >>> _parse_proxy('joe:password@proxy.example.com:3128')
597 (None, 'joe', 'password', 'proxy.example.com:3128')
598
599 Same examples, but with URLs instead:
600
601 >>> _parse_proxy('http://proxy.example.com/')
602 ('http', None, None, 'proxy.example.com')
603 >>> _parse_proxy('http://proxy.example.com:3128/')
604 ('http', None, None, 'proxy.example.com:3128')
605 >>> _parse_proxy('http://joe:password@proxy.example.com/')
606 ('http', 'joe', 'password', 'proxy.example.com')
607 >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
608 ('http', 'joe', 'password', 'proxy.example.com:3128')
609
610 Everything after the authority is ignored:
611
612 >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
613 ('ftp', 'joe', 'password', 'proxy.example.com')
614
615 Test for no trailing '/' case:
616
617 >>> _parse_proxy('http://joe:password@proxy.example.com')
618 ('http', 'joe', 'password', 'proxy.example.com')
619
620 """
Georg Brandl13e89462008-07-01 19:56:00 +0000621 scheme, r_scheme = splittype(proxy)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000622 if not r_scheme.startswith("/"):
623 # authority
624 scheme = None
625 authority = proxy
626 else:
627 # URL
628 if not r_scheme.startswith("//"):
629 raise ValueError("proxy URL with no authority: %r" % proxy)
630 # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
631 # and 3.3.), path is empty or starts with '/'
632 end = r_scheme.find("/", 2)
633 if end == -1:
634 end = None
635 authority = r_scheme[2:end]
Georg Brandl13e89462008-07-01 19:56:00 +0000636 userinfo, hostport = splituser(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000637 if userinfo is not None:
Georg Brandl13e89462008-07-01 19:56:00 +0000638 user, password = splitpasswd(userinfo)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000639 else:
640 user = password = None
641 return scheme, user, password, hostport
642
643class ProxyHandler(BaseHandler):
644 # Proxies must be in front
645 handler_order = 100
646
647 def __init__(self, proxies=None):
648 if proxies is None:
649 proxies = getproxies()
650 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
651 self.proxies = proxies
652 for type, url in proxies.items():
653 setattr(self, '%s_open' % type,
654 lambda r, proxy=url, type=type, meth=self.proxy_open: \
655 meth(r, proxy, type))
656
657 def proxy_open(self, req, proxy, type):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000658 orig_type = req.type
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000659 proxy_type, user, password, hostport = _parse_proxy(proxy)
660 if proxy_type is None:
661 proxy_type = orig_type
Senthil Kumaran11301632009-10-11 06:07:46 +0000662
663 if req.host and proxy_bypass(req.host):
664 return None
665
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000666 if user and password:
Georg Brandl13e89462008-07-01 19:56:00 +0000667 user_pass = '%s:%s' % (unquote(user),
668 unquote(password))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000669 creds = base64.b64encode(user_pass.encode()).decode("ascii")
670 req.add_header('Proxy-authorization', 'Basic ' + creds)
Georg Brandl13e89462008-07-01 19:56:00 +0000671 hostport = unquote(hostport)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000672 req.set_proxy(hostport, proxy_type)
Senthil Kumaran0ac1f832009-07-26 12:39:47 +0000673 if orig_type == proxy_type or orig_type == 'https':
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000674 # let other handlers take care of it
675 return None
676 else:
677 # need to start over, because the other handlers don't
678 # grok the proxy's URL type
679 # e.g. if we have a constructor arg proxies like so:
680 # {'http': 'ftp://proxy.example.com'}, we may end up turning
681 # a request for http://acme.example.com/a into one for
682 # ftp://proxy.example.com/a
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000683 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000684
685class HTTPPasswordMgr:
686
687 def __init__(self):
688 self.passwd = {}
689
690 def add_password(self, realm, uri, user, passwd):
691 # uri could be a single URI or a sequence
692 if isinstance(uri, str):
693 uri = [uri]
694 if not realm in self.passwd:
695 self.passwd[realm] = {}
696 for default_port in True, False:
697 reduced_uri = tuple(
698 [self.reduce_uri(u, default_port) for u in uri])
699 self.passwd[realm][reduced_uri] = (user, passwd)
700
701 def find_user_password(self, realm, authuri):
702 domains = self.passwd.get(realm, {})
703 for default_port in True, False:
704 reduced_authuri = self.reduce_uri(authuri, default_port)
705 for uris, authinfo in domains.items():
706 for uri in uris:
707 if self.is_suburi(uri, reduced_authuri):
708 return authinfo
709 return None, None
710
711 def reduce_uri(self, uri, default_port=True):
712 """Accept authority or URI and extract only the authority and path."""
713 # note HTTP URLs do not have a userinfo component
Georg Brandl13e89462008-07-01 19:56:00 +0000714 parts = urlsplit(uri)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000715 if parts[1]:
716 # URI
717 scheme = parts[0]
718 authority = parts[1]
719 path = parts[2] or '/'
720 else:
721 # host or host:port
722 scheme = None
723 authority = uri
724 path = '/'
Georg Brandl13e89462008-07-01 19:56:00 +0000725 host, port = splitport(authority)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000726 if default_port and port is None and scheme is not None:
727 dport = {"http": 80,
728 "https": 443,
729 }.get(scheme)
730 if dport is not None:
731 authority = "%s:%d" % (host, dport)
732 return authority, path
733
734 def is_suburi(self, base, test):
735 """Check if test is below base in a URI tree
736
737 Both args must be URIs in reduced form.
738 """
739 if base == test:
740 return True
741 if base[0] != test[0]:
742 return False
743 common = posixpath.commonprefix((base[1], test[1]))
744 if len(common) == len(base[1]):
745 return True
746 return False
747
748
749class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
750
751 def find_user_password(self, realm, authuri):
752 user, password = HTTPPasswordMgr.find_user_password(self, realm,
753 authuri)
754 if user is not None:
755 return user, password
756 return HTTPPasswordMgr.find_user_password(self, None, authuri)
757
758
759class AbstractBasicAuthHandler:
760
761 # XXX this allows for multiple auth-schemes, but will stupidly pick
762 # the last one with a realm specified.
763
764 # allow for double- and single-quoted realm values
765 # (single quotes are a violation of the RFC, but appear in the wild)
766 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
767 'realm=(["\'])(.*?)\\2', re.I)
768
769 # XXX could pre-emptively send auth info already accepted (RFC 2617,
770 # end of section 2, and section 1.2 immediately after "credentials"
771 # production).
772
773 def __init__(self, password_mgr=None):
774 if password_mgr is None:
775 password_mgr = HTTPPasswordMgr()
776 self.passwd = password_mgr
777 self.add_password = self.passwd.add_password
778
779 def http_error_auth_reqed(self, authreq, host, req, headers):
780 # host may be an authority (without userinfo) or a URL with an
781 # authority
782 # XXX could be multiple headers
783 authreq = headers.get(authreq, None)
784 if authreq:
785 mo = AbstractBasicAuthHandler.rx.search(authreq)
786 if mo:
787 scheme, quote, realm = mo.groups()
788 if scheme.lower() == 'basic':
789 return self.retry_http_basic_auth(host, req, realm)
790
791 def retry_http_basic_auth(self, host, req, realm):
792 user, pw = self.passwd.find_user_password(realm, host)
793 if pw is not None:
794 raw = "%s:%s" % (user, pw)
795 auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
796 if req.headers.get(self.auth_header, None) == auth:
797 return None
Senthil Kumaranefcd8832010-02-24 16:56:20 +0000798 req.add_unredirected_header(self.auth_header, auth)
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000799 return self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000800 else:
801 return None
802
803
804class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
805
806 auth_header = 'Authorization'
807
808 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000809 url = req.full_url
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000810 return self.http_error_auth_reqed('www-authenticate',
811 url, req, headers)
812
813
814class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
815
816 auth_header = 'Proxy-authorization'
817
818 def http_error_407(self, req, fp, code, msg, headers):
819 # http_error_auth_reqed requires that there is no userinfo component in
Georg Brandl029986a2008-06-23 11:44:14 +0000820 # authority. Assume there isn't one, since urllib.request does not (and
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000821 # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
822 # userinfo.
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000823 authority = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000824 return self.http_error_auth_reqed('proxy-authenticate',
825 authority, req, headers)
826
827
828def randombytes(n):
829 """Return n random bytes."""
830 return os.urandom(n)
831
832class AbstractDigestAuthHandler:
833 # Digest authentication is specified in RFC 2617.
834
835 # XXX The client does not inspect the Authentication-Info header
836 # in a successful response.
837
838 # XXX It should be possible to test this implementation against
839 # a mock server that just generates a static set of challenges.
840
841 # XXX qop="auth-int" supports is shaky
842
843 def __init__(self, passwd=None):
844 if passwd is None:
845 passwd = HTTPPasswordMgr()
846 self.passwd = passwd
847 self.add_password = self.passwd.add_password
848 self.retried = 0
849 self.nonce_count = 0
Senthil Kumaranb58474f2009-11-15 08:45:27 +0000850 self.last_nonce = None
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000851
852 def reset_retry_count(self):
853 self.retried = 0
854
855 def http_error_auth_reqed(self, auth_header, host, req, headers):
856 authreq = headers.get(auth_header, None)
857 if self.retried > 5:
858 # Don't fail endlessly - if we failed once, we'll probably
859 # fail a second time. Hm. Unless the Password Manager is
860 # prompting for the information. Crap. This isn't great
861 # but it's better than the current 'repeat until recursion
862 # depth exceeded' approach <wink>
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000863 raise HTTPError(req.full_url, 401, "digest auth failed",
Georg Brandl13e89462008-07-01 19:56:00 +0000864 headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000865 else:
866 self.retried += 1
867 if authreq:
868 scheme = authreq.split()[0]
869 if scheme.lower() == 'digest':
870 return self.retry_http_digest_auth(req, authreq)
871
872 def retry_http_digest_auth(self, req, auth):
873 token, challenge = auth.split(' ', 1)
874 chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
875 auth = self.get_authorization(req, chal)
876 if auth:
877 auth_val = 'Digest %s' % auth
878 if req.headers.get(self.auth_header, None) == auth_val:
879 return None
880 req.add_unredirected_header(self.auth_header, auth_val)
Senthil Kumarane9da06f2009-07-19 04:20:12 +0000881 resp = self.parent.open(req, timeout=req.timeout)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000882 return resp
883
884 def get_cnonce(self, nonce):
885 # The cnonce-value is an opaque
886 # quoted string value provided by the client and used by both client
887 # and server to avoid chosen plaintext attacks, to provide mutual
888 # authentication, and to provide some message integrity protection.
889 # This isn't a fabulous effort, but it's probably Good Enough.
890 s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
891 b = s.encode("ascii") + randombytes(8)
892 dig = hashlib.sha1(b).hexdigest()
893 return dig[:16]
894
895 def get_authorization(self, req, chal):
896 try:
897 realm = chal['realm']
898 nonce = chal['nonce']
899 qop = chal.get('qop')
900 algorithm = chal.get('algorithm', 'MD5')
901 # mod_digest doesn't send an opaque, even though it isn't
902 # supposed to be optional
903 opaque = chal.get('opaque', None)
904 except KeyError:
905 return None
906
907 H, KD = self.get_algorithm_impls(algorithm)
908 if H is None:
909 return None
910
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000911 user, pw = self.passwd.find_user_password(realm, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000912 if user is None:
913 return None
914
915 # XXX not implemented yet
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000916 if req.data is not None:
917 entdig = self.get_entity_digest(req.data, chal)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000918 else:
919 entdig = None
920
921 A1 = "%s:%s:%s" % (user, realm, pw)
922 A2 = "%s:%s" % (req.get_method(),
923 # XXX selector: what about proxies and full urls
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000924 req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000925 if qop == 'auth':
Senthil Kumaranb58474f2009-11-15 08:45:27 +0000926 if nonce == self.last_nonce:
927 self.nonce_count += 1
928 else:
929 self.nonce_count = 1
930 self.last_nonce = nonce
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000931 ncvalue = '%08x' % self.nonce_count
932 cnonce = self.get_cnonce(nonce)
933 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
934 respdig = KD(H(A1), noncebit)
935 elif qop is None:
936 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
937 else:
938 # XXX handle auth-int.
Georg Brandl13e89462008-07-01 19:56:00 +0000939 raise URLError("qop '%s' is not supported." % qop)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000940
941 # XXX should the partial digests be encoded too?
942
943 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000944 'response="%s"' % (user, realm, nonce, req.selector,
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000945 respdig)
946 if opaque:
947 base += ', opaque="%s"' % opaque
948 if entdig:
949 base += ', digest="%s"' % entdig
950 base += ', algorithm="%s"' % algorithm
951 if qop:
952 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
953 return base
954
955 def get_algorithm_impls(self, algorithm):
956 # lambdas assume digest modules are imported at the top level
957 if algorithm == 'MD5':
958 H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
959 elif algorithm == 'SHA':
960 H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
961 # XXX MD5-sess
962 KD = lambda s, d: H("%s:%s" % (s, d))
963 return H, KD
964
965 def get_entity_digest(self, data, chal):
966 # XXX not implemented yet
967 return None
968
969
970class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
971 """An authentication protocol defined by RFC 2069
972
973 Digest authentication improves on basic authentication because it
974 does not transmit passwords in the clear.
975 """
976
977 auth_header = 'Authorization'
978 handler_order = 490 # before Basic auth
979
980 def http_error_401(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000981 host = urlparse(req.full_url)[1]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000982 retry = self.http_error_auth_reqed('www-authenticate',
983 host, req, headers)
984 self.reset_retry_count()
985 return retry
986
987
988class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
989
990 auth_header = 'Proxy-Authorization'
991 handler_order = 490 # before Basic auth
992
993 def http_error_407(self, req, fp, code, msg, headers):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +0000994 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000995 retry = self.http_error_auth_reqed('proxy-authenticate',
996 host, req, headers)
997 self.reset_retry_count()
998 return retry
999
1000class AbstractHTTPHandler(BaseHandler):
1001
1002 def __init__(self, debuglevel=0):
1003 self._debuglevel = debuglevel
1004
1005 def set_http_debuglevel(self, level):
1006 self._debuglevel = level
1007
1008 def do_request_(self, request):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001009 host = request.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001010 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001011 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001012
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001013 if request.data is not None: # POST
1014 data = request.data
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001015 if not request.has_header('Content-type'):
1016 request.add_unredirected_header(
1017 'Content-type',
1018 'application/x-www-form-urlencoded')
1019 if not request.has_header('Content-length'):
1020 request.add_unredirected_header(
1021 'Content-length', '%d' % len(data))
1022
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001023 sel_host = host
1024 if request.has_proxy():
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001025 scheme, sel = splittype(request.selector)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001026 sel_host, sel_path = splithost(sel)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001027 if not request.has_header('Host'):
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001028 request.add_unredirected_header('Host', sel_host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001029 for name, value in self.parent.addheaders:
1030 name = name.capitalize()
1031 if not request.has_header(name):
1032 request.add_unredirected_header(name, value)
1033
1034 return request
1035
1036 def do_open(self, http_class, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001037 """Return an HTTPResponse object for the request, using http_class.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001038
1039 http_class must implement the HTTPConnection API from http.client.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001040 """
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001041 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001042 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001043 raise URLError('no host given')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001044
1045 h = http_class(host, timeout=req.timeout) # will parse host:port
1046 headers = dict(req.headers)
1047 headers.update(req.unredirected_hdrs)
1048
1049 # TODO(jhylton): Should this be redesigned to handle
1050 # persistent connections?
1051
1052 # We want to make an HTTP/1.1 request, but the addinfourl
1053 # class isn't prepared to deal with a persistent connection.
1054 # It will try to read all remaining data from the socket,
1055 # which will block while the server waits for the next request.
1056 # So make sure the connection gets closed after the (only)
1057 # request.
1058 headers["Connection"] = "close"
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001059 headers = dict((name.title(), val) for name, val in headers.items())
Senthil Kumaran0ac1f832009-07-26 12:39:47 +00001060
1061 if req._tunnel_host:
Senthil Kumaran4b9fbeb2009-12-20 07:18:22 +00001062 tunnel_headers = {}
1063 proxy_auth_hdr = "Proxy-Authorization"
1064 if proxy_auth_hdr in headers:
1065 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1066 # Proxy-Authorization should not be sent to origin
1067 # server.
1068 del headers[proxy_auth_hdr]
1069 h._set_tunnel(req._tunnel_host, headers=tunnel_headers)
Senthil Kumaran0ac1f832009-07-26 12:39:47 +00001070
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001071 try:
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001072 h.request(req.get_method(), req.selector, req.data, headers)
1073 r = h.getresponse() # an HTTPResponse instance
1074 except socket.error as err:
Georg Brandl13e89462008-07-01 19:56:00 +00001075 raise URLError(err)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001076
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001077 r.url = req.full_url
1078 # This line replaces the .msg attribute of the HTTPResponse
1079 # with .headers, because urllib clients expect the response to
1080 # have the reason in .msg. It would be good to mark this
1081 # attribute is deprecated and get then to use info() or
1082 # .headers.
1083 r.msg = r.reason
1084 return r
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001085
1086
1087class HTTPHandler(AbstractHTTPHandler):
1088
1089 def http_open(self, req):
1090 return self.do_open(http.client.HTTPConnection, req)
1091
1092 http_request = AbstractHTTPHandler.do_request_
1093
1094if hasattr(http.client, 'HTTPSConnection'):
1095 class HTTPSHandler(AbstractHTTPHandler):
1096
1097 def https_open(self, req):
1098 return self.do_open(http.client.HTTPSConnection, req)
1099
1100 https_request = AbstractHTTPHandler.do_request_
1101
1102class HTTPCookieProcessor(BaseHandler):
1103 def __init__(self, cookiejar=None):
1104 import http.cookiejar
1105 if cookiejar is None:
1106 cookiejar = http.cookiejar.CookieJar()
1107 self.cookiejar = cookiejar
1108
1109 def http_request(self, request):
1110 self.cookiejar.add_cookie_header(request)
1111 return request
1112
1113 def http_response(self, request, response):
1114 self.cookiejar.extract_cookies(response, request)
1115 return response
1116
1117 https_request = http_request
1118 https_response = http_response
1119
1120class UnknownHandler(BaseHandler):
1121 def unknown_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001122 type = req.type
Georg Brandl13e89462008-07-01 19:56:00 +00001123 raise URLError('unknown url type: %s' % type)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001124
1125def parse_keqv_list(l):
1126 """Parse list of key=value strings where keys are not duplicated."""
1127 parsed = {}
1128 for elt in l:
1129 k, v = elt.split('=', 1)
1130 if v[0] == '"' and v[-1] == '"':
1131 v = v[1:-1]
1132 parsed[k] = v
1133 return parsed
1134
1135def parse_http_list(s):
1136 """Parse lists as described by RFC 2068 Section 2.
1137
1138 In particular, parse comma-separated lists where the elements of
1139 the list may include quoted-strings. A quoted-string could
1140 contain a comma. A non-quoted string could have quotes in the
1141 middle. Neither commas nor quotes count if they are escaped.
1142 Only double-quotes count, not single-quotes.
1143 """
1144 res = []
1145 part = ''
1146
1147 escape = quote = False
1148 for cur in s:
1149 if escape:
1150 part += cur
1151 escape = False
1152 continue
1153 if quote:
1154 if cur == '\\':
1155 escape = True
1156 continue
1157 elif cur == '"':
1158 quote = False
1159 part += cur
1160 continue
1161
1162 if cur == ',':
1163 res.append(part)
1164 part = ''
1165 continue
1166
1167 if cur == '"':
1168 quote = True
1169
1170 part += cur
1171
1172 # append last part
1173 if part:
1174 res.append(part)
1175
1176 return [part.strip() for part in res]
1177
1178class FileHandler(BaseHandler):
1179 # Use local file or FTP depending on form of URL
1180 def file_open(self, req):
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001181 url = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001182 if url[:2] == '//' and url[2:3] != '/':
1183 req.type = 'ftp'
1184 return self.parent.open(req)
1185 else:
1186 return self.open_local_file(req)
1187
1188 # names for the localhost
1189 names = None
1190 def get_names(self):
1191 if FileHandler.names is None:
1192 try:
Senthil Kumaran88a495d2009-12-27 10:15:45 +00001193 FileHandler.names = tuple(
1194 socket.gethostbyname_ex('localhost')[2] +
1195 socket.gethostbyname_ex(socket.gethostname())[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001196 except socket.gaierror:
1197 FileHandler.names = (socket.gethostbyname('localhost'),)
1198 return FileHandler.names
1199
1200 # not entirely sure what the rules are here
1201 def open_local_file(self, req):
1202 import email.utils
1203 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001204 host = req.host
1205 file = req.selector
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001206 localfile = url2pathname(file)
1207 try:
1208 stats = os.stat(localfile)
1209 size = stats.st_size
1210 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1211 mtype = mimetypes.guess_type(file)[0]
1212 headers = email.message_from_string(
1213 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1214 (mtype or 'text/plain', size, modified))
1215 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001216 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001217 if not host or \
1218 (not port and _safe_gethostbyname(host) in self.get_names()):
Senthil Kumaran51964772010-05-08 03:31:56 +00001219 return addinfourl(open(localfile, 'rb'), headers, 'file://'+
1220 host + file)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001221 except OSError as msg:
Georg Brandl029986a2008-06-23 11:44:14 +00001222 # users shouldn't expect OSErrors coming from urlopen()
Georg Brandl13e89462008-07-01 19:56:00 +00001223 raise URLError(msg)
1224 raise URLError('file not on local host')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001225
1226def _safe_gethostbyname(host):
1227 try:
1228 return socket.gethostbyname(host)
1229 except socket.gaierror:
1230 return None
1231
1232class FTPHandler(BaseHandler):
1233 def ftp_open(self, req):
1234 import ftplib
1235 import mimetypes
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001236 host = req.host
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001237 if not host:
Georg Brandl13e89462008-07-01 19:56:00 +00001238 raise URLError('ftp error: no host given')
1239 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001240 if port is None:
1241 port = ftplib.FTP_PORT
1242 else:
1243 port = int(port)
1244
1245 # username/password handling
Georg Brandl13e89462008-07-01 19:56:00 +00001246 user, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001247 if user:
Georg Brandl13e89462008-07-01 19:56:00 +00001248 user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001249 else:
1250 passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001251 host = unquote(host)
1252 user = unquote(user or '')
1253 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001254
1255 try:
1256 host = socket.gethostbyname(host)
1257 except socket.error as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001258 raise URLError(msg)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001259 path, attrs = splitattr(req.selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001260 dirs = path.split('/')
Georg Brandl13e89462008-07-01 19:56:00 +00001261 dirs = list(map(unquote, dirs))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001262 dirs, file = dirs[:-1], dirs[-1]
1263 if dirs and not dirs[0]:
1264 dirs = dirs[1:]
1265 try:
1266 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1267 type = file and 'I' or 'D'
1268 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001269 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001270 if attr.lower() == 'type' and \
1271 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1272 type = value.upper()
1273 fp, retrlen = fw.retrfile(file, type)
1274 headers = ""
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001275 mtype = mimetypes.guess_type(req.full_url)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001276 if mtype:
1277 headers += "Content-type: %s\n" % mtype
1278 if retrlen is not None and retrlen >= 0:
1279 headers += "Content-length: %d\n" % retrlen
1280 headers = email.message_from_string(headers)
Jeremy Hylton6c5e28c2009-03-31 14:35:53 +00001281 return addinfourl(fp, headers, req.full_url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001282 except ftplib.all_errors as msg:
Georg Brandl13e89462008-07-01 19:56:00 +00001283 exc = URLError('ftp error: %s' % msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001284 raise exc.with_traceback(sys.exc_info()[2])
1285
1286 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1287 fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
1288 return fw
1289
1290class CacheFTPHandler(FTPHandler):
1291 # XXX would be nice to have pluggable cache strategies
1292 # XXX this stuff is definitely not thread safe
1293 def __init__(self):
1294 self.cache = {}
1295 self.timeout = {}
1296 self.soonest = 0
1297 self.delay = 60
1298 self.max_conns = 16
1299
1300 def setTimeout(self, t):
1301 self.delay = t
1302
1303 def setMaxConns(self, m):
1304 self.max_conns = m
1305
1306 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1307 key = user, host, port, '/'.join(dirs), timeout
1308 if key in self.cache:
1309 self.timeout[key] = time.time() + self.delay
1310 else:
1311 self.cache[key] = ftpwrapper(user, passwd, host, port,
1312 dirs, timeout)
1313 self.timeout[key] = time.time() + self.delay
1314 self.check_cache()
1315 return self.cache[key]
1316
1317 def check_cache(self):
1318 # first check for old ones
1319 t = time.time()
1320 if self.soonest <= t:
1321 for k, v in list(self.timeout.items()):
1322 if v < t:
1323 self.cache[k].close()
1324 del self.cache[k]
1325 del self.timeout[k]
1326 self.soonest = min(list(self.timeout.values()))
1327
1328 # then check the size
1329 if len(self.cache) == self.max_conns:
1330 for k, v in list(self.timeout.items()):
1331 if v == self.soonest:
1332 del self.cache[k]
1333 del self.timeout[k]
1334 break
1335 self.soonest = min(list(self.timeout.values()))
1336
1337# Code move from the old urllib module
1338
1339MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1340
1341# Helper for non-unix systems
1342if os.name == 'mac':
1343 from macurl2path import url2pathname, pathname2url
1344elif os.name == 'nt':
1345 from nturl2path import url2pathname, pathname2url
1346else:
1347 def url2pathname(pathname):
1348 """OS-specific conversion from a relative URL of the 'file' scheme
1349 to a file system path; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001350 return unquote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001351
1352 def pathname2url(pathname):
1353 """OS-specific conversion from a file system path to a relative URL
1354 of the 'file' scheme; not recommended for general use."""
Georg Brandl13e89462008-07-01 19:56:00 +00001355 return quote(pathname)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001356
1357# This really consists of two pieces:
1358# (1) a class which handles opening of all sorts of URLs
1359# (plus assorted utilities etc.)
1360# (2) a set of functions for parsing URLs
1361# XXX Should these be separated out into different modules?
1362
1363
1364ftpcache = {}
1365class URLopener:
1366 """Class to open URLs.
1367 This is a class rather than just a subroutine because we may need
1368 more than one set of global protocol-specific options.
1369 Note -- this is a base class for those who don't want the
1370 automatic handling of errors type 302 (relocated) and 401
1371 (authorization needed)."""
1372
1373 __tempfiles = None
1374
1375 version = "Python-urllib/%s" % __version__
1376
1377 # Constructor
1378 def __init__(self, proxies=None, **x509):
1379 if proxies is None:
1380 proxies = getproxies()
1381 assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1382 self.proxies = proxies
1383 self.key_file = x509.get('key_file')
1384 self.cert_file = x509.get('cert_file')
1385 self.addheaders = [('User-Agent', self.version)]
1386 self.__tempfiles = []
1387 self.__unlink = os.unlink # See cleanup()
1388 self.tempcache = None
1389 # Undocumented feature: if you assign {} to tempcache,
1390 # it is used to cache files retrieved with
1391 # self.retrieve(). This is not enabled by default
1392 # since it does not work for changing documents (and I
1393 # haven't got the logic to check expiration headers
1394 # yet).
1395 self.ftpcache = ftpcache
1396 # Undocumented feature: you can use a different
1397 # ftp cache by assigning to the .ftpcache member;
1398 # in case you want logically independent URL openers
1399 # XXX This is not threadsafe. Bah.
1400
1401 def __del__(self):
1402 self.close()
1403
1404 def close(self):
1405 self.cleanup()
1406
1407 def cleanup(self):
1408 # This code sometimes runs when the rest of this module
1409 # has already been deleted, so it can't use any globals
1410 # or import anything.
1411 if self.__tempfiles:
1412 for file in self.__tempfiles:
1413 try:
1414 self.__unlink(file)
1415 except OSError:
1416 pass
1417 del self.__tempfiles[:]
1418 if self.tempcache:
1419 self.tempcache.clear()
1420
1421 def addheader(self, *args):
1422 """Add a header to be used by the HTTP interface only
1423 e.g. u.addheader('Accept', 'sound/basic')"""
1424 self.addheaders.append(args)
1425
1426 # External interface
1427 def open(self, fullurl, data=None):
1428 """Use URLopener().open(file) instead of open(file, 'r')."""
Georg Brandl13e89462008-07-01 19:56:00 +00001429 fullurl = unwrap(to_bytes(fullurl))
Senthil Kumaran0e7e9ae2010-02-20 22:30:21 +00001430 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001431 if self.tempcache and fullurl in self.tempcache:
1432 filename, headers = self.tempcache[fullurl]
1433 fp = open(filename, 'rb')
Georg Brandl13e89462008-07-01 19:56:00 +00001434 return addinfourl(fp, headers, fullurl)
1435 urltype, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001436 if not urltype:
1437 urltype = 'file'
1438 if urltype in self.proxies:
1439 proxy = self.proxies[urltype]
Georg Brandl13e89462008-07-01 19:56:00 +00001440 urltype, proxyhost = splittype(proxy)
1441 host, selector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001442 url = (host, fullurl) # Signal special case to open_*()
1443 else:
1444 proxy = None
1445 name = 'open_' + urltype
1446 self.type = urltype
1447 name = name.replace('-', '_')
1448 if not hasattr(self, name):
1449 if proxy:
1450 return self.open_unknown_proxy(proxy, fullurl, data)
1451 else:
1452 return self.open_unknown(fullurl, data)
1453 try:
1454 if data is None:
1455 return getattr(self, name)(url)
1456 else:
1457 return getattr(self, name)(url, data)
1458 except socket.error as msg:
1459 raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1460
1461 def open_unknown(self, fullurl, data=None):
1462 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001463 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001464 raise IOError('url error', 'unknown url type', type)
1465
1466 def open_unknown_proxy(self, proxy, fullurl, data=None):
1467 """Overridable interface to open unknown URL type."""
Georg Brandl13e89462008-07-01 19:56:00 +00001468 type, url = splittype(fullurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001469 raise IOError('url error', 'invalid proxy for %s' % type, proxy)
1470
1471 # External interface
1472 def retrieve(self, url, filename=None, reporthook=None, data=None):
1473 """retrieve(url) returns (filename, headers) for a local object
1474 or (tempfilename, headers) for a remote object."""
Georg Brandl13e89462008-07-01 19:56:00 +00001475 url = unwrap(to_bytes(url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001476 if self.tempcache and url in self.tempcache:
1477 return self.tempcache[url]
Georg Brandl13e89462008-07-01 19:56:00 +00001478 type, url1 = splittype(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001479 if filename is None and (not type or type == 'file'):
1480 try:
1481 fp = self.open_local_file(url1)
1482 hdrs = fp.info()
1483 del fp
Georg Brandl13e89462008-07-01 19:56:00 +00001484 return url2pathname(splithost(url1)[1]), hdrs
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001485 except IOError as msg:
1486 pass
1487 fp = self.open(url, data)
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001488 try:
1489 headers = fp.info()
1490 if filename:
1491 tfp = open(filename, 'wb')
1492 else:
1493 import tempfile
1494 garbage, path = splittype(url)
1495 garbage, path = splithost(path or "")
1496 path, garbage = splitquery(path or "")
1497 path, garbage = splitattr(path or "")
1498 suffix = os.path.splitext(path)[1]
1499 (fd, filename) = tempfile.mkstemp(suffix)
1500 self.__tempfiles.append(filename)
1501 tfp = os.fdopen(fd, 'wb')
1502 try:
1503 result = filename, headers
1504 if self.tempcache is not None:
1505 self.tempcache[url] = result
1506 bs = 1024*8
1507 size = -1
1508 read = 0
1509 blocknum = 0
1510 if reporthook:
1511 if "content-length" in headers:
1512 size = int(headers["Content-Length"])
1513 reporthook(blocknum, bs, size)
1514 while 1:
1515 block = fp.read(bs)
1516 if not block:
1517 break
1518 read += len(block)
1519 tfp.write(block)
1520 blocknum += 1
1521 if reporthook:
1522 reporthook(blocknum, bs, size)
1523 finally:
1524 tfp.close()
1525 finally:
1526 fp.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001527 del fp
1528 del tfp
1529
1530 # raise exception if actual size does not match content-length header
1531 if size >= 0 and read < size:
Georg Brandl13e89462008-07-01 19:56:00 +00001532 raise ContentTooShortError(
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001533 "retrieval incomplete: got only %i out of %i bytes"
1534 % (read, size), result)
1535
1536 return result
1537
1538 # Each method named open_<type> knows how to open that type of URL
1539
1540 def _open_generic_http(self, connection_factory, url, data):
1541 """Make an HTTP connection using connection_class.
1542
1543 This is an internal method that should be called from
1544 open_http() or open_https().
1545
1546 Arguments:
1547 - connection_factory should take a host name and return an
1548 HTTPConnection instance.
1549 - url is the url to retrieval or a host, relative-path pair.
1550 - data is payload for a POST request or None.
1551 """
1552
1553 user_passwd = None
1554 proxy_passwd= None
1555 if isinstance(url, str):
Georg Brandl13e89462008-07-01 19:56:00 +00001556 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001557 if host:
Georg Brandl13e89462008-07-01 19:56:00 +00001558 user_passwd, host = splituser(host)
1559 host = unquote(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001560 realhost = host
1561 else:
1562 host, selector = url
1563 # check whether the proxy contains authorization information
Georg Brandl13e89462008-07-01 19:56:00 +00001564 proxy_passwd, host = splituser(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001565 # now we proceed with the url we want to obtain
Georg Brandl13e89462008-07-01 19:56:00 +00001566 urltype, rest = splittype(selector)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001567 url = rest
1568 user_passwd = None
1569 if urltype.lower() != 'http':
1570 realhost = None
1571 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001572 realhost, rest = splithost(rest)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001573 if realhost:
Georg Brandl13e89462008-07-01 19:56:00 +00001574 user_passwd, realhost = splituser(realhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001575 if user_passwd:
1576 selector = "%s://%s%s" % (urltype, realhost, rest)
1577 if proxy_bypass(realhost):
1578 host = realhost
1579
1580 #print "proxy via http:", host, selector
1581 if not host: raise IOError('http error', 'no host given')
1582
1583 if proxy_passwd:
1584 import base64
1585 proxy_auth = base64.b64encode(proxy_passwd).strip()
1586 else:
1587 proxy_auth = None
1588
1589 if user_passwd:
1590 import base64
1591 auth = base64.b64encode(user_passwd).strip()
1592 else:
1593 auth = None
1594 http_conn = connection_factory(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001595 headers = {}
1596 if proxy_auth:
1597 headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1598 if auth:
1599 headers["Authorization"] = "Basic %s" % auth
1600 if realhost:
1601 headers["Host"] = realhost
1602 for header, value in self.addheaders:
1603 headers[header] = value
1604
1605 if data is not None:
1606 headers["Content-Type"] = "application/x-www-form-urlencoded"
1607 http_conn.request("POST", selector, data, headers)
1608 else:
1609 http_conn.request("GET", selector, headers=headers)
1610
1611 try:
1612 response = http_conn.getresponse()
1613 except http.client.BadStatusLine:
1614 # something went wrong with the HTTP status line
Georg Brandl13e89462008-07-01 19:56:00 +00001615 raise URLError("http protocol error: bad status line")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001616
1617 # According to RFC 2616, "2xx" code indicates that the client's
1618 # request was successfully received, understood, and accepted.
1619 if 200 <= response.status < 300:
Antoine Pitroub353c122009-02-11 00:39:14 +00001620 return addinfourl(response, response.msg, "http:" + url,
Georg Brandl13e89462008-07-01 19:56:00 +00001621 response.status)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001622 else:
1623 return self.http_error(
1624 url, response.fp,
1625 response.status, response.reason, response.msg, data)
1626
1627 def open_http(self, url, data=None):
1628 """Use HTTP protocol."""
1629 return self._open_generic_http(http.client.HTTPConnection, url, data)
1630
1631 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1632 """Handle http errors.
1633
1634 Derived class can override this, or provide specific handlers
1635 named http_error_DDD where DDD is the 3-digit error code."""
1636 # First check if there's a specific handler for this error
1637 name = 'http_error_%d' % errcode
1638 if hasattr(self, name):
1639 method = getattr(self, name)
1640 if data is None:
1641 result = method(url, fp, errcode, errmsg, headers)
1642 else:
1643 result = method(url, fp, errcode, errmsg, headers, data)
1644 if result: return result
1645 return self.http_error_default(url, fp, errcode, errmsg, headers)
1646
1647 def http_error_default(self, url, fp, errcode, errmsg, headers):
1648 """Default error handler: close the connection and raise IOError."""
1649 void = fp.read()
1650 fp.close()
Georg Brandl13e89462008-07-01 19:56:00 +00001651 raise HTTPError(url, errcode, errmsg, headers, None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001652
1653 if _have_ssl:
1654 def _https_connection(self, host):
1655 return http.client.HTTPSConnection(host,
1656 key_file=self.key_file,
1657 cert_file=self.cert_file)
1658
1659 def open_https(self, url, data=None):
1660 """Use HTTPS protocol."""
1661 return self._open_generic_http(self._https_connection, url, data)
1662
1663 def open_file(self, url):
1664 """Use local file or FTP depending on form of URL."""
1665 if not isinstance(url, str):
1666 raise URLError('file error', 'proxy support for file protocol currently not implemented')
1667 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
1668 return self.open_ftp(url)
1669 else:
1670 return self.open_local_file(url)
1671
1672 def open_local_file(self, url):
1673 """Use local file."""
1674 import mimetypes, email.utils
1675 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001676 host, file = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001677 localname = url2pathname(file)
1678 try:
1679 stats = os.stat(localname)
1680 except OSError as e:
1681 raise URLError(e.errno, e.strerror, e.filename)
1682 size = stats.st_size
1683 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1684 mtype = mimetypes.guess_type(url)[0]
1685 headers = email.message_from_string(
1686 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
1687 (mtype or 'text/plain', size, modified))
1688 if not host:
1689 urlfile = file
1690 if file[:1] == '/':
1691 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001692 return addinfourl(open(localname, 'rb'), headers, urlfile)
1693 host, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001694 if (not port
Senthil Kumaran88a495d2009-12-27 10:15:45 +00001695 and socket.gethostbyname(host) in (localhost() + thishost())):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001696 urlfile = file
1697 if file[:1] == '/':
1698 urlfile = 'file://' + file
Georg Brandl13e89462008-07-01 19:56:00 +00001699 return addinfourl(open(localname, 'rb'), headers, urlfile)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001700 raise URLError('local file error', 'not on local host')
1701
1702 def open_ftp(self, url):
1703 """Use FTP protocol."""
1704 if not isinstance(url, str):
1705 raise URLError('ftp error', 'proxy support for ftp protocol currently not implemented')
1706 import mimetypes
1707 from io import StringIO
Georg Brandl13e89462008-07-01 19:56:00 +00001708 host, path = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001709 if not host: raise URLError('ftp error', 'no host given')
Georg Brandl13e89462008-07-01 19:56:00 +00001710 host, port = splitport(host)
1711 user, host = splituser(host)
1712 if user: user, passwd = splitpasswd(user)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001713 else: passwd = None
Georg Brandl13e89462008-07-01 19:56:00 +00001714 host = unquote(host)
1715 user = unquote(user or '')
1716 passwd = unquote(passwd or '')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001717 host = socket.gethostbyname(host)
1718 if not port:
1719 import ftplib
1720 port = ftplib.FTP_PORT
1721 else:
1722 port = int(port)
Georg Brandl13e89462008-07-01 19:56:00 +00001723 path, attrs = splitattr(path)
1724 path = unquote(path)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001725 dirs = path.split('/')
1726 dirs, file = dirs[:-1], dirs[-1]
1727 if dirs and not dirs[0]: dirs = dirs[1:]
1728 if dirs and not dirs[0]: dirs[0] = '/'
1729 key = user, host, port, '/'.join(dirs)
1730 # XXX thread unsafe!
1731 if len(self.ftpcache) > MAXFTPCACHE:
1732 # Prune the cache, rather arbitrarily
1733 for k in self.ftpcache.keys():
1734 if k != key:
1735 v = self.ftpcache[k]
1736 del self.ftpcache[k]
1737 v.close()
1738 try:
1739 if not key in self.ftpcache:
1740 self.ftpcache[key] = \
1741 ftpwrapper(user, passwd, host, port, dirs)
1742 if not file: type = 'D'
1743 else: type = 'I'
1744 for attr in attrs:
Georg Brandl13e89462008-07-01 19:56:00 +00001745 attr, value = splitvalue(attr)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001746 if attr.lower() == 'type' and \
1747 value in ('a', 'A', 'i', 'I', 'd', 'D'):
1748 type = value.upper()
1749 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
1750 mtype = mimetypes.guess_type("ftp:" + url)[0]
1751 headers = ""
1752 if mtype:
1753 headers += "Content-Type: %s\n" % mtype
1754 if retrlen is not None and retrlen >= 0:
1755 headers += "Content-Length: %d\n" % retrlen
1756 headers = email.message_from_string(headers)
Georg Brandl13e89462008-07-01 19:56:00 +00001757 return addinfourl(fp, headers, "ftp:" + url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001758 except ftperrors() as msg:
1759 raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2])
1760
1761 def open_data(self, url, data=None):
1762 """Use "data" URL."""
1763 if not isinstance(url, str):
1764 raise URLError('data error', 'proxy support for data protocol currently not implemented')
1765 # ignore POSTed data
1766 #
1767 # syntax of data URLs:
1768 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1769 # mediatype := [ type "/" subtype ] *( ";" parameter )
1770 # data := *urlchar
1771 # parameter := attribute "=" value
1772 try:
1773 [type, data] = url.split(',', 1)
1774 except ValueError:
1775 raise IOError('data error', 'bad data URL')
1776 if not type:
1777 type = 'text/plain;charset=US-ASCII'
1778 semi = type.rfind(';')
1779 if semi >= 0 and '=' not in type[semi:]:
1780 encoding = type[semi+1:]
1781 type = type[:semi]
1782 else:
1783 encoding = ''
1784 msg = []
Senthil Kumaran5a3bc652010-05-01 08:32:23 +00001785 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001786 time.gmtime(time.time())))
1787 msg.append('Content-type: %s' % type)
1788 if encoding == 'base64':
1789 import base64
Georg Brandl706824f2009-06-04 09:42:55 +00001790 # XXX is this encoding/decoding ok?
1791 data = base64.decodebytes(data.encode('ascii')).decode('latin1')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001792 else:
Georg Brandl13e89462008-07-01 19:56:00 +00001793 data = unquote(data)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001794 msg.append('Content-Length: %d' % len(data))
1795 msg.append('')
1796 msg.append(data)
1797 msg = '\n'.join(msg)
Georg Brandl13e89462008-07-01 19:56:00 +00001798 headers = email.message_from_string(msg)
1799 f = io.StringIO(msg)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001800 #f.fileno = None # needed for addinfourl
Georg Brandl13e89462008-07-01 19:56:00 +00001801 return addinfourl(f, headers, url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001802
1803
1804class FancyURLopener(URLopener):
1805 """Derived class with handlers for errors we can handle (perhaps)."""
1806
1807 def __init__(self, *args, **kwargs):
1808 URLopener.__init__(self, *args, **kwargs)
1809 self.auth_cache = {}
1810 self.tries = 0
1811 self.maxtries = 10
1812
1813 def http_error_default(self, url, fp, errcode, errmsg, headers):
1814 """Default error handling -- don't raise an exception."""
Georg Brandl13e89462008-07-01 19:56:00 +00001815 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001816
1817 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
1818 """Error 302 -- relocated (temporarily)."""
1819 self.tries += 1
1820 if self.maxtries and self.tries >= self.maxtries:
1821 if hasattr(self, "http_error_500"):
1822 meth = self.http_error_500
1823 else:
1824 meth = self.http_error_default
1825 self.tries = 0
1826 return meth(url, fp, 500,
1827 "Internal Server Error: Redirect Recursion", headers)
1828 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
1829 data)
1830 self.tries = 0
1831 return result
1832
1833 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
1834 if 'location' in headers:
1835 newurl = headers['location']
1836 elif 'uri' in headers:
1837 newurl = headers['uri']
1838 else:
1839 return
1840 void = fp.read()
1841 fp.close()
1842 # In case the server sent a relative URL, join with original:
Georg Brandl13e89462008-07-01 19:56:00 +00001843 newurl = urljoin(self.type + ":" + url, newurl)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001844 return self.open(newurl)
1845
1846 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
1847 """Error 301 -- also relocated (permanently)."""
1848 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1849
1850 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
1851 """Error 303 -- also relocated (essentially identical to 302)."""
1852 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1853
1854 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
1855 """Error 307 -- relocated, but turn POST into error."""
1856 if data is None:
1857 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1858 else:
1859 return self.http_error_default(url, fp, errcode, errmsg, headers)
1860
1861 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
1862 """Error 401 -- authentication required.
1863 This function supports Basic authentication only."""
1864 if not 'www-authenticate' in headers:
1865 URLopener.http_error_default(self, url, fp,
1866 errcode, errmsg, headers)
1867 stuff = headers['www-authenticate']
1868 import re
1869 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1870 if not match:
1871 URLopener.http_error_default(self, url, fp,
1872 errcode, errmsg, headers)
1873 scheme, realm = match.groups()
1874 if scheme.lower() != 'basic':
1875 URLopener.http_error_default(self, url, fp,
1876 errcode, errmsg, headers)
1877 name = 'retry_' + self.type + '_basic_auth'
1878 if data is None:
1879 return getattr(self,name)(url, realm)
1880 else:
1881 return getattr(self,name)(url, realm, data)
1882
1883 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
1884 """Error 407 -- proxy authentication required.
1885 This function supports Basic authentication only."""
1886 if not 'proxy-authenticate' in headers:
1887 URLopener.http_error_default(self, url, fp,
1888 errcode, errmsg, headers)
1889 stuff = headers['proxy-authenticate']
1890 import re
1891 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
1892 if not match:
1893 URLopener.http_error_default(self, url, fp,
1894 errcode, errmsg, headers)
1895 scheme, realm = match.groups()
1896 if scheme.lower() != 'basic':
1897 URLopener.http_error_default(self, url, fp,
1898 errcode, errmsg, headers)
1899 name = 'retry_proxy_' + self.type + '_basic_auth'
1900 if data is None:
1901 return getattr(self,name)(url, realm)
1902 else:
1903 return getattr(self,name)(url, realm, data)
1904
1905 def retry_proxy_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001906 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001907 newurl = 'http://' + host + selector
1908 proxy = self.proxies['http']
Georg Brandl13e89462008-07-01 19:56:00 +00001909 urltype, proxyhost = splittype(proxy)
1910 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001911 i = proxyhost.find('@') + 1
1912 proxyhost = proxyhost[i:]
1913 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1914 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001915 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001916 quote(passwd, safe=''), proxyhost)
1917 self.proxies['http'] = 'http://' + proxyhost + proxyselector
1918 if data is None:
1919 return self.open(newurl)
1920 else:
1921 return self.open(newurl, data)
1922
1923 def retry_proxy_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001924 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001925 newurl = 'https://' + host + selector
1926 proxy = self.proxies['https']
Georg Brandl13e89462008-07-01 19:56:00 +00001927 urltype, proxyhost = splittype(proxy)
1928 proxyhost, proxyselector = splithost(proxyhost)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001929 i = proxyhost.find('@') + 1
1930 proxyhost = proxyhost[i:]
1931 user, passwd = self.get_user_passwd(proxyhost, realm, i)
1932 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001933 proxyhost = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001934 quote(passwd, safe=''), proxyhost)
1935 self.proxies['https'] = 'https://' + proxyhost + proxyselector
1936 if data is None:
1937 return self.open(newurl)
1938 else:
1939 return self.open(newurl, data)
1940
1941 def retry_http_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001942 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001943 i = host.find('@') + 1
1944 host = host[i:]
1945 user, passwd = self.get_user_passwd(host, realm, i)
1946 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001947 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001948 quote(passwd, safe=''), host)
1949 newurl = 'http://' + host + selector
1950 if data is None:
1951 return self.open(newurl)
1952 else:
1953 return self.open(newurl, data)
1954
1955 def retry_https_basic_auth(self, url, realm, data=None):
Georg Brandl13e89462008-07-01 19:56:00 +00001956 host, selector = splithost(url)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001957 i = host.find('@') + 1
1958 host = host[i:]
1959 user, passwd = self.get_user_passwd(host, realm, i)
1960 if not (user or passwd): return None
Georg Brandl13e89462008-07-01 19:56:00 +00001961 host = "%s:%s@%s" % (quote(user, safe=''),
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001962 quote(passwd, safe=''), host)
1963 newurl = 'https://' + host + selector
1964 if data is None:
1965 return self.open(newurl)
1966 else:
1967 return self.open(newurl, data)
1968
1969 def get_user_passwd(self, host, realm, clear_cache = 0):
1970 key = realm + '@' + host.lower()
1971 if key in self.auth_cache:
1972 if clear_cache:
1973 del self.auth_cache[key]
1974 else:
1975 return self.auth_cache[key]
1976 user, passwd = self.prompt_user_passwd(host, realm)
1977 if user or passwd: self.auth_cache[key] = (user, passwd)
1978 return user, passwd
1979
1980 def prompt_user_passwd(self, host, realm):
1981 """Override this in a GUI environment!"""
1982 import getpass
1983 try:
1984 user = input("Enter username for %s at %s: " % (realm, host))
1985 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
1986 (user, realm, host))
1987 return user, passwd
1988 except KeyboardInterrupt:
1989 print()
1990 return None, None
1991
1992
1993# Utility functions
1994
1995_localhost = None
1996def localhost():
1997 """Return the IP address of the magic hostname 'localhost'."""
1998 global _localhost
1999 if _localhost is None:
2000 _localhost = socket.gethostbyname('localhost')
2001 return _localhost
2002
2003_thishost = None
2004def thishost():
Senthil Kumaran88a495d2009-12-27 10:15:45 +00002005 """Return the IP addresses of the current host."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002006 global _thishost
2007 if _thishost is None:
Senthil Kumaran88a495d2009-12-27 10:15:45 +00002008 _thishost = tuple(socket.gethostbyname_ex(socket.gethostname()[2]))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002009 return _thishost
2010
2011_ftperrors = None
2012def ftperrors():
2013 """Return the set of errors raised by the FTP class."""
2014 global _ftperrors
2015 if _ftperrors is None:
2016 import ftplib
2017 _ftperrors = ftplib.all_errors
2018 return _ftperrors
2019
2020_noheaders = None
2021def noheaders():
Georg Brandl13e89462008-07-01 19:56:00 +00002022 """Return an empty email Message object."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002023 global _noheaders
2024 if _noheaders is None:
Georg Brandl13e89462008-07-01 19:56:00 +00002025 _noheaders = email.message_from_string("")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002026 return _noheaders
2027
2028
2029# Utility classes
2030
2031class ftpwrapper:
2032 """Class used by open_ftp() for cache of open FTP connections."""
2033
2034 def __init__(self, user, passwd, host, port, dirs, timeout=None):
2035 self.user = user
2036 self.passwd = passwd
2037 self.host = host
2038 self.port = port
2039 self.dirs = dirs
2040 self.timeout = timeout
2041 self.init()
2042
2043 def init(self):
2044 import ftplib
2045 self.busy = 0
2046 self.ftp = ftplib.FTP()
2047 self.ftp.connect(self.host, self.port, self.timeout)
2048 self.ftp.login(self.user, self.passwd)
2049 for dir in self.dirs:
2050 self.ftp.cwd(dir)
2051
2052 def retrfile(self, file, type):
2053 import ftplib
2054 self.endtransfer()
2055 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2056 else: cmd = 'TYPE ' + type; isdir = 0
2057 try:
2058 self.ftp.voidcmd(cmd)
2059 except ftplib.all_errors:
2060 self.init()
2061 self.ftp.voidcmd(cmd)
2062 conn = None
2063 if file and not isdir:
2064 # Try to retrieve as a file
2065 try:
2066 cmd = 'RETR ' + file
2067 conn = self.ftp.ntransfercmd(cmd)
2068 except ftplib.error_perm as reason:
2069 if str(reason)[:3] != '550':
Georg Brandl13e89462008-07-01 19:56:00 +00002070 raise URLError('ftp error', reason).with_traceback(
2071 sys.exc_info()[2])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002072 if not conn:
2073 # Set transfer mode to ASCII!
2074 self.ftp.voidcmd('TYPE A')
2075 # Try a directory listing. Verify that directory exists.
2076 if file:
2077 pwd = self.ftp.pwd()
2078 try:
2079 try:
2080 self.ftp.cwd(file)
2081 except ftplib.error_perm as reason:
Georg Brandl13e89462008-07-01 19:56:00 +00002082 raise URLError('ftp error', reason) from reason
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002083 finally:
2084 self.ftp.cwd(pwd)
2085 cmd = 'LIST ' + file
2086 else:
2087 cmd = 'LIST'
2088 conn = self.ftp.ntransfercmd(cmd)
2089 self.busy = 1
2090 # Pass back both a suitably decorated object and a retrieval length
Georg Brandl13e89462008-07-01 19:56:00 +00002091 return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002092 def endtransfer(self):
2093 if not self.busy:
2094 return
2095 self.busy = 0
2096 try:
2097 self.ftp.voidresp()
2098 except ftperrors():
2099 pass
2100
2101 def close(self):
2102 self.endtransfer()
2103 try:
2104 self.ftp.close()
2105 except ftperrors():
2106 pass
2107
2108# Proxy handling
2109def getproxies_environment():
2110 """Return a dictionary of scheme -> proxy server URL mappings.
2111
2112 Scan the environment for variables named <scheme>_proxy;
2113 this seems to be the standard convention. If you need a
2114 different way, you can pass a proxies dictionary to the
2115 [Fancy]URLopener constructor.
2116
2117 """
2118 proxies = {}
2119 for name, value in os.environ.items():
2120 name = name.lower()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002121 if value and name[-6:] == '_proxy':
2122 proxies[name[:-6]] = value
2123 return proxies
2124
2125def proxy_bypass_environment(host):
2126 """Test if proxies should not be used for a particular host.
2127
2128 Checks the environment for a variable named no_proxy, which should
2129 be a list of DNS suffixes separated by commas, or '*' for all hosts.
2130 """
2131 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
2132 # '*' is special case for always bypass
2133 if no_proxy == '*':
2134 return 1
2135 # strip port off host
Georg Brandl13e89462008-07-01 19:56:00 +00002136 hostonly, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002137 # check if the host ends with any of the DNS suffixes
2138 for name in no_proxy.split(','):
2139 if name and (hostonly.endswith(name) or host.endswith(name)):
2140 return 1
2141 # otherwise, don't bypass
2142 return 0
2143
2144
2145if sys.platform == 'darwin':
Ronald Oussoren218cc582010-04-18 20:49:34 +00002146 from _scproxy import _get_proxy_settings, _get_proxies
2147
2148 def proxy_bypass_macosx_sysconf(host):
2149 """
2150 Return True iff this host shouldn't be accessed using a proxy
2151
2152 This function uses the MacOSX framework SystemConfiguration
2153 to fetch the proxy information.
2154 """
2155 import re
2156 import socket
2157 from fnmatch import fnmatch
2158
2159 hostonly, port = splitport(host)
2160
2161 def ip2num(ipAddr):
2162 parts = ipAddr.split('.')
2163 parts = map(int, parts)
2164 if len(parts) != 4:
2165 parts = (parts + [0, 0, 0, 0])[:4]
2166 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2167
2168 proxy_settings = _get_proxy_settings()
2169
2170 # Check for simple host names:
2171 if '.' not in host:
2172 if proxy_settings['exclude_simple']:
2173 return True
2174
2175 hostIP = None
2176
2177 for value in proxy_settings.get('exceptions', ()):
2178 # Items in the list are strings like these: *.local, 169.254/16
2179 if not value: continue
2180
2181 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2182 if m is not None:
2183 if hostIP is None:
2184 try:
2185 hostIP = socket.gethostbyname(hostonly)
2186 hostIP = ip2num(hostIP)
2187 except socket.error:
2188 continue
2189
2190 base = ip2num(m.group(1))
2191 mask = int(m.group(2)[1:])
2192 mask = 32 - mask
2193
2194 if (hostIP >> mask) == (base >> mask):
2195 return True
2196
2197 elif fnmatch(host, value):
2198 return True
2199
2200 return False
2201
2202
2203 def getproxies_macosx_sysconf():
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002204 """Return a dictionary of scheme -> proxy server URL mappings.
2205
Ronald Oussoren218cc582010-04-18 20:49:34 +00002206 This function uses the MacOSX framework SystemConfiguration
2207 to fetch the proxy information.
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002208 """
Ronald Oussoren218cc582010-04-18 20:49:34 +00002209 return _get_proxies()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002210
Ronald Oussoren218cc582010-04-18 20:49:34 +00002211
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002212
2213 def proxy_bypass(host):
2214 if getproxies_environment():
2215 return proxy_bypass_environment(host)
2216 else:
Ronald Oussoren218cc582010-04-18 20:49:34 +00002217 return proxy_bypass_macosx_sysconf(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002218
2219 def getproxies():
Ronald Oussoren218cc582010-04-18 20:49:34 +00002220 return getproxies_environment() or getproxies_macosx_sysconf()
2221
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002222
2223elif os.name == 'nt':
2224 def getproxies_registry():
2225 """Return a dictionary of scheme -> proxy server URL mappings.
2226
2227 Win32 uses the registry to store proxies.
2228
2229 """
2230 proxies = {}
2231 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002232 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002233 except ImportError:
2234 # Std module, so should be around - but you never know!
2235 return proxies
2236 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002237 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002238 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002239 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002240 'ProxyEnable')[0]
2241 if proxyEnable:
2242 # Returned as Unicode but problems if not converted to ASCII
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002243 proxyServer = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002244 'ProxyServer')[0])
2245 if '=' in proxyServer:
2246 # Per-protocol settings
2247 for p in proxyServer.split(';'):
2248 protocol, address = p.split('=', 1)
2249 # See if address has a type:// prefix
2250 import re
2251 if not re.match('^([^/:]+)://', address):
2252 address = '%s://%s' % (protocol, address)
2253 proxies[protocol] = address
2254 else:
2255 # Use one setting for all protocols
2256 if proxyServer[:5] == 'http:':
2257 proxies['http'] = proxyServer
2258 else:
2259 proxies['http'] = 'http://%s' % proxyServer
2260 proxies['ftp'] = 'ftp://%s' % proxyServer
2261 internetSettings.Close()
2262 except (WindowsError, ValueError, TypeError):
2263 # Either registry key not found etc, or the value in an
2264 # unexpected format.
2265 # proxies already set up to be empty so nothing to do
2266 pass
2267 return proxies
2268
2269 def getproxies():
2270 """Return a dictionary of scheme -> proxy server URL mappings.
2271
2272 Returns settings gathered from the environment, if specified,
2273 or the registry.
2274
2275 """
2276 return getproxies_environment() or getproxies_registry()
2277
2278 def proxy_bypass_registry(host):
2279 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002280 import winreg
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002281 import re
2282 except ImportError:
2283 # Std modules, so should be around - but you never know!
2284 return 0
2285 try:
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002286 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002287 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002288 proxyEnable = winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002289 'ProxyEnable')[0]
Georg Brandl4ed72ac2009-04-01 04:28:33 +00002290 proxyOverride = str(winreg.QueryValueEx(internetSettings,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002291 'ProxyOverride')[0])
2292 # ^^^^ Returned as Unicode but problems if not converted to ASCII
2293 except WindowsError:
2294 return 0
2295 if not proxyEnable or not proxyOverride:
2296 return 0
2297 # try to make a host list from name and IP address.
Georg Brandl13e89462008-07-01 19:56:00 +00002298 rawHost, port = splitport(host)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002299 host = [rawHost]
2300 try:
2301 addr = socket.gethostbyname(rawHost)
2302 if addr != rawHost:
2303 host.append(addr)
2304 except socket.error:
2305 pass
2306 try:
2307 fqdn = socket.getfqdn(rawHost)
2308 if fqdn != rawHost:
2309 host.append(fqdn)
2310 except socket.error:
2311 pass
2312 # make a check value list from the registry entry: replace the
2313 # '<local>' string by the localhost entry and the corresponding
2314 # canonical entry.
2315 proxyOverride = proxyOverride.split(';')
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002316 # now check if we match one of the registry values.
2317 for test in proxyOverride:
Senthil Kumaran49476062009-05-01 06:00:23 +00002318 if test == '<local>':
2319 if '.' not in rawHost:
2320 return 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00002321 test = test.replace(".", r"\.") # mask dots
2322 test = test.replace("*", r".*") # change glob sequence
2323 test = test.replace("?", r".") # change glob char
2324 for val in host:
2325 # print "%s <--> %s" %( test, val )
2326 if re.match(test, val, re.I):
2327 return 1
2328 return 0
2329
2330 def proxy_bypass(host):
2331 """Return a dictionary of scheme -> proxy server URL mappings.
2332
2333 Returns settings gathered from the environment, if specified,
2334 or the registry.
2335
2336 """
2337 if getproxies_environment():
2338 return proxy_bypass_environment(host)
2339 else:
2340 return proxy_bypass_registry(host)
2341
2342else:
2343 # By default use environment variables
2344 getproxies = getproxies_environment
2345 proxy_bypass = proxy_bypass_environment