Debian Codegraph @

cpython27/Lib/urllib.py

raw symbols SCIP
1 """Open an arbitrary URL.
2
3 See the following document for more info on URLs:
4 "Names and Addresses, URIs, URLs, URNs, URCs", at
5 http://www.w3.org/pub/WWW/Addressing/Overview.html
6
7 See also the HTTP spec (from which the error codes are derived):
8 "HTTP - Hypertext Transfer Protocol", at
9 http://www.w3.org/pub/WWW/Protocols/
10
11 Related standards and specs:
12 - RFC1808: the "relative URL" spec. (authoritative status)
13 - RFC1738 - the "URL standard". (authoritative status)
14 - RFC1630 - the "URI spec". (informational status)
15
16 The object returned by URLopener().open(file) will differ per
17 protocol. All you know is that is has methods read(), readline(),
18 readlines(), fileno(), close() and info(). The read*(), fileno()
19 and close() methods work like those of open files.
20 The info() method returns a mimetools.Message object which can be
21 used to query various info about the object, if available.
22 (mimetools.Message objects are queried with the getheader() method.)
23 """
24
25 import string
26 import socket
27 import os
28 import time
29 import sys
30 import base64
31 import re
32
33 from urlparse import urljoin as basejoin
34
35 __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
36 "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
37 "urlencode", "url2pathname", "pathname2url", "splittag",
38 "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
39 "splittype", "splithost", "splituser", "splitpasswd", "splitport",
40 "splitnport", "splitquery", "splitattr", "splitvalue",
41 "getproxies"]
42
43 __version__ = '1.17' # XXX This version is not always updated :-(
44
45 MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
46
47 # Helper for non-unix systems
48 if os.name == 'nt':
49 from nturl2path import url2pathname, pathname2url
50 elif os.name == 'riscos':
51 from rourl2path import url2pathname, pathname2url
52 else:
53 def url2pathname(pathname):
54 """OS-specific conversion from a relative URL of the 'file' scheme
55 to a file system path; not recommended for general use."""
56 return unquote(pathname)
57
58 def pathname2url(pathname):
59 """OS-specific conversion from a file system path to a relative URL
60 of the 'file' scheme; not recommended for general use."""
61 return quote(pathname)
62
63 # This really consists of two pieces:
64 # (1) a class which handles opening of all sorts of URLs
65 # (plus assorted utilities etc.)
66 # (2) a set of functions for parsing URLs
67 # XXX Should these be separated out into different modules?
68
69
70 # Shortcut for basic usage
71 _urlopener = None
72 def urlopen(url, data=None, proxies=None, context=None):
73 """Create a file-like object for the specified URL to read from."""
74 from warnings import warnpy3k
75 warnpy3k("urllib.urlopen() has been removed in Python 3.0 in "
76 "favor of urllib2.urlopen()", stacklevel=2)
77
78 global _urlopener
79 if proxies is not None or context is not None:
80 opener = FancyURLopener(proxies=proxies, context=context)
81 elif not _urlopener:
82 opener = FancyURLopener()
83 _urlopener = opener
84 else:
85 opener = _urlopener
86 if data is None:
87 return opener.open(url)
88 else:
89 return opener.open(url, data)
90 def urlretrieve(url, filename=None, reporthook=None, data=None, context=None):
91 global _urlopener
92 if context is not None:
93 opener = FancyURLopener(context=context)
94 elif not _urlopener:
95 _urlopener = opener = FancyURLopener()
96 else:
97 opener = _urlopener
98 return opener.retrieve(url, filename, reporthook, data)
99 def urlcleanup():
100 if _urlopener:
101 _urlopener.cleanup()
102 _safe_quoters.clear()
103 ftpcache.clear()
104
105 # check for SSL
106 try:
107 import ssl
108 except:
109 _have_ssl = False
110 else:
111 _have_ssl = True
112
113 # exception raised when downloaded size does not match content-length
114 class ContentTooShortError(IOError):
115 def __init__(self, message, content):
116 IOError.__init__(self, message)
117 self.content = content
118
119 ftpcache = {}
120 class URLopener:
121 """Class to open URLs.
122 This is a class rather than just a subroutine because we may need
123 more than one set of global protocol-specific options.
124 Note -- this is a base class for those who don't want the
125 automatic handling of errors type 302 (relocated) and 401
126 (authorization needed)."""
127
128 __tempfiles = None
129
130 version = "Python-urllib/%s" % __version__
131
132 # Constructor
133 def __init__(self, proxies=None, context=None, **x509):
134 if proxies is None:
135 proxies = getproxies()
136 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
137 self.proxies = proxies
138 self.key_file = x509.get('key_file')
139 self.cert_file = x509.get('cert_file')
140 self.context = context
141 self.addheaders = [('User-Agent', self.version), ('Accept', '*/*')]
142 self.__tempfiles = []
143 self.__unlink = os.unlink # See cleanup()
144 self.tempcache = None
145 # Undocumented feature: if you assign {} to tempcache,
146 # it is used to cache files retrieved with
147 # self.retrieve(). This is not enabled by default
148 # since it does not work for changing documents (and I
149 # haven't got the logic to check expiration headers
150 # yet).
151 self.ftpcache = ftpcache
152 # Undocumented feature: you can use a different
153 # ftp cache by assigning to the .ftpcache member;
154 # in case you want logically independent URL openers
155 # XXX This is not threadsafe. Bah.
156
157 def __del__(self):
158 self.close()
159
160 def close(self):
161 self.cleanup()
162
163 def cleanup(self):
164 # This code sometimes runs when the rest of this module
165 # has already been deleted, so it can't use any globals
166 # or import anything.
167 if self.__tempfiles:
168 for file in self.__tempfiles:
169 try:
170 self.__unlink(file)
171 except OSError:
172 pass
173 del self.__tempfiles[:]
174 if self.tempcache:
175 self.tempcache.clear()
176
177 def addheader(self, *args):
178 """Add a header to be used by the HTTP interface only
179 e.g. u.addheader('Accept', 'sound/basic')"""
180 self.addheaders.append(args)
181
182 # External interface
183 def open(self, fullurl, data=None):
184 """Use URLopener().open(file) instead of open(file, 'r')."""
185 fullurl = unwrap(toBytes(fullurl))
186 # percent encode url, fixing lame server errors for e.g, like space
187 # within url paths.
188 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
189 if self.tempcache and fullurl in self.tempcache:
190 filename, headers = self.tempcache[fullurl]
191 fp = open(filename, 'rb')
192 return addinfourl(fp, headers, fullurl)
193 urltype, url = splittype(fullurl)
194 if not urltype:
195 urltype = 'file'
196 if urltype in self.proxies:
197 proxy = self.proxies[urltype]
198 urltype, proxyhost = splittype(proxy)
199 host, selector = splithost(proxyhost)
200 url = (host, fullurl) # Signal special case to open_*()
201 else:
202 proxy = None
203 name = 'open_' + urltype
204 self.type = urltype
205 name = name.replace('-', '_')
206
207 # bpo-35907: disallow the file reading with the type not allowed
208 if not hasattr(self, name) or name == 'open_local_file':
209 if proxy:
210 return self.open_unknown_proxy(proxy, fullurl, data)
211 else:
212 return self.open_unknown(fullurl, data)
213 try:
214 if data is None:
215 return getattr(self, name)(url)
216 else:
217 return getattr(self, name)(url, data)
218 except socket.error, msg:
219 raise IOError, ('socket error', msg), sys.exc_info()[2]
220
221 def open_unknown(self, fullurl, data=None):
222 """Overridable interface to open unknown URL type."""
223 type, url = splittype(fullurl)
224 raise IOError, ('url error', 'unknown url type', type)
225
226 def open_unknown_proxy(self, proxy, fullurl, data=None):
227 """Overridable interface to open unknown URL type."""
228 type, url = splittype(fullurl)
229 raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
230
231 # External interface
232 def retrieve(self, url, filename=None, reporthook=None, data=None):
233 """retrieve(url) returns (filename, headers) for a local object
234 or (tempfilename, headers) for a remote object."""
235 url = unwrap(toBytes(url))
236 if self.tempcache and url in self.tempcache:
237 return self.tempcache[url]
238 type, url1 = splittype(url)
239 if filename is None and (not type or type == 'file'):
240 try:
241 fp = self.open_local_file(url1)
242 hdrs = fp.info()
243 fp.close()
244 return url2pathname(splithost(url1)[1]), hdrs
245 except IOError:
246 pass
247 fp = self.open(url, data)
248 try:
249 headers = fp.info()
250 if filename:
251 tfp = open(filename, 'wb')
252 else:
253 import tempfile
254 garbage, path = splittype(url)
255 garbage, path = splithost(path or "")
256 path, garbage = splitquery(path or "")
257 path, garbage = splitattr(path or "")
258 suffix = os.path.splitext(path)[1]
259 (fd, filename) = tempfile.mkstemp(suffix)
260 self.__tempfiles.append(filename)
261 tfp = os.fdopen(fd, 'wb')
262 try:
263 result = filename, headers
264 if self.tempcache is not None:
265 self.tempcache[url] = result
266 bs = 1024*8
267 size = -1
268 read = 0
269 blocknum = 0
270 if "content-length" in headers:
271 size = int(headers["Content-Length"])
272 if reporthook:
273 reporthook(blocknum, bs, size)
274 while 1:
275 block = fp.read(bs)
276 if block == "":
277 break
278 read += len(block)
279 tfp.write(block)
280 blocknum += 1
281 if reporthook:
282 reporthook(blocknum, bs, size)
283 finally:
284 tfp.close()
285 finally:
286 fp.close()
287
288 # raise exception if actual size does not match content-length header
289 if size >= 0 and read < size:
290 raise ContentTooShortError("retrieval incomplete: got only %i out "
291 "of %i bytes" % (read, size), result)
292
293 return result
294
295 # Each method named open_<type> knows how to open that type of URL
296
297 def open_http(self, url, data=None):
298 """Use HTTP protocol."""
299 import httplib
300 user_passwd = None
301 proxy_passwd= None
302 if isinstance(url, str):
303 host, selector = splithost(url)
304 if host:
305 user_passwd, host = splituser(host)
306 host = unquote(host)
307 realhost = host
308 else:
309 host, selector = url
310 # check whether the proxy contains authorization information
311 proxy_passwd, host = splituser(host)
312 # now we proceed with the url we want to obtain
313 urltype, rest = splittype(selector)
314 url = rest
315 user_passwd = None
316 if urltype.lower() != 'http':
317 realhost = None
318 else:
319 realhost, rest = splithost(rest)
320 if realhost:
321 user_passwd, realhost = splituser(realhost)
322 if user_passwd:
323 selector = "%s://%s%s" % (urltype, realhost, rest)
324 if proxy_bypass(realhost):
325 host = realhost
326
327 #print "proxy via http:", host, selector
328 if not host: raise IOError, ('http error', 'no host given')
329
330 if proxy_passwd:
331 proxy_passwd = unquote(proxy_passwd)
332 proxy_auth = base64.b64encode(proxy_passwd).strip()
333 else:
334 proxy_auth = None
335
336 if user_passwd:
337 user_passwd = unquote(user_passwd)
338 auth = base64.b64encode(user_passwd).strip()
339 else:
340 auth = None
341 h = httplib.HTTP(host)
342 if data is not None:
343 h.putrequest('POST', selector)
344 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
345 h.putheader('Content-Length', '%d' % len(data))
346 else:
347 h.putrequest('GET', selector)
348 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
349 if auth: h.putheader('Authorization', 'Basic %s' % auth)
350 if realhost: h.putheader('Host', realhost)
351 for args in self.addheaders: h.putheader(*args)
352 h.endheaders(data)
353 errcode, errmsg, headers = h.getreply()
354 fp = h.getfile()
355 if errcode == -1:
356 if fp: fp.close()
357 # something went wrong with the HTTP status line
358 raise IOError, ('http protocol error', 0,
359 'got a bad status line', None)
360 # According to RFC 2616, "2xx" code indicates that the client's
361 # request was successfully received, understood, and accepted.
362 if (200 <= errcode < 300):
363 return addinfourl(fp, headers, "http:" + url, errcode)
364 else:
365 if data is None:
366 return self.http_error(url, fp, errcode, errmsg, headers)
367 else:
368 return self.http_error(url, fp, errcode, errmsg, headers, data)
369
370 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
371 """Handle http errors.
372 Derived class can override this, or provide specific handlers
373 named http_error_DDD where DDD is the 3-digit error code."""
374 # First check if there's a specific handler for this error
375 name = 'http_error_%d' % errcode
376 if hasattr(self, name):
377 method = getattr(self, name)
378 if data is None:
379 result = method(url, fp, errcode, errmsg, headers)
380 else:
381 result = method(url, fp, errcode, errmsg, headers, data)
382 if result: return result
383 return self.http_error_default(url, fp, errcode, errmsg, headers)
384
385 def http_error_default(self, url, fp, errcode, errmsg, headers):
386 """Default error handler: close the connection and raise IOError."""
387 fp.close()
388 raise IOError, ('http error', errcode, errmsg, headers)
389
390 if _have_ssl:
391 def open_https(self, url, data=None):
392 """Use HTTPS protocol."""
393
394 import httplib
395 user_passwd = None
396 proxy_passwd = None
397 if isinstance(url, str):
398 host, selector = splithost(url)
399 if host:
400 user_passwd, host = splituser(host)
401 host = unquote(host)
402 realhost = host
403 else:
404 host, selector = url
405 # here, we determine, whether the proxy contains authorization information
406 proxy_passwd, host = splituser(host)
407 urltype, rest = splittype(selector)
408 url = rest
409 user_passwd = None
410 if urltype.lower() != 'https':
411 realhost = None
412 else:
413 realhost, rest = splithost(rest)
414 if realhost:
415 user_passwd, realhost = splituser(realhost)
416 if user_passwd:
417 selector = "%s://%s%s" % (urltype, realhost, rest)
418 #print "proxy via https:", host, selector
419 if not host: raise IOError, ('https error', 'no host given')
420 if proxy_passwd:
421 proxy_passwd = unquote(proxy_passwd)
422 proxy_auth = base64.b64encode(proxy_passwd).strip()
423 else:
424 proxy_auth = None
425 if user_passwd:
426 user_passwd = unquote(user_passwd)
427 auth = base64.b64encode(user_passwd).strip()
428 else:
429 auth = None
430 h = httplib.HTTPS(host, 0,
431 key_file=self.key_file,
432 cert_file=self.cert_file,
433 context=self.context)
434 if data is not None:
435 h.putrequest('POST', selector)
436 h.putheader('Content-Type',
437 'application/x-www-form-urlencoded')
438 h.putheader('Content-Length', '%d' % len(data))
439 else:
440 h.putrequest('GET', selector)
441 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
442 if auth: h.putheader('Authorization', 'Basic %s' % auth)
443 if realhost: h.putheader('Host', realhost)
444 for args in self.addheaders: h.putheader(*args)
445 h.endheaders(data)
446 errcode, errmsg, headers = h.getreply()
447 fp = h.getfile()
448 if errcode == -1:
449 if fp: fp.close()
450 # something went wrong with the HTTP status line
451 raise IOError, ('http protocol error', 0,
452 'got a bad status line', None)
453 # According to RFC 2616, "2xx" code indicates that the client's
454 # request was successfully received, understood, and accepted.
455 if (200 <= errcode < 300):
456 return addinfourl(fp, headers, "https:" + url, errcode)
457 else:
458 if data is None:
459 return self.http_error(url, fp, errcode, errmsg, headers)
460 else:
461 return self.http_error(url, fp, errcode, errmsg, headers,
462 data)
463
464 def open_file(self, url):
465 """Use local file or FTP depending on form of URL."""
466 if not isinstance(url, str):
467 raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
468 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
469 return self.open_ftp(url)
470 else:
471 return self.open_local_file(url)
472
473 def open_local_file(self, url):
474 """Use local file."""
475 import mimetypes, mimetools, email.utils
476 try:
477 from cStringIO import StringIO
478 except ImportError:
479 from StringIO import StringIO
480 host, file = splithost(url)
481 localname = url2pathname(file)
482 try:
483 stats = os.stat(localname)
484 except OSError, e:
485 raise IOError(e.errno, e.strerror, e.filename)
486 size = stats.st_size
487 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
488 mtype = mimetypes.guess_type(url)[0]
489 headers = mimetools.Message(StringIO(
490 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
491 (mtype or 'text/plain', size, modified)))
492 if not host:
493 urlfile = file
494 if file[:1] == '/':
495 urlfile = 'file://' + file
496 elif file[:2] == './':
497 raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
498 return addinfourl(open(localname, 'rb'),
499 headers, urlfile)
500 host, port = splitport(host)
501 if not port \
502 and socket.gethostbyname(host) in (localhost(), thishost()):
503 urlfile = file
504 if file[:1] == '/':
505 urlfile = 'file://' + file
506 return addinfourl(open(localname, 'rb'),
507 headers, urlfile)
508 raise IOError, ('local file error', 'not on local host')
509
510 def open_ftp(self, url):
511 """Use FTP protocol."""
512 if not isinstance(url, str):
513 raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
514 import mimetypes, mimetools
515 try:
516 from cStringIO import StringIO
517 except ImportError:
518 from StringIO import StringIO
519 host, path = splithost(url)
520 if not host: raise IOError, ('ftp error', 'no host given')
521 host, port = splitport(host)
522 user, host = splituser(host)
523 if user: user, passwd = splitpasswd(user)
524 else: passwd = None
525 host = unquote(host)
526 user = user or ''
527 passwd = passwd or ''
528 host = socket.gethostbyname(host)
529 if not port:
530 import ftplib
531 port = ftplib.FTP_PORT
532 else:
533 port = int(port)
534 path, attrs = splitattr(path)
535 path = unquote(path)
536 dirs = path.split('/')
537 dirs, file = dirs[:-1], dirs[-1]
538 if dirs and not dirs[0]: dirs = dirs[1:]
539 if dirs and not dirs[0]: dirs[0] = '/'
540 key = user, host, port, '/'.join(dirs)
541 # XXX thread unsafe!
542 if len(self.ftpcache) > MAXFTPCACHE:
543 # Prune the cache, rather arbitrarily
544 for k in self.ftpcache.keys():
545 if k != key:
546 v = self.ftpcache[k]
547 del self.ftpcache[k]
548 v.close()
549 try:
550 if not key in self.ftpcache:
551 self.ftpcache[key] = \
552 ftpwrapper(user, passwd, host, port, dirs)
553 if not file: type = 'D'
554 else: type = 'I'
555 for attr in attrs:
556 attr, value = splitvalue(attr)
557 if attr.lower() == 'type' and \
558 value in ('a', 'A', 'i', 'I', 'd', 'D'):
559 type = value.upper()
560 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
561 mtype = mimetypes.guess_type("ftp:" + url)[0]
562 headers = ""
563 if mtype:
564 headers += "Content-Type: %s\n" % mtype
565 if retrlen is not None and retrlen >= 0:
566 headers += "Content-Length: %d\n" % retrlen
567 headers = mimetools.Message(StringIO(headers))
568 return addinfourl(fp, headers, "ftp:" + url)
569 except ftperrors(), msg:
570 raise IOError, ('ftp error', msg), sys.exc_info()[2]
571
572 def open_data(self, url, data=None):
573 """Use "data" URL."""
574 if not isinstance(url, str):
575 raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
576 # ignore POSTed data
577 #
578 # syntax of data URLs:
579 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
580 # mediatype := [ type "/" subtype ] *( ";" parameter )
581 # data := *urlchar
582 # parameter := attribute "=" value
583 import mimetools
584 try:
585 from cStringIO import StringIO
586 except ImportError:
587 from StringIO import StringIO
588 try:
589 [type, data] = url.split(',', 1)
590 except ValueError:
591 raise IOError, ('data error', 'bad data URL')
592 if not type:
593 type = 'text/plain;charset=US-ASCII'
594 semi = type.rfind(';')
595 if semi >= 0 and '=' not in type[semi:]:
596 encoding = type[semi+1:]
597 type = type[:semi]
598 else:
599 encoding = ''
600 msg = []
601 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
602 time.gmtime(time.time())))
603 msg.append('Content-type: %s' % type)
604 if encoding == 'base64':
605 data = base64.decodestring(data)
606 else:
607 data = unquote(data)
608 msg.append('Content-Length: %d' % len(data))
609 msg.append('')
610 msg.append(data)
611 msg = '\n'.join(msg)
612 f = StringIO(msg)
613 headers = mimetools.Message(f, 0)
614 #f.fileno = None # needed for addinfourl
615 return addinfourl(f, headers, url)
616
617
618 class FancyURLopener(URLopener):
619 """Derived class with handlers for errors we can handle (perhaps)."""
620
621 def __init__(self, *args, **kwargs):
622 URLopener.__init__(self, *args, **kwargs)
623 self.auth_cache = {}
624 self.tries = 0
625 self.maxtries = 10
626
627 def http_error_default(self, url, fp, errcode, errmsg, headers):
628 """Default error handling -- don't raise an exception."""
629 return addinfourl(fp, headers, "http:" + url, errcode)
630
631 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
632 """Error 302 -- relocated (temporarily)."""
633 self.tries += 1
634 try:
635 if self.maxtries and self.tries >= self.maxtries:
636 if hasattr(self, "http_error_500"):
637 meth = self.http_error_500
638 else:
639 meth = self.http_error_default
640 return meth(url, fp, 500,
641 "Internal Server Error: Redirect Recursion",
642 headers)
643 result = self.redirect_internal(url, fp, errcode, errmsg,
644 headers, data)
645 return result
646 finally:
647 self.tries = 0
648
649 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
650 if 'location' in headers:
651 newurl = headers['location']
652 elif 'uri' in headers:
653 newurl = headers['uri']
654 else:
655 return
656 fp.close()
657 # In case the server sent a relative URL, join with original:
658 newurl = basejoin(self.type + ":" + url, newurl)
659
660 # For security reasons we do not allow redirects to protocols
661 # other than HTTP, HTTPS or FTP.
662 newurl_lower = newurl.lower()
663 if not (newurl_lower.startswith('http://') or
664 newurl_lower.startswith('https://') or
665 newurl_lower.startswith('ftp://')):
666 raise IOError('redirect error', errcode,
667 errmsg + " - Redirection to url '%s' is not allowed" %
668 newurl,
669 headers)
670
671 return self.open(newurl)
672
673 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
674 """Error 301 -- also relocated (permanently)."""
675 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
676
677 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
678 """Error 303 -- also relocated (essentially identical to 302)."""
679 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
680
681 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
682 """Error 307 -- relocated, but turn POST into error."""
683 if data is None:
684 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
685 else:
686 return self.http_error_default(url, fp, errcode, errmsg, headers)
687
688 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
689 """Error 401 -- authentication required.
690 This function supports Basic authentication only."""
691 if not 'www-authenticate' in headers:
692 URLopener.http_error_default(self, url, fp,
693 errcode, errmsg, headers)
694 stuff = headers['www-authenticate']
695 import re
696 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
697 if not match:
698 URLopener.http_error_default(self, url, fp,
699 errcode, errmsg, headers)
700 scheme, realm = match.groups()
701 if scheme.lower() != 'basic':
702 URLopener.http_error_default(self, url, fp,
703 errcode, errmsg, headers)
704 name = 'retry_' + self.type + '_basic_auth'
705 if data is None:
706 return getattr(self,name)(url, realm)
707 else:
708 return getattr(self,name)(url, realm, data)
709
710 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
711 """Error 407 -- proxy authentication required.
712 This function supports Basic authentication only."""
713 if not 'proxy-authenticate' in headers:
714 URLopener.http_error_default(self, url, fp,
715 errcode, errmsg, headers)
716 stuff = headers['proxy-authenticate']
717 import re
718 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
719 if not match:
720 URLopener.http_error_default(self, url, fp,
721 errcode, errmsg, headers)
722 scheme, realm = match.groups()
723 if scheme.lower() != 'basic':
724 URLopener.http_error_default(self, url, fp,
725 errcode, errmsg, headers)
726 name = 'retry_proxy_' + self.type + '_basic_auth'
727 if data is None:
728 return getattr(self,name)(url, realm)
729 else:
730 return getattr(self,name)(url, realm, data)
731
732 def retry_proxy_http_basic_auth(self, url, realm, data=None):
733 host, selector = splithost(url)
734 newurl = 'http://' + host + selector
735 proxy = self.proxies['http']
736 urltype, proxyhost = splittype(proxy)
737 proxyhost, proxyselector = splithost(proxyhost)
738 i = proxyhost.find('@') + 1
739 proxyhost = proxyhost[i:]
740 user, passwd = self.get_user_passwd(proxyhost, realm, i)
741 if not (user or passwd): return None
742 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
743 self.proxies['http'] = 'http://' + proxyhost + proxyselector
744 if data is None:
745 return self.open(newurl)
746 else:
747 return self.open(newurl, data)
748
749 def retry_proxy_https_basic_auth(self, url, realm, data=None):
750 host, selector = splithost(url)
751 newurl = 'https://' + host + selector
752 proxy = self.proxies['https']
753 urltype, proxyhost = splittype(proxy)
754 proxyhost, proxyselector = splithost(proxyhost)
755 i = proxyhost.find('@') + 1
756 proxyhost = proxyhost[i:]
757 user, passwd = self.get_user_passwd(proxyhost, realm, i)
758 if not (user or passwd): return None
759 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
760 self.proxies['https'] = 'https://' + proxyhost + proxyselector
761 if data is None:
762 return self.open(newurl)
763 else:
764 return self.open(newurl, data)
765
766 def retry_http_basic_auth(self, url, realm, data=None):
767 host, selector = splithost(url)
768 i = host.find('@') + 1
769 host = host[i:]
770 user, passwd = self.get_user_passwd(host, realm, i)
771 if not (user or passwd): return None
772 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
773 newurl = 'http://' + host + selector
774 if data is None:
775 return self.open(newurl)
776 else:
777 return self.open(newurl, data)
778
779 def retry_https_basic_auth(self, url, realm, data=None):
780 host, selector = splithost(url)
781 i = host.find('@') + 1
782 host = host[i:]
783 user, passwd = self.get_user_passwd(host, realm, i)
784 if not (user or passwd): return None
785 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
786 newurl = 'https://' + host + selector
787 if data is None:
788 return self.open(newurl)
789 else:
790 return self.open(newurl, data)
791
792 def get_user_passwd(self, host, realm, clear_cache=0):
793 key = realm + '@' + host.lower()
794 if key in self.auth_cache:
795 if clear_cache:
796 del self.auth_cache[key]
797 else:
798 return self.auth_cache[key]
799 user, passwd = self.prompt_user_passwd(host, realm)
800 if user or passwd: self.auth_cache[key] = (user, passwd)
801 return user, passwd
802
803 def prompt_user_passwd(self, host, realm):
804 """Override this in a GUI environment!"""
805 import getpass
806 try:
807 user = raw_input("Enter username for %s at %s: " % (realm,
808 host))
809 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
810 (user, realm, host))
811 return user, passwd
812 except KeyboardInterrupt:
813 print
814 return None, None
815
816
817 # Utility functions
818
819 _localhost = None
820 def localhost():
821 """Return the IP address of the magic hostname 'localhost'."""
822 global _localhost
823 if _localhost is None:
824 _localhost = socket.gethostbyname('localhost')
825 return _localhost
826
827 _thishost = None
828 def thishost():
829 """Return the IP address of the current host."""
830 global _thishost
831 if _thishost is None:
832 try:
833 _thishost = socket.gethostbyname(socket.gethostname())
834 except socket.gaierror:
835 _thishost = socket.gethostbyname('localhost')
836 return _thishost
837
838 _ftperrors = None
839 def ftperrors():
840 """Return the set of errors raised by the FTP class."""
841 global _ftperrors
842 if _ftperrors is None:
843 import ftplib
844 _ftperrors = ftplib.all_errors
845 return _ftperrors
846
847 _noheaders = None
848 def noheaders():
849 """Return an empty mimetools.Message object."""
850 global _noheaders
851 if _noheaders is None:
852 import mimetools
853 try:
854 from cStringIO import StringIO
855 except ImportError:
856 from StringIO import StringIO
857 _noheaders = mimetools.Message(StringIO(), 0)
858 _noheaders.fp.close() # Recycle file descriptor
859 return _noheaders
860
861
862 # Utility classes
863
864 class ftpwrapper:
865 """Class used by open_ftp() for cache of open FTP connections."""
866
867 def __init__(self, user, passwd, host, port, dirs,
868 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
869 persistent=True):
870 self.user = user
871 self.passwd = passwd
872 self.host = host
873 self.port = port
874 self.dirs = dirs
875 self.timeout = timeout
876 self.refcount = 0
877 self.keepalive = persistent
878 try:
879 self.init()
880 except:
881 self.close()
882 raise
883
884 def init(self):
885 import ftplib
886 self.busy = 0
887 self.ftp = ftplib.FTP()
888 self.ftp.connect(self.host, self.port, self.timeout)
889 self.ftp.login(self.user, self.passwd)
890 _target = '/'.join(self.dirs)
891 self.ftp.cwd(_target)
892
893 def retrfile(self, file, type):
894 import ftplib
895 self.endtransfer()
896 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
897 else: cmd = 'TYPE ' + type; isdir = 0
898 try:
899 self.ftp.voidcmd(cmd)
900 except ftplib.all_errors:
901 self.init()
902 self.ftp.voidcmd(cmd)
903 conn = None
904 if file and not isdir:
905 # Try to retrieve as a file
906 try:
907 cmd = 'RETR ' + file
908 conn, retrlen = self.ftp.ntransfercmd(cmd)
909 except ftplib.error_perm, reason:
910 if str(reason)[:3] != '550':
911 raise IOError, ('ftp error', reason), sys.exc_info()[2]
912 if not conn:
913 # Set transfer mode to ASCII!
914 self.ftp.voidcmd('TYPE A')
915 # Try a directory listing. Verify that directory exists.
916 if file:
917 pwd = self.ftp.pwd()
918 try:
919 try:
920 self.ftp.cwd(file)
921 except ftplib.error_perm, reason:
922 raise IOError, ('ftp error', reason), sys.exc_info()[2]
923 finally:
924 self.ftp.cwd(pwd)
925 cmd = 'LIST ' + file
926 else:
927 cmd = 'LIST'
928 conn, retrlen = self.ftp.ntransfercmd(cmd)
929 self.busy = 1
930 ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
931 self.refcount += 1
932 conn.close()
933 # Pass back both a suitably decorated object and a retrieval length
934 return (ftpobj, retrlen)
935
936 def endtransfer(self):
937 if not self.busy:
938 return
939 self.busy = 0
940 try:
941 self.ftp.voidresp()
942 except ftperrors():
943 pass
944
945 def close(self):
946 self.keepalive = False
947 if self.refcount <= 0:
948 self.real_close()
949
950 def file_close(self):
951 self.endtransfer()
952 self.refcount -= 1
953 if self.refcount <= 0 and not self.keepalive:
954 self.real_close()
955
956 def real_close(self):
957 self.endtransfer()
958 try:
959 self.ftp.close()
960 except ftperrors():
961 pass
962
963 class addbase:
964 """Base class for addinfo and addclosehook."""
965
966 def __init__(self, fp):
967 self.fp = fp
968 self.read = self.fp.read
969 self.readline = self.fp.readline
970 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
971 if hasattr(self.fp, "fileno"):
972 self.fileno = self.fp.fileno
973 else:
974 self.fileno = lambda: None
975 if hasattr(self.fp, "__iter__"):
976 self.__iter__ = self.fp.__iter__
977 if hasattr(self.fp, "next"):
978 self.next = self.fp.next
979
980 def __repr__(self):
981 return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
982 id(self), self.fp)
983
984 def close(self):
985 self.read = None
986 self.readline = None
987 self.readlines = None
988 self.fileno = None
989 if self.fp: self.fp.close()
990 self.fp = None
991
992 class addclosehook(addbase):
993 """Class to add a close hook to an open file."""
994
995 def __init__(self, fp, closehook, *hookargs):
996 addbase.__init__(self, fp)
997 self.closehook = closehook
998 self.hookargs = hookargs
999
1000 def close(self):
1001 try:
1002 closehook = self.closehook
1003 hookargs = self.hookargs
1004 if closehook:
1005 self.closehook = None
1006 self.hookargs = None
1007 closehook(*hookargs)
1008 finally:
1009 addbase.close(self)
1010
1011
1012 class addinfo(addbase):
1013 """class to add an info() method to an open file."""
1014
1015 def __init__(self, fp, headers):
1016 addbase.__init__(self, fp)
1017 self.headers = headers
1018
1019 def info(self):
1020 return self.headers
1021
1022 class addinfourl(addbase):
1023 """class to add info() and geturl() methods to an open file."""
1024
1025 def __init__(self, fp, headers, url, code=None):
1026 addbase.__init__(self, fp)
1027 self.headers = headers
1028 self.url = url
1029 self.code = code
1030
1031 def info(self):
1032 return self.headers
1033
1034 def getcode(self):
1035 return self.code
1036
1037 def geturl(self):
1038 return self.url
1039
1040
1041 # Utilities to parse URLs (most of these return None for missing parts):
1042 # unwrap('<URL:type://host/path>') --> 'type://host/path'
1043 # splittype('type:opaquestring') --> 'type', 'opaquestring'
1044 # splithost('//host[:port]/path') --> 'host[:port]', '/path'
1045 # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
1046 # splitpasswd('user:passwd') -> 'user', 'passwd'
1047 # splitport('host:port') --> 'host', 'port'
1048 # splitquery('/path?query') --> '/path', 'query'
1049 # splittag('/path#tag') --> '/path', 'tag'
1050 # splitattr('/path;attr1=value1;attr2=value2;...') ->
1051 # '/path', ['attr1=value1', 'attr2=value2', ...]
1052 # splitvalue('attr=value') --> 'attr', 'value'
1053 # unquote('abc%20def') -> 'abc def'
1054 # quote('abc def') -> 'abc%20def')
1055
1056 try:
1057 unicode
1058 except NameError:
1059 def _is_unicode(x):
1060 return 0
1061 else:
1062 def _is_unicode(x):
1063 return isinstance(x, unicode)
1064
1065 def toBytes(url):
1066 """toBytes(u"URL") --> 'URL'."""
1067 # Most URL schemes require ASCII. If that changes, the conversion
1068 # can be relaxed
1069 if _is_unicode(url):
1070 try:
1071 url = url.encode("ASCII")
1072 except UnicodeError:
1073 raise UnicodeError("URL " + repr(url) +
1074 " contains non-ASCII characters")
1075 return url
1076
1077 def unwrap(url):
1078 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
1079 url = url.strip()
1080 if url[:1] == '<' and url[-1:] == '>':
1081 url = url[1:-1].strip()
1082 if url[:4] == 'URL:': url = url[4:].strip()
1083 return url
1084
1085 _typeprog = None
1086 def splittype(url):
1087 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
1088 global _typeprog
1089 if _typeprog is None:
1090 import re
1091 _typeprog = re.compile('^([^/:]+):')
1092
1093 match = _typeprog.match(url)
1094 if match:
1095 scheme = match.group(1)
1096 return scheme.lower(), url[len(scheme) + 1:]
1097 return None, url
1098
1099 _hostprog = None
1100 def splithost(url):
1101 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
1102 global _hostprog
1103 if _hostprog is None:
1104 _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
1105
1106 match = _hostprog.match(url)
1107 if match:
1108 host_port = match.group(1)
1109 path = match.group(2)
1110 if path and not path.startswith('/'):
1111 path = '/' + path
1112 return host_port, path
1113 return None, url
1114
1115 _userprog = None
1116 def splituser(host):
1117 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
1118 global _userprog
1119 if _userprog is None:
1120 import re
1121 _userprog = re.compile('^(.*)@(.*)$')
1122
1123 match = _userprog.match(host)
1124 if match: return match.group(1, 2)
1125 return None, host
1126
1127 _passwdprog = None
1128 def splitpasswd(user):
1129 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
1130 global _passwdprog
1131 if _passwdprog is None:
1132 import re
1133 _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
1134
1135 match = _passwdprog.match(user)
1136 if match: return match.group(1, 2)
1137 return user, None
1138
1139 # splittag('/path#tag') --> '/path', 'tag'
1140 _portprog = None
1141 def splitport(host):
1142 """splitport('host:port') --> 'host', 'port'."""
1143 global _portprog
1144 if _portprog is None:
1145 import re
1146 _portprog = re.compile('^(.*):([0-9]*)$')
1147
1148 match = _portprog.match(host)
1149 if match:
1150 host, port = match.groups()
1151 if port:
1152 return host, port
1153 return host, None
1154
1155 _nportprog = None
1156 def splitnport(host, defport=-1):
1157 """Split host and port, returning numeric port.
1158 Return given default port if no ':' found; defaults to -1.
1159 Return numerical port if a valid number are found after ':'.
1160 Return None if ':' but not a valid number."""
1161 global _nportprog
1162 if _nportprog is None:
1163 import re
1164 _nportprog = re.compile('^(.*):(.*)$')
1165
1166 match = _nportprog.match(host)
1167 if match:
1168 host, port = match.group(1, 2)
1169 if port:
1170 try:
1171 nport = int(port)
1172 except ValueError:
1173 nport = None
1174 return host, nport
1175 return host, defport
1176
1177 _queryprog = None
1178 def splitquery(url):
1179 """splitquery('/path?query') --> '/path', 'query'."""
1180 global _queryprog
1181 if _queryprog is None:
1182 import re
1183 _queryprog = re.compile('^(.*)\?([^?]*)$')
1184
1185 match = _queryprog.match(url)
1186 if match: return match.group(1, 2)
1187 return url, None
1188
1189 _tagprog = None
1190 def splittag(url):
1191 """splittag('/path#tag') --> '/path', 'tag'."""
1192 global _tagprog
1193 if _tagprog is None:
1194 import re
1195 _tagprog = re.compile('^(.*)#([^#]*)$')
1196
1197 match = _tagprog.match(url)
1198 if match: return match.group(1, 2)
1199 return url, None
1200
1201 def splitattr(url):
1202 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1203 '/path', ['attr1=value1', 'attr2=value2', ...]."""
1204 words = url.split(';')
1205 return words[0], words[1:]
1206
1207 _valueprog = None
1208 def splitvalue(attr):
1209 """splitvalue('attr=value') --> 'attr', 'value'."""
1210 global _valueprog
1211 if _valueprog is None:
1212 import re
1213 _valueprog = re.compile('^([^=]*)=(.*)$')
1214
1215 match = _valueprog.match(attr)
1216 if match: return match.group(1, 2)
1217 return attr, None
1218
1219 # urlparse contains a duplicate of this method to avoid a circular import. If
1220 # you update this method, also update the copy in urlparse. This code
1221 # duplication does not exist in Python3.
1222
1223 _hexdig = '0123456789ABCDEFabcdef'
1224 _hextochr = dict((a + b, chr(int(a + b, 16)))
1225 for a in _hexdig for b in _hexdig)
1226 _asciire = re.compile('([\x00-\x7f]+)')
1227
1228 def unquote(s):
1229 """unquote('abc%20def') -> 'abc def'."""
1230 if _is_unicode(s):
1231 if '%' not in s:
1232 return s
1233 bits = _asciire.split(s)
1234 res = [bits[0]]
1235 append = res.append
1236 for i in range(1, len(bits), 2):
1237 append(unquote(str(bits[i])).decode('latin1'))
1238 append(bits[i + 1])
1239 return ''.join(res)
1240
1241 bits = s.split('%')
1242 # fastpath
1243 if len(bits) == 1:
1244 return s
1245 res = [bits[0]]
1246 append = res.append
1247 for item in bits[1:]:
1248 try:
1249 append(_hextochr[item[:2]])
1250 append(item[2:])
1251 except KeyError:
1252 append('%')
1253 append(item)
1254 return ''.join(res)
1255
1256 def unquote_plus(s):
1257 """unquote('%7e/abc+def') -> '~/abc def'"""
1258 s = s.replace('+', ' ')
1259 return unquote(s)
1260
1261 always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1262 'abcdefghijklmnopqrstuvwxyz'
1263 '0123456789' '_.-')
1264 _safe_map = {}
1265 for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
1266 _safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i)
1267 _safe_quoters = {}
1268
1269 def quote(s, safe='/'):
1270 """quote('abc def') -> 'abc%20def'
1271
1272 Each part of a URL, e.g. the path info, the query, etc., has a
1273 different set of reserved characters that must be quoted.
1274
1275 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
1276 the following reserved characters.
1277
1278 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
1279 "$" | ","
1280
1281 Each of these characters is reserved in some component of a URL,
1282 but not necessarily in all of them.
1283
1284 By default, the quote function is intended for quoting the path
1285 section of a URL. Thus, it will not encode '/'. This character
1286 is reserved, but in typical usage the quote function is being
1287 called on a path where the existing slash characters are used as
1288 reserved characters.
1289 """
1290 # fastpath
1291 if not s:
1292 if s is None:
1293 raise TypeError('None object cannot be quoted')
1294 return s
1295 cachekey = (safe, always_safe)
1296 try:
1297 (quoter, safe) = _safe_quoters[cachekey]
1298 except KeyError:
1299 safe_map = _safe_map.copy()
1300 safe_map.update([(c, c) for c in safe])
1301 quoter = safe_map.__getitem__
1302 safe = always_safe + safe
1303 _safe_quoters[cachekey] = (quoter, safe)
1304 if not s.rstrip(safe):
1305 return s
1306 return ''.join(map(quoter, s))
1307
1308 def quote_plus(s, safe=''):
1309 """Quote the query fragment of a URL; replacing ' ' with '+'"""
1310 if ' ' in s:
1311 s = quote(s, safe + ' ')
1312 return s.replace(' ', '+')
1313 return quote(s, safe)
1314
1315 def urlencode(query, doseq=0):
1316 """Encode a sequence of two-element tuples or dictionary into a URL query string.
1317
1318 If any values in the query arg are sequences and doseq is true, each
1319 sequence element is converted to a separate parameter.
1320
1321 If the query arg is a sequence of two-element tuples, the order of the
1322 parameters in the output will match the order of parameters in the
1323 input.
1324 """
1325
1326 if hasattr(query,"items"):
1327 # mapping objects
1328 query = query.items()
1329 else:
1330 # it's a bother at times that strings and string-like objects are
1331 # sequences...
1332 try:
1333 # non-sequence items should not work with len()
1334 # non-empty strings will fail this
1335 if len(query) and not isinstance(query[0], tuple):
1336 raise TypeError
1337 # zero-length sequences of all types will get here and succeed,
1338 # but that's a minor nit - since the original implementation
1339 # allowed empty dicts that type of behavior probably should be
1340 # preserved for consistency
1341 except TypeError:
1342 ty,va,tb = sys.exc_info()
1343 raise TypeError, "not a valid non-string sequence or mapping object", tb
1344
1345 l = []
1346 if not doseq:
1347 # preserve old behavior
1348 for k, v in query:
1349 k = quote_plus(str(k))
1350 v = quote_plus(str(v))
1351 l.append(k + '=' + v)
1352 else:
1353 for k, v in query:
1354 k = quote_plus(str(k))
1355 if isinstance(v, str):
1356 v = quote_plus(v)
1357 l.append(k + '=' + v)
1358 elif _is_unicode(v):
1359 # is there a reasonable way to convert to ASCII?
1360 # encode generates a string, but "replace" or "ignore"
1361 # lose information and "strict" can raise UnicodeError
1362 v = quote_plus(v.encode("ASCII","replace"))
1363 l.append(k + '=' + v)
1364 else:
1365 try:
1366 # is this a sufficient test for sequence-ness?
1367 len(v)
1368 except TypeError:
1369 # not a sequence
1370 v = quote_plus(str(v))
1371 l.append(k + '=' + v)
1372 else:
1373 # loop over the sequence
1374 for elt in v:
1375 l.append(k + '=' + quote_plus(str(elt)))
1376 return '&'.join(l)
1377
1378 # Proxy handling
1379 def getproxies_environment():
1380 """Return a dictionary of scheme -> proxy server URL mappings.
1381
1382 Scan the environment for variables named <scheme>_proxy;
1383 this seems to be the standard convention. In order to prefer lowercase
1384 variables, we process the environment in two passes, first matches any
1385 and second matches only lower case proxies.
1386
1387 If you need a different way, you can pass a proxies dictionary to the
1388 [Fancy]URLopener constructor.
1389 """
1390 # Get all variables
1391 proxies = {}
1392 for name, value in os.environ.items():
1393 name = name.lower()
1394 if value and name[-6:] == '_proxy':
1395 proxies[name[:-6]] = value
1396
1397 # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY
1398 # (non-all-lowercase) as it may be set from the web server by a "Proxy:"
1399 # header from the client
1400 # If "proxy" is lowercase, it will still be used thanks to the next block
1401 if 'REQUEST_METHOD' in os.environ:
1402 proxies.pop('http', None)
1403
1404 # Get lowercase variables
1405 for name, value in os.environ.items():
1406 if name[-6:] == '_proxy':
1407 name = name.lower()
1408 if value:
1409 proxies[name[:-6]] = value
1410 else:
1411 proxies.pop(name[:-6], None)
1412
1413 return proxies
1414
1415 def proxy_bypass_environment(host, proxies=None):
1416 """Test if proxies should not be used for a particular host.
1417
1418 Checks the proxies dict for the value of no_proxy, which should be a
1419 list of comma separated DNS suffixes, or '*' for all hosts.
1420 """
1421 if proxies is None:
1422 proxies = getproxies_environment()
1423 # don't bypass, if no_proxy isn't specified
1424 try:
1425 no_proxy = proxies['no']
1426 except KeyError:
1427 return 0
1428 # '*' is special case for always bypass
1429 if no_proxy == '*':
1430 return 1
1431 # strip port off host
1432 hostonly, port = splitport(host)
1433 # check if the host ends with any of the DNS suffixes
1434 no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
1435 for name in no_proxy_list:
1436 if name:
1437 name = name.lstrip('.') # ignore leading dots
1438 name = re.escape(name)
1439 pattern = r'(.+\.)?%s$' % name
1440 if (re.match(pattern, hostonly, re.I)
1441 or re.match(pattern, host, re.I)):
1442 return 1
1443 # otherwise, don't bypass
1444 return 0
1445
1446
1447 if sys.platform == 'darwin':
1448 from _scproxy import _get_proxy_settings, _get_proxies
1449
1450 def proxy_bypass_macosx_sysconf(host):
1451 """
1452 Return True iff this host shouldn't be accessed using a proxy
1453
1454 This function uses the MacOSX framework SystemConfiguration
1455 to fetch the proxy information.
1456 """
1457 import re
1458 import socket
1459 from fnmatch import fnmatch
1460
1461 hostonly, port = splitport(host)
1462
1463 def ip2num(ipAddr):
1464 parts = ipAddr.split('.')
1465 parts = map(int, parts)
1466 if len(parts) != 4:
1467 parts = (parts + [0, 0, 0, 0])[:4]
1468 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
1469
1470 proxy_settings = _get_proxy_settings()
1471
1472 # Check for simple host names:
1473 if '.' not in host:
1474 if proxy_settings['exclude_simple']:
1475 return True
1476
1477 hostIP = None
1478
1479 for value in proxy_settings.get('exceptions', ()):
1480 # Items in the list are strings like these: *.local, 169.254/16
1481 if not value: continue
1482
1483 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
1484 if m is not None:
1485 if hostIP is None:
1486 try:
1487 hostIP = socket.gethostbyname(hostonly)
1488 hostIP = ip2num(hostIP)
1489 except socket.error:
1490 continue
1491
1492 base = ip2num(m.group(1))
1493 mask = m.group(2)
1494 if mask is None:
1495 mask = 8 * (m.group(1).count('.') + 1)
1496
1497 else:
1498 mask = int(mask[1:])
1499 mask = 32 - mask
1500
1501 if (hostIP >> mask) == (base >> mask):
1502 return True
1503
1504 elif fnmatch(host, value):
1505 return True
1506
1507 return False
1508
1509 def getproxies_macosx_sysconf():
1510 """Return a dictionary of scheme -> proxy server URL mappings.
1511
1512 This function uses the MacOSX framework SystemConfiguration
1513 to fetch the proxy information.
1514 """
1515 return _get_proxies()
1516
1517 def proxy_bypass(host):
1518 """Return True, if a host should be bypassed.
1519
1520 Checks proxy settings gathered from the environment, if specified, or
1521 from the MacOSX framework SystemConfiguration.
1522 """
1523 proxies = getproxies_environment()
1524 if proxies:
1525 return proxy_bypass_environment(host, proxies)
1526 else:
1527 return proxy_bypass_macosx_sysconf(host)
1528
1529 def getproxies():
1530 return getproxies_environment() or getproxies_macosx_sysconf()
1531
1532 elif os.name == 'nt':
1533 def getproxies_registry():
1534 """Return a dictionary of scheme -> proxy server URL mappings.
1535
1536 Win32 uses the registry to store proxies.
1537
1538 """
1539 proxies = {}
1540 try:
1541 import _winreg
1542 except ImportError:
1543 # Std module, so should be around - but you never know!
1544 return proxies
1545 try:
1546 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1547 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
1548 proxyEnable = _winreg.QueryValueEx(internetSettings,
1549 'ProxyEnable')[0]
1550 if proxyEnable:
1551 # Returned as Unicode but problems if not converted to ASCII
1552 proxyServer = str(_winreg.QueryValueEx(internetSettings,
1553 'ProxyServer')[0])
1554 if '=' in proxyServer:
1555 # Per-protocol settings
1556 for p in proxyServer.split(';'):
1557 protocol, address = p.split('=', 1)
1558 # See if address has a type:// prefix
1559 import re
1560 if not re.match('^([^/:]+)://', address):
1561 address = '%s://%s' % (protocol, address)
1562 proxies[protocol] = address
1563 else:
1564 # Use one setting for all protocols
1565 if proxyServer[:5] == 'http:':
1566 proxies['http'] = proxyServer
1567 else:
1568 proxies['http'] = 'http://%s' % proxyServer
1569 proxies['https'] = 'https://%s' % proxyServer
1570 proxies['ftp'] = 'ftp://%s' % proxyServer
1571 internetSettings.Close()
1572 except (WindowsError, ValueError, TypeError):
1573 # Either registry key not found etc, or the value in an
1574 # unexpected format.
1575 # proxies already set up to be empty so nothing to do
1576 pass
1577 return proxies
1578
1579 def getproxies():
1580 """Return a dictionary of scheme -> proxy server URL mappings.
1581
1582 Returns settings gathered from the environment, if specified,
1583 or the registry.
1584
1585 """
1586 return getproxies_environment() or getproxies_registry()
1587
1588 def proxy_bypass_registry(host):
1589 try:
1590 import _winreg
1591 import re
1592 except ImportError:
1593 # Std modules, so should be around - but you never know!
1594 return 0
1595 try:
1596 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1597 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
1598 proxyEnable = _winreg.QueryValueEx(internetSettings,
1599 'ProxyEnable')[0]
1600 proxyOverride = str(_winreg.QueryValueEx(internetSettings,
1601 'ProxyOverride')[0])
1602 # ^^^^ Returned as Unicode but problems if not converted to ASCII
1603 except WindowsError:
1604 return 0
1605 if not proxyEnable or not proxyOverride:
1606 return 0
1607 # try to make a host list from name and IP address.
1608 rawHost, port = splitport(host)
1609 host = [rawHost]
1610 try:
1611 addr = socket.gethostbyname(rawHost)
1612 if addr != rawHost:
1613 host.append(addr)
1614 except socket.error:
1615 pass
1616 try:
1617 fqdn = socket.getfqdn(rawHost)
1618 if fqdn != rawHost:
1619 host.append(fqdn)
1620 except socket.error:
1621 pass
1622 # make a check value list from the registry entry: replace the
1623 # '<local>' string by the localhost entry and the corresponding
1624 # canonical entry.
1625 proxyOverride = proxyOverride.split(';')
1626 # now check if we match one of the registry values.
1627 for test in proxyOverride:
1628 if test == '<local>':
1629 if '.' not in rawHost:
1630 return 1
1631 test = test.replace(".", r"\.") # mask dots
1632 test = test.replace("*", r".*") # change glob sequence
1633 test = test.replace("?", r".") # change glob char
1634 for val in host:
1635 # print "%s <--> %s" %( test, val )
1636 if re.match(test, val, re.I):
1637 return 1
1638 return 0
1639
1640 def proxy_bypass(host):
1641 """Return True, if the host should be bypassed.
1642
1643 Checks proxy settings gathered from the environment, if specified,
1644 or the registry.
1645 """
1646 proxies = getproxies_environment()
1647 if proxies:
1648 return proxy_bypass_environment(host, proxies)
1649 else:
1650 return proxy_bypass_registry(host)
1651
1652 else:
1653 # By default use environment variables
1654 getproxies = getproxies_environment
1655 proxy_bypass = proxy_bypass_environment
1656
1657 # Test and time quote() and unquote()
1658 def test1():
1659 s = ''
1660 for i in range(256): s = s + chr(i)
1661 s = s*4
1662 t0 = time.time()
1663 qs = quote(s)
1664 uqs = unquote(qs)
1665 t1 = time.time()
1666 if uqs != s:
1667 print 'Wrong!'
1668 print repr(s)
1669 print repr(qs)
1670 print repr(uqs)
1671 print round(t1 - t0, 3), 'sec'
1672
1673
1674 def reporthook(blocknum, blocksize, totalsize):
1675 # Report during remote transfers
1676 print "Block number: %d, Block size: %d, Total size: %d" % (
1677 blocknum, blocksize, totalsize)