blob: 6d17e6ff23a02071a8d80456e519b38ba1bddb2c [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Open an arbitrary URL.
2
3See the following document for more info on URLs:
4"Names and Addresses, URIs, URLs, URNs, URCs", at
5http://www.w3.org/pub/WWW/Addressing/Overview.html
6
7See also the HTTP spec (from which the error codes are derived):
8"HTTP - Hypertext Transfer Protocol", at
9http://www.w3.org/pub/WWW/Protocols/
10
11Related 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
16The object returned by URLopener().open(file) will differ per
17protocol. All you know is that is has methods read(), readline(),
18readlines(), fileno(), close() and info(). The read*(), fileno()
Fredrik Lundhb49f88b2000-09-24 18:51:25 +000019and close() methods work like those of open files.
Guido van Rossume7b146f2000-02-04 15:28:42 +000020The info() method returns a mimetools.Message object which can be
21used to query various info about the object, if available.
22(mimetools.Message objects are queried with the getheader() method.)
23"""
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000024
Guido van Rossum7c395db1994-07-04 22:14:49 +000025import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000026import socket
Jack Jansendc3e3f61995-12-15 13:22:13 +000027import os
Guido van Rossumf0713d32001-08-09 17:43:35 +000028import time
Guido van Rossum3c8484e1996-11-20 22:02:24 +000029import sys
Senthil Kumaranbcd833f2012-01-11 00:09:24 +080030import base64
Serhiy Storchaka923baea2013-03-14 21:31:09 +020031import re
Senthil Kumaranbcd833f2012-01-11 00:09:24 +080032
Brett Cannon69200fa2004-03-23 21:26:39 +000033from urlparse import urljoin as basejoin
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000034
Skip Montanaro40fc1602001-03-01 04:27:19 +000035__all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
36 "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
Skip Montanaro44d5e0c2001-03-13 19:47:16 +000037 "urlencode", "url2pathname", "pathname2url", "splittag",
38 "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
39 "splittype", "splithost", "splituser", "splitpasswd", "splitport",
40 "splitnport", "splitquery", "splitattr", "splitvalue",
Brett Cannond75f0432007-05-16 22:42:29 +000041 "getproxies"]
Skip Montanaro40fc1602001-03-01 04:27:19 +000042
Martin v. Löwis3e865952006-01-24 15:51:21 +000043__version__ = '1.17' # XXX This version is not always updated :-(
Guido van Rossumf668d171997-06-06 21:11:11 +000044
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000045MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000046
Jack Jansendc3e3f61995-12-15 13:22:13 +000047# Helper for non-unix systems
Ronald Oussoren9545a232010-05-05 19:09:31 +000048if os.name == 'nt':
Fredrik Lundhb49f88b2000-09-24 18:51:25 +000049 from nturl2path import url2pathname, pathname2url
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000050elif os.name == 'riscos':
51 from rourl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000052else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000053 def url2pathname(pathname):
Georg Brandlc0b24732005-12-26 22:53:56 +000054 """OS-specific conversion from a relative URL of the 'file' scheme
55 to a file system path; not recommended for general use."""
Guido van Rossum367ac801999-03-12 14:31:10 +000056 return unquote(pathname)
Georg Brandlc0b24732005-12-26 22:53:56 +000057
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000058 def pathname2url(pathname):
Georg Brandlc0b24732005-12-26 22:53:56 +000059 """OS-specific conversion from a file system path to a relative URL
60 of the 'file' scheme; not recommended for general use."""
Guido van Rossum367ac801999-03-12 14:31:10 +000061 return quote(pathname)
Guido van Rossum33add0a1998-12-18 15:25:22 +000062
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000063# 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
Benjamin Petersonb2064732014-11-23 20:55:24 -060072def urlopen(url, data=None, proxies=None, context=None):
Brett Cannon8bb8fa52008-07-02 01:57:08 +000073 """Create a file-like object for the specified URL to read from."""
74 from warnings import warnpy3k
Georg Brandl48e65f52010-02-06 22:44:17 +000075 warnpy3k("urllib.urlopen() has been removed in Python 3.0 in "
76 "favor of urllib2.urlopen()", stacklevel=2)
Brett Cannon8bb8fa52008-07-02 01:57:08 +000077
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000078 global _urlopener
Benjamin Petersonb2064732014-11-23 20:55:24 -060079 if proxies is not None or context is not None:
80 opener = FancyURLopener(proxies=proxies, context=context)
Fred Drakedf6eca72002-04-04 20:41:34 +000081 elif not _urlopener:
82 opener = FancyURLopener()
83 _urlopener = opener
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000084 else:
Fred Drakedf6eca72002-04-04 20:41:34 +000085 opener = _urlopener
86 if data is None:
87 return opener.open(url)
88 else:
89 return opener.open(url, data)
Benjamin Petersonb2064732014-11-23 20:55:24 -060090def urlretrieve(url, filename=None, reporthook=None, data=None, context=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000091 global _urlopener
Benjamin Petersonb2064732014-11-23 20:55:24 -060092 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)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000099def urlcleanup():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000100 if _urlopener:
101 _urlopener.cleanup()
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +0000102 _safe_quoters.clear()
Antoine Pitrouca173e22009-12-08 19:35:12 +0000103 ftpcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000104
Bill Janssen426ea0a2007-08-29 22:35:05 +0000105# check for SSL
106try:
107 import ssl
108except:
109 _have_ssl = False
110else:
111 _have_ssl = True
112
Georg Brandlb9256022005-08-24 18:46:39 +0000113# exception raised when downloaded size does not match content-length
114class ContentTooShortError(IOError):
115 def __init__(self, message, content):
116 IOError.__init__(self, message)
117 self.content = content
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000118
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000119ftpcache = {}
120class URLopener:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000121 """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)."""
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000127
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000128 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +0000129
Guido van Rossumba311382000-08-24 16:18:04 +0000130 version = "Python-urllib/%s" % __version__
131
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000132 # Constructor
Benjamin Petersonb2064732014-11-23 20:55:24 -0600133 def __init__(self, proxies=None, context=None, **x509):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000134 if proxies is None:
135 proxies = getproxies()
136 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
137 self.proxies = proxies
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000138 self.key_file = x509.get('key_file')
139 self.cert_file = x509.get('cert_file')
Benjamin Petersonb2064732014-11-23 20:55:24 -0600140 self.context = context
Georg Brandl0619a322006-07-26 07:40:17 +0000141 self.addheaders = [('User-Agent', self.version)]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000142 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.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000156
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000157 def __del__(self):
158 self.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000159
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000160 def close(self):
161 self.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000162
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000163 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)
Martin v. Löwis58682b72001-08-11 15:02:57 +0000171 except OSError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000172 pass
173 del self.__tempfiles[:]
174 if self.tempcache:
175 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000176
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000177 def addheader(self, *args):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000178 """Add a header to be used by the HTTP interface only
179 e.g. u.addheader('Accept', 'sound/basic')"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000180 self.addheaders.append(args)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000181
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000182 # External interface
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000183 def open(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000184 """Use URLopener().open(file) instead of open(file, 'r')."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000185 fullurl = unwrap(toBytes(fullurl))
Senthil Kumaran7c2867f2009-04-21 03:24:19 +0000186 # percent encode url, fixing lame server errors for e.g, like space
187 # within url paths.
Senthil Kumaran18d5a692010-02-20 22:05:34 +0000188 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000189 if self.tempcache and fullurl in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000190 filename, headers = self.tempcache[fullurl]
191 fp = open(filename, 'rb')
192 return addinfourl(fp, headers, fullurl)
Martin v. Löwis1d994332000-12-03 18:30:10 +0000193 urltype, url = splittype(fullurl)
194 if not urltype:
195 urltype = 'file'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000196 if urltype in self.proxies:
Martin v. Löwis1d994332000-12-03 18:30:10 +0000197 proxy = self.proxies[urltype]
198 urltype, proxyhost = splittype(proxy)
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000199 host, selector = splithost(proxyhost)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000200 url = (host, fullurl) # Signal special case to open_*()
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000201 else:
202 proxy = None
Martin v. Löwis1d994332000-12-03 18:30:10 +0000203 name = 'open_' + urltype
204 self.type = urltype
Brett Cannonaaeffaf2004-03-23 23:50:17 +0000205 name = name.replace('-', '_')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000206 if not hasattr(self, name):
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000207 if proxy:
208 return self.open_unknown_proxy(proxy, fullurl, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000209 else:
210 return self.open_unknown(fullurl, data)
211 try:
212 if data is None:
213 return getattr(self, name)(url)
214 else:
215 return getattr(self, name)(url, data)
216 except socket.error, msg:
217 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000218
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000219 def open_unknown(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000220 """Overridable interface to open unknown URL type."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000221 type, url = splittype(fullurl)
222 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossumca445401995-08-29 19:19:12 +0000223
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000224 def open_unknown_proxy(self, proxy, fullurl, data=None):
225 """Overridable interface to open unknown URL type."""
226 type, url = splittype(fullurl)
227 raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
228
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000229 # External interface
Sjoerd Mullenderd7b86f02000-08-25 11:23:36 +0000230 def retrieve(self, url, filename=None, reporthook=None, data=None):
Brett Cannon7d618c72003-04-24 02:43:20 +0000231 """retrieve(url) returns (filename, headers) for a local object
Guido van Rossume7b146f2000-02-04 15:28:42 +0000232 or (tempfilename, headers) for a remote object."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000233 url = unwrap(toBytes(url))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000234 if self.tempcache and url in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000235 return self.tempcache[url]
236 type, url1 = splittype(url)
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000237 if filename is None and (not type or type == 'file'):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000238 try:
239 fp = self.open_local_file(url1)
240 hdrs = fp.info()
Philip Jenvey0299d0d2009-12-03 02:40:13 +0000241 fp.close()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000242 return url2pathname(splithost(url1)[1]), hdrs
Georg Brandl84fedf72010-02-06 22:59:15 +0000243 except IOError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000244 pass
Fred Drake316a7932000-08-24 01:01:26 +0000245 fp = self.open(url, data)
Benjamin Petersonb364bfe2009-03-22 17:45:11 +0000246 try:
247 headers = fp.info()
248 if filename:
249 tfp = open(filename, 'wb')
250 else:
251 import tempfile
252 garbage, path = splittype(url)
253 garbage, path = splithost(path or "")
254 path, garbage = splitquery(path or "")
255 path, garbage = splitattr(path or "")
256 suffix = os.path.splitext(path)[1]
257 (fd, filename) = tempfile.mkstemp(suffix)
258 self.__tempfiles.append(filename)
259 tfp = os.fdopen(fd, 'wb')
260 try:
261 result = filename, headers
262 if self.tempcache is not None:
263 self.tempcache[url] = result
264 bs = 1024*8
265 size = -1
266 read = 0
267 blocknum = 0
Senthil Kumaran87e58552011-11-01 02:44:45 +0800268 if "content-length" in headers:
269 size = int(headers["Content-Length"])
Benjamin Petersonb364bfe2009-03-22 17:45:11 +0000270 if reporthook:
Benjamin Petersonb364bfe2009-03-22 17:45:11 +0000271 reporthook(blocknum, bs, size)
272 while 1:
273 block = fp.read(bs)
274 if block == "":
275 break
276 read += len(block)
277 tfp.write(block)
278 blocknum += 1
279 if reporthook:
280 reporthook(blocknum, bs, size)
281 finally:
282 tfp.close()
283 finally:
284 fp.close()
Georg Brandlb9256022005-08-24 18:46:39 +0000285
286 # raise exception if actual size does not match content-length header
287 if size >= 0 and read < size:
288 raise ContentTooShortError("retrieval incomplete: got only %i out "
289 "of %i bytes" % (read, size), result)
290
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000291 return result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000292
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000293 # Each method named open_<type> knows how to open that type of URL
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000294
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000295 def open_http(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000296 """Use HTTP protocol."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000297 import httplib
298 user_passwd = None
Martin v. Löwis3e865952006-01-24 15:51:21 +0000299 proxy_passwd= None
Walter Dörwald65230a22002-06-03 15:58:32 +0000300 if isinstance(url, str):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000301 host, selector = splithost(url)
302 if host:
303 user_passwd, host = splituser(host)
304 host = unquote(host)
305 realhost = host
306 else:
307 host, selector = url
Martin v. Löwis3e865952006-01-24 15:51:21 +0000308 # check whether the proxy contains authorization information
309 proxy_passwd, host = splituser(host)
310 # now we proceed with the url we want to obtain
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000311 urltype, rest = splittype(selector)
312 url = rest
313 user_passwd = None
Guido van Rossumb2493f82000-12-15 15:01:37 +0000314 if urltype.lower() != 'http':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000315 realhost = None
316 else:
317 realhost, rest = splithost(rest)
318 if realhost:
319 user_passwd, realhost = splituser(realhost)
320 if user_passwd:
321 selector = "%s://%s%s" % (urltype, realhost, rest)
Tim Peters55c12d42001-08-09 18:04:14 +0000322 if proxy_bypass(realhost):
323 host = realhost
324
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000325 #print "proxy via http:", host, selector
326 if not host: raise IOError, ('http error', 'no host given')
Tim Peters92037a12006-01-24 22:44:08 +0000327
Martin v. Löwis3e865952006-01-24 15:51:21 +0000328 if proxy_passwd:
Senthil Kumaranbcd833f2012-01-11 00:09:24 +0800329 proxy_passwd = unquote(proxy_passwd)
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000330 proxy_auth = base64.b64encode(proxy_passwd).strip()
Martin v. Löwis3e865952006-01-24 15:51:21 +0000331 else:
332 proxy_auth = None
333
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000334 if user_passwd:
Senthil Kumaranbcd833f2012-01-11 00:09:24 +0800335 user_passwd = unquote(user_passwd)
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000336 auth = base64.b64encode(user_passwd).strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000337 else:
338 auth = None
339 h = httplib.HTTP(host)
340 if data is not None:
341 h.putrequest('POST', selector)
Georg Brandl0619a322006-07-26 07:40:17 +0000342 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
343 h.putheader('Content-Length', '%d' % len(data))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000344 else:
345 h.putrequest('GET', selector)
Martin v. Löwis3e865952006-01-24 15:51:21 +0000346 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000347 if auth: h.putheader('Authorization', 'Basic %s' % auth)
348 if realhost: h.putheader('Host', realhost)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000349 for args in self.addheaders: h.putheader(*args)
Kristján Valur Jónsson84040db2009-01-09 20:27:16 +0000350 h.endheaders(data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000351 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000352 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000353 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000354 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000355 # something went wrong with the HTTP status line
356 raise IOError, ('http protocol error', 0,
357 'got a bad status line', None)
Sean Reifscheidera1afbf62007-09-19 07:52:56 +0000358 # According to RFC 2616, "2xx" code indicates that the client's
359 # request was successfully received, understood, and accepted.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000360 if (200 <= errcode < 300):
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000361 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000362 else:
363 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000364 return self.http_error(url, fp, errcode, errmsg, headers)
Guido van Rossum29aab751999-03-09 19:31:21 +0000365 else:
366 return self.http_error(url, fp, errcode, errmsg, headers, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000367
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000368 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000369 """Handle http errors.
370 Derived class can override this, or provide specific handlers
371 named http_error_DDD where DDD is the 3-digit error code."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000372 # First check if there's a specific handler for this error
373 name = 'http_error_%d' % errcode
374 if hasattr(self, name):
375 method = getattr(self, name)
376 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000377 result = method(url, fp, errcode, errmsg, headers)
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000378 else:
379 result = method(url, fp, errcode, errmsg, headers, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000380 if result: return result
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000381 return self.http_error_default(url, fp, errcode, errmsg, headers)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000382
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000383 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000384 """Default error handler: close the connection and raise IOError."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000385 fp.close()
386 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000387
Bill Janssen426ea0a2007-08-29 22:35:05 +0000388 if _have_ssl:
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000389 def open_https(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000390 """Use HTTPS protocol."""
Bill Janssen426ea0a2007-08-29 22:35:05 +0000391
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000392 import httplib
Fred Drake567ca8e2000-08-21 21:42:42 +0000393 user_passwd = None
Martin v. Löwis3e865952006-01-24 15:51:21 +0000394 proxy_passwd = None
Walter Dörwald65230a22002-06-03 15:58:32 +0000395 if isinstance(url, str):
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000396 host, selector = splithost(url)
Fred Drake567ca8e2000-08-21 21:42:42 +0000397 if host:
398 user_passwd, host = splituser(host)
399 host = unquote(host)
400 realhost = host
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000401 else:
402 host, selector = url
Martin v. Löwis3e865952006-01-24 15:51:21 +0000403 # here, we determine, whether the proxy contains authorization information
404 proxy_passwd, host = splituser(host)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000405 urltype, rest = splittype(selector)
Fred Drake567ca8e2000-08-21 21:42:42 +0000406 url = rest
407 user_passwd = None
Guido van Rossumb2493f82000-12-15 15:01:37 +0000408 if urltype.lower() != 'https':
Fred Drake567ca8e2000-08-21 21:42:42 +0000409 realhost = None
410 else:
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000411 realhost, rest = splithost(rest)
Fred Drake567ca8e2000-08-21 21:42:42 +0000412 if realhost:
413 user_passwd, realhost = splituser(realhost)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000414 if user_passwd:
415 selector = "%s://%s%s" % (urltype, realhost, rest)
Andrew M. Kuchling7ad47922000-06-10 01:41:48 +0000416 #print "proxy via https:", host, selector
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000417 if not host: raise IOError, ('https error', 'no host given')
Martin v. Löwis3e865952006-01-24 15:51:21 +0000418 if proxy_passwd:
Senthil Kumaranbcd833f2012-01-11 00:09:24 +0800419 proxy_passwd = unquote(proxy_passwd)
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000420 proxy_auth = base64.b64encode(proxy_passwd).strip()
Martin v. Löwis3e865952006-01-24 15:51:21 +0000421 else:
422 proxy_auth = None
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000423 if user_passwd:
Senthil Kumaranbcd833f2012-01-11 00:09:24 +0800424 user_passwd = unquote(user_passwd)
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000425 auth = base64.b64encode(user_passwd).strip()
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000426 else:
427 auth = None
428 h = httplib.HTTPS(host, 0,
429 key_file=self.key_file,
Benjamin Petersonb2064732014-11-23 20:55:24 -0600430 cert_file=self.cert_file,
431 context=self.context)
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000432 if data is not None:
433 h.putrequest('POST', selector)
Georg Brandl0619a322006-07-26 07:40:17 +0000434 h.putheader('Content-Type',
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000435 'application/x-www-form-urlencoded')
Georg Brandl0619a322006-07-26 07:40:17 +0000436 h.putheader('Content-Length', '%d' % len(data))
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000437 else:
438 h.putrequest('GET', selector)
Andrew M. Kuchling52278572006-12-19 15:11:41 +0000439 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
440 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Fred Drake567ca8e2000-08-21 21:42:42 +0000441 if realhost: h.putheader('Host', realhost)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000442 for args in self.addheaders: h.putheader(*args)
Kristján Valur Jónsson84040db2009-01-09 20:27:16 +0000443 h.endheaders(data)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000444 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000445 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000446 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000447 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000448 # something went wrong with the HTTP status line
449 raise IOError, ('http protocol error', 0,
450 'got a bad status line', None)
Georg Brandl9b915672007-09-24 18:08:24 +0000451 # According to RFC 2616, "2xx" code indicates that the client's
452 # request was successfully received, understood, and accepted.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000453 if (200 <= errcode < 300):
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000454 return addinfourl(fp, headers, "https:" + url, errcode)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000455 else:
Fred Drake567ca8e2000-08-21 21:42:42 +0000456 if data is None:
457 return self.http_error(url, fp, errcode, errmsg, headers)
458 else:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000459 return self.http_error(url, fp, errcode, errmsg, headers,
460 data)
Fred Drake567ca8e2000-08-21 21:42:42 +0000461
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000462 def open_file(self, url):
Neal Norwitzc5d0dbd2006-04-09 04:00:49 +0000463 """Use local file or FTP depending on form of URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000464 if not isinstance(url, str):
465 raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
Jack Jansen4ef11032002-09-12 20:14:04 +0000466 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000467 return self.open_ftp(url)
468 else:
469 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000470
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000471 def open_local_file(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000472 """Use local file."""
Georg Brandl5a096e12007-01-22 19:40:21 +0000473 import mimetypes, mimetools, email.utils
Raymond Hettingera6172712004-12-31 19:15:26 +0000474 try:
475 from cStringIO import StringIO
476 except ImportError:
477 from StringIO import StringIO
Guido van Rossumf0713d32001-08-09 17:43:35 +0000478 host, file = splithost(url)
479 localname = url2pathname(file)
Guido van Rossuma2da3052002-04-15 00:25:01 +0000480 try:
481 stats = os.stat(localname)
482 except OSError, e:
483 raise IOError(e.errno, e.strerror, e.filename)
Walter Dörwald92b48b72002-03-22 17:30:38 +0000484 size = stats.st_size
Georg Brandl5a096e12007-01-22 19:40:21 +0000485 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000486 mtype = mimetypes.guess_type(url)[0]
Raymond Hettingera6172712004-12-31 19:15:26 +0000487 headers = mimetools.Message(StringIO(
Guido van Rossumf0713d32001-08-09 17:43:35 +0000488 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
489 (mtype or 'text/plain', size, modified)))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000490 if not host:
Guido van Rossum336a2011999-06-24 15:27:36 +0000491 urlfile = file
492 if file[:1] == '/':
493 urlfile = 'file://' + file
Senthil Kumaran58c60622012-01-21 11:43:02 +0800494 elif file[:2] == './':
495 raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
Guido van Rossumf0713d32001-08-09 17:43:35 +0000496 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000497 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000498 host, port = splitport(host)
499 if not port \
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000500 and socket.gethostbyname(host) in (localhost(), thishost()):
Guido van Rossum336a2011999-06-24 15:27:36 +0000501 urlfile = file
502 if file[:1] == '/':
503 urlfile = 'file://' + file
Guido van Rossumf0713d32001-08-09 17:43:35 +0000504 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000505 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000506 raise IOError, ('local file error', 'not on local host')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000507
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000508 def open_ftp(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000509 """Use FTP protocol."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000510 if not isinstance(url, str):
511 raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
Raymond Hettingera6172712004-12-31 19:15:26 +0000512 import mimetypes, mimetools
513 try:
514 from cStringIO import StringIO
515 except ImportError:
516 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000517 host, path = splithost(url)
518 if not host: raise IOError, ('ftp error', 'no host given')
519 host, port = splitport(host)
520 user, host = splituser(host)
521 if user: user, passwd = splitpasswd(user)
522 else: passwd = None
523 host = unquote(host)
Senthil Kumaran9fce5512010-11-20 11:24:08 +0000524 user = user or ''
525 passwd = passwd or ''
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000526 host = socket.gethostbyname(host)
527 if not port:
528 import ftplib
529 port = ftplib.FTP_PORT
530 else:
531 port = int(port)
532 path, attrs = splitattr(path)
533 path = unquote(path)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000534 dirs = path.split('/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000535 dirs, file = dirs[:-1], dirs[-1]
536 if dirs and not dirs[0]: dirs = dirs[1:]
Guido van Rossum5e006a31999-08-18 17:40:33 +0000537 if dirs and not dirs[0]: dirs[0] = '/'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000538 key = user, host, port, '/'.join(dirs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000539 # XXX thread unsafe!
540 if len(self.ftpcache) > MAXFTPCACHE:
541 # Prune the cache, rather arbitrarily
542 for k in self.ftpcache.keys():
543 if k != key:
544 v = self.ftpcache[k]
545 del self.ftpcache[k]
546 v.close()
547 try:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000548 if not key in self.ftpcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000549 self.ftpcache[key] = \
550 ftpwrapper(user, passwd, host, port, dirs)
551 if not file: type = 'D'
552 else: type = 'I'
553 for attr in attrs:
554 attr, value = splitvalue(attr)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000555 if attr.lower() == 'type' and \
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000556 value in ('a', 'A', 'i', 'I', 'd', 'D'):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000557 type = value.upper()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000558 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000559 mtype = mimetypes.guess_type("ftp:" + url)[0]
560 headers = ""
561 if mtype:
562 headers += "Content-Type: %s\n" % mtype
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000563 if retrlen is not None and retrlen >= 0:
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000564 headers += "Content-Length: %d\n" % retrlen
Raymond Hettingera6172712004-12-31 19:15:26 +0000565 headers = mimetools.Message(StringIO(headers))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000566 return addinfourl(fp, headers, "ftp:" + url)
567 except ftperrors(), msg:
568 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000569
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000570 def open_data(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000571 """Use "data" URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000572 if not isinstance(url, str):
573 raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000574 # ignore POSTed data
575 #
576 # syntax of data URLs:
577 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
578 # mediatype := [ type "/" subtype ] *( ";" parameter )
579 # data := *urlchar
580 # parameter := attribute "=" value
Raymond Hettingera6172712004-12-31 19:15:26 +0000581 import mimetools
582 try:
583 from cStringIO import StringIO
584 except ImportError:
585 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000586 try:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000587 [type, data] = url.split(',', 1)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000588 except ValueError:
589 raise IOError, ('data error', 'bad data URL')
590 if not type:
591 type = 'text/plain;charset=US-ASCII'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000592 semi = type.rfind(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000593 if semi >= 0 and '=' not in type[semi:]:
594 encoding = type[semi+1:]
595 type = type[:semi]
596 else:
597 encoding = ''
598 msg = []
Senthil Kumaran1b7f9e52010-05-01 08:01:56 +0000599 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000600 time.gmtime(time.time())))
601 msg.append('Content-type: %s' % type)
602 if encoding == 'base64':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000603 data = base64.decodestring(data)
604 else:
605 data = unquote(data)
Georg Brandl0619a322006-07-26 07:40:17 +0000606 msg.append('Content-Length: %d' % len(data))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000607 msg.append('')
608 msg.append(data)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000609 msg = '\n'.join(msg)
Raymond Hettingera6172712004-12-31 19:15:26 +0000610 f = StringIO(msg)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000611 headers = mimetools.Message(f, 0)
Georg Brandl1f663572005-11-26 16:50:44 +0000612 #f.fileno = None # needed for addinfourl
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000613 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000614
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000615
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000616class FancyURLopener(URLopener):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000617 """Derived class with handlers for errors we can handle (perhaps)."""
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000618
Neal Norwitz60e04cd2002-06-11 13:38:51 +0000619 def __init__(self, *args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000620 URLopener.__init__(self, *args, **kwargs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000621 self.auth_cache = {}
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000622 self.tries = 0
623 self.maxtries = 10
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000624
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000625 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000626 """Default error handling -- don't raise an exception."""
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000627 return addinfourl(fp, headers, "http:" + url, errcode)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000628
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000629 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000630 """Error 302 -- relocated (temporarily)."""
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000631 self.tries += 1
Martin Panterade40972016-02-04 06:01:35 +0000632 try:
633 if self.maxtries and self.tries >= self.maxtries:
634 if hasattr(self, "http_error_500"):
635 meth = self.http_error_500
636 else:
637 meth = self.http_error_default
638 return meth(url, fp, 500,
639 "Internal Server Error: Redirect Recursion",
640 headers)
641 result = self.redirect_internal(url, fp, errcode, errmsg,
642 headers, data)
643 return result
644 finally:
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000645 self.tries = 0
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000646
647 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000648 if 'location' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000649 newurl = headers['location']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000650 elif 'uri' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000651 newurl = headers['uri']
652 else:
653 return
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000654 fp.close()
Guido van Rossum3527f591999-03-29 20:23:41 +0000655 # In case the server sent a relative URL, join with original:
Moshe Zadka5d87d472001-04-09 14:54:21 +0000656 newurl = basejoin(self.type + ":" + url, newurl)
guido@google.com60a4a902011-03-24 08:07:45 -0700657
658 # For security reasons we do not allow redirects to protocols
guido@google.com2bc23b82011-03-24 10:44:17 -0700659 # other than HTTP, HTTPS or FTP.
guido@google.com60a4a902011-03-24 08:07:45 -0700660 newurl_lower = newurl.lower()
661 if not (newurl_lower.startswith('http://') or
guido@google.com2bc23b82011-03-24 10:44:17 -0700662 newurl_lower.startswith('https://') or
663 newurl_lower.startswith('ftp://')):
guido@google.comf1509302011-03-28 13:47:01 -0700664 raise IOError('redirect error', errcode,
665 errmsg + " - Redirection to url '%s' is not allowed" %
666 newurl,
667 headers)
guido@google.com60a4a902011-03-24 08:07:45 -0700668
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000669 return self.open(newurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000670
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000671 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000672 """Error 301 -- also relocated (permanently)."""
673 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000674
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000675 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
676 """Error 303 -- also relocated (essentially identical to 302)."""
677 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
678
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000679 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
680 """Error 307 -- relocated, but turn POST into error."""
681 if data is None:
682 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
683 else:
684 return self.http_error_default(url, fp, errcode, errmsg, headers)
685
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000686 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000687 """Error 401 -- authentication required.
Martin v. Löwis3e865952006-01-24 15:51:21 +0000688 This function supports Basic authentication only."""
Raymond Hettinger54f02222002-06-01 14:18:47 +0000689 if not 'www-authenticate' in headers:
Tim Peters85ba6732001-02-28 08:26:44 +0000690 URLopener.http_error_default(self, url, fp,
Fred Drakec680ae82001-10-13 18:37:07 +0000691 errcode, errmsg, headers)
Moshe Zadkae99bd172001-02-27 06:27:04 +0000692 stuff = headers['www-authenticate']
693 import re
694 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
695 if not match:
Tim Peters85ba6732001-02-28 08:26:44 +0000696 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000697 errcode, errmsg, headers)
698 scheme, realm = match.groups()
699 if scheme.lower() != 'basic':
Tim Peters85ba6732001-02-28 08:26:44 +0000700 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000701 errcode, errmsg, headers)
702 name = 'retry_' + self.type + '_basic_auth'
703 if data is None:
704 return getattr(self,name)(url, realm)
705 else:
706 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000707
Martin v. Löwis3e865952006-01-24 15:51:21 +0000708 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
709 """Error 407 -- proxy authentication required.
710 This function supports Basic authentication only."""
711 if not 'proxy-authenticate' in headers:
712 URLopener.http_error_default(self, url, fp,
713 errcode, errmsg, headers)
714 stuff = headers['proxy-authenticate']
715 import re
716 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
717 if not match:
718 URLopener.http_error_default(self, url, fp,
719 errcode, errmsg, headers)
720 scheme, realm = match.groups()
721 if scheme.lower() != 'basic':
722 URLopener.http_error_default(self, url, fp,
723 errcode, errmsg, headers)
724 name = 'retry_proxy_' + self.type + '_basic_auth'
725 if data is None:
726 return getattr(self,name)(url, realm)
727 else:
728 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000729
Martin v. Löwis3e865952006-01-24 15:51:21 +0000730 def retry_proxy_http_basic_auth(self, url, realm, data=None):
731 host, selector = splithost(url)
732 newurl = 'http://' + host + selector
733 proxy = self.proxies['http']
734 urltype, proxyhost = splittype(proxy)
735 proxyhost, proxyselector = splithost(proxyhost)
736 i = proxyhost.find('@') + 1
737 proxyhost = proxyhost[i:]
738 user, passwd = self.get_user_passwd(proxyhost, realm, i)
739 if not (user or passwd): return None
740 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
741 self.proxies['http'] = 'http://' + proxyhost + proxyselector
742 if data is None:
743 return self.open(newurl)
744 else:
745 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000746
Martin v. Löwis3e865952006-01-24 15:51:21 +0000747 def retry_proxy_https_basic_auth(self, url, realm, data=None):
748 host, selector = splithost(url)
749 newurl = 'https://' + host + selector
750 proxy = self.proxies['https']
751 urltype, proxyhost = splittype(proxy)
752 proxyhost, proxyselector = splithost(proxyhost)
753 i = proxyhost.find('@') + 1
754 proxyhost = proxyhost[i:]
755 user, passwd = self.get_user_passwd(proxyhost, realm, i)
756 if not (user or passwd): return None
757 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
758 self.proxies['https'] = 'https://' + proxyhost + proxyselector
759 if data is None:
760 return self.open(newurl)
761 else:
762 return self.open(newurl, data)
Tim Peters92037a12006-01-24 22:44:08 +0000763
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000764 def retry_http_basic_auth(self, url, realm, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000765 host, selector = splithost(url)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000766 i = host.find('@') + 1
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000767 host = host[i:]
768 user, passwd = self.get_user_passwd(host, realm, i)
769 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000770 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000771 newurl = 'http://' + host + selector
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000772 if data is None:
773 return self.open(newurl)
774 else:
775 return self.open(newurl, data)
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000776
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000777 def retry_https_basic_auth(self, url, realm, data=None):
Tim Peterse1190062001-01-15 03:34:38 +0000778 host, selector = splithost(url)
779 i = host.find('@') + 1
780 host = host[i:]
781 user, passwd = self.get_user_passwd(host, realm, i)
782 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000783 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Martin v. Löwis3e865952006-01-24 15:51:21 +0000784 newurl = 'https://' + host + selector
785 if data is None:
786 return self.open(newurl)
787 else:
788 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000789
Florent Xiclunae127e242010-05-17 10:39:07 +0000790 def get_user_passwd(self, host, realm, clear_cache=0):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000791 key = realm + '@' + host.lower()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000792 if key in self.auth_cache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000793 if clear_cache:
794 del self.auth_cache[key]
795 else:
796 return self.auth_cache[key]
797 user, passwd = self.prompt_user_passwd(host, realm)
798 if user or passwd: self.auth_cache[key] = (user, passwd)
799 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000800
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000801 def prompt_user_passwd(self, host, realm):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000802 """Override this in a GUI environment!"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000803 import getpass
804 try:
805 user = raw_input("Enter username for %s at %s: " % (realm,
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000806 host))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000807 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
808 (user, realm, host))
809 return user, passwd
810 except KeyboardInterrupt:
811 print
812 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000813
814
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000815# Utility functions
816
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000817_localhost = None
818def localhost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000819 """Return the IP address of the magic hostname 'localhost'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000820 global _localhost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000821 if _localhost is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000822 _localhost = socket.gethostbyname('localhost')
823 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000824
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000825_thishost = None
826def thishost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000827 """Return the IP address of the current host."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000828 global _thishost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000829 if _thishost is None:
Senthil Kumaran7351b662013-06-01 11:11:30 -0700830 try:
831 _thishost = socket.gethostbyname(socket.gethostname())
832 except socket.gaierror:
833 _thishost = socket.gethostbyname('localhost')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000834 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000835
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000836_ftperrors = None
837def ftperrors():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000838 """Return the set of errors raised by the FTP class."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000839 global _ftperrors
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000840 if _ftperrors is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000841 import ftplib
842 _ftperrors = ftplib.all_errors
843 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000844
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000845_noheaders = None
846def noheaders():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000847 """Return an empty mimetools.Message object."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000848 global _noheaders
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000849 if _noheaders is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000850 import mimetools
Raymond Hettingera6172712004-12-31 19:15:26 +0000851 try:
852 from cStringIO import StringIO
853 except ImportError:
854 from StringIO import StringIO
855 _noheaders = mimetools.Message(StringIO(), 0)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000856 _noheaders.fp.close() # Recycle file descriptor
857 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000858
859
860# Utility classes
861
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000862class ftpwrapper:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000863 """Class used by open_ftp() for cache of open FTP connections."""
864
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000865 def __init__(self, user, passwd, host, port, dirs,
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200866 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
Nadeem Vawdaa620fac2011-07-23 17:04:42 +0200867 persistent=True):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000868 self.user = user
869 self.passwd = passwd
870 self.host = host
871 self.port = port
872 self.dirs = dirs
Facundo Batista711a54e2007-05-24 17:50:54 +0000873 self.timeout = timeout
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200874 self.refcount = 0
875 self.keepalive = persistent
Victor Stinner5ab1c012015-04-07 12:47:57 +0200876 try:
877 self.init()
878 except:
879 self.close()
880 raise
Guido van Rossume7b146f2000-02-04 15:28:42 +0000881
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000882 def init(self):
883 import ftplib
884 self.busy = 0
885 self.ftp = ftplib.FTP()
Facundo Batista711a54e2007-05-24 17:50:54 +0000886 self.ftp.connect(self.host, self.port, self.timeout)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000887 self.ftp.login(self.user, self.passwd)
Senthil Kumaran964c25f2013-06-02 11:59:09 -0700888 _target = '/'.join(self.dirs)
889 self.ftp.cwd(_target)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000890
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000891 def retrfile(self, file, type):
892 import ftplib
893 self.endtransfer()
894 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
895 else: cmd = 'TYPE ' + type; isdir = 0
896 try:
897 self.ftp.voidcmd(cmd)
898 except ftplib.all_errors:
899 self.init()
900 self.ftp.voidcmd(cmd)
901 conn = None
902 if file and not isdir:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000903 # Try to retrieve as a file
904 try:
905 cmd = 'RETR ' + file
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200906 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000907 except ftplib.error_perm, reason:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000908 if str(reason)[:3] != '550':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000909 raise IOError, ('ftp error', reason), sys.exc_info()[2]
910 if not conn:
911 # Set transfer mode to ASCII!
912 self.ftp.voidcmd('TYPE A')
Georg Brandld5e6cf22008-01-20 12:18:17 +0000913 # Try a directory listing. Verify that directory exists.
914 if file:
915 pwd = self.ftp.pwd()
916 try:
917 try:
918 self.ftp.cwd(file)
919 except ftplib.error_perm, reason:
920 raise IOError, ('ftp error', reason), sys.exc_info()[2]
921 finally:
922 self.ftp.cwd(pwd)
923 cmd = 'LIST ' + file
924 else:
925 cmd = 'LIST'
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200926 conn, retrlen = self.ftp.ntransfercmd(cmd)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000927 self.busy = 1
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200928 ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
929 self.refcount += 1
930 conn.close()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000931 # Pass back both a suitably decorated object and a retrieval length
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200932 return (ftpobj, retrlen)
933
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000934 def endtransfer(self):
935 if not self.busy:
936 return
937 self.busy = 0
938 try:
939 self.ftp.voidresp()
940 except ftperrors():
941 pass
Guido van Rossume7b146f2000-02-04 15:28:42 +0000942
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000943 def close(self):
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200944 self.keepalive = False
945 if self.refcount <= 0:
946 self.real_close()
947
948 def file_close(self):
949 self.endtransfer()
950 self.refcount -= 1
951 if self.refcount <= 0 and not self.keepalive:
952 self.real_close()
953
954 def real_close(self):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000955 self.endtransfer()
956 try:
957 self.ftp.close()
958 except ftperrors():
959 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000960
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000961class addbase:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000962 """Base class for addinfo and addclosehook."""
963
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000964 def __init__(self, fp):
965 self.fp = fp
966 self.read = self.fp.read
967 self.readline = self.fp.readline
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000968 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
Georg Brandl1f663572005-11-26 16:50:44 +0000969 if hasattr(self.fp, "fileno"):
970 self.fileno = self.fp.fileno
971 else:
972 self.fileno = lambda: None
Raymond Hettinger42182eb2003-03-09 05:33:33 +0000973 if hasattr(self.fp, "__iter__"):
974 self.__iter__ = self.fp.__iter__
975 if hasattr(self.fp, "next"):
976 self.next = self.fp.next
Guido van Rossume7b146f2000-02-04 15:28:42 +0000977
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000978 def __repr__(self):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000979 return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
980 id(self), self.fp)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000981
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000982 def close(self):
983 self.read = None
984 self.readline = None
985 self.readlines = None
986 self.fileno = None
987 if self.fp: self.fp.close()
988 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000989
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000990class addclosehook(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000991 """Class to add a close hook to an open file."""
992
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000993 def __init__(self, fp, closehook, *hookargs):
994 addbase.__init__(self, fp)
995 self.closehook = closehook
996 self.hookargs = hookargs
Guido van Rossume7b146f2000-02-04 15:28:42 +0000997
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000998 def close(self):
Serhiy Storchaka1aa2c0f2015-04-10 13:24:10 +0300999 try:
1000 closehook = self.closehook
1001 hookargs = self.hookargs
1002 if closehook:
1003 self.closehook = None
1004 self.hookargs = None
1005 closehook(*hookargs)
1006 finally:
1007 addbase.close(self)
1008
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001009
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001010class addinfo(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001011 """class to add an info() method to an open file."""
1012
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001013 def __init__(self, fp, headers):
1014 addbase.__init__(self, fp)
1015 self.headers = headers
Guido van Rossume7b146f2000-02-04 15:28:42 +00001016
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001017 def info(self):
1018 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001019
Guido van Rossume6ad8911996-09-10 17:02:56 +00001020class addinfourl(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001021 """class to add info() and geturl() methods to an open file."""
1022
Georg Brandl9b0d46d2008-01-20 11:43:03 +00001023 def __init__(self, fp, headers, url, code=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001024 addbase.__init__(self, fp)
1025 self.headers = headers
1026 self.url = url
Georg Brandl9b0d46d2008-01-20 11:43:03 +00001027 self.code = code
Guido van Rossume7b146f2000-02-04 15:28:42 +00001028
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001029 def info(self):
1030 return self.headers
Guido van Rossume7b146f2000-02-04 15:28:42 +00001031
Georg Brandl9b0d46d2008-01-20 11:43:03 +00001032 def getcode(self):
1033 return self.code
1034
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001035 def geturl(self):
1036 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +00001037
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001038
Guido van Rossum7c395db1994-07-04 22:14:49 +00001039# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +00001040# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001041# splittype('type:opaquestring') --> 'type', 'opaquestring'
1042# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +00001043# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
1044# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001045# splitport('host:port') --> 'host', 'port'
1046# splitquery('/path?query') --> '/path', 'query'
1047# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +00001048# splitattr('/path;attr1=value1;attr2=value2;...') ->
1049# '/path', ['attr1=value1', 'attr2=value2', ...]
1050# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001051# unquote('abc%20def') -> 'abc def'
1052# quote('abc def') -> 'abc%20def')
1053
Walter Dörwald65230a22002-06-03 15:58:32 +00001054try:
1055 unicode
1056except NameError:
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001057 def _is_unicode(x):
1058 return 0
Walter Dörwald65230a22002-06-03 15:58:32 +00001059else:
1060 def _is_unicode(x):
1061 return isinstance(x, unicode)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001062
Martin v. Löwis1d994332000-12-03 18:30:10 +00001063def toBytes(url):
1064 """toBytes(u"URL") --> 'URL'."""
1065 # Most URL schemes require ASCII. If that changes, the conversion
1066 # can be relaxed
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001067 if _is_unicode(url):
Martin v. Löwis1d994332000-12-03 18:30:10 +00001068 try:
1069 url = url.encode("ASCII")
1070 except UnicodeError:
Guido van Rossumb2493f82000-12-15 15:01:37 +00001071 raise UnicodeError("URL " + repr(url) +
1072 " contains non-ASCII characters")
Martin v. Löwis1d994332000-12-03 18:30:10 +00001073 return url
1074
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001075def unwrap(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001076 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001077 url = url.strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001078 if url[:1] == '<' and url[-1:] == '>':
Guido van Rossumb2493f82000-12-15 15:01:37 +00001079 url = url[1:-1].strip()
1080 if url[:4] == 'URL:': url = url[4:].strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001081 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001082
Guido van Rossum332e1441997-09-29 23:23:46 +00001083_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001084def splittype(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001085 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001086 global _typeprog
1087 if _typeprog is None:
1088 import re
1089 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +00001090
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001091 match = _typeprog.match(url)
1092 if match:
1093 scheme = match.group(1)
Fred Drake9e94afd2000-07-01 07:03:30 +00001094 return scheme.lower(), url[len(scheme) + 1:]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001095 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001096
Guido van Rossum332e1441997-09-29 23:23:46 +00001097_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001098def splithost(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001099 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001100 global _hostprog
1101 if _hostprog is None:
1102 import re
Georg Brandl1c168d82006-03-26 20:59:38 +00001103 _hostprog = re.compile('^//([^/?]*)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001104
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001105 match = _hostprog.match(url)
Senthil Kumaran0b7cac12010-11-22 05:04:33 +00001106 if match:
1107 host_port = match.group(1)
1108 path = match.group(2)
1109 if path and not path.startswith('/'):
1110 path = '/' + path
1111 return host_port, path
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001112 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001113
Guido van Rossum332e1441997-09-29 23:23:46 +00001114_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001115def splituser(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001116 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001117 global _userprog
1118 if _userprog is None:
1119 import re
Raymond Hettingerf2e45dd2002-08-18 20:08:56 +00001120 _userprog = re.compile('^(.*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001121
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001122 match = _userprog.match(host)
Senthil Kumaran9fce5512010-11-20 11:24:08 +00001123 if match: return match.group(1, 2)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001124 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +00001125
Guido van Rossum332e1441997-09-29 23:23:46 +00001126_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001127def splitpasswd(user):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001128 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001129 global _passwdprog
1130 if _passwdprog is None:
1131 import re
Senthil Kumaran5e95e762009-03-30 21:51:50 +00001132 _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
Guido van Rossum332e1441997-09-29 23:23:46 +00001133
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001134 match = _passwdprog.match(user)
1135 if match: return match.group(1, 2)
1136 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001137
Guido van Rossume7b146f2000-02-04 15:28:42 +00001138# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum332e1441997-09-29 23:23:46 +00001139_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001140def splitport(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001141 """splitport('host:port') --> 'host', 'port'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001142 global _portprog
1143 if _portprog is None:
1144 import re
Serhiy Storchaka326b5ab2014-01-18 18:30:09 +02001145 _portprog = re.compile('^(.*):([0-9]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001146
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001147 match = _portprog.match(host)
Serhiy Storchaka326b5ab2014-01-18 18:30:09 +02001148 if match:
1149 host, port = match.groups()
1150 if port:
1151 return host, port
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001152 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001153
Guido van Rossum332e1441997-09-29 23:23:46 +00001154_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +00001155def splitnport(host, defport=-1):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001156 """Split host and port, returning numeric port.
1157 Return given default port if no ':' found; defaults to -1.
1158 Return numerical port if a valid number are found after ':'.
1159 Return None if ':' but not a valid number."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001160 global _nportprog
1161 if _nportprog is None:
1162 import re
1163 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001164
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001165 match = _nportprog.match(host)
1166 if match:
1167 host, port = match.group(1, 2)
Serhiy Storchaka326b5ab2014-01-18 18:30:09 +02001168 if port:
1169 try:
1170 nport = int(port)
1171 except ValueError:
1172 nport = None
1173 return host, nport
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001174 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +00001175
Guido van Rossum332e1441997-09-29 23:23:46 +00001176_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001177def splitquery(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001178 """splitquery('/path?query') --> '/path', 'query'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001179 global _queryprog
1180 if _queryprog is None:
1181 import re
1182 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001183
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001184 match = _queryprog.match(url)
1185 if match: return match.group(1, 2)
1186 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001187
Guido van Rossum332e1441997-09-29 23:23:46 +00001188_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001189def splittag(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001190 """splittag('/path#tag') --> '/path', 'tag'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001191 global _tagprog
1192 if _tagprog is None:
1193 import re
1194 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001195
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001196 match = _tagprog.match(url)
1197 if match: return match.group(1, 2)
1198 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001199
Guido van Rossum7c395db1994-07-04 22:14:49 +00001200def splitattr(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001201 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1202 '/path', ['attr1=value1', 'attr2=value2', ...]."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001203 words = url.split(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001204 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +00001205
Guido van Rossum332e1441997-09-29 23:23:46 +00001206_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001207def splitvalue(attr):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001208 """splitvalue('attr=value') --> 'attr', 'value'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001209 global _valueprog
1210 if _valueprog is None:
1211 import re
1212 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001213
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001214 match = _valueprog.match(attr)
1215 if match: return match.group(1, 2)
1216 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001217
R. David Murraybfbdefe2010-05-25 15:20:46 +00001218# urlparse contains a duplicate of this method to avoid a circular import. If
1219# you update this method, also update the copy in urlparse. This code
1220# duplication does not exist in Python3.
1221
Senthil Kumaranf3e9b2a2010-03-18 12:14:15 +00001222_hexdig = '0123456789ABCDEFabcdef'
Florent Xiclunae127e242010-05-17 10:39:07 +00001223_hextochr = dict((a + b, chr(int(a + b, 16)))
1224 for a in _hexdig for b in _hexdig)
Serhiy Storchaka923baea2013-03-14 21:31:09 +02001225_asciire = re.compile('([\x00-\x7f]+)')
Raymond Hettinger803ce802005-09-10 06:49:04 +00001226
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001227def unquote(s):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001228 """unquote('abc%20def') -> 'abc def'."""
Serhiy Storchaka923baea2013-03-14 21:31:09 +02001229 if _is_unicode(s):
1230 if '%' not in s:
1231 return s
1232 bits = _asciire.split(s)
1233 res = [bits[0]]
1234 append = res.append
1235 for i in range(1, len(bits), 2):
1236 append(unquote(str(bits[i])).decode('latin1'))
1237 append(bits[i + 1])
1238 return ''.join(res)
1239
1240 bits = s.split('%')
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001241 # fastpath
Serhiy Storchaka923baea2013-03-14 21:31:09 +02001242 if len(bits) == 1:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001243 return s
Serhiy Storchaka923baea2013-03-14 21:31:09 +02001244 res = [bits[0]]
1245 append = res.append
1246 for item in bits[1:]:
Raymond Hettinger803ce802005-09-10 06:49:04 +00001247 try:
Serhiy Storchaka923baea2013-03-14 21:31:09 +02001248 append(_hextochr[item[:2]])
1249 append(item[2:])
Raymond Hettinger803ce802005-09-10 06:49:04 +00001250 except KeyError:
Serhiy Storchaka923baea2013-03-14 21:31:09 +02001251 append('%')
1252 append(item)
1253 return ''.join(res)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001254
Guido van Rossum0564e121996-12-13 14:47:36 +00001255def unquote_plus(s):
Skip Montanaro79f1c172000-08-22 03:00:52 +00001256 """unquote('%7e/abc+def') -> '~/abc def'"""
Brett Cannonaaeffaf2004-03-23 23:50:17 +00001257 s = s.replace('+', ' ')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001258 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +00001259
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001260always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Jeremy Hylton6102e292000-08-31 15:48:10 +00001261 'abcdefghijklmnopqrstuvwxyz'
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001262 '0123456789' '_.-')
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001263_safe_map = {}
1264for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
1265 _safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i)
1266_safe_quoters = {}
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001267
Senthil Kumaran880685f2010-07-22 01:47:30 +00001268def quote(s, safe='/'):
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001269 """quote('abc def') -> 'abc%20def'
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001270
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001271 Each part of a URL, e.g. the path info, the query, etc., has a
1272 different set of reserved characters that must be quoted.
1273
1274 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
1275 the following reserved characters.
1276
1277 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
1278 "$" | ","
1279
1280 Each of these characters is reserved in some component of a URL,
1281 but not necessarily in all of them.
1282
1283 By default, the quote function is intended for quoting the path
1284 section of a URL. Thus, it will not encode '/'. This character
1285 is reserved, but in typical usage the quote function is being
1286 called on a path where the existing slash characters are used as
1287 reserved characters.
1288 """
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001289 # fastpath
1290 if not s:
Senthil Kumaranc7743aa2010-07-19 17:35:50 +00001291 if s is None:
1292 raise TypeError('None object cannot be quoted')
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001293 return s
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001294 cachekey = (safe, always_safe)
1295 try:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001296 (quoter, safe) = _safe_quoters[cachekey]
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001297 except KeyError:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001298 safe_map = _safe_map.copy()
1299 safe_map.update([(c, c) for c in safe])
1300 quoter = safe_map.__getitem__
1301 safe = always_safe + safe
1302 _safe_quoters[cachekey] = (quoter, safe)
1303 if not s.rstrip(safe):
1304 return s
1305 return ''.join(map(quoter, s))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001306
Senthil Kumaran880685f2010-07-22 01:47:30 +00001307def quote_plus(s, safe=''):
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001308 """Quote the query fragment of a URL; replacing ' ' with '+'"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001309 if ' ' in s:
Senthil Kumaran880685f2010-07-22 01:47:30 +00001310 s = quote(s, safe + ' ')
Raymond Hettingercf6b6322005-09-10 18:17:54 +00001311 return s.replace(' ', '+')
Senthil Kumaran880685f2010-07-22 01:47:30 +00001312 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +00001313
Florent Xiclunae127e242010-05-17 10:39:07 +00001314def urlencode(query, doseq=0):
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001315 """Encode a sequence of two-element tuples or dictionary into a URL query string.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001316
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001317 If any values in the query arg are sequences and doseq is true, each
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001318 sequence element is converted to a separate parameter.
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001319
1320 If the query arg is a sequence of two-element tuples, the order of the
1321 parameters in the output will match the order of parameters in the
1322 input.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001323 """
Tim Peters658cba62001-02-09 20:06:00 +00001324
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001325 if hasattr(query,"items"):
1326 # mapping objects
1327 query = query.items()
1328 else:
1329 # it's a bother at times that strings and string-like objects are
1330 # sequences...
1331 try:
1332 # non-sequence items should not work with len()
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001333 # non-empty strings will fail this
Walter Dörwald65230a22002-06-03 15:58:32 +00001334 if len(query) and not isinstance(query[0], tuple):
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001335 raise TypeError
1336 # zero-length sequences of all types will get here and succeed,
1337 # but that's a minor nit - since the original implementation
1338 # allowed empty dicts that type of behavior probably should be
1339 # preserved for consistency
1340 except TypeError:
1341 ty,va,tb = sys.exc_info()
1342 raise TypeError, "not a valid non-string sequence or mapping object", tb
1343
Guido van Rossume7b146f2000-02-04 15:28:42 +00001344 l = []
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001345 if not doseq:
1346 # preserve old behavior
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001347 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001348 k = quote_plus(str(k))
1349 v = quote_plus(str(v))
1350 l.append(k + '=' + v)
1351 else:
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001352 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001353 k = quote_plus(str(k))
Walter Dörwald65230a22002-06-03 15:58:32 +00001354 if isinstance(v, str):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001355 v = quote_plus(v)
1356 l.append(k + '=' + v)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001357 elif _is_unicode(v):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001358 # is there a reasonable way to convert to ASCII?
1359 # encode generates a string, but "replace" or "ignore"
1360 # lose information and "strict" can raise UnicodeError
1361 v = quote_plus(v.encode("ASCII","replace"))
1362 l.append(k + '=' + v)
1363 else:
1364 try:
1365 # is this a sufficient test for sequence-ness?
Georg Brandl84fedf72010-02-06 22:59:15 +00001366 len(v)
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001367 except TypeError:
1368 # not a sequence
1369 v = quote_plus(str(v))
1370 l.append(k + '=' + v)
1371 else:
1372 # loop over the sequence
1373 for elt in v:
1374 l.append(k + '=' + quote_plus(str(elt)))
Guido van Rossumb2493f82000-12-15 15:01:37 +00001375 return '&'.join(l)
Guido van Rossum810a3391998-07-22 21:33:23 +00001376
Guido van Rossum442e7201996-03-20 15:33:11 +00001377# Proxy handling
Mark Hammond4f570b92000-07-26 07:04:38 +00001378def getproxies_environment():
1379 """Return a dictionary of scheme -> proxy server URL mappings.
1380
1381 Scan the environment for variables named <scheme>_proxy;
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001382 this seems to be the standard convention. In order to prefer lowercase
1383 variables, we process the environment in two passes, first matches any
1384 and second matches only lower case proxies.
Mark Hammond4f570b92000-07-26 07:04:38 +00001385
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001386 If you need a different way, you can pass a proxies dictionary to the
1387 [Fancy]URLopener constructor.
Mark Hammond4f570b92000-07-26 07:04:38 +00001388 """
1389 proxies = {}
1390 for name, value in os.environ.items():
Guido van Rossumb2493f82000-12-15 15:01:37 +00001391 name = name.lower()
Mark Hammond4f570b92000-07-26 07:04:38 +00001392 if value and name[-6:] == '_proxy':
1393 proxies[name[:-6]] = value
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001394
1395 for name, value in os.environ.items():
1396 if name[-6:] == '_proxy':
1397 name = name.lower()
1398 if value:
1399 proxies[name[:-6]] = value
1400 else:
1401 proxies.pop(name[:-6], None)
1402
Mark Hammond4f570b92000-07-26 07:04:38 +00001403 return proxies
1404
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001405def proxy_bypass_environment(host, proxies=None):
Georg Brandl22350112008-01-20 12:05:43 +00001406 """Test if proxies should not be used for a particular host.
1407
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001408 Checks the proxies dict for the value of no_proxy, which should be a
1409 list of comma separated DNS suffixes, or '*' for all hosts.
Georg Brandl22350112008-01-20 12:05:43 +00001410 """
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001411 if proxies is None:
1412 proxies = getproxies_environment()
1413 # don't bypass, if no_proxy isn't specified
1414 try:
1415 no_proxy = proxies['no']
1416 except KeyError:
1417 return 0
Georg Brandl22350112008-01-20 12:05:43 +00001418 # '*' is special case for always bypass
1419 if no_proxy == '*':
1420 return 1
1421 # strip port off host
1422 hostonly, port = splitport(host)
1423 # check if the host ends with any of the DNS suffixes
Senthil Kumaranb5bd4c82011-08-06 12:24:33 +08001424 no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
1425 for name in no_proxy_list:
Georg Brandl22350112008-01-20 12:05:43 +00001426 if name and (hostonly.endswith(name) or host.endswith(name)):
1427 return 1
1428 # otherwise, don't bypass
1429 return 0
1430
1431
Jack Jansen11d9b062004-07-16 11:45:00 +00001432if sys.platform == 'darwin':
Ronald Oussoren51f06332009-09-20 10:31:22 +00001433 from _scproxy import _get_proxy_settings, _get_proxies
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001434
1435 def proxy_bypass_macosx_sysconf(host):
1436 """
1437 Return True iff this host shouldn't be accessed using a proxy
1438
1439 This function uses the MacOSX framework SystemConfiguration
1440 to fetch the proxy information.
1441 """
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001442 import re
1443 import socket
1444 from fnmatch import fnmatch
1445
Ronald Oussoren31802d02009-10-18 07:07:00 +00001446 hostonly, port = splitport(host)
1447
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001448 def ip2num(ipAddr):
1449 parts = ipAddr.split('.')
1450 parts = map(int, parts)
1451 if len(parts) != 4:
1452 parts = (parts + [0, 0, 0, 0])[:4]
1453 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
1454
Ronald Oussoren51f06332009-09-20 10:31:22 +00001455 proxy_settings = _get_proxy_settings()
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001456
Ronald Oussoren51f06332009-09-20 10:31:22 +00001457 # Check for simple host names:
1458 if '.' not in host:
1459 if proxy_settings['exclude_simple']:
1460 return True
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001461
Ronald Oussoren31802d02009-10-18 07:07:00 +00001462 hostIP = None
1463
Ronald Oussoren809073b2009-09-20 10:54:07 +00001464 for value in proxy_settings.get('exceptions', ()):
Ronald Oussoren51f06332009-09-20 10:31:22 +00001465 # Items in the list are strings like these: *.local, 169.254/16
Ronald Oussoren51f06332009-09-20 10:31:22 +00001466 if not value: continue
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001467
Ronald Oussoren51f06332009-09-20 10:31:22 +00001468 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
1469 if m is not None:
1470 if hostIP is None:
Ronald Oussoren31802d02009-10-18 07:07:00 +00001471 try:
1472 hostIP = socket.gethostbyname(hostonly)
1473 hostIP = ip2num(hostIP)
1474 except socket.error:
1475 continue
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001476
Ronald Oussoren51f06332009-09-20 10:31:22 +00001477 base = ip2num(m.group(1))
Ronald Oussorenb96fbb82010-06-27 13:59:39 +00001478 mask = m.group(2)
1479 if mask is None:
1480 mask = 8 * (m.group(1).count('.') + 1)
1481
1482 else:
1483 mask = int(mask[1:])
Ronald Oussoren1aa999c2011-03-14 18:53:59 -04001484 mask = 32 - mask
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001485
Ronald Oussoren51f06332009-09-20 10:31:22 +00001486 if (hostIP >> mask) == (base >> mask):
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001487 return True
1488
Ronald Oussoren51f06332009-09-20 10:31:22 +00001489 elif fnmatch(host, value):
1490 return True
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001491
Ronald Oussoren51f06332009-09-20 10:31:22 +00001492 return False
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001493
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001494 def getproxies_macosx_sysconf():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001495 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +00001496
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001497 This function uses the MacOSX framework SystemConfiguration
1498 to fetch the proxy information.
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001499 """
Ronald Oussoren51f06332009-09-20 10:31:22 +00001500 return _get_proxies()
Mark Hammond4f570b92000-07-26 07:04:38 +00001501
Georg Brandl22350112008-01-20 12:05:43 +00001502 def proxy_bypass(host):
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001503 """Return True, if a host should be bypassed.
1504
1505 Checks proxy settings gathered from the environment, if specified, or
1506 from the MacOSX framework SystemConfiguration.
1507 """
1508 proxies = getproxies_environment()
1509 if proxies:
1510 return proxy_bypass_environment(host, proxies)
Georg Brandl22350112008-01-20 12:05:43 +00001511 else:
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001512 return proxy_bypass_macosx_sysconf(host)
Tim Peters55c12d42001-08-09 18:04:14 +00001513
Jack Jansen11d9b062004-07-16 11:45:00 +00001514 def getproxies():
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001515 return getproxies_environment() or getproxies_macosx_sysconf()
Tim Peters182b5ac2004-07-18 06:16:08 +00001516
Mark Hammond4f570b92000-07-26 07:04:38 +00001517elif os.name == 'nt':
1518 def getproxies_registry():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001519 """Return a dictionary of scheme -> proxy server URL mappings.
Mark Hammond4f570b92000-07-26 07:04:38 +00001520
1521 Win32 uses the registry to store proxies.
1522
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001523 """
1524 proxies = {}
Mark Hammond4f570b92000-07-26 07:04:38 +00001525 try:
1526 import _winreg
1527 except ImportError:
1528 # Std module, so should be around - but you never know!
1529 return proxies
1530 try:
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001531 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1532 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Mark Hammond4f570b92000-07-26 07:04:38 +00001533 proxyEnable = _winreg.QueryValueEx(internetSettings,
1534 'ProxyEnable')[0]
1535 if proxyEnable:
1536 # Returned as Unicode but problems if not converted to ASCII
1537 proxyServer = str(_winreg.QueryValueEx(internetSettings,
1538 'ProxyServer')[0])
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001539 if '=' in proxyServer:
1540 # Per-protocol settings
Mark Hammond4f570b92000-07-26 07:04:38 +00001541 for p in proxyServer.split(';'):
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001542 protocol, address = p.split('=', 1)
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001543 # See if address has a type:// prefix
Guido van Rossum64e5aa92002-04-02 14:38:16 +00001544 import re
1545 if not re.match('^([^/:]+)://', address):
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001546 address = '%s://%s' % (protocol, address)
1547 proxies[protocol] = address
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001548 else:
1549 # Use one setting for all protocols
1550 if proxyServer[:5] == 'http:':
1551 proxies['http'] = proxyServer
1552 else:
1553 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran0fdd3852010-07-14 20:22:17 +00001554 proxies['https'] = 'https://%s' % proxyServer
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001555 proxies['ftp'] = 'ftp://%s' % proxyServer
Mark Hammond4f570b92000-07-26 07:04:38 +00001556 internetSettings.Close()
1557 except (WindowsError, ValueError, TypeError):
1558 # Either registry key not found etc, or the value in an
1559 # unexpected format.
1560 # proxies already set up to be empty so nothing to do
1561 pass
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001562 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +00001563
Mark Hammond4f570b92000-07-26 07:04:38 +00001564 def getproxies():
1565 """Return a dictionary of scheme -> proxy server URL mappings.
1566
1567 Returns settings gathered from the environment, if specified,
1568 or the registry.
1569
1570 """
1571 return getproxies_environment() or getproxies_registry()
Tim Peters55c12d42001-08-09 18:04:14 +00001572
Georg Brandl22350112008-01-20 12:05:43 +00001573 def proxy_bypass_registry(host):
Tim Peters55c12d42001-08-09 18:04:14 +00001574 try:
1575 import _winreg
1576 import re
Tim Peters55c12d42001-08-09 18:04:14 +00001577 except ImportError:
1578 # Std modules, so should be around - but you never know!
1579 return 0
1580 try:
1581 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1582 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
1583 proxyEnable = _winreg.QueryValueEx(internetSettings,
1584 'ProxyEnable')[0]
1585 proxyOverride = str(_winreg.QueryValueEx(internetSettings,
1586 'ProxyOverride')[0])
1587 # ^^^^ Returned as Unicode but problems if not converted to ASCII
1588 except WindowsError:
1589 return 0
1590 if not proxyEnable or not proxyOverride:
1591 return 0
1592 # try to make a host list from name and IP address.
Georg Brandl1f636702006-02-18 23:10:23 +00001593 rawHost, port = splitport(host)
1594 host = [rawHost]
Tim Peters55c12d42001-08-09 18:04:14 +00001595 try:
Georg Brandl1f636702006-02-18 23:10:23 +00001596 addr = socket.gethostbyname(rawHost)
1597 if addr != rawHost:
Tim Peters55c12d42001-08-09 18:04:14 +00001598 host.append(addr)
1599 except socket.error:
1600 pass
Georg Brandl1f636702006-02-18 23:10:23 +00001601 try:
1602 fqdn = socket.getfqdn(rawHost)
1603 if fqdn != rawHost:
1604 host.append(fqdn)
1605 except socket.error:
1606 pass
Tim Peters55c12d42001-08-09 18:04:14 +00001607 # make a check value list from the registry entry: replace the
1608 # '<local>' string by the localhost entry and the corresponding
1609 # canonical entry.
1610 proxyOverride = proxyOverride.split(';')
Tim Peters55c12d42001-08-09 18:04:14 +00001611 # now check if we match one of the registry values.
1612 for test in proxyOverride:
Senthil Kumaran4af40d22009-05-01 05:59:52 +00001613 if test == '<local>':
1614 if '.' not in rawHost:
1615 return 1
Tim Petersab9ba272001-08-09 21:40:30 +00001616 test = test.replace(".", r"\.") # mask dots
1617 test = test.replace("*", r".*") # change glob sequence
1618 test = test.replace("?", r".") # change glob char
Tim Peters55c12d42001-08-09 18:04:14 +00001619 for val in host:
1620 # print "%s <--> %s" %( test, val )
1621 if re.match(test, val, re.I):
1622 return 1
1623 return 0
1624
Georg Brandl22350112008-01-20 12:05:43 +00001625 def proxy_bypass(host):
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001626 """Return True, if the host should be bypassed.
Georg Brandl22350112008-01-20 12:05:43 +00001627
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001628 Checks proxy settings gathered from the environment, if specified,
Georg Brandl22350112008-01-20 12:05:43 +00001629 or the registry.
Georg Brandl22350112008-01-20 12:05:43 +00001630 """
Senthil Kumaranb31c87b2016-04-25 09:17:54 -07001631 proxies = getproxies_environment()
1632 if proxies:
1633 return proxy_bypass_environment(host, proxies)
Georg Brandl22350112008-01-20 12:05:43 +00001634 else:
1635 return proxy_bypass_registry(host)
1636
Mark Hammond4f570b92000-07-26 07:04:38 +00001637else:
1638 # By default use environment variables
1639 getproxies = getproxies_environment
Georg Brandl22350112008-01-20 12:05:43 +00001640 proxy_bypass = proxy_bypass_environment
Guido van Rossum442e7201996-03-20 15:33:11 +00001641
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001642# Test and time quote() and unquote()
1643def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001644 s = ''
1645 for i in range(256): s = s + chr(i)
1646 s = s*4
1647 t0 = time.time()
1648 qs = quote(s)
1649 uqs = unquote(qs)
1650 t1 = time.time()
1651 if uqs != s:
1652 print 'Wrong!'
Walter Dörwald70a6b492004-02-12 17:35:32 +00001653 print repr(s)
1654 print repr(qs)
1655 print repr(uqs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001656 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001657
1658
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001659def reporthook(blocknum, blocksize, totalsize):
1660 # Report during remote transfers
Guido van Rossumb2493f82000-12-15 15:01:37 +00001661 print "Block number: %d, Block size: %d, Total size: %d" % (
1662 blocknum, blocksize, totalsize)