blob: 96115fbe50d206ba3e3239eabed6e2e2725cedfc [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
45if os.name == 'mac':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000046 from macurl2path import url2pathname, pathname2url
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +000047elif os.name == 'nt':
Fredrik Lundhb49f88b2000-09-24 18:51:25 +000048 from nturl2path import url2pathname, pathname2url
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000049elif os.name == 'riscos':
50 from rourl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000051else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000052 def url2pathname(pathname):
Georg Brandlc0b24732005-12-26 22:53:56 +000053 """OS-specific conversion from a relative URL of the 'file' scheme
54 to a file system path; not recommended for general use."""
Guido van Rossum367ac801999-03-12 14:31:10 +000055 return unquote(pathname)
Georg Brandlc0b24732005-12-26 22:53:56 +000056
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000057 def pathname2url(pathname):
Georg Brandlc0b24732005-12-26 22:53:56 +000058 """OS-specific conversion from a file system path to a relative URL
59 of the 'file' scheme; not recommended for general use."""
Guido van Rossum367ac801999-03-12 14:31:10 +000060 return quote(pathname)
Guido van Rossum33add0a1998-12-18 15:25:22 +000061
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000062# This really consists of two pieces:
63# (1) a class which handles opening of all sorts of URLs
64# (plus assorted utilities etc.)
65# (2) a set of functions for parsing URLs
66# XXX Should these be separated out into different modules?
67
68
69# Shortcut for basic usage
70_urlopener = None
Fred Drakedf6eca72002-04-04 20:41:34 +000071def urlopen(url, data=None, proxies=None):
Skip Montanaro79f1c172000-08-22 03:00:52 +000072 """urlopen(url [, data]) -> open file-like object"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000073 global _urlopener
Fred Drakedf6eca72002-04-04 20:41:34 +000074 if proxies is not None:
75 opener = FancyURLopener(proxies=proxies)
76 elif not _urlopener:
77 opener = FancyURLopener()
78 _urlopener = opener
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000079 else:
Fred Drakedf6eca72002-04-04 20:41:34 +000080 opener = _urlopener
81 if data is None:
82 return opener.open(url)
83 else:
84 return opener.open(url, data)
Fred Drake316a7932000-08-24 01:01:26 +000085def urlretrieve(url, filename=None, reporthook=None, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000086 global _urlopener
87 if not _urlopener:
88 _urlopener = FancyURLopener()
Fred Drake316a7932000-08-24 01:01:26 +000089 return _urlopener.retrieve(url, filename, reporthook, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000090def urlcleanup():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000091 if _urlopener:
92 _urlopener.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000093
Bill Janssen426ea0a2007-08-29 22:35:05 +000094# check for SSL
95try:
96 import ssl
97except:
98 _have_ssl = False
99else:
100 _have_ssl = True
101
Georg Brandlb9256022005-08-24 18:46:39 +0000102# exception raised when downloaded size does not match content-length
103class ContentTooShortError(IOError):
104 def __init__(self, message, content):
105 IOError.__init__(self, message)
106 self.content = content
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000107
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000108ftpcache = {}
109class URLopener:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000110 """Class to open URLs.
111 This is a class rather than just a subroutine because we may need
112 more than one set of global protocol-specific options.
113 Note -- this is a base class for those who don't want the
114 automatic handling of errors type 302 (relocated) and 401
115 (authorization needed)."""
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000116
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000117 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +0000118
Guido van Rossumba311382000-08-24 16:18:04 +0000119 version = "Python-urllib/%s" % __version__
120
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000121 # Constructor
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000122 def __init__(self, proxies=None, **x509):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000123 if proxies is None:
124 proxies = getproxies()
125 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
126 self.proxies = proxies
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000127 self.key_file = x509.get('key_file')
128 self.cert_file = x509.get('cert_file')
Georg Brandl0619a322006-07-26 07:40:17 +0000129 self.addheaders = [('User-Agent', self.version)]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000130 self.__tempfiles = []
131 self.__unlink = os.unlink # See cleanup()
132 self.tempcache = None
133 # Undocumented feature: if you assign {} to tempcache,
134 # it is used to cache files retrieved with
135 # self.retrieve(). This is not enabled by default
136 # since it does not work for changing documents (and I
137 # haven't got the logic to check expiration headers
138 # yet).
139 self.ftpcache = ftpcache
140 # Undocumented feature: you can use a different
141 # ftp cache by assigning to the .ftpcache member;
142 # in case you want logically independent URL openers
143 # XXX This is not threadsafe. Bah.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000144
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000145 def __del__(self):
146 self.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000147
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000148 def close(self):
149 self.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000150
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000151 def cleanup(self):
152 # This code sometimes runs when the rest of this module
153 # has already been deleted, so it can't use any globals
154 # or import anything.
155 if self.__tempfiles:
156 for file in self.__tempfiles:
157 try:
158 self.__unlink(file)
Martin v. Löwis58682b72001-08-11 15:02:57 +0000159 except OSError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000160 pass
161 del self.__tempfiles[:]
162 if self.tempcache:
163 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000164
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000165 def addheader(self, *args):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000166 """Add a header to be used by the HTTP interface only
167 e.g. u.addheader('Accept', 'sound/basic')"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000168 self.addheaders.append(args)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000169
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000170 # External interface
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000171 def open(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000172 """Use URLopener().open(file) instead of open(file, 'r')."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000173 fullurl = unwrap(toBytes(fullurl))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000174 if self.tempcache and fullurl in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000175 filename, headers = self.tempcache[fullurl]
176 fp = open(filename, 'rb')
177 return addinfourl(fp, headers, fullurl)
Martin v. Löwis1d994332000-12-03 18:30:10 +0000178 urltype, url = splittype(fullurl)
179 if not urltype:
180 urltype = 'file'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000181 if urltype in self.proxies:
Martin v. Löwis1d994332000-12-03 18:30:10 +0000182 proxy = self.proxies[urltype]
183 urltype, proxyhost = splittype(proxy)
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000184 host, selector = splithost(proxyhost)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000185 url = (host, fullurl) # Signal special case to open_*()
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000186 else:
187 proxy = None
Martin v. Löwis1d994332000-12-03 18:30:10 +0000188 name = 'open_' + urltype
189 self.type = urltype
Brett Cannonaaeffaf2004-03-23 23:50:17 +0000190 name = name.replace('-', '_')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000191 if not hasattr(self, name):
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000192 if proxy:
193 return self.open_unknown_proxy(proxy, fullurl, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000194 else:
195 return self.open_unknown(fullurl, data)
196 try:
197 if data is None:
198 return getattr(self, name)(url)
199 else:
200 return getattr(self, name)(url, data)
201 except socket.error, msg:
202 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000203
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000204 def open_unknown(self, fullurl, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000205 """Overridable interface to open unknown URL type."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000206 type, url = splittype(fullurl)
207 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossumca445401995-08-29 19:19:12 +0000208
Jeremy Hyltond52755f2000-10-02 23:04:02 +0000209 def open_unknown_proxy(self, proxy, fullurl, data=None):
210 """Overridable interface to open unknown URL type."""
211 type, url = splittype(fullurl)
212 raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
213
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000214 # External interface
Sjoerd Mullenderd7b86f02000-08-25 11:23:36 +0000215 def retrieve(self, url, filename=None, reporthook=None, data=None):
Brett Cannon7d618c72003-04-24 02:43:20 +0000216 """retrieve(url) returns (filename, headers) for a local object
Guido van Rossume7b146f2000-02-04 15:28:42 +0000217 or (tempfilename, headers) for a remote object."""
Martin v. Löwis1d994332000-12-03 18:30:10 +0000218 url = unwrap(toBytes(url))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000219 if self.tempcache and url in self.tempcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000220 return self.tempcache[url]
221 type, url1 = splittype(url)
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000222 if filename is None and (not type or type == 'file'):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000223 try:
224 fp = self.open_local_file(url1)
225 hdrs = fp.info()
226 del fp
227 return url2pathname(splithost(url1)[1]), hdrs
228 except IOError, msg:
229 pass
Fred Drake316a7932000-08-24 01:01:26 +0000230 fp = self.open(url, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000231 headers = fp.info()
Guido van Rossum3b0a3292002-08-09 16:38:32 +0000232 if filename:
233 tfp = open(filename, 'wb')
234 else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000235 import tempfile
236 garbage, path = splittype(url)
237 garbage, path = splithost(path or "")
238 path, garbage = splitquery(path or "")
239 path, garbage = splitattr(path or "")
240 suffix = os.path.splitext(path)[1]
Guido van Rossum3b0a3292002-08-09 16:38:32 +0000241 (fd, filename) = tempfile.mkstemp(suffix)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000242 self.__tempfiles.append(filename)
Jeremy Hylton3bd6fde2002-10-11 14:36:24 +0000243 tfp = os.fdopen(fd, 'wb')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000244 result = filename, headers
245 if self.tempcache is not None:
246 self.tempcache[url] = result
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000247 bs = 1024*8
248 size = -1
Georg Brandlb9256022005-08-24 18:46:39 +0000249 read = 0
Georg Brandl5a650a22005-08-26 08:51:34 +0000250 blocknum = 0
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000251 if reporthook:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000252 if "content-length" in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000253 size = int(headers["Content-Length"])
Georg Brandl5a650a22005-08-26 08:51:34 +0000254 reporthook(blocknum, bs, size)
255 while 1:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000256 block = fp.read(bs)
Georg Brandl5a650a22005-08-26 08:51:34 +0000257 if block == "":
258 break
Georg Brandlb9256022005-08-24 18:46:39 +0000259 read += len(block)
Georg Brandl5a650a22005-08-26 08:51:34 +0000260 tfp.write(block)
Georg Brandlb9256022005-08-24 18:46:39 +0000261 blocknum += 1
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000262 if reporthook:
263 reporthook(blocknum, bs, size)
264 fp.close()
265 tfp.close()
266 del fp
267 del tfp
Georg Brandlb9256022005-08-24 18:46:39 +0000268
269 # raise exception if actual size does not match content-length header
270 if size >= 0 and read < size:
271 raise ContentTooShortError("retrieval incomplete: got only %i out "
272 "of %i bytes" % (read, size), result)
273
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000274 return result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000275
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000276 # Each method named open_<type> knows how to open that type of URL
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000277
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000278 def open_http(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000279 """Use HTTP protocol."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000280 import httplib
281 user_passwd = None
Martin v. Löwis3e865952006-01-24 15:51:21 +0000282 proxy_passwd= None
Walter Dörwald65230a22002-06-03 15:58:32 +0000283 if isinstance(url, str):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000284 host, selector = splithost(url)
285 if host:
286 user_passwd, host = splituser(host)
287 host = unquote(host)
288 realhost = host
289 else:
290 host, selector = url
Martin v. Löwis3e865952006-01-24 15:51:21 +0000291 # check whether the proxy contains authorization information
292 proxy_passwd, host = splituser(host)
293 # now we proceed with the url we want to obtain
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000294 urltype, rest = splittype(selector)
295 url = rest
296 user_passwd = None
Guido van Rossumb2493f82000-12-15 15:01:37 +0000297 if urltype.lower() != 'http':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000298 realhost = None
299 else:
300 realhost, rest = splithost(rest)
301 if realhost:
302 user_passwd, realhost = splituser(realhost)
303 if user_passwd:
304 selector = "%s://%s%s" % (urltype, realhost, rest)
Tim Peters55c12d42001-08-09 18:04:14 +0000305 if proxy_bypass(realhost):
306 host = realhost
307
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000308 #print "proxy via http:", host, selector
309 if not host: raise IOError, ('http error', 'no host given')
Tim Peters92037a12006-01-24 22:44:08 +0000310
Martin v. Löwis3e865952006-01-24 15:51:21 +0000311 if proxy_passwd:
312 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000313 proxy_auth = base64.b64encode(proxy_passwd).strip()
Martin v. Löwis3e865952006-01-24 15:51:21 +0000314 else:
315 proxy_auth = None
316
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000317 if user_passwd:
318 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000319 auth = base64.b64encode(user_passwd).strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000320 else:
321 auth = None
322 h = httplib.HTTP(host)
323 if data is not None:
324 h.putrequest('POST', selector)
Georg Brandl0619a322006-07-26 07:40:17 +0000325 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
326 h.putheader('Content-Length', '%d' % len(data))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000327 else:
328 h.putrequest('GET', selector)
Martin v. Löwis3e865952006-01-24 15:51:21 +0000329 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000330 if auth: h.putheader('Authorization', 'Basic %s' % auth)
331 if realhost: h.putheader('Host', realhost)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000332 for args in self.addheaders: h.putheader(*args)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000333 h.endheaders()
334 if data is not None:
Fred Drakeec3dfde2001-07-04 05:18:29 +0000335 h.send(data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000336 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000337 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000338 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000339 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000340 # something went wrong with the HTTP status line
341 raise IOError, ('http protocol error', 0,
342 'got a bad status line', None)
Sean Reifscheidera1afbf62007-09-19 07:52:56 +0000343 # According to RFC 2616, "2xx" code indicates that the client's
344 # request was successfully received, understood, and accepted.
345 if not (200 <= errcode < 300):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000346 return addinfourl(fp, headers, "http:" + url)
347 else:
348 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000349 return self.http_error(url, fp, errcode, errmsg, headers)
Guido van Rossum29aab751999-03-09 19:31:21 +0000350 else:
351 return self.http_error(url, fp, errcode, errmsg, headers, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000352
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000353 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000354 """Handle http errors.
355 Derived class can override this, or provide specific handlers
356 named http_error_DDD where DDD is the 3-digit error code."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000357 # First check if there's a specific handler for this error
358 name = 'http_error_%d' % errcode
359 if hasattr(self, name):
360 method = getattr(self, name)
361 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000362 result = method(url, fp, errcode, errmsg, headers)
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000363 else:
364 result = method(url, fp, errcode, errmsg, headers, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000365 if result: return result
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000366 return self.http_error_default(url, fp, errcode, errmsg, headers)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000367
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000368 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000369 """Default error handler: close the connection and raise IOError."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000370 void = fp.read()
371 fp.close()
372 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000373
Bill Janssen426ea0a2007-08-29 22:35:05 +0000374 if _have_ssl:
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000375 def open_https(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000376 """Use HTTPS protocol."""
Bill Janssen426ea0a2007-08-29 22:35:05 +0000377
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000378 import httplib
Fred Drake567ca8e2000-08-21 21:42:42 +0000379 user_passwd = None
Martin v. Löwis3e865952006-01-24 15:51:21 +0000380 proxy_passwd = None
Walter Dörwald65230a22002-06-03 15:58:32 +0000381 if isinstance(url, str):
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000382 host, selector = splithost(url)
Fred Drake567ca8e2000-08-21 21:42:42 +0000383 if host:
384 user_passwd, host = splituser(host)
385 host = unquote(host)
386 realhost = host
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000387 else:
388 host, selector = url
Martin v. Löwis3e865952006-01-24 15:51:21 +0000389 # here, we determine, whether the proxy contains authorization information
390 proxy_passwd, host = splituser(host)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000391 urltype, rest = splittype(selector)
Fred Drake567ca8e2000-08-21 21:42:42 +0000392 url = rest
393 user_passwd = None
Guido van Rossumb2493f82000-12-15 15:01:37 +0000394 if urltype.lower() != 'https':
Fred Drake567ca8e2000-08-21 21:42:42 +0000395 realhost = None
396 else:
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000397 realhost, rest = splithost(rest)
Fred Drake567ca8e2000-08-21 21:42:42 +0000398 if realhost:
399 user_passwd, realhost = splituser(realhost)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000400 if user_passwd:
401 selector = "%s://%s%s" % (urltype, realhost, rest)
Andrew M. Kuchling7ad47922000-06-10 01:41:48 +0000402 #print "proxy via https:", host, selector
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000403 if not host: raise IOError, ('https error', 'no host given')
Martin v. Löwis3e865952006-01-24 15:51:21 +0000404 if proxy_passwd:
405 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000406 proxy_auth = base64.b64encode(proxy_passwd).strip()
Martin v. Löwis3e865952006-01-24 15:51:21 +0000407 else:
408 proxy_auth = None
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000409 if user_passwd:
410 import base64
Andrew M. Kuchling872dba42006-10-27 17:11:23 +0000411 auth = base64.b64encode(user_passwd).strip()
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000412 else:
413 auth = None
414 h = httplib.HTTPS(host, 0,
415 key_file=self.key_file,
416 cert_file=self.cert_file)
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000417 if data is not None:
418 h.putrequest('POST', selector)
Georg Brandl0619a322006-07-26 07:40:17 +0000419 h.putheader('Content-Type',
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000420 'application/x-www-form-urlencoded')
Georg Brandl0619a322006-07-26 07:40:17 +0000421 h.putheader('Content-Length', '%d' % len(data))
Andrew M. Kuchling141e9892000-04-23 02:53:11 +0000422 else:
423 h.putrequest('GET', selector)
Andrew M. Kuchling52278572006-12-19 15:11:41 +0000424 if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
425 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Fred Drake567ca8e2000-08-21 21:42:42 +0000426 if realhost: h.putheader('Host', realhost)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000427 for args in self.addheaders: h.putheader(*args)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000428 h.endheaders()
Andrew M. Kuchling43c5af02000-04-24 14:17:06 +0000429 if data is not None:
Fred Drakeec3dfde2001-07-04 05:18:29 +0000430 h.send(data)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000431 errcode, errmsg, headers = h.getreply()
Neal Norwitzce55e212007-03-20 08:14:57 +0000432 fp = h.getfile()
Georg Brandlf66b6032007-03-14 08:27:52 +0000433 if errcode == -1:
Neal Norwitzce55e212007-03-20 08:14:57 +0000434 if fp: fp.close()
Georg Brandlf66b6032007-03-14 08:27:52 +0000435 # something went wrong with the HTTP status line
436 raise IOError, ('http protocol error', 0,
437 'got a bad status line', None)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000438 if errcode == 200:
Guido van Rossumb931bf32001-12-08 17:09:07 +0000439 return addinfourl(fp, headers, "https:" + url)
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000440 else:
Fred Drake567ca8e2000-08-21 21:42:42 +0000441 if data is None:
442 return self.http_error(url, fp, errcode, errmsg, headers)
443 else:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000444 return self.http_error(url, fp, errcode, errmsg, headers,
445 data)
Fred Drake567ca8e2000-08-21 21:42:42 +0000446
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000447 def open_file(self, url):
Neal Norwitzc5d0dbd2006-04-09 04:00:49 +0000448 """Use local file or FTP depending on form of URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000449 if not isinstance(url, str):
450 raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
Jack Jansen4ef11032002-09-12 20:14:04 +0000451 if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000452 return self.open_ftp(url)
453 else:
454 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000455
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000456 def open_local_file(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000457 """Use local file."""
Georg Brandl5a096e12007-01-22 19:40:21 +0000458 import mimetypes, mimetools, email.utils
Raymond Hettingera6172712004-12-31 19:15:26 +0000459 try:
460 from cStringIO import StringIO
461 except ImportError:
462 from StringIO import StringIO
Guido van Rossumf0713d32001-08-09 17:43:35 +0000463 host, file = splithost(url)
464 localname = url2pathname(file)
Guido van Rossuma2da3052002-04-15 00:25:01 +0000465 try:
466 stats = os.stat(localname)
467 except OSError, e:
468 raise IOError(e.errno, e.strerror, e.filename)
Walter Dörwald92b48b72002-03-22 17:30:38 +0000469 size = stats.st_size
Georg Brandl5a096e12007-01-22 19:40:21 +0000470 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000471 mtype = mimetypes.guess_type(url)[0]
Raymond Hettingera6172712004-12-31 19:15:26 +0000472 headers = mimetools.Message(StringIO(
Guido van Rossumf0713d32001-08-09 17:43:35 +0000473 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
474 (mtype or 'text/plain', size, modified)))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000475 if not host:
Guido van Rossum336a2011999-06-24 15:27:36 +0000476 urlfile = file
477 if file[:1] == '/':
478 urlfile = 'file://' + file
Guido van Rossumf0713d32001-08-09 17:43:35 +0000479 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000480 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000481 host, port = splitport(host)
482 if not port \
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000483 and socket.gethostbyname(host) in (localhost(), thishost()):
Guido van Rossum336a2011999-06-24 15:27:36 +0000484 urlfile = file
485 if file[:1] == '/':
486 urlfile = 'file://' + file
Guido van Rossumf0713d32001-08-09 17:43:35 +0000487 return addinfourl(open(localname, 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000488 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000489 raise IOError, ('local file error', 'not on local host')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000490
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000491 def open_ftp(self, url):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000492 """Use FTP protocol."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000493 if not isinstance(url, str):
494 raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
Raymond Hettingera6172712004-12-31 19:15:26 +0000495 import mimetypes, mimetools
496 try:
497 from cStringIO import StringIO
498 except ImportError:
499 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000500 host, path = splithost(url)
501 if not host: raise IOError, ('ftp error', 'no host given')
502 host, port = splitport(host)
503 user, host = splituser(host)
504 if user: user, passwd = splitpasswd(user)
505 else: passwd = None
506 host = unquote(host)
507 user = unquote(user or '')
508 passwd = unquote(passwd or '')
509 host = socket.gethostbyname(host)
510 if not port:
511 import ftplib
512 port = ftplib.FTP_PORT
513 else:
514 port = int(port)
515 path, attrs = splitattr(path)
516 path = unquote(path)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000517 dirs = path.split('/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000518 dirs, file = dirs[:-1], dirs[-1]
519 if dirs and not dirs[0]: dirs = dirs[1:]
Guido van Rossum5e006a31999-08-18 17:40:33 +0000520 if dirs and not dirs[0]: dirs[0] = '/'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000521 key = user, host, port, '/'.join(dirs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000522 # XXX thread unsafe!
523 if len(self.ftpcache) > MAXFTPCACHE:
524 # Prune the cache, rather arbitrarily
525 for k in self.ftpcache.keys():
526 if k != key:
527 v = self.ftpcache[k]
528 del self.ftpcache[k]
529 v.close()
530 try:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000531 if not key in self.ftpcache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000532 self.ftpcache[key] = \
533 ftpwrapper(user, passwd, host, port, dirs)
534 if not file: type = 'D'
535 else: type = 'I'
536 for attr in attrs:
537 attr, value = splitvalue(attr)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000538 if attr.lower() == 'type' and \
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000539 value in ('a', 'A', 'i', 'I', 'd', 'D'):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000540 type = value.upper()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000541 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000542 mtype = mimetypes.guess_type("ftp:" + url)[0]
543 headers = ""
544 if mtype:
545 headers += "Content-Type: %s\n" % mtype
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000546 if retrlen is not None and retrlen >= 0:
Guido van Rossum88e0b5b2001-08-23 13:38:15 +0000547 headers += "Content-Length: %d\n" % retrlen
Raymond Hettingera6172712004-12-31 19:15:26 +0000548 headers = mimetools.Message(StringIO(headers))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000549 return addinfourl(fp, headers, "ftp:" + url)
550 except ftperrors(), msg:
551 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000552
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000553 def open_data(self, url, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000554 """Use "data" URL."""
Martin v. Löwis3e865952006-01-24 15:51:21 +0000555 if not isinstance(url, str):
556 raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000557 # ignore POSTed data
558 #
559 # syntax of data URLs:
560 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
561 # mediatype := [ type "/" subtype ] *( ";" parameter )
562 # data := *urlchar
563 # parameter := attribute "=" value
Raymond Hettingera6172712004-12-31 19:15:26 +0000564 import mimetools
565 try:
566 from cStringIO import StringIO
567 except ImportError:
568 from StringIO import StringIO
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000569 try:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000570 [type, data] = url.split(',', 1)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000571 except ValueError:
572 raise IOError, ('data error', 'bad data URL')
573 if not type:
574 type = 'text/plain;charset=US-ASCII'
Guido van Rossumb2493f82000-12-15 15:01:37 +0000575 semi = type.rfind(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000576 if semi >= 0 and '=' not in type[semi:]:
577 encoding = type[semi+1:]
578 type = type[:semi]
579 else:
580 encoding = ''
581 msg = []
582 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
583 time.gmtime(time.time())))
584 msg.append('Content-type: %s' % type)
585 if encoding == 'base64':
586 import base64
587 data = base64.decodestring(data)
588 else:
589 data = unquote(data)
Georg Brandl0619a322006-07-26 07:40:17 +0000590 msg.append('Content-Length: %d' % len(data))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000591 msg.append('')
592 msg.append(data)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000593 msg = '\n'.join(msg)
Raymond Hettingera6172712004-12-31 19:15:26 +0000594 f = StringIO(msg)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000595 headers = mimetools.Message(f, 0)
Georg Brandl1f663572005-11-26 16:50:44 +0000596 #f.fileno = None # needed for addinfourl
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000597 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000598
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000599
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000600class FancyURLopener(URLopener):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000601 """Derived class with handlers for errors we can handle (perhaps)."""
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000602
Neal Norwitz60e04cd2002-06-11 13:38:51 +0000603 def __init__(self, *args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000604 URLopener.__init__(self, *args, **kwargs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000605 self.auth_cache = {}
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000606 self.tries = 0
607 self.maxtries = 10
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000608
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000609 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000610 """Default error handling -- don't raise an exception."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000611 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000612
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000613 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000614 """Error 302 -- relocated (temporarily)."""
Skip Montanaroc3e11d62001-02-15 16:56:36 +0000615 self.tries += 1
616 if self.maxtries and self.tries >= self.maxtries:
617 if hasattr(self, "http_error_500"):
618 meth = self.http_error_500
619 else:
620 meth = self.http_error_default
621 self.tries = 0
622 return meth(url, fp, 500,
623 "Internal Server Error: Redirect Recursion", headers)
624 result = self.redirect_internal(url, fp, errcode, errmsg, headers,
625 data)
626 self.tries = 0
627 return result
628
629 def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000630 if 'location' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000631 newurl = headers['location']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000632 elif 'uri' in headers:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000633 newurl = headers['uri']
634 else:
635 return
636 void = fp.read()
637 fp.close()
Guido van Rossum3527f591999-03-29 20:23:41 +0000638 # In case the server sent a relative URL, join with original:
Moshe Zadka5d87d472001-04-09 14:54:21 +0000639 newurl = basejoin(self.type + ":" + url, newurl)
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000640 return self.open(newurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000641
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000642 def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000643 """Error 301 -- also relocated (permanently)."""
644 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000645
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000646 def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
647 """Error 303 -- also relocated (essentially identical to 302)."""
648 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
649
Guido van Rossumfa19f7c2003-05-16 01:46:51 +0000650 def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
651 """Error 307 -- relocated, but turn POST into error."""
652 if data is None:
653 return self.http_error_302(url, fp, errcode, errmsg, headers, data)
654 else:
655 return self.http_error_default(url, fp, errcode, errmsg, headers)
656
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000657 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000658 """Error 401 -- authentication required.
Martin v. Löwis3e865952006-01-24 15:51:21 +0000659 This function supports Basic authentication only."""
Raymond Hettinger54f02222002-06-01 14:18:47 +0000660 if not 'www-authenticate' in headers:
Tim Peters85ba6732001-02-28 08:26:44 +0000661 URLopener.http_error_default(self, url, fp,
Fred Drakec680ae82001-10-13 18:37:07 +0000662 errcode, errmsg, headers)
Moshe Zadkae99bd172001-02-27 06:27:04 +0000663 stuff = headers['www-authenticate']
664 import re
665 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
666 if not match:
Tim Peters85ba6732001-02-28 08:26:44 +0000667 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000668 errcode, errmsg, headers)
669 scheme, realm = match.groups()
670 if scheme.lower() != 'basic':
Tim Peters85ba6732001-02-28 08:26:44 +0000671 URLopener.http_error_default(self, url, fp,
Moshe Zadkae99bd172001-02-27 06:27:04 +0000672 errcode, errmsg, headers)
673 name = 'retry_' + self.type + '_basic_auth'
674 if data is None:
675 return getattr(self,name)(url, realm)
676 else:
677 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000678
Martin v. Löwis3e865952006-01-24 15:51:21 +0000679 def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
680 """Error 407 -- proxy authentication required.
681 This function supports Basic authentication only."""
682 if not 'proxy-authenticate' in headers:
683 URLopener.http_error_default(self, url, fp,
684 errcode, errmsg, headers)
685 stuff = headers['proxy-authenticate']
686 import re
687 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
688 if not match:
689 URLopener.http_error_default(self, url, fp,
690 errcode, errmsg, headers)
691 scheme, realm = match.groups()
692 if scheme.lower() != 'basic':
693 URLopener.http_error_default(self, url, fp,
694 errcode, errmsg, headers)
695 name = 'retry_proxy_' + self.type + '_basic_auth'
696 if data is None:
697 return getattr(self,name)(url, realm)
698 else:
699 return getattr(self,name)(url, realm, data)
Tim Peters92037a12006-01-24 22:44:08 +0000700
Martin v. Löwis3e865952006-01-24 15:51:21 +0000701 def retry_proxy_http_basic_auth(self, url, realm, data=None):
702 host, selector = splithost(url)
703 newurl = 'http://' + host + selector
704 proxy = self.proxies['http']
705 urltype, proxyhost = splittype(proxy)
706 proxyhost, proxyselector = splithost(proxyhost)
707 i = proxyhost.find('@') + 1
708 proxyhost = proxyhost[i:]
709 user, passwd = self.get_user_passwd(proxyhost, realm, i)
710 if not (user or passwd): return None
711 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
712 self.proxies['http'] = 'http://' + proxyhost + proxyselector
713 if data is None:
714 return self.open(newurl)
715 else:
716 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000717
Martin v. Löwis3e865952006-01-24 15:51:21 +0000718 def retry_proxy_https_basic_auth(self, url, realm, data=None):
719 host, selector = splithost(url)
720 newurl = 'https://' + host + selector
721 proxy = self.proxies['https']
722 urltype, proxyhost = splittype(proxy)
723 proxyhost, proxyselector = splithost(proxyhost)
724 i = proxyhost.find('@') + 1
725 proxyhost = proxyhost[i:]
726 user, passwd = self.get_user_passwd(proxyhost, realm, i)
727 if not (user or passwd): return None
728 proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost
729 self.proxies['https'] = 'https://' + proxyhost + proxyselector
730 if data is None:
731 return self.open(newurl)
732 else:
733 return self.open(newurl, data)
Tim Peters92037a12006-01-24 22:44:08 +0000734
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000735 def retry_http_basic_auth(self, url, realm, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000736 host, selector = splithost(url)
Guido van Rossumb2493f82000-12-15 15:01:37 +0000737 i = host.find('@') + 1
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000738 host = host[i:]
739 user, passwd = self.get_user_passwd(host, realm, i)
740 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000741 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000742 newurl = 'http://' + host + selector
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000743 if data is None:
744 return self.open(newurl)
745 else:
746 return self.open(newurl, data)
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000747
Guido van Rossum3c8baed2000-02-01 23:36:55 +0000748 def retry_https_basic_auth(self, url, realm, data=None):
Tim Peterse1190062001-01-15 03:34:38 +0000749 host, selector = splithost(url)
750 i = host.find('@') + 1
751 host = host[i:]
752 user, passwd = self.get_user_passwd(host, realm, i)
753 if not (user or passwd): return None
Guido van Rossumafc4f042001-01-15 18:31:13 +0000754 host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
Martin v. Löwis3e865952006-01-24 15:51:21 +0000755 newurl = 'https://' + host + selector
756 if data is None:
757 return self.open(newurl)
758 else:
759 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000760
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000761 def get_user_passwd(self, host, realm, clear_cache = 0):
Guido van Rossumb2493f82000-12-15 15:01:37 +0000762 key = realm + '@' + host.lower()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000763 if key in self.auth_cache:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000764 if clear_cache:
765 del self.auth_cache[key]
766 else:
767 return self.auth_cache[key]
768 user, passwd = self.prompt_user_passwd(host, realm)
769 if user or passwd: self.auth_cache[key] = (user, passwd)
770 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000771
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000772 def prompt_user_passwd(self, host, realm):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000773 """Override this in a GUI environment!"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000774 import getpass
775 try:
776 user = raw_input("Enter username for %s at %s: " % (realm,
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000777 host))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000778 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
779 (user, realm, host))
780 return user, passwd
781 except KeyboardInterrupt:
782 print
783 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000784
785
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000786# Utility functions
787
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000788_localhost = None
789def localhost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000790 """Return the IP address of the magic hostname 'localhost'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000791 global _localhost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000792 if _localhost is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000793 _localhost = socket.gethostbyname('localhost')
794 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000795
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000796_thishost = None
797def thishost():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000798 """Return the IP address of the current host."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000799 global _thishost
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000800 if _thishost is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000801 _thishost = socket.gethostbyname(socket.gethostname())
802 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000803
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000804_ftperrors = None
805def ftperrors():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000806 """Return the set of errors raised by the FTP class."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000807 global _ftperrors
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000808 if _ftperrors is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000809 import ftplib
810 _ftperrors = ftplib.all_errors
811 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000812
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000813_noheaders = None
814def noheaders():
Guido van Rossume7b146f2000-02-04 15:28:42 +0000815 """Return an empty mimetools.Message object."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000816 global _noheaders
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000817 if _noheaders is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000818 import mimetools
Raymond Hettingera6172712004-12-31 19:15:26 +0000819 try:
820 from cStringIO import StringIO
821 except ImportError:
822 from StringIO import StringIO
823 _noheaders = mimetools.Message(StringIO(), 0)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000824 _noheaders.fp.close() # Recycle file descriptor
825 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000826
827
828# Utility classes
829
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000830class ftpwrapper:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000831 """Class used by open_ftp() for cache of open FTP connections."""
832
Facundo Batista711a54e2007-05-24 17:50:54 +0000833 def __init__(self, user, passwd, host, port, dirs, timeout=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000834 self.user = user
835 self.passwd = passwd
836 self.host = host
837 self.port = port
838 self.dirs = dirs
Facundo Batista711a54e2007-05-24 17:50:54 +0000839 self.timeout = timeout
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000840 self.init()
Guido van Rossume7b146f2000-02-04 15:28:42 +0000841
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000842 def init(self):
843 import ftplib
844 self.busy = 0
845 self.ftp = ftplib.FTP()
Facundo Batista711a54e2007-05-24 17:50:54 +0000846 self.ftp.connect(self.host, self.port, self.timeout)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000847 self.ftp.login(self.user, self.passwd)
848 for dir in self.dirs:
849 self.ftp.cwd(dir)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000850
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000851 def retrfile(self, file, type):
852 import ftplib
853 self.endtransfer()
854 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
855 else: cmd = 'TYPE ' + type; isdir = 0
856 try:
857 self.ftp.voidcmd(cmd)
858 except ftplib.all_errors:
859 self.init()
860 self.ftp.voidcmd(cmd)
861 conn = None
862 if file and not isdir:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000863 # Try to retrieve as a file
864 try:
865 cmd = 'RETR ' + file
866 conn = self.ftp.ntransfercmd(cmd)
867 except ftplib.error_perm, reason:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000868 if str(reason)[:3] != '550':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000869 raise IOError, ('ftp error', reason), sys.exc_info()[2]
870 if not conn:
871 # Set transfer mode to ASCII!
872 self.ftp.voidcmd('TYPE A')
873 # Try a directory listing
874 if file: cmd = 'LIST ' + file
875 else: cmd = 'LIST'
876 conn = self.ftp.ntransfercmd(cmd)
877 self.busy = 1
878 # Pass back both a suitably decorated object and a retrieval length
879 return (addclosehook(conn[0].makefile('rb'),
Fredrik Lundhb49f88b2000-09-24 18:51:25 +0000880 self.endtransfer), conn[1])
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000881 def endtransfer(self):
882 if not self.busy:
883 return
884 self.busy = 0
885 try:
886 self.ftp.voidresp()
887 except ftperrors():
888 pass
Guido van Rossume7b146f2000-02-04 15:28:42 +0000889
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000890 def close(self):
891 self.endtransfer()
892 try:
893 self.ftp.close()
894 except ftperrors():
895 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000896
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000897class addbase:
Guido van Rossume7b146f2000-02-04 15:28:42 +0000898 """Base class for addinfo and addclosehook."""
899
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000900 def __init__(self, fp):
901 self.fp = fp
902 self.read = self.fp.read
903 self.readline = self.fp.readline
Guido van Rossum09c8b6c1999-12-07 21:37:17 +0000904 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
Georg Brandl1f663572005-11-26 16:50:44 +0000905 if hasattr(self.fp, "fileno"):
906 self.fileno = self.fp.fileno
907 else:
908 self.fileno = lambda: None
Raymond Hettinger42182eb2003-03-09 05:33:33 +0000909 if hasattr(self.fp, "__iter__"):
910 self.__iter__ = self.fp.__iter__
911 if hasattr(self.fp, "next"):
912 self.next = self.fp.next
Guido van Rossume7b146f2000-02-04 15:28:42 +0000913
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000914 def __repr__(self):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000915 return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
916 id(self), self.fp)
Guido van Rossume7b146f2000-02-04 15:28:42 +0000917
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000918 def close(self):
919 self.read = None
920 self.readline = None
921 self.readlines = None
922 self.fileno = None
923 if self.fp: self.fp.close()
924 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000925
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000926class addclosehook(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000927 """Class to add a close hook to an open file."""
928
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000929 def __init__(self, fp, closehook, *hookargs):
930 addbase.__init__(self, fp)
931 self.closehook = closehook
932 self.hookargs = hookargs
Guido van Rossume7b146f2000-02-04 15:28:42 +0000933
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000934 def close(self):
Guido van Rossumc580dae2000-05-24 13:21:46 +0000935 addbase.close(self)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000936 if self.closehook:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000937 self.closehook(*self.hookargs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000938 self.closehook = None
939 self.hookargs = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000940
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000941class addinfo(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000942 """class to add an info() method to an open file."""
943
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000944 def __init__(self, fp, headers):
945 addbase.__init__(self, fp)
946 self.headers = headers
Guido van Rossume7b146f2000-02-04 15:28:42 +0000947
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000948 def info(self):
949 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000950
Guido van Rossume6ad8911996-09-10 17:02:56 +0000951class addinfourl(addbase):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000952 """class to add info() and geturl() methods to an open file."""
953
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000954 def __init__(self, fp, headers, url):
955 addbase.__init__(self, fp)
956 self.headers = headers
957 self.url = url
Guido van Rossume7b146f2000-02-04 15:28:42 +0000958
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000959 def info(self):
960 return self.headers
Guido van Rossume7b146f2000-02-04 15:28:42 +0000961
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000962 def geturl(self):
963 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +0000964
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000965
Guido van Rossum7c395db1994-07-04 22:14:49 +0000966# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000967# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000968# splittype('type:opaquestring') --> 'type', 'opaquestring'
969# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000970# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
971# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000972# splitport('host:port') --> 'host', 'port'
973# splitquery('/path?query') --> '/path', 'query'
974# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000975# splitattr('/path;attr1=value1;attr2=value2;...') ->
976# '/path', ['attr1=value1', 'attr2=value2', ...]
977# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000978# unquote('abc%20def') -> 'abc def'
979# quote('abc def') -> 'abc%20def')
980
Walter Dörwald65230a22002-06-03 15:58:32 +0000981try:
982 unicode
983except NameError:
Guido van Rossum4b46c0a2002-05-24 17:58:05 +0000984 def _is_unicode(x):
985 return 0
Walter Dörwald65230a22002-06-03 15:58:32 +0000986else:
987 def _is_unicode(x):
988 return isinstance(x, unicode)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +0000989
Martin v. Löwis1d994332000-12-03 18:30:10 +0000990def toBytes(url):
991 """toBytes(u"URL") --> 'URL'."""
992 # Most URL schemes require ASCII. If that changes, the conversion
993 # can be relaxed
Guido van Rossum4b46c0a2002-05-24 17:58:05 +0000994 if _is_unicode(url):
Martin v. Löwis1d994332000-12-03 18:30:10 +0000995 try:
996 url = url.encode("ASCII")
997 except UnicodeError:
Guido van Rossumb2493f82000-12-15 15:01:37 +0000998 raise UnicodeError("URL " + repr(url) +
999 " contains non-ASCII characters")
Martin v. Löwis1d994332000-12-03 18:30:10 +00001000 return url
1001
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001002def unwrap(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001003 """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001004 url = url.strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001005 if url[:1] == '<' and url[-1:] == '>':
Guido van Rossumb2493f82000-12-15 15:01:37 +00001006 url = url[1:-1].strip()
1007 if url[:4] == 'URL:': url = url[4:].strip()
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001008 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001009
Guido van Rossum332e1441997-09-29 23:23:46 +00001010_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001011def splittype(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001012 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001013 global _typeprog
1014 if _typeprog is None:
1015 import re
1016 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +00001017
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001018 match = _typeprog.match(url)
1019 if match:
1020 scheme = match.group(1)
Fred Drake9e94afd2000-07-01 07:03:30 +00001021 return scheme.lower(), url[len(scheme) + 1:]
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001022 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001023
Guido van Rossum332e1441997-09-29 23:23:46 +00001024_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001025def splithost(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001026 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001027 global _hostprog
1028 if _hostprog is None:
1029 import re
Georg Brandl1c168d82006-03-26 20:59:38 +00001030 _hostprog = re.compile('^//([^/?]*)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001031
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001032 match = _hostprog.match(url)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001033 if match: return match.group(1, 2)
1034 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001035
Guido van Rossum332e1441997-09-29 23:23:46 +00001036_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001037def splituser(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001038 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001039 global _userprog
1040 if _userprog is None:
1041 import re
Raymond Hettingerf2e45dd2002-08-18 20:08:56 +00001042 _userprog = re.compile('^(.*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001043
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001044 match = _userprog.match(host)
Fred Drake567ca8e2000-08-21 21:42:42 +00001045 if match: return map(unquote, match.group(1, 2))
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001046 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +00001047
Guido van Rossum332e1441997-09-29 23:23:46 +00001048_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001049def splitpasswd(user):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001050 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001051 global _passwdprog
1052 if _passwdprog is None:
1053 import re
1054 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001055
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001056 match = _passwdprog.match(user)
1057 if match: return match.group(1, 2)
1058 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001059
Guido van Rossume7b146f2000-02-04 15:28:42 +00001060# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum332e1441997-09-29 23:23:46 +00001061_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001062def splitport(host):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001063 """splitport('host:port') --> 'host', 'port'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001064 global _portprog
1065 if _portprog is None:
1066 import re
1067 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001068
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001069 match = _portprog.match(host)
1070 if match: return match.group(1, 2)
1071 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001072
Guido van Rossum332e1441997-09-29 23:23:46 +00001073_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +00001074def splitnport(host, defport=-1):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001075 """Split host and port, returning numeric port.
1076 Return given default port if no ':' found; defaults to -1.
1077 Return numerical port if a valid number are found after ':'.
1078 Return None if ':' but not a valid number."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001079 global _nportprog
1080 if _nportprog is None:
1081 import re
1082 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001083
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001084 match = _nportprog.match(host)
1085 if match:
1086 host, port = match.group(1, 2)
1087 try:
Guido van Rossumb2493f82000-12-15 15:01:37 +00001088 if not port: raise ValueError, "no digits"
1089 nport = int(port)
1090 except ValueError:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001091 nport = None
1092 return host, nport
1093 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +00001094
Guido van Rossum332e1441997-09-29 23:23:46 +00001095_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001096def splitquery(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001097 """splitquery('/path?query') --> '/path', 'query'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001098 global _queryprog
1099 if _queryprog is None:
1100 import re
1101 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001102
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001103 match = _queryprog.match(url)
1104 if match: return match.group(1, 2)
1105 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001106
Guido van Rossum332e1441997-09-29 23:23:46 +00001107_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001108def splittag(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001109 """splittag('/path#tag') --> '/path', 'tag'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001110 global _tagprog
1111 if _tagprog is None:
1112 import re
1113 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001114
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001115 match = _tagprog.match(url)
1116 if match: return match.group(1, 2)
1117 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001118
Guido van Rossum7c395db1994-07-04 22:14:49 +00001119def splitattr(url):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001120 """splitattr('/path;attr1=value1;attr2=value2;...') ->
1121 '/path', ['attr1=value1', 'attr2=value2', ...]."""
Guido van Rossumb2493f82000-12-15 15:01:37 +00001122 words = url.split(';')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001123 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +00001124
Guido van Rossum332e1441997-09-29 23:23:46 +00001125_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001126def splitvalue(attr):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001127 """splitvalue('attr=value') --> 'attr', 'value'."""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001128 global _valueprog
1129 if _valueprog is None:
1130 import re
1131 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +00001132
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001133 match = _valueprog.match(attr)
1134 if match: return match.group(1, 2)
1135 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +00001136
Raymond Hettinger803ce802005-09-10 06:49:04 +00001137_hextochr = dict(('%02x' % i, chr(i)) for i in range(256))
1138_hextochr.update(('%02X' % i, chr(i)) for i in range(256))
1139
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001140def unquote(s):
Guido van Rossume7b146f2000-02-04 15:28:42 +00001141 """unquote('abc%20def') -> 'abc def'."""
Raymond Hettinger803ce802005-09-10 06:49:04 +00001142 res = s.split('%')
1143 for i in xrange(1, len(res)):
1144 item = res[i]
1145 try:
1146 res[i] = _hextochr[item[:2]] + item[2:]
1147 except KeyError:
1148 res[i] = '%' + item
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +00001149 except UnicodeDecodeError:
1150 res[i] = unichr(int(item[:2], 16)) + item[2:]
Guido van Rossumb2493f82000-12-15 15:01:37 +00001151 return "".join(res)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001152
Guido van Rossum0564e121996-12-13 14:47:36 +00001153def unquote_plus(s):
Skip Montanaro79f1c172000-08-22 03:00:52 +00001154 """unquote('%7e/abc+def') -> '~/abc def'"""
Brett Cannonaaeffaf2004-03-23 23:50:17 +00001155 s = s.replace('+', ' ')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001156 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +00001157
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001158always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Jeremy Hylton6102e292000-08-31 15:48:10 +00001159 'abcdefghijklmnopqrstuvwxyz'
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001160 '0123456789' '_.-')
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001161_safemaps = {}
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001162
Guido van Rossum7c395db1994-07-04 22:14:49 +00001163def quote(s, safe = '/'):
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001164 """quote('abc def') -> 'abc%20def'
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001165
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001166 Each part of a URL, e.g. the path info, the query, etc., has a
1167 different set of reserved characters that must be quoted.
1168
1169 RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
1170 the following reserved characters.
1171
1172 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
1173 "$" | ","
1174
1175 Each of these characters is reserved in some component of a URL,
1176 but not necessarily in all of them.
1177
1178 By default, the quote function is intended for quoting the path
1179 section of a URL. Thus, it will not encode '/'. This character
1180 is reserved, but in typical usage the quote function is being
1181 called on a path where the existing slash characters are used as
1182 reserved characters.
1183 """
Raymond Hettinger199d2f72005-09-09 22:27:13 +00001184 cachekey = (safe, always_safe)
1185 try:
1186 safe_map = _safemaps[cachekey]
1187 except KeyError:
1188 safe += always_safe
1189 safe_map = {}
1190 for i in range(256):
1191 c = chr(i)
1192 safe_map[c] = (c in safe) and c or ('%%%02X' % i)
1193 _safemaps[cachekey] = safe_map
1194 res = map(safe_map.__getitem__, s)
Guido van Rossumb2493f82000-12-15 15:01:37 +00001195 return ''.join(res)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001196
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +00001197def quote_plus(s, safe = ''):
1198 """Quote the query fragment of a URL; replacing ' ' with '+'"""
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001199 if ' ' in s:
Raymond Hettingercf6b6322005-09-10 18:17:54 +00001200 s = quote(s, safe + ' ')
1201 return s.replace(' ', '+')
1202 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +00001203
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001204def urlencode(query,doseq=0):
1205 """Encode a sequence of two-element tuples or dictionary into a URL query string.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001206
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001207 If any values in the query arg are sequences and doseq is true, each
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001208 sequence element is converted to a separate parameter.
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001209
1210 If the query arg is a sequence of two-element tuples, the order of the
1211 parameters in the output will match the order of parameters in the
1212 input.
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001213 """
Tim Peters658cba62001-02-09 20:06:00 +00001214
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001215 if hasattr(query,"items"):
1216 # mapping objects
1217 query = query.items()
1218 else:
1219 # it's a bother at times that strings and string-like objects are
1220 # sequences...
1221 try:
1222 # non-sequence items should not work with len()
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001223 # non-empty strings will fail this
Walter Dörwald65230a22002-06-03 15:58:32 +00001224 if len(query) and not isinstance(query[0], tuple):
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001225 raise TypeError
1226 # zero-length sequences of all types will get here and succeed,
1227 # but that's a minor nit - since the original implementation
1228 # allowed empty dicts that type of behavior probably should be
1229 # preserved for consistency
1230 except TypeError:
1231 ty,va,tb = sys.exc_info()
1232 raise TypeError, "not a valid non-string sequence or mapping object", tb
1233
Guido van Rossume7b146f2000-02-04 15:28:42 +00001234 l = []
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001235 if not doseq:
1236 # preserve old behavior
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001237 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001238 k = quote_plus(str(k))
1239 v = quote_plus(str(v))
1240 l.append(k + '=' + v)
1241 else:
Skip Montanaro14f1ad42001-01-28 21:11:12 +00001242 for k, v in query:
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001243 k = quote_plus(str(k))
Walter Dörwald65230a22002-06-03 15:58:32 +00001244 if isinstance(v, str):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001245 v = quote_plus(v)
1246 l.append(k + '=' + v)
Guido van Rossum4b46c0a2002-05-24 17:58:05 +00001247 elif _is_unicode(v):
Skip Montanaroa5d23a12001-01-20 15:56:39 +00001248 # is there a reasonable way to convert to ASCII?
1249 # encode generates a string, but "replace" or "ignore"
1250 # lose information and "strict" can raise UnicodeError
1251 v = quote_plus(v.encode("ASCII","replace"))
1252 l.append(k + '=' + v)
1253 else:
1254 try:
1255 # is this a sufficient test for sequence-ness?
1256 x = len(v)
1257 except TypeError:
1258 # not a sequence
1259 v = quote_plus(str(v))
1260 l.append(k + '=' + v)
1261 else:
1262 # loop over the sequence
1263 for elt in v:
1264 l.append(k + '=' + quote_plus(str(elt)))
Guido van Rossumb2493f82000-12-15 15:01:37 +00001265 return '&'.join(l)
Guido van Rossum810a3391998-07-22 21:33:23 +00001266
Guido van Rossum442e7201996-03-20 15:33:11 +00001267# Proxy handling
Mark Hammond4f570b92000-07-26 07:04:38 +00001268def getproxies_environment():
1269 """Return a dictionary of scheme -> proxy server URL mappings.
1270
1271 Scan the environment for variables named <scheme>_proxy;
1272 this seems to be the standard convention. If you need a
1273 different way, you can pass a proxies dictionary to the
1274 [Fancy]URLopener constructor.
1275
1276 """
1277 proxies = {}
1278 for name, value in os.environ.items():
Guido van Rossumb2493f82000-12-15 15:01:37 +00001279 name = name.lower()
Mark Hammond4f570b92000-07-26 07:04:38 +00001280 if value and name[-6:] == '_proxy':
1281 proxies[name[:-6]] = value
1282 return proxies
1283
Jack Jansen11d9b062004-07-16 11:45:00 +00001284if sys.platform == 'darwin':
1285 def getproxies_internetconfig():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001286 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +00001287
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001288 By convention the mac uses Internet Config to store
1289 proxies. An HTTP proxy, for instance, is stored under
1290 the HttpProxy key.
Guido van Rossum442e7201996-03-20 15:33:11 +00001291
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001292 """
1293 try:
1294 import ic
1295 except ImportError:
1296 return {}
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001297
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001298 try:
1299 config = ic.IC()
1300 except ic.error:
1301 return {}
1302 proxies = {}
1303 # HTTP:
Raymond Hettinger54f02222002-06-01 14:18:47 +00001304 if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001305 try:
1306 value = config['HTTPProxyHost']
1307 except ic.error:
1308 pass
1309 else:
1310 proxies['http'] = 'http://%s' % value
1311 # FTP: XXXX To be done.
1312 # Gopher: XXXX To be done.
1313 return proxies
Mark Hammond4f570b92000-07-26 07:04:38 +00001314
Tim Peters55c12d42001-08-09 18:04:14 +00001315 def proxy_bypass(x):
1316 return 0
1317
Jack Jansen11d9b062004-07-16 11:45:00 +00001318 def getproxies():
1319 return getproxies_environment() or getproxies_internetconfig()
Tim Peters182b5ac2004-07-18 06:16:08 +00001320
Mark Hammond4f570b92000-07-26 07:04:38 +00001321elif os.name == 'nt':
1322 def getproxies_registry():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001323 """Return a dictionary of scheme -> proxy server URL mappings.
Mark Hammond4f570b92000-07-26 07:04:38 +00001324
1325 Win32 uses the registry to store proxies.
1326
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001327 """
1328 proxies = {}
Mark Hammond4f570b92000-07-26 07:04:38 +00001329 try:
1330 import _winreg
1331 except ImportError:
1332 # Std module, so should be around - but you never know!
1333 return proxies
1334 try:
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001335 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1336 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
Mark Hammond4f570b92000-07-26 07:04:38 +00001337 proxyEnable = _winreg.QueryValueEx(internetSettings,
1338 'ProxyEnable')[0]
1339 if proxyEnable:
1340 # Returned as Unicode but problems if not converted to ASCII
1341 proxyServer = str(_winreg.QueryValueEx(internetSettings,
1342 'ProxyServer')[0])
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001343 if '=' in proxyServer:
1344 # Per-protocol settings
Mark Hammond4f570b92000-07-26 07:04:38 +00001345 for p in proxyServer.split(';'):
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001346 protocol, address = p.split('=', 1)
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001347 # See if address has a type:// prefix
Guido van Rossum64e5aa92002-04-02 14:38:16 +00001348 import re
1349 if not re.match('^([^/:]+)://', address):
Guido van Rossumb955d6c2002-03-31 23:38:48 +00001350 address = '%s://%s' % (protocol, address)
1351 proxies[protocol] = address
Fredrik Lundhb49f88b2000-09-24 18:51:25 +00001352 else:
1353 # Use one setting for all protocols
1354 if proxyServer[:5] == 'http:':
1355 proxies['http'] = proxyServer
1356 else:
1357 proxies['http'] = 'http://%s' % proxyServer
1358 proxies['ftp'] = 'ftp://%s' % proxyServer
Mark Hammond4f570b92000-07-26 07:04:38 +00001359 internetSettings.Close()
1360 except (WindowsError, ValueError, TypeError):
1361 # Either registry key not found etc, or the value in an
1362 # unexpected format.
1363 # proxies already set up to be empty so nothing to do
1364 pass
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001365 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +00001366
Mark Hammond4f570b92000-07-26 07:04:38 +00001367 def getproxies():
1368 """Return a dictionary of scheme -> proxy server URL mappings.
1369
1370 Returns settings gathered from the environment, if specified,
1371 or the registry.
1372
1373 """
1374 return getproxies_environment() or getproxies_registry()
Tim Peters55c12d42001-08-09 18:04:14 +00001375
1376 def proxy_bypass(host):
1377 try:
1378 import _winreg
1379 import re
Tim Peters55c12d42001-08-09 18:04:14 +00001380 except ImportError:
1381 # Std modules, so should be around - but you never know!
1382 return 0
1383 try:
1384 internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1385 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
1386 proxyEnable = _winreg.QueryValueEx(internetSettings,
1387 'ProxyEnable')[0]
1388 proxyOverride = str(_winreg.QueryValueEx(internetSettings,
1389 'ProxyOverride')[0])
1390 # ^^^^ Returned as Unicode but problems if not converted to ASCII
1391 except WindowsError:
1392 return 0
1393 if not proxyEnable or not proxyOverride:
1394 return 0
1395 # try to make a host list from name and IP address.
Georg Brandl1f636702006-02-18 23:10:23 +00001396 rawHost, port = splitport(host)
1397 host = [rawHost]
Tim Peters55c12d42001-08-09 18:04:14 +00001398 try:
Georg Brandl1f636702006-02-18 23:10:23 +00001399 addr = socket.gethostbyname(rawHost)
1400 if addr != rawHost:
Tim Peters55c12d42001-08-09 18:04:14 +00001401 host.append(addr)
1402 except socket.error:
1403 pass
Georg Brandl1f636702006-02-18 23:10:23 +00001404 try:
1405 fqdn = socket.getfqdn(rawHost)
1406 if fqdn != rawHost:
1407 host.append(fqdn)
1408 except socket.error:
1409 pass
Tim Peters55c12d42001-08-09 18:04:14 +00001410 # make a check value list from the registry entry: replace the
1411 # '<local>' string by the localhost entry and the corresponding
1412 # canonical entry.
1413 proxyOverride = proxyOverride.split(';')
1414 i = 0
1415 while i < len(proxyOverride):
1416 if proxyOverride[i] == '<local>':
1417 proxyOverride[i:i+1] = ['localhost',
1418 '127.0.0.1',
1419 socket.gethostname(),
1420 socket.gethostbyname(
1421 socket.gethostname())]
1422 i += 1
1423 # print proxyOverride
1424 # now check if we match one of the registry values.
1425 for test in proxyOverride:
Tim Petersab9ba272001-08-09 21:40:30 +00001426 test = test.replace(".", r"\.") # mask dots
1427 test = test.replace("*", r".*") # change glob sequence
1428 test = test.replace("?", r".") # change glob char
Tim Peters55c12d42001-08-09 18:04:14 +00001429 for val in host:
1430 # print "%s <--> %s" %( test, val )
1431 if re.match(test, val, re.I):
1432 return 1
1433 return 0
1434
Mark Hammond4f570b92000-07-26 07:04:38 +00001435else:
1436 # By default use environment variables
1437 getproxies = getproxies_environment
1438
Tim Peters55c12d42001-08-09 18:04:14 +00001439 def proxy_bypass(host):
1440 return 0
Guido van Rossum442e7201996-03-20 15:33:11 +00001441
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001442# Test and time quote() and unquote()
1443def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001444 s = ''
1445 for i in range(256): s = s + chr(i)
1446 s = s*4
1447 t0 = time.time()
1448 qs = quote(s)
1449 uqs = unquote(qs)
1450 t1 = time.time()
1451 if uqs != s:
1452 print 'Wrong!'
Walter Dörwald70a6b492004-02-12 17:35:32 +00001453 print repr(s)
1454 print repr(qs)
1455 print repr(uqs)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001456 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001457
1458
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001459def reporthook(blocknum, blocksize, totalsize):
1460 # Report during remote transfers
Guido van Rossumb2493f82000-12-15 15:01:37 +00001461 print "Block number: %d, Block size: %d, Total size: %d" % (
1462 blocknum, blocksize, totalsize)
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001463
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001464# Test program
Guido van Rossum23490151998-06-25 02:39:00 +00001465def test(args=[]):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001466 if not args:
1467 args = [
1468 '/etc/passwd',
1469 'file:/etc/passwd',
1470 'file://localhost/etc/passwd',
Collin Winter071d1ae2007-03-12 01:55:54 +00001471 'ftp://ftp.gnu.org/pub/README',
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001472 'http://www.python.org/index.html',
1473 ]
Guido van Rossum09c8b6c1999-12-07 21:37:17 +00001474 if hasattr(URLopener, "open_https"):
1475 args.append('https://synergy.as.cmu.edu/~geek/')
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001476 try:
1477 for url in args:
1478 print '-'*10, url, '-'*10
1479 fn, h = urlretrieve(url, None, reporthook)
Guido van Rossumb2493f82000-12-15 15:01:37 +00001480 print fn
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001481 if h:
1482 print '======'
1483 for k in h.keys(): print k + ':', h[k]
1484 print '======'
1485 fp = open(fn, 'rb')
1486 data = fp.read()
1487 del fp
1488 if '\r' in data:
1489 table = string.maketrans("", "")
Guido van Rossumb2493f82000-12-15 15:01:37 +00001490 data = data.translate(table, "\r")
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001491 print data
1492 fn, h = None, None
1493 print '-'*40
1494 finally:
1495 urlcleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001496
Guido van Rossum23490151998-06-25 02:39:00 +00001497def main():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001498 import getopt, sys
1499 try:
1500 opts, args = getopt.getopt(sys.argv[1:], "th")
1501 except getopt.error, msg:
1502 print msg
1503 print "Use -h for help"
1504 return
1505 t = 0
1506 for o, a in opts:
1507 if o == '-t':
1508 t = t + 1
1509 if o == '-h':
1510 print "Usage: python urllib.py [-t] [url ...]"
1511 print "-t runs self-test;",
1512 print "otherwise, contents of urls are printed"
1513 return
1514 if t:
1515 if t > 1:
1516 test1()
1517 test(args)
1518 else:
1519 if not args:
1520 print "Use -h for help"
1521 for url in args:
1522 print urlopen(url).read(),
Guido van Rossum23490151998-06-25 02:39:00 +00001523
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001524# Run test program when run as a script
1525if __name__ == '__main__':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001526 main()