blob: 541cec8888266ce407a9ce46f3d5048f845862ab [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
Brett Cannon8bb8fa52008-07-02 01:57:08 +000031import warnings
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000032
Skip Montanaro40fc1602001-03-01 04:27:19 +000033__all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
34 "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
Skip Montanaro44d5e0c2001-03-13 19:47:16 +000035 "urlencode", "url2pathname", "pathname2url", "splittag",
36 "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
37 "splittype", "splithost", "splituser", "splitpasswd", "splitport",
38 "splitnport", "splitquery", "splitattr", "splitvalue",
Brett Cannond75f0432007-05-16 22:42:29 +000039 "getproxies"]
Skip Montanaro40fc1602001-03-01 04:27:19 +000040
Martin v. Löwis3e865952006-01-24 15:51:21 +000041__version__ = '1.17' # XXX This version is not always updated :-(
Guido van Rossumf668d171997-06-06 21:11:11 +000042
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000043MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000044
Jack Jansendc3e3f61995-12-15 13:22:13 +000045# Helper for non-unix systems
46if os.name == 'mac':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000047 from macurl2path import url2pathname, pathname2url
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +000048elif 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
Fred Drakedf6eca72002-04-04 20:41:34 +000072def urlopen(url, data=None, proxies=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
75 warnings.warnpy3k("urllib.urlopen() has been removed in Python 3.0 in "
76 "favor of urllib2.urlopen()", stacklevel=2)
77
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000078 global _urlopener
Fred Drakedf6eca72002-04-04 20:41:34 +000079 if proxies is not None:
80 opener = FancyURLopener(proxies=proxies)
81 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)
Fred Drake316a7932000-08-24 01:01:26 +000090def urlretrieve(url, filename=None, reporthook=None, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000091 global _urlopener
92 if not _urlopener:
93 _urlopener = FancyURLopener()
Fred Drake316a7932000-08-24 01:01:26 +000094 return _urlopener.retrieve(url, filename, reporthook, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000095def urlcleanup():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000096 if _urlopener:
97 _urlopener.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000098
Bill Janssen426ea0a2007-08-29 22:35:05 +000099# check for SSL
100try:
101 import ssl
102except:
103 _have_ssl = False
104else:
105 _have_ssl = True
106
Georg Brandlb9256022005-08-24 18:46:39 +0000107# exception raised when downloaded size does not match content-length
108class ContentTooShortError(IOError):
109 def __init__(self, message, content):
110 IOError.__init__(self, message)
111 self.content = content
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000112
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000113ftpcache = {}
114class URLopener:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000115 """Class to open URLs.
116 This is a class rather than just a subroutine because we may need
117 more than one set of global protocol-specific options.
118 Note -- this is a base class for those who don't want the
119 automatic handling of errors type 302 (relocated) and 401
120 (authorization needed)."""
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000121
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000122 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +0000123
Guido van Rossumba311382000-08-24 16:18:04 +0000124 version = "Python-urllib/%s" % __version__
125
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000126 # Constructor
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000127 def __init__(self, proxies=None, **x509):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000128 if proxies is None:
129 proxies = getproxies()
130 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
131 self.proxies = proxies
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000132 self.key_file = x509.get('key_file')
133 self.cert_file = x509.get('cert_file')
Georg Brandl0619a322006-07-26 07:40:17 +0000134 self.addheaders = [('User-Agent', self.version)]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000135 self.__tempfiles = []
136 self.__unlink = os.unlink # See cleanup()
137 self.tempcache = None
138 # Undocumented feature: if you assign {} to tempcache,
139 # it is used to cache files retrieved with
140 # self.retrieve(). This is not enabled by default
141 # since it does not work for changing documents (and I
142 # haven't got the logic to check expiration headers
143 # yet).
144 self.ftpcache = ftpcache
145 # Undocumented feature: you can use a different
146 # ftp cache by assigning to the .ftpcache member;
147 # in case you want logically independent URL openers
148 # XXX This is not threadsafe. Bah.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000149
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000150 def __del__(self):
151 self.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000152
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000153 def close(self):
154 self.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000155
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000156 def cleanup(self):
157 # This code sometimes runs when the rest of this module
158 # has already been deleted, so it can't use any globals
159 # or import anything.
160 if self.__tempfiles:
161 for file in self.__tempfiles:
162 try:
163 self.__unlink(file)
Martin v. Löwis58682b72001-08-11 15:02:57 +0000164 except OSError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000165 pass
166 del self.__tempfiles[:]
167 if self.tempcache:
168 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000169
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000170 def addheader(self, *args):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000171 """Add a header to be used by the HTTP interface only
172 e.g. u.addheader('Accept', 'sound/basic')"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000173 self.addheaders.append(args)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000174
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000175 # External interface
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000176 def open(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000177 """Use URLopener().open(file) instead of open(file, 'r')."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000178 fullurl = unwrap(toBytes(fullurl))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000179 if self.tempcache and fullurl in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000180 filename, headers = self.tempcache[fullurl]
181 fp = open(filename, 'rb')
182 return addinfourl(fp, headers, fullurl)
Martin v. Löwis1d994332000-12-03 18:30:10 +0000183 urltype, url = splittype(fullurl)
184 if not urltype:
185 urltype = 'file'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000186 if urltype in self.proxies:
Martin v. Löwis1d994332000-12-03 18:30:10 +0000187 proxy = self.proxies[urltype]
188 urltype, proxyhost = splittype(proxy)
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000189 host, selector = splithost(proxyhost)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000190 url = (host, fullurl) # Signal special case to open_*()
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000191 else:
192 proxy = None
Martin v. Löwis1d994332000-12-03 18:30:10 +0000193 name = 'open_' + urltype
194 self.type = urltype
Brett Cannonaaeffaf2004-03-23 23:50:17 +0000195 name = name.replace('-', '_')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000196 if not hasattr(self, name):
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000197 if proxy:
198 return self.open_unknown_proxy(proxy, fullurl, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000199 else:
200 return self.open_unknown(fullurl, data)
201 try:
202 if data is None:
203 return getattr(self, name)(url)
204 else:
205 return getattr(self, name)(url, data)
206 except socket.error, msg:
207 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000208
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000209 def open_unknown(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000210 """Overridable interface to open unknown URL type."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000211 type, url = splittype(fullurl)
212 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossumca445401995-08-29 19:19:12 +0000213
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000214 def open_unknown_proxy(self, proxy, fullurl, data=None):
215 """Overridable interface to open unknown URL type."""
216 type, url = splittype(fullurl)
217 raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
218
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000219 # External interface
Sjoerd Mullenderd7b86f02000-08-25 11:23:36 +0000220 def retrieve(self, url, filename=None, reporthook=None, data=None):
Brett Cannon7d618c72003-04-24 02:43:20 +0000221 """retrieve(url) returns (filename, headers) for a local object
Guido van Rossume7b146f2000-02-04 15:28:42 +0000222 or (tempfilename, headers) for a remote object."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000223 url = unwrap(toBytes(url))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000224 if self.tempcache and url in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000225 return self.tempcache[url]
226 type, url1 = splittype(url)
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000227 if filename is None and (not type or type == 'file'):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000228 try:
229 fp = self.open_local_file(url1)
230 hdrs = fp.info()
231 del fp
232 return url2pathname(splithost(url1)[1]), hdrs
233 except IOError, msg:
234 pass
Fred Drake316a7932000-08-24 01:01:26 +0000235 fp = self.open(url, data)
Benjamin Peterson373498f2009-03-22 17:49:21 +0000236 try:
237 headers = fp.info()
238 if filename:
239 tfp = open(filename, 'wb')
240 else:
241 import tempfile
242 garbage, path = splittype(url)
243 garbage, path = splithost(path or "")
244 path, garbage = splitquery(path or "")
245 path, garbage = splitattr(path or "")
246 suffix = os.path.splitext(path)[1]
247 (fd, filename) = tempfile.mkstemp(suffix)
248 self.__tempfiles.append(filename)
249 tfp = os.fdopen(fd, 'wb')
250 try:
251 result = filename, headers
252 if self.tempcache is not None:
253 self.tempcache[url] = result
254 bs = 1024*8
255 size = -1
256 read = 0
257 blocknum = 0
258 if reporthook:
259 if "content-length" in headers:
260 size = int(headers["Content-Length"])
261 reporthook(blocknum, bs, size)
262 while 1:
263 block = fp.read(bs)
264 if block == "":
265 break
266 read += len(block)
267 tfp.write(block)
268 blocknum += 1
269 if reporthook:
270 reporthook(blocknum, bs, size)
271 finally:
272 tfp.close()
273 finally:
274 fp.close()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000275 del fp
276 del tfp
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)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000342 h.endheaders()
343 if data is not None:
Fred Drakeec3dfde2001-07-04 05:18:29 +0000344 h.send(data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000345 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000346 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000347 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000348 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000349 # something went wrong with the HTTP status line
350 raise IOError, ('http protocol error', 0,
351 'got a bad status line', None)
Sean Reifscheidera1afbf62007-09-19 07:52:56 +0000352 # According to RFC 2616, "2xx" code indicates that the client's
353 # request was successfully received, understood, and accepted.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000354 if (200 <= errcode < 300):
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000355 return addinfourl(fp, headers, "http:" + url, errcode)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000356 else:
357 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000358 return self.http_error(url, fp, errcode, errmsg, headers)
Guido van Rossum29aab751999-03-09 19:31:21 +0000359 else:
360 return self.http_error(url, fp, errcode, errmsg, headers, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000361
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000362 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000363 """Handle http errors.
364 Derived class can override this, or provide specific handlers
365 named http_error_DDD where DDD is the 3-digit error code."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000366 # First check if there's a specific handler for this error
367 name = 'http_error_%d' % errcode
368 if hasattr(self, name):
369 method = getattr(self, name)
370 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000371 result = method(url, fp, errcode, errmsg, headers)
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000372 else:
373 result = method(url, fp, errcode, errmsg, headers, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000374 if result: return result
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000375 return self.http_error_default(url, fp, errcode, errmsg, headers)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000376
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000377 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000378 """Default error handler: close the connection and raise IOError."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000379 void = fp.read()
380 fp.close()
381 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000382
Bill Janssen426ea0a2007-08-29 22:35:05 +0000383 if _have_ssl:
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000384 def open_https(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000385 """Use HTTPS protocol."""
Bill Janssen426ea0a2007-08-29 22:35:05 +0000386
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000387 import httplib
Fred Drake567ca8e2000-08-21 21:42:42 +0000388 user_passwd = None
Martin v. Löwis3e865952006-01-24 15:51:21 +0000389 proxy_passwd = None
Walter Dörwald65230a22002-06-03 15:58:32 +0000390 if isinstance(url, str):
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000391 host, selector = splithost(url)
Fred Drake567ca8e2000-08-21 21:42:42 +0000392 if host:
393 user_passwd, host = splituser(host)
394 host = unquote(host)
395 realhost = host
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000396 else:
397 host, selector = url
Martin v. Löwis3e865952006-01-24 15:51:21 +0000398 # here, we determine, whether the proxy contains authorization information
399 proxy_passwd, host = splituser(host)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000400 urltype, rest = splittype(selector)
Fred Drake567ca8e2000-08-21 21:42:42 +0000401 url = rest
402 user_passwd = None
Guido van Rossumb2493f82000-12-15 15:01:37 +0000403 if urltype.lower() != 'https':
Fred Drake567ca8e2000-08-21 21:42:42 +0000404 realhost = None
405 else:
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000406 realhost, rest = splithost(rest)
Fred Drake567ca8e2000-08-21 21:42:42 +0000407 if realhost:
408 user_passwd, realhost = splituser(realhost)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000409 if user_passwd:
410 selector = "%s://%s%s" % (urltype, realhost, rest)
Andrew M. Kuchling7ad47922000-06-10 01:41:48 +0000411 #print "proxy via https:", host, selector
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000412 if not host: raise IOError, ('https error', 'no host given')
Martin v. Löwis3e865952006-01-24 15:51:21 +0000413 if proxy_passwd:
414 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000415 proxy_auth = base64.b64encode(proxy_passwd).strip()
Martin v. Löwis3e865952006-01-24 15:51:21 +0000416 else:
417 proxy_auth = None
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000418 if user_passwd:
419 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000420 auth = base64.b64encode(user_passwd).strip()
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000421 else:
422 auth = None
423 h = httplib.HTTPS(host, 0,
424 key_file=self.key_file,
425 cert_file=self.cert_file)
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000426 if data is not None:
427 h.putrequest('POST', selector)
Georg Brandl0619a322006-07-26 07:40:17 +0000428 h.putheader('Content-Type',
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000429 'application/x-www-form-urlencoded')
Georg Brandl0619a322006-07-26 07:40:17 +0000430 h.putheader('Content-Length', '%d' % len(data))
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000431 else:
432 h.putrequest('GET', selector)
Andrew M. Kuchling52278572006-12-19 15:11:41 +0000433 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
434 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Fred Drake567ca8e2000-08-21 21:42:42 +0000435 if realhost: h.putheader('Host', realhost)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000436 for args in self.addheaders: h.putheader(*args)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000437 h.endheaders()
Andrew M. Kuchling43c5af02000-04-24 14:17:06 +0000438 if data is not None:
Fred Drakeec3dfde2001-07-04 05:18:29 +0000439 h.send(data)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000440 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000441 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000442 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000443 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000444 # something went wrong with the HTTP status line
445 raise IOError, ('http protocol error', 0,
446 'got a bad status line', None)
Georg Brandl9b915672007-09-24 18:08:24 +0000447 # According to RFC 2616, "2xx" code indicates that the client's
448 # request was successfully received, understood, and accepted.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000449 if (200 <= errcode < 300):
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000450 return addinfourl(fp, headers, "https:" + url, errcode)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000451 else:
Fred Drake567ca8e2000-08-21 21:42:42 +0000452 if data is None:
453 return self.http_error(url, fp, errcode, errmsg, headers)
454 else:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000455 return self.http_error(url, fp, errcode, errmsg, headers,
456 data)
Fred Drake567ca8e2000-08-21 21:42:42 +0000457
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000458 def open_file(self, url):
Neal Norwitzc5d0dbd2006-04-09 04:00:49 +0000459 """Use local file or FTP depending on form of URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000460 if not isinstance(url, str):
461 raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
Jack Jansen4ef11032002-09-12 20:14:04 +0000462 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000463 return self.open_ftp(url)
464 else:
465 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000466
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000467 def open_local_file(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000468 """Use local file."""
Georg Brandl5a096e12007-01-22 19:40:21 +0000469 import mimetypes, mimetools, email.utils
Raymond Hettingera6172712004-12-31 19:15:26 +0000470 try:
471 from cStringIO import StringIO
472 except ImportError:
473 from StringIO import StringIO
Guido van Rossumf0713d32001-08-09 17:43:35 +0000474 host, file = splithost(url)
475 localname = url2pathname(file)
Guido van Rossuma2da3052002-04-15 00:25:01 +0000476 try:
477 stats = os.stat(localname)
478 except OSError, e:
479 raise IOError(e.errno, e.strerror, e.filename)
Walter Dörwald92b48b72002-03-22 17:30:38 +0000480 size = stats.st_size
Georg Brandl5a096e12007-01-22 19:40:21 +0000481 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000482 mtype = mimetypes.guess_type(url)[0]
Raymond Hettingera6172712004-12-31 19:15:26 +0000483 headers = mimetools.Message(StringIO(
Guido van Rossumf0713d32001-08-09 17:43:35 +0000484 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
485 (mtype or 'text/plain', size, modified)))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000486 if not host:
Guido van Rossum336a2011999-06-24 15:27:36 +0000487 urlfile = file
488 if file[:1] == '/':
489 urlfile = 'file://' + file
Guido van Rossumf0713d32001-08-09 17:43:35 +0000490 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000491 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000492 host, port = splitport(host)
493 if not port \
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000494 and socket.gethostbyname(host) in (localhost(), thishost()):
Guido van Rossum336a2011999-06-24 15:27:36 +0000495 urlfile = file
496 if file[:1] == '/':
497 urlfile = 'file://' + file
Guido van Rossumf0713d32001-08-09 17:43:35 +0000498 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000499 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000500 raise IOError, ('local file error', 'not on local host')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000501
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000502 def open_ftp(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000503 """Use FTP protocol."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000504 if not isinstance(url, str):
505 raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
Raymond Hettingera6172712004-12-31 19:15:26 +0000506 import mimetypes, mimetools
507 try:
508 from cStringIO import StringIO
509 except ImportError:
510 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000511 host, path = splithost(url)
512 if not host: raise IOError, ('ftp error', 'no host given')
513 host, port = splitport(host)
514 user, host = splituser(host)
515 if user: user, passwd = splitpasswd(user)
516 else: passwd = None
517 host = unquote(host)
518 user = unquote(user or '')
519 passwd = unquote(passwd or '')
520 host = socket.gethostbyname(host)
521 if not port:
522 import ftplib
523 port = ftplib.FTP_PORT
524 else:
525 port = int(port)
526 path, attrs = splitattr(path)
527 path = unquote(path)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000528 dirs = path.split('/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000529 dirs, file = dirs[:-1], dirs[-1]
530 if dirs and not dirs[0]: dirs = dirs[1:]
Guido van Rossum5e006a31999-08-18 17:40:33 +0000531 if dirs and not dirs[0]: dirs[0] = '/'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000532 key = user, host, port, '/'.join(dirs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000533 # XXX thread unsafe!
534 if len(self.ftpcache) > MAXFTPCACHE:
535 # Prune the cache, rather arbitrarily
536 for k in self.ftpcache.keys():
537 if k != key:
538 v = self.ftpcache[k]
539 del self.ftpcache[k]
540 v.close()
541 try:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000542 if not key in self.ftpcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000543 self.ftpcache[key] = \
544 ftpwrapper(user, passwd, host, port, dirs)
545 if not file: type = 'D'
546 else: type = 'I'
547 for attr in attrs:
548 attr, value = splitvalue(attr)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000549 if attr.lower() == 'type' and \
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000550 value in ('a', 'A', 'i', 'I', 'd', 'D'):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000551 type = value.upper()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000552 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000553 mtype = mimetypes.guess_type("ftp:" + url)[0]
554 headers = ""
555 if mtype:
556 headers += "Content-Type: %s\n" % mtype
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000557 if retrlen is not None and retrlen >= 0:
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000558 headers += "Content-Length: %d\n" % retrlen
Raymond Hettingera6172712004-12-31 19:15:26 +0000559 headers = mimetools.Message(StringIO(headers))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000560 return addinfourl(fp, headers, "ftp:" + url)
561 except ftperrors(), msg:
562 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000563
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000564 def open_data(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000565 """Use "data" URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000566 if not isinstance(url, str):
567 raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000568 # ignore POSTed data
569 #
570 # syntax of data URLs:
571 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
572 # mediatype := [ type "/" subtype ] *( ";" parameter )
573 # data := *urlchar
574 # parameter := attribute "=" value
Raymond Hettingera6172712004-12-31 19:15:26 +0000575 import mimetools
576 try:
577 from cStringIO import StringIO
578 except ImportError:
579 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000580 try:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000581 [type, data] = url.split(',', 1)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000582 except ValueError:
583 raise IOError, ('data error', 'bad data URL')
584 if not type:
585 type = 'text/plain;charset=US-ASCII'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000586 semi = type.rfind(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000587 if semi >= 0 and '=' not in type[semi:]:
588 encoding = type[semi+1:]
589 type = type[:semi]
590 else:
591 encoding = ''
592 msg = []
593 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
594 time.gmtime(time.time())))
595 msg.append('Content-type: %s' % type)
596 if encoding == 'base64':
597 import base64
598 data = base64.decodestring(data)
599 else:
600 data = unquote(data)
Georg Brandl0619a322006-07-26 07:40:17 +0000601 msg.append('Content-Length: %d' % len(data))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000602 msg.append('')
603 msg.append(data)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000604 msg = '\n'.join(msg)
Raymond Hettingera6172712004-12-31 19:15:26 +0000605 f = StringIO(msg)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000606 headers = mimetools.Message(f, 0)
Georg Brandl1f663572005-11-26 16:50:44 +0000607 #f.fileno = None # needed for addinfourl
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000608 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000609
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000610
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000611class FancyURLopener(URLopener):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000612 """Derived class with handlers for errors we can handle (perhaps)."""
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000613
Neal Norwitz60e04cd2002-06-11 13:38:51 +0000614 def __init__(self, *args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000615 URLopener.__init__(self, *args, **kwargs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000616 self.auth_cache = {}
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000617 self.tries = 0
618 self.maxtries = 10
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000619
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000620 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000621 """Default error handling -- don't raise an exception."""
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000622 return addinfourl(fp, headers, "http:" + url, errcode)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000623
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000624 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000625 """Error 302 -- relocated (temporarily)."""
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000626 self.tries += 1
627 if self.maxtries and self.tries >= self.maxtries:
628 if hasattr(self, "http_error_500"):
629 meth = self.http_error_500
630 else:
631 meth = self.http_error_default
632 self.tries = 0
633 return meth(url, fp, 500,
634 "Internal Server Error: Redirect Recursion", headers)
635 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
636 data)
637 self.tries = 0
638 return result
639
640 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000641 if 'location' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000642 newurl = headers['location']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000643 elif 'uri' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000644 newurl = headers['uri']
645 else:
646 return
647 void = fp.read()
648 fp.close()
Guido van Rossum3527f591999-03-29 20:23:41 +0000649 # In case the server sent a relative URL, join with original:
Moshe Zadka5d87d472001-04-09 14:54:21 +0000650 newurl = basejoin(self.type + ":" + url, newurl)
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000651 return self.open(newurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000652
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000653 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000654 """Error 301 -- also relocated (permanently)."""
655 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000656
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000657 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
658 """Error 303 -- also relocated (essentially identical to 302)."""
659 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
660
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000661 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
662 """Error 307 -- relocated, but turn POST into error."""
663 if data is None:
664 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
665 else:
666 return self.http_error_default(url, fp, errcode, errmsg, headers)
667
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000668 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000669 """Error 401 -- authentication required.
Martin v. Löwis3e865952006-01-24 15:51:21 +0000670 This function supports Basic authentication only."""
Raymond Hettinger54f02222002-06-01 14:18:47 +0000671 if not 'www-authenticate' in headers:
Tim Peters85ba6732001-02-28 08:26:44 +0000672 URLopener.http_error_default(self, url, fp,
Fred Drakec680ae82001-10-13 18:37:07 +0000673 errcode, errmsg, headers)
Moshe Zadkae99bd172001-02-27 06:27:04 +0000674 stuff = headers['www-authenticate']
675 import re
676 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
677 if not match:
Tim Peters85ba6732001-02-28 08:26:44 +0000678 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000679 errcode, errmsg, headers)
680 scheme, realm = match.groups()
681 if scheme.lower() != 'basic':
Tim Peters85ba6732001-02-28 08:26:44 +0000682 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000683 errcode, errmsg, headers)
684 name = 'retry_' + self.type + '_basic_auth'
685 if data is None:
686 return getattr(self,name)(url, realm)
687 else:
688 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000689
Martin v. Löwis3e865952006-01-24 15:51:21 +0000690 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
691 """Error 407 -- proxy authentication required.
692 This function supports Basic authentication only."""
693 if not 'proxy-authenticate' in headers:
694 URLopener.http_error_default(self, url, fp,
695 errcode, errmsg, headers)
696 stuff = headers['proxy-authenticate']
697 import re
698 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
699 if not match:
700 URLopener.http_error_default(self, url, fp,
701 errcode, errmsg, headers)
702 scheme, realm = match.groups()
703 if scheme.lower() != 'basic':
704 URLopener.http_error_default(self, url, fp,
705 errcode, errmsg, headers)
706 name = 'retry_proxy_' + self.type + '_basic_auth'
707 if data is None:
708 return getattr(self,name)(url, realm)
709 else:
710 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000711
Martin v. Löwis3e865952006-01-24 15:51:21 +0000712 def retry_proxy_http_basic_auth(self, url, realm, data=None):
713 host, selector = splithost(url)
714 newurl = 'http://' + host + selector
715 proxy = self.proxies['http']
716 urltype, proxyhost = splittype(proxy)
717 proxyhost, proxyselector = splithost(proxyhost)
718 i = proxyhost.find('@') + 1
719 proxyhost = proxyhost[i:]
720 user, passwd = self.get_user_passwd(proxyhost, realm, i)
721 if not (user or passwd): return None
722 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
723 self.proxies['http'] = 'http://' + proxyhost + proxyselector
724 if data is None:
725 return self.open(newurl)
726 else:
727 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000728
Martin v. Löwis3e865952006-01-24 15:51:21 +0000729 def retry_proxy_https_basic_auth(self, url, realm, data=None):
730 host, selector = splithost(url)
731 newurl = 'https://' + host + selector
732 proxy = self.proxies['https']
733 urltype, proxyhost = splittype(proxy)
734 proxyhost, proxyselector = splithost(proxyhost)
735 i = proxyhost.find('@') + 1
736 proxyhost = proxyhost[i:]
737 user, passwd = self.get_user_passwd(proxyhost, realm, i)
738 if not (user or passwd): return None
739 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
740 self.proxies['https'] = 'https://' + proxyhost + proxyselector
741 if data is None:
742 return self.open(newurl)
743 else:
744 return self.open(newurl, data)
Tim Peters92037a12006-01-24 22:44:08 +0000745
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000746 def retry_http_basic_auth(self, url, realm, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000747 host, selector = splithost(url)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000748 i = host.find('@') + 1
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000749 host = host[i:]
750 user, passwd = self.get_user_passwd(host, realm, i)
751 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000752 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000753 newurl = 'http://' + host + selector
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000754 if data is None:
755 return self.open(newurl)
756 else:
757 return self.open(newurl, data)
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000758
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000759 def retry_https_basic_auth(self, url, realm, data=None):
Tim Peterse1190062001-01-15 03:34:38 +0000760 host, selector = splithost(url)
761 i = host.find('@') + 1
762 host = host[i:]
763 user, passwd = self.get_user_passwd(host, realm, i)
764 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000765 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Martin v. Löwis3e865952006-01-24 15:51:21 +0000766 newurl = 'https://' + host + selector
767 if data is None:
768 return self.open(newurl)
769 else:
770 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000771
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000772 def get_user_passwd(self, host, realm, clear_cache = 0):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000773 key = realm + '@' + host.lower()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000774 if key in self.auth_cache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000775 if clear_cache:
776 del self.auth_cache[key]
777 else:
778 return self.auth_cache[key]
779 user, passwd = self.prompt_user_passwd(host, realm)
780 if user or passwd: self.auth_cache[key] = (user, passwd)
781 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000782
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000783 def prompt_user_passwd(self, host, realm):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000784 """Override this in a GUI environment!"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000785 import getpass
786 try:
787 user = raw_input("Enter username for %s at %s: " % (realm,
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000788 host))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000789 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
790 (user, realm, host))
791 return user, passwd
792 except KeyboardInterrupt:
793 print
794 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000795
796
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000797# Utility functions
798
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000799_localhost = None
800def localhost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000801 """Return the IP address of the magic hostname 'localhost'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000802 global _localhost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000803 if _localhost is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000804 _localhost = socket.gethostbyname('localhost')
805 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000806
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000807_thishost = None
808def thishost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000809 """Return the IP address of the current host."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000810 global _thishost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000811 if _thishost is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000812 _thishost = socket.gethostbyname(socket.gethostname())
813 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000814
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000815_ftperrors = None
816def ftperrors():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000817 """Return the set of errors raised by the FTP class."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000818 global _ftperrors
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000819 if _ftperrors is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000820 import ftplib
821 _ftperrors = ftplib.all_errors
822 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000823
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000824_noheaders = None
825def noheaders():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000826 """Return an empty mimetools.Message object."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000827 global _noheaders
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000828 if _noheaders is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000829 import mimetools
Raymond Hettingera6172712004-12-31 19:15:26 +0000830 try:
831 from cStringIO import StringIO
832 except ImportError:
833 from StringIO import StringIO
834 _noheaders = mimetools.Message(StringIO(), 0)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000835 _noheaders.fp.close() # Recycle file descriptor
836 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000837
838
839# Utility classes
840
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000841class ftpwrapper:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000842 """Class used by open_ftp() for cache of open FTP connections."""
843
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000844 def __init__(self, user, passwd, host, port, dirs,
845 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000846 self.user = user
847 self.passwd = passwd
848 self.host = host
849 self.port = port
850 self.dirs = dirs
Facundo Batista711a54e2007-05-24 17:50:54 +0000851 self.timeout = timeout
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000852 self.init()
Guido van Rossume7b146f2000-02-04 15:28:42 +0000853
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000854 def init(self):
855 import ftplib
856 self.busy = 0
857 self.ftp = ftplib.FTP()
Facundo Batista711a54e2007-05-24 17:50:54 +0000858 self.ftp.connect(self.host, self.port, self.timeout)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000859 self.ftp.login(self.user, self.passwd)
860 for dir in self.dirs:
861 self.ftp.cwd(dir)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000862
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000863 def retrfile(self, file, type):
864 import ftplib
865 self.endtransfer()
866 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
867 else: cmd = 'TYPE ' + type; isdir = 0
868 try:
869 self.ftp.voidcmd(cmd)
870 except ftplib.all_errors:
871 self.init()
872 self.ftp.voidcmd(cmd)
873 conn = None
874 if file and not isdir:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000875 # Try to retrieve as a file
876 try:
877 cmd = 'RETR ' + file
878 conn = self.ftp.ntransfercmd(cmd)
879 except ftplib.error_perm, reason:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000880 if str(reason)[:3] != '550':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000881 raise IOError, ('ftp error', reason), sys.exc_info()[2]
882 if not conn:
883 # Set transfer mode to ASCII!
884 self.ftp.voidcmd('TYPE A')
Georg Brandld5e6cf22008-01-20 12:18:17 +0000885 # Try a directory listing. Verify that directory exists.
886 if file:
887 pwd = self.ftp.pwd()
888 try:
889 try:
890 self.ftp.cwd(file)
891 except ftplib.error_perm, reason:
892 raise IOError, ('ftp error', reason), sys.exc_info()[2]
893 finally:
894 self.ftp.cwd(pwd)
895 cmd = 'LIST ' + file
896 else:
897 cmd = 'LIST'
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000898 conn = self.ftp.ntransfercmd(cmd)
899 self.busy = 1
900 # Pass back both a suitably decorated object and a retrieval length
901 return (addclosehook(conn[0].makefile('rb'),
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000902 self.endtransfer), conn[1])
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000903 def endtransfer(self):
904 if not self.busy:
905 return
906 self.busy = 0
907 try:
908 self.ftp.voidresp()
909 except ftperrors():
910 pass
Guido van Rossume7b146f2000-02-04 15:28:42 +0000911
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000912 def close(self):
913 self.endtransfer()
914 try:
915 self.ftp.close()
916 except ftperrors():
917 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000918
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000919class addbase:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000920 """Base class for addinfo and addclosehook."""
921
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000922 def __init__(self, fp):
923 self.fp = fp
924 self.read = self.fp.read
925 self.readline = self.fp.readline
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000926 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
Georg Brandl1f663572005-11-26 16:50:44 +0000927 if hasattr(self.fp, "fileno"):
928 self.fileno = self.fp.fileno
929 else:
930 self.fileno = lambda: None
Raymond Hettinger42182eb2003-03-09 05:33:33 +0000931 if hasattr(self.fp, "__iter__"):
932 self.__iter__ = self.fp.__iter__
933 if hasattr(self.fp, "next"):
934 self.next = self.fp.next
Guido van Rossume7b146f2000-02-04 15:28:42 +0000935
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000936 def __repr__(self):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000937 return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
938 id(self), self.fp)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000939
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000940 def close(self):
941 self.read = None
942 self.readline = None
943 self.readlines = None
944 self.fileno = None
945 if self.fp: self.fp.close()
946 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000947
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000948class addclosehook(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000949 """Class to add a close hook to an open file."""
950
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000951 def __init__(self, fp, closehook, *hookargs):
952 addbase.__init__(self, fp)
953 self.closehook = closehook
954 self.hookargs = hookargs
Guido van Rossume7b146f2000-02-04 15:28:42 +0000955
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000956 def close(self):
Guido van Rossumc580dae2000-05-24 13:21:46 +0000957 addbase.close(self)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000958 if self.closehook:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000959 self.closehook(*self.hookargs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000960 self.closehook = None
961 self.hookargs = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000962
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000963class addinfo(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000964 """class to add an info() method to an open file."""
965
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000966 def __init__(self, fp, headers):
967 addbase.__init__(self, fp)
968 self.headers = headers
Guido van Rossume7b146f2000-02-04 15:28:42 +0000969
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000970 def info(self):
971 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000972
Guido van Rossume6ad8911996-09-10 17:02:56 +0000973class addinfourl(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000974 """class to add info() and geturl() methods to an open file."""
975
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000976 def __init__(self, fp, headers, url, code=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000977 addbase.__init__(self, fp)
978 self.headers = headers
979 self.url = url
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000980 self.code = code
Guido van Rossume7b146f2000-02-04 15:28:42 +0000981
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000982 def info(self):
983 return self.headers
Guido van Rossume7b146f2000-02-04 15:28:42 +0000984
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000985 def getcode(self):
986 return self.code
987
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000988 def geturl(self):
989 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +0000990
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000991
Guido van Rossum7c395db1994-07-04 22:14:49 +0000992# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000993# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000994# splittype('type:opaquestring') --> 'type', 'opaquestring'
995# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000996# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
997# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000998# splitport('host:port') --> 'host', 'port'
999# splitquery('/path?query') --> '/path', 'query'
1000# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +00001001# splitattr('/path;attr1=value1;attr2=value2;...') ->
1002# '/path', ['attr1=value1', 'attr2=value2', ...]
1003# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001004# unquote('abc%20def') -> 'abc def'
1005# quote('abc def') -> 'abc%20def')
1006
Walter Dörwald65230a22002-06-03 15:58:32 +00001007try:
1008 unicode
1009except NameError:
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001010 def _is_unicode(x):
1011 return 0
Walter Dörwald65230a22002-06-03 15:58:32 +00001012else:
1013 def _is_unicode(x):
1014 return isinstance(x, unicode)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001015
Martin v. Löwis1d994332000-12-03 18:30:10 +00001016def toBytes(url):
1017 """toBytes(u"URL") --> 'URL'."""
1018 # Most URL schemes require ASCII. If that changes, the conversion
1019 # can be relaxed
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001020 if _is_unicode(url):
Martin v. Löwis1d994332000-12-03 18:30:10 +00001021 try:
1022 url = url.encode("ASCII")
1023 except UnicodeError:
Guido van Rossumb2493f82000-12-15 15:01:37 +00001024 raise UnicodeError("URL " + repr(url) +
1025 " contains non-ASCII characters")
Martin v. Löwis1d994332000-12-03 18:30:10 +00001026 return url
1027
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001028def unwrap(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001029 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001030 url = url.strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001031 if url[:1] == '<' and url[-1:] == '>':
Guido van Rossumb2493f82000-12-15 15:01:37 +00001032 url = url[1:-1].strip()
1033 if url[:4] == 'URL:': url = url[4:].strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001034 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001035
Guido van Rossum332e1441997-09-29 23:23:46 +00001036_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001037def splittype(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001038 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001039 global _typeprog
1040 if _typeprog is None:
1041 import re
1042 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +00001043
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001044 match = _typeprog.match(url)
1045 if match:
1046 scheme = match.group(1)
Fred Drake9e94afd2000-07-01 07:03:30 +00001047 return scheme.lower(), url[len(scheme) + 1:]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001048 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001049
Guido van Rossum332e1441997-09-29 23:23:46 +00001050_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001051def splithost(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001052 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001053 global _hostprog
1054 if _hostprog is None:
1055 import re
Georg Brandl1c168d82006-03-26 20:59:38 +00001056 _hostprog = re.compile('^//([^/?]*)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001057
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001058 match = _hostprog.match(url)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001059 if match: return match.group(1, 2)
1060 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001061
Guido van Rossum332e1441997-09-29 23:23:46 +00001062_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001063def splituser(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001064 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001065 global _userprog
1066 if _userprog is None:
1067 import re
Raymond Hettingerf2e45dd2002-08-18 20:08:56 +00001068 _userprog = re.compile('^(.*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001069
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001070 match = _userprog.match(host)
Fred Drake567ca8e2000-08-21 21:42:42 +00001071 if match: return map(unquote, match.group(1, 2))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001072 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +00001073
Guido van Rossum332e1441997-09-29 23:23:46 +00001074_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001075def splitpasswd(user):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001076 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001077 global _passwdprog
1078 if _passwdprog is None:
1079 import re
1080 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001081
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001082 match = _passwdprog.match(user)
1083 if match: return match.group(1, 2)
1084 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001085
Guido van Rossume7b146f2000-02-04 15:28:42 +00001086# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum332e1441997-09-29 23:23:46 +00001087_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001088def splitport(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001089 """splitport('host:port') --> 'host', 'port'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001090 global _portprog
1091 if _portprog is None:
1092 import re
1093 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001094
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001095 match = _portprog.match(host)
1096 if match: return match.group(1, 2)
1097 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001098
Guido van Rossum332e1441997-09-29 23:23:46 +00001099_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +00001100def splitnport(host, defport=-1):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001101 """Split host and port, returning numeric port.
1102 Return given default port if no ':' found; defaults to -1.
1103 Return numerical port if a valid number are found after ':'.
1104 Return None if ':' but not a valid number."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001105 global _nportprog
1106 if _nportprog is None:
1107 import re
1108 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001109
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001110 match = _nportprog.match(host)
1111 if match:
1112 host, port = match.group(1, 2)
1113 try:
Guido van Rossumb2493f82000-12-15 15:01:37 +00001114 if not port: raise ValueError, "no digits"
1115 nport = int(port)
1116 except ValueError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001117 nport = None
1118 return host, nport
1119 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +00001120
Guido van Rossum332e1441997-09-29 23:23:46 +00001121_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001122def splitquery(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001123 """splitquery('/path?query') --> '/path', 'query'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001124 global _queryprog
1125 if _queryprog is None:
1126 import re
1127 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001128
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001129 match = _queryprog.match(url)
1130 if match: return match.group(1, 2)
1131 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001132
Guido van Rossum332e1441997-09-29 23:23:46 +00001133_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001134def splittag(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001135 """splittag('/path#tag') --> '/path', 'tag'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001136 global _tagprog
1137 if _tagprog is None:
1138 import re
1139 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001140
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001141 match = _tagprog.match(url)
1142 if match: return match.group(1, 2)
1143 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001144
Guido van Rossum7c395db1994-07-04 22:14:49 +00001145def splitattr(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001146 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1147 '/path', ['attr1=value1', 'attr2=value2', ...]."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001148 words = url.split(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001149 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +00001150
Guido van Rossum332e1441997-09-29 23:23:46 +00001151_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001152def splitvalue(attr):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001153 """splitvalue('attr=value') --> 'attr', 'value'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001154 global _valueprog
1155 if _valueprog is None:
1156 import re
1157 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001158
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001159 match = _valueprog.match(attr)
1160 if match: return match.group(1, 2)
1161 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001162
Raymond Hettinger803ce802005-09-10 06:49:04 +00001163_hextochr = dict(('%02x' % i, chr(i)) for i in range(256))
1164_hextochr.update(('%02X' % i, chr(i)) for i in range(256))
1165
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001166def unquote(s):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001167 """unquote('abc%20def') -> 'abc def'."""
Raymond Hettinger803ce802005-09-10 06:49:04 +00001168 res = s.split('%')
1169 for i in xrange(1, len(res)):
1170 item = res[i]
1171 try:
1172 res[i] = _hextochr[item[:2]] + item[2:]
1173 except KeyError:
1174 res[i] = '%' + item
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +00001175 except UnicodeDecodeError:
1176 res[i] = unichr(int(item[:2], 16)) + item[2:]
Guido van Rossumb2493f82000-12-15 15:01:37 +00001177 return "".join(res)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001178
Guido van Rossum0564e121996-12-13 14:47:36 +00001179def unquote_plus(s):
Skip Montanaro79f1c172000-08-22 03:00:52 +00001180 """unquote('%7e/abc+def') -> '~/abc def'"""
Brett Cannonaaeffaf2004-03-23 23:50:17 +00001181 s = s.replace('+', ' ')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001182 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +00001183
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001184always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Jeremy Hylton6102e292000-08-31 15:48:10 +00001185 'abcdefghijklmnopqrstuvwxyz'
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001186 '0123456789' '_.-')
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001187_safemaps = {}
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001188
Guido van Rossum7c395db1994-07-04 22:14:49 +00001189def quote(s, safe = '/'):
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001190 """quote('abc def') -> 'abc%20def'
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001191
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001192 Each part of a URL, e.g. the path info, the query, etc., has a
1193 different set of reserved characters that must be quoted.
1194
1195 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
1196 the following reserved characters.
1197
1198 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
1199 "$" | ","
1200
1201 Each of these characters is reserved in some component of a URL,
1202 but not necessarily in all of them.
1203
1204 By default, the quote function is intended for quoting the path
1205 section of a URL. Thus, it will not encode '/'. This character
1206 is reserved, but in typical usage the quote function is being
1207 called on a path where the existing slash characters are used as
1208 reserved characters.
1209 """
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001210 cachekey = (safe, always_safe)
1211 try:
1212 safe_map = _safemaps[cachekey]
1213 except KeyError:
1214 safe += always_safe
1215 safe_map = {}
1216 for i in range(256):
1217 c = chr(i)
1218 safe_map[c] = (c in safe) and c or ('%%%02X' % i)
1219 _safemaps[cachekey] = safe_map
1220 res = map(safe_map.__getitem__, s)
Guido van Rossumb2493f82000-12-15 15:01:37 +00001221 return ''.join(res)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001222
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001223def quote_plus(s, safe = ''):
1224 """Quote the query fragment of a URL; replacing ' ' with '+'"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001225 if ' ' in s:
Raymond Hettingercf6b6322005-09-10 18:17:54 +00001226 s = quote(s, safe + ' ')
1227 return s.replace(' ', '+')
1228 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +00001229
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001230def urlencode(query,doseq=0):
1231 """Encode a sequence of two-element tuples or dictionary into a URL query string.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001232
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001233 If any values in the query arg are sequences and doseq is true, each
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001234 sequence element is converted to a separate parameter.
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001235
1236 If the query arg is a sequence of two-element tuples, the order of the
1237 parameters in the output will match the order of parameters in the
1238 input.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001239 """
Tim Peters658cba62001-02-09 20:06:00 +00001240
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001241 if hasattr(query,"items"):
1242 # mapping objects
1243 query = query.items()
1244 else:
1245 # it's a bother at times that strings and string-like objects are
1246 # sequences...
1247 try:
1248 # non-sequence items should not work with len()
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001249 # non-empty strings will fail this
Walter Dörwald65230a22002-06-03 15:58:32 +00001250 if len(query) and not isinstance(query[0], tuple):
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001251 raise TypeError
1252 # zero-length sequences of all types will get here and succeed,
1253 # but that's a minor nit - since the original implementation
1254 # allowed empty dicts that type of behavior probably should be
1255 # preserved for consistency
1256 except TypeError:
1257 ty,va,tb = sys.exc_info()
1258 raise TypeError, "not a valid non-string sequence or mapping object", tb
1259
Guido van Rossume7b146f2000-02-04 15:28:42 +00001260 l = []
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001261 if not doseq:
1262 # preserve old behavior
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001263 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001264 k = quote_plus(str(k))
1265 v = quote_plus(str(v))
1266 l.append(k + '=' + v)
1267 else:
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001268 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001269 k = quote_plus(str(k))
Walter Dörwald65230a22002-06-03 15:58:32 +00001270 if isinstance(v, str):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001271 v = quote_plus(v)
1272 l.append(k + '=' + v)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001273 elif _is_unicode(v):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001274 # is there a reasonable way to convert to ASCII?
1275 # encode generates a string, but "replace" or "ignore"
1276 # lose information and "strict" can raise UnicodeError
1277 v = quote_plus(v.encode("ASCII","replace"))
1278 l.append(k + '=' + v)
1279 else:
1280 try:
1281 # is this a sufficient test for sequence-ness?
1282 x = len(v)
1283 except TypeError:
1284 # not a sequence
1285 v = quote_plus(str(v))
1286 l.append(k + '=' + v)
1287 else:
1288 # loop over the sequence
1289 for elt in v:
1290 l.append(k + '=' + quote_plus(str(elt)))
Guido van Rossumb2493f82000-12-15 15:01:37 +00001291 return '&'.join(l)
Guido van Rossum810a3391998-07-22 21:33:23 +00001292
Guido van Rossum442e7201996-03-20 15:33:11 +00001293# Proxy handling
Mark Hammond4f570b92000-07-26 07:04:38 +00001294def getproxies_environment():
1295 """Return a dictionary of scheme -> proxy server URL mappings.
1296
1297 Scan the environment for variables named <scheme>_proxy;
1298 this seems to be the standard convention. If you need a
1299 different way, you can pass a proxies dictionary to the
1300 [Fancy]URLopener constructor.
1301
1302 """
1303 proxies = {}
1304 for name, value in os.environ.items():
Guido van Rossumb2493f82000-12-15 15:01:37 +00001305 name = name.lower()
Mark Hammond4f570b92000-07-26 07:04:38 +00001306 if value and name[-6:] == '_proxy':
1307 proxies[name[:-6]] = value
1308 return proxies
1309
Georg Brandl22350112008-01-20 12:05:43 +00001310def proxy_bypass_environment(host):
1311 """Test if proxies should not be used for a particular host.
1312
1313 Checks the environment for a variable named no_proxy, which should
1314 be a list of DNS suffixes separated by commas, or '*' for all hosts.
1315 """
1316 no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
1317 # '*' is special case for always bypass
1318 if no_proxy == '*':
1319 return 1
1320 # strip port off host
1321 hostonly, port = splitport(host)
1322 # check if the host ends with any of the DNS suffixes
1323 for name in no_proxy.split(','):
1324 if name and (hostonly.endswith(name) or host.endswith(name)):
1325 return 1
1326 # otherwise, don't bypass
1327 return 0
1328
1329
Jack Jansen11d9b062004-07-16 11:45:00 +00001330if sys.platform == 'darwin':
Ronald Oussoren099646f2008-05-18 20:09:54 +00001331
1332 def _CFSetup(sc):
1333 from ctypes import c_int32, c_void_p, c_char_p, c_int
1334 sc.CFStringCreateWithCString.argtypes = [ c_void_p, c_char_p, c_int32 ]
1335 sc.CFStringCreateWithCString.restype = c_void_p
1336 sc.SCDynamicStoreCopyProxies.argtypes = [ c_void_p ]
1337 sc.SCDynamicStoreCopyProxies.restype = c_void_p
1338 sc.CFDictionaryGetValue.argtypes = [ c_void_p, c_void_p ]
1339 sc.CFDictionaryGetValue.restype = c_void_p
1340 sc.CFStringGetLength.argtypes = [ c_void_p ]
1341 sc.CFStringGetLength.restype = c_int32
1342 sc.CFStringGetCString.argtypes = [ c_void_p, c_char_p, c_int32, c_int32 ]
1343 sc.CFStringGetCString.restype = c_int32
1344 sc.CFNumberGetValue.argtypes = [ c_void_p, c_int, c_void_p ]
1345 sc.CFNumberGetValue.restype = c_int32
1346 sc.CFRelease.argtypes = [ c_void_p ]
1347 sc.CFRelease.restype = None
1348
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001349 def _CStringFromCFString(sc, value):
1350 from ctypes import create_string_buffer
1351 length = sc.CFStringGetLength(value) + 1
1352 buff = create_string_buffer(length)
1353 sc.CFStringGetCString(value, buff, length, 0)
1354 return buff.value
1355
1356 def _CFNumberToInt32(sc, cfnum):
1357 from ctypes import byref, c_int
1358 val = c_int()
1359 kCFNumberSInt32Type = 3
1360 sc.CFNumberGetValue(cfnum, kCFNumberSInt32Type, byref(val))
1361 return val.value
1362
1363
1364 def proxy_bypass_macosx_sysconf(host):
1365 """
1366 Return True iff this host shouldn't be accessed using a proxy
1367
1368 This function uses the MacOSX framework SystemConfiguration
1369 to fetch the proxy information.
1370 """
1371 from ctypes import cdll
1372 from ctypes.util import find_library
1373 import re
1374 import socket
1375 from fnmatch import fnmatch
1376
1377 def ip2num(ipAddr):
1378 parts = ipAddr.split('.')
1379 parts = map(int, parts)
1380 if len(parts) != 4:
1381 parts = (parts + [0, 0, 0, 0])[:4]
1382 return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
1383
1384 sc = cdll.LoadLibrary(find_library("SystemConfiguration"))
Ronald Oussoren099646f2008-05-18 20:09:54 +00001385 _CFSetup(sc)
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001386
1387 hostIP = None
1388
1389 if not sc:
1390 return False
1391
1392 kSCPropNetProxiesExceptionsList = sc.CFStringCreateWithCString(0, "ExceptionsList", 0)
1393 kSCPropNetProxiesExcludeSimpleHostnames = sc.CFStringCreateWithCString(0,
1394 "ExcludeSimpleHostnames", 0)
1395
1396
1397 proxyDict = sc.SCDynamicStoreCopyProxies(None)
Ronald Oussoren099646f2008-05-18 20:09:54 +00001398 if proxyDict is None:
1399 return False
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001400
1401 try:
1402 # Check for simple host names:
1403 if '.' not in host:
1404 exclude_simple = sc.CFDictionaryGetValue(proxyDict,
1405 kSCPropNetProxiesExcludeSimpleHostnames)
1406 if exclude_simple and _CFNumberToInt32(sc, exclude_simple):
1407 return True
1408
1409
1410 # Check the exceptions list:
1411 exceptions = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesExceptionsList)
1412 if exceptions:
1413 # Items in the list are strings like these: *.local, 169.254/16
1414 for index in xrange(sc.CFArrayGetCount(exceptions)):
1415 value = sc.CFArrayGetValueAtIndex(exceptions, index)
1416 if not value: continue
1417 value = _CStringFromCFString(sc, value)
1418
1419 m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
1420 if m is not None:
1421 if hostIP is None:
1422 hostIP = socket.gethostbyname(host)
1423 hostIP = ip2num(hostIP)
1424
1425 base = ip2num(m.group(1))
1426 mask = int(m.group(2)[1:])
1427 mask = 32 - mask
1428
1429 if (hostIP >> mask) == (base >> mask):
1430 return True
1431
1432 elif fnmatch(host, value):
1433 return True
1434
1435 return False
1436
1437 finally:
1438 sc.CFRelease(kSCPropNetProxiesExceptionsList)
1439 sc.CFRelease(kSCPropNetProxiesExcludeSimpleHostnames)
1440
1441
1442
1443 def getproxies_macosx_sysconf():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001444 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +00001445
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001446 This function uses the MacOSX framework SystemConfiguration
1447 to fetch the proxy information.
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001448 """
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001449 from ctypes import cdll
1450 from ctypes.util import find_library
1451
1452 sc = cdll.LoadLibrary(find_library("SystemConfiguration"))
Ronald Oussoren099646f2008-05-18 20:09:54 +00001453 _CFSetup(sc)
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001454
1455 if not sc:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001456 return {}
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001457
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001458 kSCPropNetProxiesHTTPEnable = sc.CFStringCreateWithCString(0, "HTTPEnable", 0)
1459 kSCPropNetProxiesHTTPProxy = sc.CFStringCreateWithCString(0, "HTTPProxy", 0)
1460 kSCPropNetProxiesHTTPPort = sc.CFStringCreateWithCString(0, "HTTPPort", 0)
1461
1462 kSCPropNetProxiesHTTPSEnable = sc.CFStringCreateWithCString(0, "HTTPSEnable", 0)
1463 kSCPropNetProxiesHTTPSProxy = sc.CFStringCreateWithCString(0, "HTTPSProxy", 0)
1464 kSCPropNetProxiesHTTPSPort = sc.CFStringCreateWithCString(0, "HTTPSPort", 0)
1465
1466 kSCPropNetProxiesFTPEnable = sc.CFStringCreateWithCString(0, "FTPEnable", 0)
1467 kSCPropNetProxiesFTPPassive = sc.CFStringCreateWithCString(0, "FTPPassive", 0)
1468 kSCPropNetProxiesFTPPort = sc.CFStringCreateWithCString(0, "FTPPort", 0)
1469 kSCPropNetProxiesFTPProxy = sc.CFStringCreateWithCString(0, "FTPProxy", 0)
1470
1471 kSCPropNetProxiesGopherEnable = sc.CFStringCreateWithCString(0, "GopherEnable", 0)
1472 kSCPropNetProxiesGopherPort = sc.CFStringCreateWithCString(0, "GopherPort", 0)
1473 kSCPropNetProxiesGopherProxy = sc.CFStringCreateWithCString(0, "GopherProxy", 0)
1474
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001475 proxies = {}
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001476 proxyDict = sc.SCDynamicStoreCopyProxies(None)
1477
1478 try:
1479 # HTTP:
1480 enabled = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesHTTPEnable)
1481 if enabled and _CFNumberToInt32(sc, enabled):
1482 proxy = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesHTTPProxy)
1483 port = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesHTTPPort)
1484
1485 if proxy:
1486 proxy = _CStringFromCFString(sc, proxy)
1487 if port:
1488 port = _CFNumberToInt32(sc, port)
1489 proxies["http"] = "http://%s:%i" % (proxy, port)
1490 else:
1491 proxies["http"] = "http://%s" % (proxy, )
1492
1493 # HTTPS:
1494 enabled = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesHTTPSEnable)
1495 if enabled and _CFNumberToInt32(sc, enabled):
1496 proxy = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesHTTPSProxy)
1497 port = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesHTTPSPort)
1498
1499 if proxy:
1500 proxy = _CStringFromCFString(sc, proxy)
1501 if port:
1502 port = _CFNumberToInt32(sc, port)
1503 proxies["https"] = "http://%s:%i" % (proxy, port)
1504 else:
1505 proxies["https"] = "http://%s" % (proxy, )
1506
1507 # FTP:
1508 enabled = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesFTPEnable)
1509 if enabled and _CFNumberToInt32(sc, enabled):
1510 proxy = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesFTPProxy)
1511 port = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesFTPPort)
1512
1513 if proxy:
1514 proxy = _CStringFromCFString(sc, proxy)
1515 if port:
1516 port = _CFNumberToInt32(sc, port)
1517 proxies["ftp"] = "http://%s:%i" % (proxy, port)
1518 else:
1519 proxies["ftp"] = "http://%s" % (proxy, )
1520
1521 # Gopher:
1522 enabled = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesGopherEnable)
1523 if enabled and _CFNumberToInt32(sc, enabled):
1524 proxy = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesGopherProxy)
1525 port = sc.CFDictionaryGetValue(proxyDict, kSCPropNetProxiesGopherPort)
1526
1527 if proxy:
1528 proxy = _CStringFromCFString(sc, proxy)
1529 if port:
1530 port = _CFNumberToInt32(sc, port)
1531 proxies["gopher"] = "http://%s:%i" % (proxy, port)
1532 else:
1533 proxies["gopher"] = "http://%s" % (proxy, )
1534 finally:
1535 sc.CFRelease(proxyDict)
1536
1537 sc.CFRelease(kSCPropNetProxiesHTTPEnable)
1538 sc.CFRelease(kSCPropNetProxiesHTTPProxy)
1539 sc.CFRelease(kSCPropNetProxiesHTTPPort)
1540 sc.CFRelease(kSCPropNetProxiesFTPEnable)
1541 sc.CFRelease(kSCPropNetProxiesFTPPassive)
1542 sc.CFRelease(kSCPropNetProxiesFTPPort)
1543 sc.CFRelease(kSCPropNetProxiesFTPProxy)
1544 sc.CFRelease(kSCPropNetProxiesGopherEnable)
1545 sc.CFRelease(kSCPropNetProxiesGopherPort)
1546 sc.CFRelease(kSCPropNetProxiesGopherProxy)
1547
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001548 return proxies
Mark Hammond4f570b92000-07-26 07:04:38 +00001549
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001550
1551
Georg Brandl22350112008-01-20 12:05:43 +00001552 def proxy_bypass(host):
1553 if getproxies_environment():
1554 return proxy_bypass_environment(host)
1555 else:
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001556 return proxy_bypass_macosx_sysconf(host)
Tim Peters55c12d42001-08-09 18:04:14 +00001557
Jack Jansen11d9b062004-07-16 11:45:00 +00001558 def getproxies():
Ronald Oussoren9dd6b1d2008-05-12 11:31:05 +00001559 return getproxies_environment() or getproxies_macosx_sysconf()
Tim Peters182b5ac2004-07-18 06:16:08 +00001560
Mark Hammond4f570b92000-07-26 07:04:38 +00001561elif os.name == 'nt':
1562 def getproxies_registry():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001563 """Return a dictionary of scheme -> proxy server URL mappings.
Mark Hammond4f570b92000-07-26 07:04:38 +00001564
1565 Win32 uses the registry to store proxies.
1566
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001567 """
1568 proxies = {}
Mark Hammond4f570b92000-07-26 07:04:38 +00001569 try:
1570 import _winreg
1571 except ImportError:
1572 # Std module, so should be around - but you never know!
1573 return proxies
1574 try:
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001575 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1576 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Mark Hammond4f570b92000-07-26 07:04:38 +00001577 proxyEnable = _winreg.QueryValueEx(internetSettings,
1578 'ProxyEnable')[0]
1579 if proxyEnable:
1580 # Returned as Unicode but problems if not converted to ASCII
1581 proxyServer = str(_winreg.QueryValueEx(internetSettings,
1582 'ProxyServer')[0])
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001583 if '=' in proxyServer:
1584 # Per-protocol settings
Mark Hammond4f570b92000-07-26 07:04:38 +00001585 for p in proxyServer.split(';'):
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001586 protocol, address = p.split('=', 1)
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001587 # See if address has a type:// prefix
Guido van Rossum64e5aa92002-04-02 14:38:16 +00001588 import re
1589 if not re.match('^([^/:]+)://', address):
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001590 address = '%s://%s' % (protocol, address)
1591 proxies[protocol] = address
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001592 else:
1593 # Use one setting for all protocols
1594 if proxyServer[:5] == 'http:':
1595 proxies['http'] = proxyServer
1596 else:
1597 proxies['http'] = 'http://%s' % proxyServer
1598 proxies['ftp'] = 'ftp://%s' % proxyServer
Mark Hammond4f570b92000-07-26 07:04:38 +00001599 internetSettings.Close()
1600 except (WindowsError, ValueError, TypeError):
1601 # Either registry key not found etc, or the value in an
1602 # unexpected format.
1603 # proxies already set up to be empty so nothing to do
1604 pass
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001605 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +00001606
Mark Hammond4f570b92000-07-26 07:04:38 +00001607 def getproxies():
1608 """Return a dictionary of scheme -> proxy server URL mappings.
1609
1610 Returns settings gathered from the environment, if specified,
1611 or the registry.
1612
1613 """
1614 return getproxies_environment() or getproxies_registry()
Tim Peters55c12d42001-08-09 18:04:14 +00001615
Georg Brandl22350112008-01-20 12:05:43 +00001616 def proxy_bypass_registry(host):
Tim Peters55c12d42001-08-09 18:04:14 +00001617 try:
1618 import _winreg
1619 import re
Tim Peters55c12d42001-08-09 18:04:14 +00001620 except ImportError:
1621 # Std modules, so should be around - but you never know!
1622 return 0
1623 try:
1624 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1625 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
1626 proxyEnable = _winreg.QueryValueEx(internetSettings,
1627 'ProxyEnable')[0]
1628 proxyOverride = str(_winreg.QueryValueEx(internetSettings,
1629 'ProxyOverride')[0])
1630 # ^^^^ Returned as Unicode but problems if not converted to ASCII
1631 except WindowsError:
1632 return 0
1633 if not proxyEnable or not proxyOverride:
1634 return 0
1635 # try to make a host list from name and IP address.
Georg Brandl1f636702006-02-18 23:10:23 +00001636 rawHost, port = splitport(host)
1637 host = [rawHost]
Tim Peters55c12d42001-08-09 18:04:14 +00001638 try:
Georg Brandl1f636702006-02-18 23:10:23 +00001639 addr = socket.gethostbyname(rawHost)
1640 if addr != rawHost:
Tim Peters55c12d42001-08-09 18:04:14 +00001641 host.append(addr)
1642 except socket.error:
1643 pass
Georg Brandl1f636702006-02-18 23:10:23 +00001644 try:
1645 fqdn = socket.getfqdn(rawHost)
1646 if fqdn != rawHost:
1647 host.append(fqdn)
1648 except socket.error:
1649 pass
Tim Peters55c12d42001-08-09 18:04:14 +00001650 # make a check value list from the registry entry: replace the
1651 # '<local>' string by the localhost entry and the corresponding
1652 # canonical entry.
1653 proxyOverride = proxyOverride.split(';')
1654 i = 0
1655 while i < len(proxyOverride):
1656 if proxyOverride[i] == '<local>':
1657 proxyOverride[i:i+1] = ['localhost',
1658 '127.0.0.1',
1659 socket.gethostname(),
1660 socket.gethostbyname(
1661 socket.gethostname())]
1662 i += 1
1663 # print proxyOverride
1664 # now check if we match one of the registry values.
1665 for test in proxyOverride:
Tim Petersab9ba272001-08-09 21:40:30 +00001666 test = test.replace(".", r"\.") # mask dots
1667 test = test.replace("*", r".*") # change glob sequence
1668 test = test.replace("?", r".") # change glob char
Tim Peters55c12d42001-08-09 18:04:14 +00001669 for val in host:
1670 # print "%s <--> %s" %( test, val )
1671 if re.match(test, val, re.I):
1672 return 1
1673 return 0
1674
Georg Brandl22350112008-01-20 12:05:43 +00001675 def proxy_bypass(host):
1676 """Return a dictionary of scheme -> proxy server URL mappings.
1677
1678 Returns settings gathered from the environment, if specified,
1679 or the registry.
1680
1681 """
1682 if getproxies_environment():
1683 return proxy_bypass_environment(host)
1684 else:
1685 return proxy_bypass_registry(host)
1686
Mark Hammond4f570b92000-07-26 07:04:38 +00001687else:
1688 # By default use environment variables
1689 getproxies = getproxies_environment
Georg Brandl22350112008-01-20 12:05:43 +00001690 proxy_bypass = proxy_bypass_environment
Guido van Rossum442e7201996-03-20 15:33:11 +00001691
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001692# Test and time quote() and unquote()
1693def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001694 s = ''
1695 for i in range(256): s = s + chr(i)
1696 s = s*4
1697 t0 = time.time()
1698 qs = quote(s)
1699 uqs = unquote(qs)
1700 t1 = time.time()
1701 if uqs != s:
1702 print 'Wrong!'
Walter Dörwald70a6b492004-02-12 17:35:32 +00001703 print repr(s)
1704 print repr(qs)
1705 print repr(uqs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001706 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001707
1708
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001709def reporthook(blocknum, blocksize, totalsize):
1710 # Report during remote transfers
Guido van Rossumb2493f82000-12-15 15:01:37 +00001711 print "Block number: %d, Block size: %d, Total size: %d" % (
1712 blocknum, blocksize, totalsize)
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001713
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001714# Test program
Guido van Rossum23490151998-06-25 02:39:00 +00001715def test(args=[]):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001716 if not args:
1717 args = [
1718 '/etc/passwd',
1719 'file:/etc/passwd',
1720 'file://localhost/etc/passwd',
Collin Winter071d1ae2007-03-12 01:55:54 +00001721 'ftp://ftp.gnu.org/pub/README',
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001722 'http://www.python.org/index.html',
1723 ]
Guido van Rossum09c8b6c1999-12-07 21:37:17 +00001724 if hasattr(URLopener, "open_https"):
1725 args.append('https://synergy.as.cmu.edu/~geek/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001726 try:
1727 for url in args:
1728 print '-'*10, url, '-'*10
1729 fn, h = urlretrieve(url, None, reporthook)
Guido van Rossumb2493f82000-12-15 15:01:37 +00001730 print fn
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001731 if h:
1732 print '======'
1733 for k in h.keys(): print k + ':', h[k]
1734 print '======'
1735 fp = open(fn, 'rb')
1736 data = fp.read()
1737 del fp
1738 if '\r' in data:
1739 table = string.maketrans("", "")
Guido van Rossumb2493f82000-12-15 15:01:37 +00001740 data = data.translate(table, "\r")
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001741 print data
1742 fn, h = None, None
1743 print '-'*40
1744 finally:
1745 urlcleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001746
Guido van Rossum23490151998-06-25 02:39:00 +00001747def main():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001748 import getopt, sys
1749 try:
1750 opts, args = getopt.getopt(sys.argv[1:], "th")
1751 except getopt.error, msg:
1752 print msg
1753 print "Use -h for help"
1754 return
1755 t = 0
1756 for o, a in opts:
1757 if o == '-t':
1758 t = t + 1
1759 if o == '-h':
1760 print "Usage: python urllib.py [-t] [url ...]"
1761 print "-t runs self-test;",
1762 print "otherwise, contents of urls are printed"
1763 return
1764 if t:
1765 if t > 1:
1766 test1()
1767 test(args)
1768 else:
1769 if not args:
1770 print "Use -h for help"
1771 for url in args:
1772 print urlopen(url).read(),
Guido van Rossum23490151998-06-25 02:39:00 +00001773
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001774# Run test program when run as a script
1775if __name__ == '__main__':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001776 main()