blob: 62c08c99d56ac6f74c28f5d6e0570ac56d136983 [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
Brett Cannon69200fa2004-03-23 21:26:39 +000030from urlparse import urljoin as basejoin
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000031
Skip Montanaro40fc1602001-03-01 04:27:19 +000032__all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
33 "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
Skip Montanaro44d5e0c2001-03-13 19:47:16 +000034 "urlencode", "url2pathname", "pathname2url", "splittag",
35 "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
36 "splittype", "splithost", "splituser", "splitpasswd", "splitport",
37 "splitnport", "splitquery", "splitattr", "splitvalue",
Brett Cannond75f0432007-05-16 22:42:29 +000038 "getproxies"]
Skip Montanaro40fc1602001-03-01 04:27:19 +000039
Martin v. Löwis3e865952006-01-24 15:51:21 +000040__version__ = '1.17' # XXX This version is not always updated :-(
Guido van Rossumf668d171997-06-06 21:11:11 +000041
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000042MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000043
Jack Jansendc3e3f61995-12-15 13:22:13 +000044# Helper for non-unix systems
Ronald Oussoren9545a232010-05-05 19:09:31 +000045if os.name == 'nt':
Fredrik Lundhb49f88b2000-09-24 18:51:25 +000046 from nturl2path import url2pathname, pathname2url
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000047elif os.name == 'riscos':
48 from rourl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000049else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000050 def url2pathname(pathname):
Georg Brandlc0b24732005-12-26 22:53:56 +000051 """OS-specific conversion from a relative URL of the 'file' scheme
52 to a file system path; not recommended for general use."""
Guido van Rossum367ac801999-03-12 14:31:10 +000053 return unquote(pathname)
Georg Brandlc0b24732005-12-26 22:53:56 +000054
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000055 def pathname2url(pathname):
Georg Brandlc0b24732005-12-26 22:53:56 +000056 """OS-specific conversion from a file system path to a relative URL
57 of the 'file' scheme; not recommended for general use."""
Guido van Rossum367ac801999-03-12 14:31:10 +000058 return quote(pathname)
Guido van Rossum33add0a1998-12-18 15:25:22 +000059
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000060# This really consists of two pieces:
61# (1) a class which handles opening of all sorts of URLs
62# (plus assorted utilities etc.)
63# (2) a set of functions for parsing URLs
64# XXX Should these be separated out into different modules?
65
66
67# Shortcut for basic usage
68_urlopener = None
Fred Drakedf6eca72002-04-04 20:41:34 +000069def urlopen(url, data=None, proxies=None):
Brett Cannon8bb8fa52008-07-02 01:57:08 +000070 """Create a file-like object for the specified URL to read from."""
71 from warnings import warnpy3k
Georg Brandl48e65f52010-02-06 22:44:17 +000072 warnpy3k("urllib.urlopen() has been removed in Python 3.0 in "
73 "favor of urllib2.urlopen()", stacklevel=2)
Brett Cannon8bb8fa52008-07-02 01:57:08 +000074
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000075 global _urlopener
Fred Drakedf6eca72002-04-04 20:41:34 +000076 if proxies is not None:
77 opener = FancyURLopener(proxies=proxies)
78 elif not _urlopener:
79 opener = FancyURLopener()
80 _urlopener = opener
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000081 else:
Fred Drakedf6eca72002-04-04 20:41:34 +000082 opener = _urlopener
83 if data is None:
84 return opener.open(url)
85 else:
86 return opener.open(url, data)
Fred Drake316a7932000-08-24 01:01:26 +000087def urlretrieve(url, filename=None, reporthook=None, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000088 global _urlopener
89 if not _urlopener:
90 _urlopener = FancyURLopener()
Fred Drake316a7932000-08-24 01:01:26 +000091 return _urlopener.retrieve(url, filename, reporthook, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000092def urlcleanup():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000093 if _urlopener:
94 _urlopener.cleanup()
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +000095 _safe_quoters.clear()
Antoine Pitrouca173e22009-12-08 19:35:12 +000096 ftpcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000097
Bill Janssen426ea0a2007-08-29 22:35:05 +000098# check for SSL
99try:
100 import ssl
101except:
102 _have_ssl = False
103else:
104 _have_ssl = True
105
Georg Brandlb9256022005-08-24 18:46:39 +0000106# exception raised when downloaded size does not match content-length
107class ContentTooShortError(IOError):
108 def __init__(self, message, content):
109 IOError.__init__(self, message)
110 self.content = content
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000111
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000112ftpcache = {}
113class URLopener:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000114 """Class to open URLs.
115 This is a class rather than just a subroutine because we may need
116 more than one set of global protocol-specific options.
117 Note -- this is a base class for those who don't want the
118 automatic handling of errors type 302 (relocated) and 401
119 (authorization needed)."""
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000120
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000121 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +0000122
Guido van Rossumba311382000-08-24 16:18:04 +0000123 version = "Python-urllib/%s" % __version__
124
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000125 # Constructor
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000126 def __init__(self, proxies=None, **x509):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000127 if proxies is None:
128 proxies = getproxies()
129 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
130 self.proxies = proxies
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000131 self.key_file = x509.get('key_file')
132 self.cert_file = x509.get('cert_file')
Georg Brandl0619a322006-07-26 07:40:17 +0000133 self.addheaders = [('User-Agent', self.version)]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000134 self.__tempfiles = []
135 self.__unlink = os.unlink # See cleanup()
136 self.tempcache = None
137 # Undocumented feature: if you assign {} to tempcache,
138 # it is used to cache files retrieved with
139 # self.retrieve(). This is not enabled by default
140 # since it does not work for changing documents (and I
141 # haven't got the logic to check expiration headers
142 # yet).
143 self.ftpcache = ftpcache
144 # Undocumented feature: you can use a different
145 # ftp cache by assigning to the .ftpcache member;
146 # in case you want logically independent URL openers
147 # XXX This is not threadsafe. Bah.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000149 def __del__(self):
150 self.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000151
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000152 def close(self):
153 self.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000154
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000155 def cleanup(self):
156 # This code sometimes runs when the rest of this module
157 # has already been deleted, so it can't use any globals
158 # or import anything.
159 if self.__tempfiles:
160 for file in self.__tempfiles:
161 try:
162 self.__unlink(file)
Martin v. Löwis58682b72001-08-11 15:02:57 +0000163 except OSError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000164 pass
165 del self.__tempfiles[:]
166 if self.tempcache:
167 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000168
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000169 def addheader(self, *args):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000170 """Add a header to be used by the HTTP interface only
171 e.g. u.addheader('Accept', 'sound/basic')"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000172 self.addheaders.append(args)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000173
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000174 # External interface
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000175 def open(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000176 """Use URLopener().open(file) instead of open(file, 'r')."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000177 fullurl = unwrap(toBytes(fullurl))
Senthil Kumaran7c2867f2009-04-21 03:24:19 +0000178 # percent encode url, fixing lame server errors for e.g, like space
179 # within url paths.
Senthil Kumaran18d5a692010-02-20 22:05:34 +0000180 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000181 if self.tempcache and fullurl in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000182 filename, headers = self.tempcache[fullurl]
183 fp = open(filename, 'rb')
184 return addinfourl(fp, headers, fullurl)
Martin v. Löwis1d994332000-12-03 18:30:10 +0000185 urltype, url = splittype(fullurl)
186 if not urltype:
187 urltype = 'file'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000188 if urltype in self.proxies:
Martin v. Löwis1d994332000-12-03 18:30:10 +0000189 proxy = self.proxies[urltype]
190 urltype, proxyhost = splittype(proxy)
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000191 host, selector = splithost(proxyhost)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000192 url = (host, fullurl) # Signal special case to open_*()
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000193 else:
194 proxy = None
Martin v. Löwis1d994332000-12-03 18:30:10 +0000195 name = 'open_' + urltype
196 self.type = urltype
Brett Cannonaaeffaf2004-03-23 23:50:17 +0000197 name = name.replace('-', '_')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000198 if not hasattr(self, name):
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000199 if proxy:
200 return self.open_unknown_proxy(proxy, fullurl, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000201 else:
202 return self.open_unknown(fullurl, data)
203 try:
204 if data is None:
205 return getattr(self, name)(url)
206 else:
207 return getattr(self, name)(url, data)
208 except socket.error, msg:
209 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000210
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000211 def open_unknown(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000212 """Overridable interface to open unknown URL type."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000213 type, url = splittype(fullurl)
214 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossumca445401995-08-29 19:19:12 +0000215
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000216 def open_unknown_proxy(self, proxy, fullurl, data=None):
217 """Overridable interface to open unknown URL type."""
218 type, url = splittype(fullurl)
219 raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
220
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000221 # External interface
Sjoerd Mullenderd7b86f02000-08-25 11:23:36 +0000222 def retrieve(self, url, filename=None, reporthook=None, data=None):
Brett Cannon7d618c72003-04-24 02:43:20 +0000223 """retrieve(url) returns (filename, headers) for a local object
Guido van Rossume7b146f2000-02-04 15:28:42 +0000224 or (tempfilename, headers) for a remote object."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000225 url = unwrap(toBytes(url))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000226 if self.tempcache and url in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000227 return self.tempcache[url]
228 type, url1 = splittype(url)
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000229 if filename is None and (not type or type == 'file'):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000230 try:
231 fp = self.open_local_file(url1)
232 hdrs = fp.info()
Philip Jenvey0299d0d2009-12-03 02:40:13 +0000233 fp.close()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000234 return url2pathname(splithost(url1)[1]), hdrs
Georg Brandl84fedf72010-02-06 22:59:15 +0000235 except IOError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000236 pass
Fred Drake316a7932000-08-24 01:01:26 +0000237 fp = self.open(url, data)
Benjamin Petersonb364bfe2009-03-22 17:45:11 +0000238 try:
239 headers = fp.info()
240 if filename:
241 tfp = open(filename, 'wb')
242 else:
243 import tempfile
244 garbage, path = splittype(url)
245 garbage, path = splithost(path or "")
246 path, garbage = splitquery(path or "")
247 path, garbage = splitattr(path or "")
248 suffix = os.path.splitext(path)[1]
249 (fd, filename) = tempfile.mkstemp(suffix)
250 self.__tempfiles.append(filename)
251 tfp = os.fdopen(fd, 'wb')
252 try:
253 result = filename, headers
254 if self.tempcache is not None:
255 self.tempcache[url] = result
256 bs = 1024*8
257 size = -1
258 read = 0
259 blocknum = 0
260 if reporthook:
261 if "content-length" in headers:
262 size = int(headers["Content-Length"])
263 reporthook(blocknum, bs, size)
264 while 1:
265 block = fp.read(bs)
266 if block == "":
267 break
268 read += len(block)
269 tfp.write(block)
270 blocknum += 1
271 if reporthook:
272 reporthook(blocknum, bs, size)
273 finally:
274 tfp.close()
275 finally:
276 fp.close()
Georg Brandlb9256022005-08-24 18:46:39 +0000277
278 # raise exception if actual size does not match content-length header
279 if size >= 0 and read < size:
280 raise ContentTooShortError("retrieval incomplete: got only %i out "
281 "of %i bytes" % (read, size), result)
282
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000283 return result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000284
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000285 # Each method named open_<type> knows how to open that type of URL
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000286
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000287 def open_http(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000288 """Use HTTP protocol."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000289 import httplib
290 user_passwd = None
Martin v. Löwis3e865952006-01-24 15:51:21 +0000291 proxy_passwd= None
Walter Dörwald65230a22002-06-03 15:58:32 +0000292 if isinstance(url, str):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000293 host, selector = splithost(url)
294 if host:
295 user_passwd, host = splituser(host)
296 host = unquote(host)
297 realhost = host
298 else:
299 host, selector = url
Martin v. Löwis3e865952006-01-24 15:51:21 +0000300 # check whether the proxy contains authorization information
301 proxy_passwd, host = splituser(host)
302 # now we proceed with the url we want to obtain
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000303 urltype, rest = splittype(selector)
304 url = rest
305 user_passwd = None
Guido van Rossumb2493f82000-12-15 15:01:37 +0000306 if urltype.lower() != 'http':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000307 realhost = None
308 else:
309 realhost, rest = splithost(rest)
310 if realhost:
311 user_passwd, realhost = splituser(realhost)
312 if user_passwd:
313 selector = "%s://%s%s" % (urltype, realhost, rest)
Tim Peters55c12d42001-08-09 18:04:14 +0000314 if proxy_bypass(realhost):
315 host = realhost
316
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000317 #print "proxy via http:", host, selector
318 if not host: raise IOError, ('http error', 'no host given')
Tim Peters92037a12006-01-24 22:44:08 +0000319
Martin v. Löwis3e865952006-01-24 15:51:21 +0000320 if proxy_passwd:
321 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000322 proxy_auth = base64.b64encode(proxy_passwd).strip()
Martin v. Löwis3e865952006-01-24 15:51:21 +0000323 else:
324 proxy_auth = None
325
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000326 if user_passwd:
327 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000328 auth = base64.b64encode(user_passwd).strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000329 else:
330 auth = None
331 h = httplib.HTTP(host)
332 if data is not None:
333 h.putrequest('POST', selector)
Georg Brandl0619a322006-07-26 07:40:17 +0000334 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
335 h.putheader('Content-Length', '%d' % len(data))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000336 else:
337 h.putrequest('GET', selector)
Martin v. Löwis3e865952006-01-24 15:51:21 +0000338 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000339 if auth: h.putheader('Authorization', 'Basic %s' % auth)
340 if realhost: h.putheader('Host', realhost)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000341 for args in self.addheaders: h.putheader(*args)
Kristján Valur Jónsson84040db2009-01-09 20:27:16 +0000342 h.endheaders(data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000343 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000344 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000345 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000346 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000347 # something went wrong with the HTTP status line
348 raise IOError, ('http protocol error', 0,
349 'got a bad status line', None)
Sean Reifscheidera1afbf62007-09-19 07:52:56 +0000350 # According to RFC 2616, "2xx" code indicates that the client's
351 # request was successfully received, understood, and accepted.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000352 if (200 <= errcode < 300):
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000353 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000354 else:
355 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000356 return self.http_error(url, fp, errcode, errmsg, headers)
Guido van Rossum29aab751999-03-09 19:31:21 +0000357 else:
358 return self.http_error(url, fp, errcode, errmsg, headers, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000359
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000360 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000361 """Handle http errors.
362 Derived class can override this, or provide specific handlers
363 named http_error_DDD where DDD is the 3-digit error code."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000364 # First check if there's a specific handler for this error
365 name = 'http_error_%d' % errcode
366 if hasattr(self, name):
367 method = getattr(self, name)
368 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000369 result = method(url, fp, errcode, errmsg, headers)
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000370 else:
371 result = method(url, fp, errcode, errmsg, headers, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000372 if result: return result
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000373 return self.http_error_default(url, fp, errcode, errmsg, headers)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000374
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000375 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000376 """Default error handler: close the connection and raise IOError."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000377 void = fp.read()
378 fp.close()
379 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000380
Bill Janssen426ea0a2007-08-29 22:35:05 +0000381 if _have_ssl:
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000382 def open_https(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000383 """Use HTTPS protocol."""
Bill Janssen426ea0a2007-08-29 22:35:05 +0000384
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000385 import httplib
Fred Drake567ca8e2000-08-21 21:42:42 +0000386 user_passwd = None
Martin v. Löwis3e865952006-01-24 15:51:21 +0000387 proxy_passwd = None
Walter Dörwald65230a22002-06-03 15:58:32 +0000388 if isinstance(url, str):
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000389 host, selector = splithost(url)
Fred Drake567ca8e2000-08-21 21:42:42 +0000390 if host:
391 user_passwd, host = splituser(host)
392 host = unquote(host)
393 realhost = host
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000394 else:
395 host, selector = url
Martin v. Löwis3e865952006-01-24 15:51:21 +0000396 # here, we determine, whether the proxy contains authorization information
397 proxy_passwd, host = splituser(host)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000398 urltype, rest = splittype(selector)
Fred Drake567ca8e2000-08-21 21:42:42 +0000399 url = rest
400 user_passwd = None
Guido van Rossumb2493f82000-12-15 15:01:37 +0000401 if urltype.lower() != 'https':
Fred Drake567ca8e2000-08-21 21:42:42 +0000402 realhost = None
403 else:
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000404 realhost, rest = splithost(rest)
Fred Drake567ca8e2000-08-21 21:42:42 +0000405 if realhost:
406 user_passwd, realhost = splituser(realhost)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000407 if user_passwd:
408 selector = "%s://%s%s" % (urltype, realhost, rest)
Andrew M. Kuchling7ad47922000-06-10 01:41:48 +0000409 #print "proxy via https:", host, selector
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000410 if not host: raise IOError, ('https error', 'no host given')
Martin v. Löwis3e865952006-01-24 15:51:21 +0000411 if proxy_passwd:
412 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000413 proxy_auth = base64.b64encode(proxy_passwd).strip()
Martin v. Löwis3e865952006-01-24 15:51:21 +0000414 else:
415 proxy_auth = None
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000416 if user_passwd:
417 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000418 auth = base64.b64encode(user_passwd).strip()
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000419 else:
420 auth = None
421 h = httplib.HTTPS(host, 0,
422 key_file=self.key_file,
423 cert_file=self.cert_file)
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000424 if data is not None:
425 h.putrequest('POST', selector)
Georg Brandl0619a322006-07-26 07:40:17 +0000426 h.putheader('Content-Type',
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000427 'application/x-www-form-urlencoded')
Georg Brandl0619a322006-07-26 07:40:17 +0000428 h.putheader('Content-Length', '%d' % len(data))
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000429 else:
430 h.putrequest('GET', selector)
Andrew M. Kuchling52278572006-12-19 15:11:41 +0000431 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
432 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Fred Drake567ca8e2000-08-21 21:42:42 +0000433 if realhost: h.putheader('Host', realhost)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000434 for args in self.addheaders: h.putheader(*args)
Kristján Valur Jónsson84040db2009-01-09 20:27:16 +0000435 h.endheaders(data)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000436 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000437 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000438 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000439 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000440 # something went wrong with the HTTP status line
441 raise IOError, ('http protocol error', 0,
442 'got a bad status line', None)
Georg Brandl9b915672007-09-24 18:08:24 +0000443 # According to RFC 2616, "2xx" code indicates that the client's
444 # request was successfully received, understood, and accepted.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000445 if (200 <= errcode < 300):
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000446 return addinfourl(fp, headers, "https:" + url, errcode)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000447 else:
Fred Drake567ca8e2000-08-21 21:42:42 +0000448 if data is None:
449 return self.http_error(url, fp, errcode, errmsg, headers)
450 else:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000451 return self.http_error(url, fp, errcode, errmsg, headers,
452 data)
Fred Drake567ca8e2000-08-21 21:42:42 +0000453
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000454 def open_file(self, url):
Neal Norwitzc5d0dbd2006-04-09 04:00:49 +0000455 """Use local file or FTP depending on form of URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000456 if not isinstance(url, str):
457 raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
Jack Jansen4ef11032002-09-12 20:14:04 +0000458 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000459 return self.open_ftp(url)
460 else:
461 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000462
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000463 def open_local_file(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000464 """Use local file."""
Georg Brandl5a096e12007-01-22 19:40:21 +0000465 import mimetypes, mimetools, email.utils
Raymond Hettingera6172712004-12-31 19:15:26 +0000466 try:
467 from cStringIO import StringIO
468 except ImportError:
469 from StringIO import StringIO
Guido van Rossumf0713d32001-08-09 17:43:35 +0000470 host, file = splithost(url)
471 localname = url2pathname(file)
Guido van Rossuma2da3052002-04-15 00:25:01 +0000472 try:
473 stats = os.stat(localname)
474 except OSError, e:
475 raise IOError(e.errno, e.strerror, e.filename)
Walter Dörwald92b48b72002-03-22 17:30:38 +0000476 size = stats.st_size
Georg Brandl5a096e12007-01-22 19:40:21 +0000477 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000478 mtype = mimetypes.guess_type(url)[0]
Raymond Hettingera6172712004-12-31 19:15:26 +0000479 headers = mimetools.Message(StringIO(
Guido van Rossumf0713d32001-08-09 17:43:35 +0000480 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
481 (mtype or 'text/plain', size, modified)))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000482 if not host:
Guido van Rossum336a2011999-06-24 15:27:36 +0000483 urlfile = file
484 if file[:1] == '/':
485 urlfile = 'file://' + file
Guido van Rossumf0713d32001-08-09 17:43:35 +0000486 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000487 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000488 host, port = splitport(host)
489 if not port \
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000490 and socket.gethostbyname(host) in (localhost(), thishost()):
Guido van Rossum336a2011999-06-24 15:27:36 +0000491 urlfile = file
492 if file[:1] == '/':
493 urlfile = 'file://' + file
Guido van Rossumf0713d32001-08-09 17:43:35 +0000494 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000495 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000496 raise IOError, ('local file error', 'not on local host')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000497
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000498 def open_ftp(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000499 """Use FTP protocol."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000500 if not isinstance(url, str):
501 raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
Raymond Hettingera6172712004-12-31 19:15:26 +0000502 import mimetypes, mimetools
503 try:
504 from cStringIO import StringIO
505 except ImportError:
506 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000507 host, path = splithost(url)
508 if not host: raise IOError, ('ftp error', 'no host given')
509 host, port = splitport(host)
510 user, host = splituser(host)
511 if user: user, passwd = splitpasswd(user)
512 else: passwd = None
513 host = unquote(host)
Senthil Kumaran9fce5512010-11-20 11:24:08 +0000514 user = user or ''
515 passwd = passwd or ''
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000516 host = socket.gethostbyname(host)
517 if not port:
518 import ftplib
519 port = ftplib.FTP_PORT
520 else:
521 port = int(port)
522 path, attrs = splitattr(path)
523 path = unquote(path)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000524 dirs = path.split('/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000525 dirs, file = dirs[:-1], dirs[-1]
526 if dirs and not dirs[0]: dirs = dirs[1:]
Guido van Rossum5e006a31999-08-18 17:40:33 +0000527 if dirs and not dirs[0]: dirs[0] = '/'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000528 key = user, host, port, '/'.join(dirs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000529 # XXX thread unsafe!
530 if len(self.ftpcache) > MAXFTPCACHE:
531 # Prune the cache, rather arbitrarily
532 for k in self.ftpcache.keys():
533 if k != key:
534 v = self.ftpcache[k]
535 del self.ftpcache[k]
536 v.close()
537 try:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000538 if not key in self.ftpcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000539 self.ftpcache[key] = \
540 ftpwrapper(user, passwd, host, port, dirs)
541 if not file: type = 'D'
542 else: type = 'I'
543 for attr in attrs:
544 attr, value = splitvalue(attr)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000545 if attr.lower() == 'type' and \
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000546 value in ('a', 'A', 'i', 'I', 'd', 'D'):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000547 type = value.upper()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000548 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000549 mtype = mimetypes.guess_type("ftp:" + url)[0]
550 headers = ""
551 if mtype:
552 headers += "Content-Type: %s\n" % mtype
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000553 if retrlen is not None and retrlen >= 0:
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000554 headers += "Content-Length: %d\n" % retrlen
Raymond Hettingera6172712004-12-31 19:15:26 +0000555 headers = mimetools.Message(StringIO(headers))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000556 return addinfourl(fp, headers, "ftp:" + url)
557 except ftperrors(), msg:
558 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000559
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000560 def open_data(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000561 """Use "data" URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000562 if not isinstance(url, str):
563 raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000564 # ignore POSTed data
565 #
566 # syntax of data URLs:
567 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
568 # mediatype := [ type "/" subtype ] *( ";" parameter )
569 # data := *urlchar
570 # parameter := attribute "=" value
Raymond Hettingera6172712004-12-31 19:15:26 +0000571 import mimetools
572 try:
573 from cStringIO import StringIO
574 except ImportError:
575 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000576 try:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000577 [type, data] = url.split(',', 1)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000578 except ValueError:
579 raise IOError, ('data error', 'bad data URL')
580 if not type:
581 type = 'text/plain;charset=US-ASCII'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000582 semi = type.rfind(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000583 if semi >= 0 and '=' not in type[semi:]:
584 encoding = type[semi+1:]
585 type = type[:semi]
586 else:
587 encoding = ''
588 msg = []
Senthil Kumaran1b7f9e52010-05-01 08:01:56 +0000589 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000590 time.gmtime(time.time())))
591 msg.append('Content-type: %s' % type)
592 if encoding == 'base64':
593 import base64
594 data = base64.decodestring(data)
595 else:
596 data = unquote(data)
Georg Brandl0619a322006-07-26 07:40:17 +0000597 msg.append('Content-Length: %d' % len(data))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000598 msg.append('')
599 msg.append(data)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000600 msg = '\n'.join(msg)
Raymond Hettingera6172712004-12-31 19:15:26 +0000601 f = StringIO(msg)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000602 headers = mimetools.Message(f, 0)
Georg Brandl1f663572005-11-26 16:50:44 +0000603 #f.fileno = None # needed for addinfourl
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000604 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000605
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000606
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000607class FancyURLopener(URLopener):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000608 """Derived class with handlers for errors we can handle (perhaps)."""
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000609
Neal Norwitz60e04cd2002-06-11 13:38:51 +0000610 def __init__(self, *args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000611 URLopener.__init__(self, *args, **kwargs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000612 self.auth_cache = {}
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000613 self.tries = 0
614 self.maxtries = 10
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000615
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000616 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000617 """Default error handling -- don't raise an exception."""
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000618 return addinfourl(fp, headers, "http:" + url, errcode)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000619
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000620 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000621 """Error 302 -- relocated (temporarily)."""
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000622 self.tries += 1
623 if self.maxtries and self.tries >= self.maxtries:
624 if hasattr(self, "http_error_500"):
625 meth = self.http_error_500
626 else:
627 meth = self.http_error_default
628 self.tries = 0
629 return meth(url, fp, 500,
630 "Internal Server Error: Redirect Recursion", headers)
631 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
632 data)
633 self.tries = 0
634 return result
635
636 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000637 if 'location' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000638 newurl = headers['location']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000639 elif 'uri' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000640 newurl = headers['uri']
641 else:
642 return
643 void = fp.read()
644 fp.close()
Guido van Rossum3527f591999-03-29 20:23:41 +0000645 # In case the server sent a relative URL, join with original:
Moshe Zadka5d87d472001-04-09 14:54:21 +0000646 newurl = basejoin(self.type + ":" + url, newurl)
guido@google.com60a4a902011-03-24 08:07:45 -0700647
648 # For security reasons we do not allow redirects to protocols
guido@google.com2bc23b82011-03-24 10:44:17 -0700649 # other than HTTP, HTTPS or FTP.
guido@google.com60a4a902011-03-24 08:07:45 -0700650 newurl_lower = newurl.lower()
651 if not (newurl_lower.startswith('http://') or
guido@google.com2bc23b82011-03-24 10:44:17 -0700652 newurl_lower.startswith('https://') or
653 newurl_lower.startswith('ftp://')):
guido@google.comf1509302011-03-28 13:47:01 -0700654 raise IOError('redirect error', errcode,
655 errmsg + " - Redirection to url '%s' is not allowed" %
656 newurl,
657 headers)
guido@google.com60a4a902011-03-24 08:07:45 -0700658
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000659 return self.open(newurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000660
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000661 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000662 """Error 301 -- also relocated (permanently)."""
663 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000664
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000665 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
666 """Error 303 -- also relocated (essentially identical to 302)."""
667 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
668
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000669 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
670 """Error 307 -- relocated, but turn POST into error."""
671 if data is None:
672 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
673 else:
674 return self.http_error_default(url, fp, errcode, errmsg, headers)
675
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000676 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000677 """Error 401 -- authentication required.
Martin v. Löwis3e865952006-01-24 15:51:21 +0000678 This function supports Basic authentication only."""
Raymond Hettinger54f02222002-06-01 14:18:47 +0000679 if not 'www-authenticate' in headers:
Tim Peters85ba6732001-02-28 08:26:44 +0000680 URLopener.http_error_default(self, url, fp,
Fred Drakec680ae82001-10-13 18:37:07 +0000681 errcode, errmsg, headers)
Moshe Zadkae99bd172001-02-27 06:27:04 +0000682 stuff = headers['www-authenticate']
683 import re
684 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
685 if not match:
Tim Peters85ba6732001-02-28 08:26:44 +0000686 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000687 errcode, errmsg, headers)
688 scheme, realm = match.groups()
689 if scheme.lower() != 'basic':
Tim Peters85ba6732001-02-28 08:26:44 +0000690 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000691 errcode, errmsg, headers)
692 name = 'retry_' + self.type + '_basic_auth'
693 if data is None:
694 return getattr(self,name)(url, realm)
695 else:
696 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000697
Martin v. Löwis3e865952006-01-24 15:51:21 +0000698 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
699 """Error 407 -- proxy authentication required.
700 This function supports Basic authentication only."""
701 if not 'proxy-authenticate' in headers:
702 URLopener.http_error_default(self, url, fp,
703 errcode, errmsg, headers)
704 stuff = headers['proxy-authenticate']
705 import re
706 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
707 if not match:
708 URLopener.http_error_default(self, url, fp,
709 errcode, errmsg, headers)
710 scheme, realm = match.groups()
711 if scheme.lower() != 'basic':
712 URLopener.http_error_default(self, url, fp,
713 errcode, errmsg, headers)
714 name = 'retry_proxy_' + self.type + '_basic_auth'
715 if data is None:
716 return getattr(self,name)(url, realm)
717 else:
718 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000719
Martin v. Löwis3e865952006-01-24 15:51:21 +0000720 def retry_proxy_http_basic_auth(self, url, realm, data=None):
721 host, selector = splithost(url)
722 newurl = 'http://' + host + selector
723 proxy = self.proxies['http']
724 urltype, proxyhost = splittype(proxy)
725 proxyhost, proxyselector = splithost(proxyhost)
726 i = proxyhost.find('@') + 1
727 proxyhost = proxyhost[i:]
728 user, passwd = self.get_user_passwd(proxyhost, realm, i)
729 if not (user or passwd): return None
730 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
731 self.proxies['http'] = 'http://' + proxyhost + proxyselector
732 if data is None:
733 return self.open(newurl)
734 else:
735 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000736
Martin v. Löwis3e865952006-01-24 15:51:21 +0000737 def retry_proxy_https_basic_auth(self, url, realm, data=None):
738 host, selector = splithost(url)
739 newurl = 'https://' + host + selector
740 proxy = self.proxies['https']
741 urltype, proxyhost = splittype(proxy)
742 proxyhost, proxyselector = splithost(proxyhost)
743 i = proxyhost.find('@') + 1
744 proxyhost = proxyhost[i:]
745 user, passwd = self.get_user_passwd(proxyhost, realm, i)
746 if not (user or passwd): return None
747 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
748 self.proxies['https'] = 'https://' + proxyhost + proxyselector
749 if data is None:
750 return self.open(newurl)
751 else:
752 return self.open(newurl, data)
Tim Peters92037a12006-01-24 22:44:08 +0000753
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000754 def retry_http_basic_auth(self, url, realm, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000755 host, selector = splithost(url)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000756 i = host.find('@') + 1
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000757 host = host[i:]
758 user, passwd = self.get_user_passwd(host, realm, i)
759 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000760 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000761 newurl = 'http://' + host + selector
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000762 if data is None:
763 return self.open(newurl)
764 else:
765 return self.open(newurl, data)
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000766
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000767 def retry_https_basic_auth(self, url, realm, data=None):
Tim Peterse1190062001-01-15 03:34:38 +0000768 host, selector = splithost(url)
769 i = host.find('@') + 1
770 host = host[i:]
771 user, passwd = self.get_user_passwd(host, realm, i)
772 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000773 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Martin v. Löwis3e865952006-01-24 15:51:21 +0000774 newurl = 'https://' + host + selector
775 if data is None:
776 return self.open(newurl)
777 else:
778 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000779
Florent Xiclunae127e242010-05-17 10:39:07 +0000780 def get_user_passwd(self, host, realm, clear_cache=0):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000781 key = realm + '@' + host.lower()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000782 if key in self.auth_cache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000783 if clear_cache:
784 del self.auth_cache[key]
785 else:
786 return self.auth_cache[key]
787 user, passwd = self.prompt_user_passwd(host, realm)
788 if user or passwd: self.auth_cache[key] = (user, passwd)
789 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000790
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000791 def prompt_user_passwd(self, host, realm):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000792 """Override this in a GUI environment!"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000793 import getpass
794 try:
795 user = raw_input("Enter username for %s at %s: " % (realm,
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000796 host))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000797 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
798 (user, realm, host))
799 return user, passwd
800 except KeyboardInterrupt:
801 print
802 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000803
804
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000805# Utility functions
806
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000807_localhost = None
808def localhost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000809 """Return the IP address of the magic hostname 'localhost'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000810 global _localhost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000811 if _localhost is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000812 _localhost = socket.gethostbyname('localhost')
813 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000814
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000815_thishost = None
816def thishost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000817 """Return the IP address of the current host."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000818 global _thishost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000819 if _thishost is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000820 _thishost = socket.gethostbyname(socket.gethostname())
821 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000822
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000823_ftperrors = None
824def ftperrors():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000825 """Return the set of errors raised by the FTP class."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000826 global _ftperrors
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000827 if _ftperrors is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000828 import ftplib
829 _ftperrors = ftplib.all_errors
830 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000831
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000832_noheaders = None
833def noheaders():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000834 """Return an empty mimetools.Message object."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000835 global _noheaders
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000836 if _noheaders is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000837 import mimetools
Raymond Hettingera6172712004-12-31 19:15:26 +0000838 try:
839 from cStringIO import StringIO
840 except ImportError:
841 from StringIO import StringIO
842 _noheaders = mimetools.Message(StringIO(), 0)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000843 _noheaders.fp.close() # Recycle file descriptor
844 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000845
846
847# Utility classes
848
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000849class ftpwrapper:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000850 """Class used by open_ftp() for cache of open FTP connections."""
851
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000852 def __init__(self, user, passwd, host, port, dirs,
853 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000854 self.user = user
855 self.passwd = passwd
856 self.host = host
857 self.port = port
858 self.dirs = dirs
Facundo Batista711a54e2007-05-24 17:50:54 +0000859 self.timeout = timeout
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000860 self.init()
Guido van Rossume7b146f2000-02-04 15:28:42 +0000861
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000862 def init(self):
863 import ftplib
864 self.busy = 0
865 self.ftp = ftplib.FTP()
Facundo Batista711a54e2007-05-24 17:50:54 +0000866 self.ftp.connect(self.host, self.port, self.timeout)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000867 self.ftp.login(self.user, self.passwd)
868 for dir in self.dirs:
869 self.ftp.cwd(dir)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000870
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000871 def retrfile(self, file, type):
872 import ftplib
873 self.endtransfer()
874 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
875 else: cmd = 'TYPE ' + type; isdir = 0
876 try:
877 self.ftp.voidcmd(cmd)
878 except ftplib.all_errors:
879 self.init()
880 self.ftp.voidcmd(cmd)
881 conn = None
882 if file and not isdir:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000883 # Try to retrieve as a file
884 try:
885 cmd = 'RETR ' + file
886 conn = self.ftp.ntransfercmd(cmd)
887 except ftplib.error_perm, reason:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000888 if str(reason)[:3] != '550':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000889 raise IOError, ('ftp error', reason), sys.exc_info()[2]
890 if not conn:
891 # Set transfer mode to ASCII!
892 self.ftp.voidcmd('TYPE A')
Georg Brandld5e6cf22008-01-20 12:18:17 +0000893 # Try a directory listing. Verify that directory exists.
894 if file:
895 pwd = self.ftp.pwd()
896 try:
897 try:
898 self.ftp.cwd(file)
899 except ftplib.error_perm, reason:
900 raise IOError, ('ftp error', reason), sys.exc_info()[2]
901 finally:
902 self.ftp.cwd(pwd)
903 cmd = 'LIST ' + file
904 else:
905 cmd = 'LIST'
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000906 conn = self.ftp.ntransfercmd(cmd)
907 self.busy = 1
908 # Pass back both a suitably decorated object and a retrieval length
909 return (addclosehook(conn[0].makefile('rb'),
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000910 self.endtransfer), conn[1])
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000911 def endtransfer(self):
912 if not self.busy:
913 return
914 self.busy = 0
915 try:
916 self.ftp.voidresp()
917 except ftperrors():
918 pass
Guido van Rossume7b146f2000-02-04 15:28:42 +0000919
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000920 def close(self):
921 self.endtransfer()
922 try:
923 self.ftp.close()
924 except ftperrors():
925 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000926
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000927class addbase:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000928 """Base class for addinfo and addclosehook."""
929
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000930 def __init__(self, fp):
931 self.fp = fp
932 self.read = self.fp.read
933 self.readline = self.fp.readline
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000934 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
Georg Brandl1f663572005-11-26 16:50:44 +0000935 if hasattr(self.fp, "fileno"):
936 self.fileno = self.fp.fileno
937 else:
938 self.fileno = lambda: None
Raymond Hettinger42182eb2003-03-09 05:33:33 +0000939 if hasattr(self.fp, "__iter__"):
940 self.__iter__ = self.fp.__iter__
941 if hasattr(self.fp, "next"):
942 self.next = self.fp.next
Guido van Rossume7b146f2000-02-04 15:28:42 +0000943
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000944 def __repr__(self):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000945 return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
946 id(self), self.fp)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000947
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000948 def close(self):
949 self.read = None
950 self.readline = None
951 self.readlines = None
952 self.fileno = None
953 if self.fp: self.fp.close()
954 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000955
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000956class addclosehook(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000957 """Class to add a close hook to an open file."""
958
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000959 def __init__(self, fp, closehook, *hookargs):
960 addbase.__init__(self, fp)
961 self.closehook = closehook
962 self.hookargs = hookargs
Guido van Rossume7b146f2000-02-04 15:28:42 +0000963
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000964 def close(self):
Guido van Rossumc580dae2000-05-24 13:21:46 +0000965 addbase.close(self)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000966 if self.closehook:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000967 self.closehook(*self.hookargs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000968 self.closehook = None
969 self.hookargs = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000970
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000971class addinfo(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000972 """class to add an info() method to an open file."""
973
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000974 def __init__(self, fp, headers):
975 addbase.__init__(self, fp)
976 self.headers = headers
Guido van Rossume7b146f2000-02-04 15:28:42 +0000977
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000978 def info(self):
979 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000980
Guido van Rossume6ad8911996-09-10 17:02:56 +0000981class addinfourl(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000982 """class to add info() and geturl() methods to an open file."""
983
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000984 def __init__(self, fp, headers, url, code=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000985 addbase.__init__(self, fp)
986 self.headers = headers
987 self.url = url
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000988 self.code = code
Guido van Rossume7b146f2000-02-04 15:28:42 +0000989
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000990 def info(self):
991 return self.headers
Guido van Rossume7b146f2000-02-04 15:28:42 +0000992
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000993 def getcode(self):
994 return self.code
995
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000996 def geturl(self):
997 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +0000998
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000999
Guido van Rossum7c395db1994-07-04 22:14:49 +00001000# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +00001001# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001002# splittype('type:opaquestring') --> 'type', 'opaquestring'
1003# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +00001004# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
1005# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001006# splitport('host:port') --> 'host', 'port'
1007# splitquery('/path?query') --> '/path', 'query'
1008# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +00001009# splitattr('/path;attr1=value1;attr2=value2;...') ->
1010# '/path', ['attr1=value1', 'attr2=value2', ...]
1011# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001012# unquote('abc%20def') -> 'abc def'
1013# quote('abc def') -> 'abc%20def')
1014
Walter Dörwald65230a22002-06-03 15:58:32 +00001015try:
1016 unicode
1017except NameError:
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001018 def _is_unicode(x):
1019 return 0
Walter Dörwald65230a22002-06-03 15:58:32 +00001020else:
1021 def _is_unicode(x):
1022 return isinstance(x, unicode)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001023
Martin v. Löwis1d994332000-12-03 18:30:10 +00001024def toBytes(url):
1025 """toBytes(u"URL") --> 'URL'."""
1026 # Most URL schemes require ASCII. If that changes, the conversion
1027 # can be relaxed
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001028 if _is_unicode(url):
Martin v. Löwis1d994332000-12-03 18:30:10 +00001029 try:
1030 url = url.encode("ASCII")
1031 except UnicodeError:
Guido van Rossumb2493f82000-12-15 15:01:37 +00001032 raise UnicodeError("URL " + repr(url) +
1033 " contains non-ASCII characters")
Martin v. Löwis1d994332000-12-03 18:30:10 +00001034 return url
1035
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001036def unwrap(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001037 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001038 url = url.strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001039 if url[:1] == '<' and url[-1:] == '>':
Guido van Rossumb2493f82000-12-15 15:01:37 +00001040 url = url[1:-1].strip()
1041 if url[:4] == 'URL:': url = url[4:].strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001042 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001043
Guido van Rossum332e1441997-09-29 23:23:46 +00001044_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001045def splittype(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001046 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001047 global _typeprog
1048 if _typeprog is None:
1049 import re
1050 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +00001051
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001052 match = _typeprog.match(url)
1053 if match:
1054 scheme = match.group(1)
Fred Drake9e94afd2000-07-01 07:03:30 +00001055 return scheme.lower(), url[len(scheme) + 1:]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001056 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001057
Guido van Rossum332e1441997-09-29 23:23:46 +00001058_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001059def splithost(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001060 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001061 global _hostprog
1062 if _hostprog is None:
1063 import re
Georg Brandl1c168d82006-03-26 20:59:38 +00001064 _hostprog = re.compile('^//([^/?]*)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001065
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001066 match = _hostprog.match(url)
Senthil Kumaran0b7cac12010-11-22 05:04:33 +00001067 if match:
1068 host_port = match.group(1)
1069 path = match.group(2)
1070 if path and not path.startswith('/'):
1071 path = '/' + path
1072 return host_port, path
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001073 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001074
Guido van Rossum332e1441997-09-29 23:23:46 +00001075_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001076def splituser(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001077 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001078 global _userprog
1079 if _userprog is None:
1080 import re
Raymond Hettingerf2e45dd2002-08-18 20:08:56 +00001081 _userprog = re.compile('^(.*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001082
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001083 match = _userprog.match(host)
Senthil Kumaran9fce5512010-11-20 11:24:08 +00001084 if match: return match.group(1, 2)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001085 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +00001086
Guido van Rossum332e1441997-09-29 23:23:46 +00001087_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001088def splitpasswd(user):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001089 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001090 global _passwdprog
1091 if _passwdprog is None:
1092 import re
Senthil Kumaran5e95e762009-03-30 21:51:50 +00001093 _passwdprog = re.compile('^([^:]*):(.*)$',re.S)
Guido van Rossum332e1441997-09-29 23:23:46 +00001094
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001095 match = _passwdprog.match(user)
1096 if match: return match.group(1, 2)
1097 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001098
Guido van Rossume7b146f2000-02-04 15:28:42 +00001099# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum332e1441997-09-29 23:23:46 +00001100_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001101def splitport(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001102 """splitport('host:port') --> 'host', 'port'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001103 global _portprog
1104 if _portprog is None:
1105 import re
1106 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001107
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001108 match = _portprog.match(host)
1109 if match: return match.group(1, 2)
1110 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001111
Guido van Rossum332e1441997-09-29 23:23:46 +00001112_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +00001113def splitnport(host, defport=-1):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001114 """Split host and port, returning numeric port.
1115 Return given default port if no ':' found; defaults to -1.
1116 Return numerical port if a valid number are found after ':'.
1117 Return None if ':' but not a valid number."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001118 global _nportprog
1119 if _nportprog is None:
1120 import re
1121 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001122
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001123 match = _nportprog.match(host)
1124 if match:
1125 host, port = match.group(1, 2)
1126 try:
Guido van Rossumb2493f82000-12-15 15:01:37 +00001127 if not port: raise ValueError, "no digits"
1128 nport = int(port)
1129 except ValueError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001130 nport = None
1131 return host, nport
1132 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +00001133
Guido van Rossum332e1441997-09-29 23:23:46 +00001134_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001135def splitquery(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001136 """splitquery('/path?query') --> '/path', 'query'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001137 global _queryprog
1138 if _queryprog is None:
1139 import re
1140 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001141
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001142 match = _queryprog.match(url)
1143 if match: return match.group(1, 2)
1144 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001145
Guido van Rossum332e1441997-09-29 23:23:46 +00001146_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001147def splittag(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001148 """splittag('/path#tag') --> '/path', 'tag'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001149 global _tagprog
1150 if _tagprog is None:
1151 import re
1152 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001153
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001154 match = _tagprog.match(url)
1155 if match: return match.group(1, 2)
1156 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001157
Guido van Rossum7c395db1994-07-04 22:14:49 +00001158def splitattr(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001159 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1160 '/path', ['attr1=value1', 'attr2=value2', ...]."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001161 words = url.split(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001162 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +00001163
Guido van Rossum332e1441997-09-29 23:23:46 +00001164_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001165def splitvalue(attr):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001166 """splitvalue('attr=value') --> 'attr', 'value'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001167 global _valueprog
1168 if _valueprog is None:
1169 import re
1170 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001171
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001172 match = _valueprog.match(attr)
1173 if match: return match.group(1, 2)
1174 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001175
R. David Murraybfbdefe2010-05-25 15:20:46 +00001176# urlparse contains a duplicate of this method to avoid a circular import. If
1177# you update this method, also update the copy in urlparse. This code
1178# duplication does not exist in Python3.
1179
Senthil Kumaranf3e9b2a2010-03-18 12:14:15 +00001180_hexdig = '0123456789ABCDEFabcdef'
Florent Xiclunae127e242010-05-17 10:39:07 +00001181_hextochr = dict((a + b, chr(int(a + b, 16)))
1182 for a in _hexdig for b in _hexdig)
Raymond Hettinger803ce802005-09-10 06:49:04 +00001183
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001184def unquote(s):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001185 """unquote('abc%20def') -> 'abc def'."""
Raymond Hettinger803ce802005-09-10 06:49:04 +00001186 res = s.split('%')
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001187 # fastpath
1188 if len(res) == 1:
1189 return s
1190 s = res[0]
1191 for item in res[1:]:
Raymond Hettinger803ce802005-09-10 06:49:04 +00001192 try:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001193 s += _hextochr[item[:2]] + item[2:]
Raymond Hettinger803ce802005-09-10 06:49:04 +00001194 except KeyError:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001195 s += '%' + item
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +00001196 except UnicodeDecodeError:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001197 s += unichr(int(item[:2], 16)) + item[2:]
1198 return s
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001199
Guido van Rossum0564e121996-12-13 14:47:36 +00001200def unquote_plus(s):
Skip Montanaro79f1c172000-08-22 03:00:52 +00001201 """unquote('%7e/abc+def') -> '~/abc def'"""
Brett Cannonaaeffaf2004-03-23 23:50:17 +00001202 s = s.replace('+', ' ')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001203 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +00001204
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001205always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Jeremy Hylton6102e292000-08-31 15:48:10 +00001206 'abcdefghijklmnopqrstuvwxyz'
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001207 '0123456789' '_.-')
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001208_safe_map = {}
1209for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
1210 _safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i)
1211_safe_quoters = {}
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001212
Senthil Kumaran880685f2010-07-22 01:47:30 +00001213def quote(s, safe='/'):
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001214 """quote('abc def') -> 'abc%20def'
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001215
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001216 Each part of a URL, e.g. the path info, the query, etc., has a
1217 different set of reserved characters that must be quoted.
1218
1219 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
1220 the following reserved characters.
1221
1222 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
1223 "$" | ","
1224
1225 Each of these characters is reserved in some component of a URL,
1226 but not necessarily in all of them.
1227
1228 By default, the quote function is intended for quoting the path
1229 section of a URL. Thus, it will not encode '/'. This character
1230 is reserved, but in typical usage the quote function is being
1231 called on a path where the existing slash characters are used as
1232 reserved characters.
1233 """
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001234 # fastpath
1235 if not s:
Senthil Kumaranc7743aa2010-07-19 17:35:50 +00001236 if s is None:
1237 raise TypeError('None object cannot be quoted')
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001238 return s
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001239 cachekey = (safe, always_safe)
1240 try:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001241 (quoter, safe) = _safe_quoters[cachekey]
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001242 except KeyError:
Florent Xiclunaaf87f9f2010-05-17 13:35:09 +00001243 safe_map = _safe_map.copy()
1244 safe_map.update([(c, c) for c in safe])
1245 quoter = safe_map.__getitem__
1246 safe = always_safe + safe
1247 _safe_quoters[cachekey] = (quoter, safe)
1248 if not s.rstrip(safe):
1249 return s
1250 return ''.join(map(quoter, s))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001251
Senthil Kumaran880685f2010-07-22 01:47:30 +00001252def quote_plus(s, safe=''):
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001253 """Quote the query fragment of a URL; replacing ' ' with '+'"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001254 if ' ' in s:
Senthil Kumaran880685f2010-07-22 01:47:30 +00001255 s = quote(s, safe + ' ')
Raymond Hettingercf6b6322005-09-10 18:17:54 +00001256 return s.replace(' ', '+')
Senthil Kumaran880685f2010-07-22 01:47:30 +00001257 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +00001258
Florent Xiclunae127e242010-05-17 10:39:07 +00001259def urlencode(query, doseq=0):
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001260 """Encode a sequence of two-element tuples or dictionary into a URL query string.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001261
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001262 If any values in the query arg are sequences and doseq is true, each
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001263 sequence element is converted to a separate parameter.
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001264
1265 If the query arg is a sequence of two-element tuples, the order of the
1266 parameters in the output will match the order of parameters in the
1267 input.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001268 """
Tim Peters658cba62001-02-09 20:06:00 +00001269
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001270 if hasattr(query,"items"):
1271 # mapping objects
1272 query = query.items()
1273 else:
1274 # it's a bother at times that strings and string-like objects are
1275 # sequences...
1276 try:
1277 # non-sequence items should not work with len()
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001278 # non-empty strings will fail this
Walter Dörwald65230a22002-06-03 15:58:32 +00001279 if len(query) and not isinstance(query[0], tuple):
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001280 raise TypeError
1281 # zero-length sequences of all types will get here and succeed,
1282 # but that's a minor nit - since the original implementation
1283 # allowed empty dicts that type of behavior probably should be
1284 # preserved for consistency
1285 except TypeError:
1286 ty,va,tb = sys.exc_info()
1287 raise TypeError, "not a valid non-string sequence or mapping object", tb
1288
Guido van Rossume7b146f2000-02-04 15:28:42 +00001289 l = []
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001290 if not doseq:
1291 # preserve old behavior
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001292 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001293 k = quote_plus(str(k))
1294 v = quote_plus(str(v))
1295 l.append(k + '=' + v)
1296 else:
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001297 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001298 k = quote_plus(str(k))
Walter Dörwald65230a22002-06-03 15:58:32 +00001299 if isinstance(v, str):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001300 v = quote_plus(v)
1301 l.append(k + '=' + v)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001302 elif _is_unicode(v):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001303 # is there a reasonable way to convert to ASCII?
1304 # encode generates a string, but "replace" or "ignore"
1305 # lose information and "strict" can raise UnicodeError
1306 v = quote_plus(v.encode("ASCII","replace"))
1307 l.append(k + '=' + v)
1308 else:
1309 try:
1310 # is this a sufficient test for sequence-ness?
Georg Brandl84fedf72010-02-06 22:59:15 +00001311 len(v)
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001312 except TypeError:
1313 # not a sequence
1314 v = quote_plus(str(v))
1315 l.append(k + '=' + v)
1316 else:
1317 # loop over the sequence
1318 for elt in v:
1319 l.append(k + '=' + quote_plus(str(elt)))
Guido van Rossumb2493f82000-12-15 15:01:37 +00001320 return '&'.join(l)
Guido van Rossum810a3391998-07-22 21:33:23 +00001321
Guido van Rossum442e7201996-03-20 15:33:11 +00001322# Proxy handling
Mark Hammond4f570b92000-07-26 07:04:38 +00001323def getproxies_environment():
1324 """Return a dictionary of scheme -> proxy server URL mappings.
1325
1326 Scan the environment for variables named <scheme>_proxy;
1327 this seems to be the standard convention. If you need a
1328 different way, you can pass a proxies dictionary to the
1329 [Fancy]URLopener constructor.
1330
1331 """
1332 proxies = {}
1333 for name, value in os.environ.items():
Guido van Rossumb2493f82000-12-15 15:01:37 +00001334 name = name.lower()
Mark Hammond4f570b92000-07-26 07:04:38 +00001335 if value and name[-6:] == '_proxy':
1336 proxies[name[:-6]] = value
1337 return proxies
1338
Georg Brandl22350112008-01-20 12:05:43 +00001339def proxy_bypass_environment(host):
1340 """Test if proxies should not be used for a particular host.
1341
1342 Checks the environment for a variable named no_proxy, which should
1343 be a list of DNS suffixes separated by commas, or '*' for all hosts.
1344 """
1345 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
1346 # '*' is special case for always bypass
1347 if no_proxy == '*':
1348 return 1
1349 # strip port off host
1350 hostonly, port = splitport(host)
1351 # check if the host ends with any of the DNS suffixes
1352 for name in no_proxy.split(','):
1353 if name and (hostonly.endswith(name) or host.endswith(name)):
1354 return 1
1355 # otherwise, don't bypass
1356 return 0
1357
1358
Jack Jansen11d9b062004-07-16 11:45:00 +00001359if sys.platform == 'darwin':
Ronald Oussoren51f06332009-09-20 10:31:22 +00001360 from _scproxy import _get_proxy_settings, _get_proxies
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001361
1362 def proxy_bypass_macosx_sysconf(host):
1363 """
1364 Return True iff this host shouldn't be accessed using a proxy
1365
1366 This function uses the MacOSX framework SystemConfiguration
1367 to fetch the proxy information.
1368 """
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001369 import re
1370 import socket
1371 from fnmatch import fnmatch
1372
Ronald Oussoren31802d02009-10-18 07:07:00 +00001373 hostonly, port = splitport(host)
1374
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001375 def ip2num(ipAddr):
1376 parts = ipAddr.split('.')
1377 parts = map(int, parts)
1378 if len(parts) != 4:
1379 parts = (parts + [0, 0, 0, 0])[:4]
1380 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
1381
Ronald Oussoren51f06332009-09-20 10:31:22 +00001382 proxy_settings = _get_proxy_settings()
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001383
Ronald Oussoren51f06332009-09-20 10:31:22 +00001384 # Check for simple host names:
1385 if '.' not in host:
1386 if proxy_settings['exclude_simple']:
1387 return True
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001388
Ronald Oussoren31802d02009-10-18 07:07:00 +00001389 hostIP = None
1390
Ronald Oussoren809073b2009-09-20 10:54:07 +00001391 for value in proxy_settings.get('exceptions', ()):
Ronald Oussoren51f06332009-09-20 10:31:22 +00001392 # Items in the list are strings like these: *.local, 169.254/16
Ronald Oussoren51f06332009-09-20 10:31:22 +00001393 if not value: continue
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001394
Ronald Oussoren51f06332009-09-20 10:31:22 +00001395 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
1396 if m is not None:
1397 if hostIP is None:
Ronald Oussoren31802d02009-10-18 07:07:00 +00001398 try:
1399 hostIP = socket.gethostbyname(hostonly)
1400 hostIP = ip2num(hostIP)
1401 except socket.error:
1402 continue
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001403
Ronald Oussoren51f06332009-09-20 10:31:22 +00001404 base = ip2num(m.group(1))
Ronald Oussorenb96fbb82010-06-27 13:59:39 +00001405 mask = m.group(2)
1406 if mask is None:
1407 mask = 8 * (m.group(1).count('.') + 1)
1408
1409 else:
1410 mask = int(mask[1:])
Ronald Oussoren1aa999c2011-03-14 18:53:59 -04001411 mask = 32 - mask
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001412
Ronald Oussoren51f06332009-09-20 10:31:22 +00001413 if (hostIP >> mask) == (base >> mask):
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001414 return True
1415
Ronald Oussoren51f06332009-09-20 10:31:22 +00001416 elif fnmatch(host, value):
1417 return True
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001418
Ronald Oussoren51f06332009-09-20 10:31:22 +00001419 return False
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001420
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001421 def getproxies_macosx_sysconf():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001422 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +00001423
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001424 This function uses the MacOSX framework SystemConfiguration
1425 to fetch the proxy information.
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001426 """
Ronald Oussoren51f06332009-09-20 10:31:22 +00001427 return _get_proxies()
Mark Hammond4f570b92000-07-26 07:04:38 +00001428
Georg Brandl22350112008-01-20 12:05:43 +00001429 def proxy_bypass(host):
1430 if getproxies_environment():
1431 return proxy_bypass_environment(host)
1432 else:
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001433 return proxy_bypass_macosx_sysconf(host)
Tim Peters55c12d42001-08-09 18:04:14 +00001434
Jack Jansen11d9b062004-07-16 11:45:00 +00001435 def getproxies():
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001436 return getproxies_environment() or getproxies_macosx_sysconf()
Tim Peters182b5ac2004-07-18 06:16:08 +00001437
Mark Hammond4f570b92000-07-26 07:04:38 +00001438elif os.name == 'nt':
1439 def getproxies_registry():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001440 """Return a dictionary of scheme -> proxy server URL mappings.
Mark Hammond4f570b92000-07-26 07:04:38 +00001441
1442 Win32 uses the registry to store proxies.
1443
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001444 """
1445 proxies = {}
Mark Hammond4f570b92000-07-26 07:04:38 +00001446 try:
1447 import _winreg
1448 except ImportError:
1449 # Std module, so should be around - but you never know!
1450 return proxies
1451 try:
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001452 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1453 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Mark Hammond4f570b92000-07-26 07:04:38 +00001454 proxyEnable = _winreg.QueryValueEx(internetSettings,
1455 'ProxyEnable')[0]
1456 if proxyEnable:
1457 # Returned as Unicode but problems if not converted to ASCII
1458 proxyServer = str(_winreg.QueryValueEx(internetSettings,
1459 'ProxyServer')[0])
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001460 if '=' in proxyServer:
1461 # Per-protocol settings
Mark Hammond4f570b92000-07-26 07:04:38 +00001462 for p in proxyServer.split(';'):
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001463 protocol, address = p.split('=', 1)
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001464 # See if address has a type:// prefix
Guido van Rossum64e5aa92002-04-02 14:38:16 +00001465 import re
1466 if not re.match('^([^/:]+)://', address):
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001467 address = '%s://%s' % (protocol, address)
1468 proxies[protocol] = address
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001469 else:
1470 # Use one setting for all protocols
1471 if proxyServer[:5] == 'http:':
1472 proxies['http'] = proxyServer
1473 else:
1474 proxies['http'] = 'http://%s' % proxyServer
Senthil Kumaran0fdd3852010-07-14 20:22:17 +00001475 proxies['https'] = 'https://%s' % proxyServer
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001476 proxies['ftp'] = 'ftp://%s' % proxyServer
Mark Hammond4f570b92000-07-26 07:04:38 +00001477 internetSettings.Close()
1478 except (WindowsError, ValueError, TypeError):
1479 # Either registry key not found etc, or the value in an
1480 # unexpected format.
1481 # proxies already set up to be empty so nothing to do
1482 pass
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001483 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +00001484
Mark Hammond4f570b92000-07-26 07:04:38 +00001485 def getproxies():
1486 """Return a dictionary of scheme -> proxy server URL mappings.
1487
1488 Returns settings gathered from the environment, if specified,
1489 or the registry.
1490
1491 """
1492 return getproxies_environment() or getproxies_registry()
Tim Peters55c12d42001-08-09 18:04:14 +00001493
Georg Brandl22350112008-01-20 12:05:43 +00001494 def proxy_bypass_registry(host):
Tim Peters55c12d42001-08-09 18:04:14 +00001495 try:
1496 import _winreg
1497 import re
Tim Peters55c12d42001-08-09 18:04:14 +00001498 except ImportError:
1499 # Std modules, so should be around - but you never know!
1500 return 0
1501 try:
1502 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1503 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
1504 proxyEnable = _winreg.QueryValueEx(internetSettings,
1505 'ProxyEnable')[0]
1506 proxyOverride = str(_winreg.QueryValueEx(internetSettings,
1507 'ProxyOverride')[0])
1508 # ^^^^ Returned as Unicode but problems if not converted to ASCII
1509 except WindowsError:
1510 return 0
1511 if not proxyEnable or not proxyOverride:
1512 return 0
1513 # try to make a host list from name and IP address.
Georg Brandl1f636702006-02-18 23:10:23 +00001514 rawHost, port = splitport(host)
1515 host = [rawHost]
Tim Peters55c12d42001-08-09 18:04:14 +00001516 try:
Georg Brandl1f636702006-02-18 23:10:23 +00001517 addr = socket.gethostbyname(rawHost)
1518 if addr != rawHost:
Tim Peters55c12d42001-08-09 18:04:14 +00001519 host.append(addr)
1520 except socket.error:
1521 pass
Georg Brandl1f636702006-02-18 23:10:23 +00001522 try:
1523 fqdn = socket.getfqdn(rawHost)
1524 if fqdn != rawHost:
1525 host.append(fqdn)
1526 except socket.error:
1527 pass
Tim Peters55c12d42001-08-09 18:04:14 +00001528 # make a check value list from the registry entry: replace the
1529 # '<local>' string by the localhost entry and the corresponding
1530 # canonical entry.
1531 proxyOverride = proxyOverride.split(';')
Tim Peters55c12d42001-08-09 18:04:14 +00001532 # now check if we match one of the registry values.
1533 for test in proxyOverride:
Senthil Kumaran4af40d22009-05-01 05:59:52 +00001534 if test == '<local>':
1535 if '.' not in rawHost:
1536 return 1
Tim Petersab9ba272001-08-09 21:40:30 +00001537 test = test.replace(".", r"\.") # mask dots
1538 test = test.replace("*", r".*") # change glob sequence
1539 test = test.replace("?", r".") # change glob char
Tim Peters55c12d42001-08-09 18:04:14 +00001540 for val in host:
1541 # print "%s <--> %s" %( test, val )
1542 if re.match(test, val, re.I):
1543 return 1
1544 return 0
1545
Georg Brandl22350112008-01-20 12:05:43 +00001546 def proxy_bypass(host):
1547 """Return a dictionary of scheme -> proxy server URL mappings.
1548
1549 Returns settings gathered from the environment, if specified,
1550 or the registry.
1551
1552 """
1553 if getproxies_environment():
1554 return proxy_bypass_environment(host)
1555 else:
1556 return proxy_bypass_registry(host)
1557
Mark Hammond4f570b92000-07-26 07:04:38 +00001558else:
1559 # By default use environment variables
1560 getproxies = getproxies_environment
Georg Brandl22350112008-01-20 12:05:43 +00001561 proxy_bypass = proxy_bypass_environment
Guido van Rossum442e7201996-03-20 15:33:11 +00001562
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001563# Test and time quote() and unquote()
1564def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001565 s = ''
1566 for i in range(256): s = s + chr(i)
1567 s = s*4
1568 t0 = time.time()
1569 qs = quote(s)
1570 uqs = unquote(qs)
1571 t1 = time.time()
1572 if uqs != s:
1573 print 'Wrong!'
Walter Dörwald70a6b492004-02-12 17:35:32 +00001574 print repr(s)
1575 print repr(qs)
1576 print repr(uqs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001577 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001578
1579
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001580def reporthook(blocknum, blocksize, totalsize):
1581 # Report during remote transfers
Guido van Rossumb2493f82000-12-15 15:01:37 +00001582 print "Block number: %d, Block size: %d, Total size: %d" % (
1583 blocknum, blocksize, totalsize)
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001584
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001585# Test program
Guido van Rossum23490151998-06-25 02:39:00 +00001586def test(args=[]):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001587 if not args:
1588 args = [
1589 '/etc/passwd',
1590 'file:/etc/passwd',
1591 'file://localhost/etc/passwd',
Collin Winter071d1ae2007-03-12 01:55:54 +00001592 'ftp://ftp.gnu.org/pub/README',
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001593 'http://www.python.org/index.html',
1594 ]
Guido van Rossum09c8b6c1999-12-07 21:37:17 +00001595 if hasattr(URLopener, "open_https"):
1596 args.append('https://synergy.as.cmu.edu/~geek/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001597 try:
1598 for url in args:
1599 print '-'*10, url, '-'*10
1600 fn, h = urlretrieve(url, None, reporthook)
Guido van Rossumb2493f82000-12-15 15:01:37 +00001601 print fn
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001602 if h:
1603 print '======'
1604 for k in h.keys(): print k + ':', h[k]
1605 print '======'
Philip Jenvey0299d0d2009-12-03 02:40:13 +00001606 with open(fn, 'rb') as fp:
1607 data = fp.read()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001608 if '\r' in data:
1609 table = string.maketrans("", "")
Guido van Rossumb2493f82000-12-15 15:01:37 +00001610 data = data.translate(table, "\r")
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001611 print data
1612 fn, h = None, None
1613 print '-'*40
1614 finally:
1615 urlcleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001616
Guido van Rossum23490151998-06-25 02:39:00 +00001617def main():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001618 import getopt, sys
1619 try:
1620 opts, args = getopt.getopt(sys.argv[1:], "th")
1621 except getopt.error, msg:
1622 print msg
1623 print "Use -h for help"
1624 return
1625 t = 0
1626 for o, a in opts:
1627 if o == '-t':
1628 t = t + 1
1629 if o == '-h':
1630 print "Usage: python urllib.py [-t] [url ...]"
1631 print "-t runs self-test;",
1632 print "otherwise, contents of urls are printed"
1633 return
1634 if t:
1635 if t > 1:
1636 test1()
1637 test(args)
1638 else:
1639 if not args:
1640 print "Use -h for help"
1641 for url in args:
1642 print urlopen(url).read(),
Guido van Rossum23490151998-06-25 02:39:00 +00001643
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001644# Run test program when run as a script
1645if __name__ == '__main__':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001646 main()