Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """Open an arbitrary URL. |
| 2 | |
| 3 | See the following document for more info on URLs: |
| 4 | "Names and Addresses, URIs, URLs, URNs, URCs", at |
| 5 | http://www.w3.org/pub/WWW/Addressing/Overview.html |
| 6 | |
| 7 | See also the HTTP spec (from which the error codes are derived): |
| 8 | "HTTP - Hypertext Transfer Protocol", at |
| 9 | http://www.w3.org/pub/WWW/Protocols/ |
| 10 | |
| 11 | Related standards and specs: |
| 12 | - RFC1808: the "relative URL" spec. (authoritative status) |
| 13 | - RFC1738 - the "URL standard". (authoritative status) |
| 14 | - RFC1630 - the "URI spec". (informational status) |
| 15 | |
| 16 | The object returned by URLopener().open(file) will differ per |
| 17 | protocol. All you know is that is has methods read(), readline(), |
| 18 | readlines(), fileno(), close() and info(). The read*(), fileno() |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 19 | and close() methods work like those of open files. |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 20 | The info() method returns a mimetools.Message object which can be |
| 21 | used to query various info about the object, if available. |
| 22 | (mimetools.Message objects are queried with the getheader() method.) |
| 23 | """ |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 24 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 25 | import string |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 26 | import socket |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 27 | import os |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 28 | import time |
Guido van Rossum | 3c8484e | 1996-11-20 22:02:24 +0000 | [diff] [blame] | 29 | import sys |
Brett Cannon | 69200fa | 2004-03-23 21:26:39 +0000 | [diff] [blame] | 30 | from urlparse import urljoin as basejoin |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 31 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 32 | __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve", |
| 33 | "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus", |
Skip Montanaro | 44d5e0c | 2001-03-13 19:47:16 +0000 | [diff] [blame] | 34 | "urlencode", "url2pathname", "pathname2url", "splittag", |
| 35 | "localhost", "thishost", "ftperrors", "basejoin", "unwrap", |
| 36 | "splittype", "splithost", "splituser", "splitpasswd", "splitport", |
| 37 | "splitnport", "splitquery", "splitattr", "splitvalue", |
Brett Cannon | d75f043 | 2007-05-16 22:42:29 +0000 | [diff] [blame] | 38 | "getproxies"] |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 39 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 40 | __version__ = '1.17' # XXX This version is not always updated :-( |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 41 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 42 | MAXFTPCACHE = 10 # Trim the ftp cache beyond this size |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 43 | |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 44 | # Helper for non-unix systems |
| 45 | if os.name == 'mac': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 46 | from macurl2path import url2pathname, pathname2url |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 47 | elif os.name == 'nt': |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 48 | from nturl2path import url2pathname, pathname2url |
Guido van Rossum | d74fb6b | 2001-03-02 06:43:49 +0000 | [diff] [blame] | 49 | elif os.name == 'riscos': |
| 50 | from rourl2path import url2pathname, pathname2url |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 51 | else: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 52 | def url2pathname(pathname): |
Georg Brandl | c0b2473 | 2005-12-26 22:53:56 +0000 | [diff] [blame] | 53 | """OS-specific conversion from a relative URL of the 'file' scheme |
| 54 | to a file system path; not recommended for general use.""" |
Guido van Rossum | 367ac80 | 1999-03-12 14:31:10 +0000 | [diff] [blame] | 55 | return unquote(pathname) |
Georg Brandl | c0b2473 | 2005-12-26 22:53:56 +0000 | [diff] [blame] | 56 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 57 | def pathname2url(pathname): |
Georg Brandl | c0b2473 | 2005-12-26 22:53:56 +0000 | [diff] [blame] | 58 | """OS-specific conversion from a file system path to a relative URL |
| 59 | of the 'file' scheme; not recommended for general use.""" |
Guido van Rossum | 367ac80 | 1999-03-12 14:31:10 +0000 | [diff] [blame] | 60 | return quote(pathname) |
Guido van Rossum | 33add0a | 1998-12-18 15:25:22 +0000 | [diff] [blame] | 61 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 62 | # 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 Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 71 | def urlopen(url, data=None, proxies=None): |
Skip Montanaro | 79f1c17 | 2000-08-22 03:00:52 +0000 | [diff] [blame] | 72 | """urlopen(url [, data]) -> open file-like object""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 73 | global _urlopener |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 74 | if proxies is not None: |
| 75 | opener = FancyURLopener(proxies=proxies) |
| 76 | elif not _urlopener: |
| 77 | opener = FancyURLopener() |
| 78 | _urlopener = opener |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 79 | else: |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 80 | opener = _urlopener |
| 81 | if data is None: |
| 82 | return opener.open(url) |
| 83 | else: |
| 84 | return opener.open(url, data) |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 85 | def urlretrieve(url, filename=None, reporthook=None, data=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 86 | global _urlopener |
| 87 | if not _urlopener: |
| 88 | _urlopener = FancyURLopener() |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 89 | return _urlopener.retrieve(url, filename, reporthook, data) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 90 | def urlcleanup(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 91 | if _urlopener: |
| 92 | _urlopener.cleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 93 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 94 | # check for SSL |
| 95 | try: |
| 96 | import ssl |
| 97 | except: |
| 98 | _have_ssl = False |
| 99 | else: |
| 100 | _have_ssl = True |
| 101 | |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 102 | # exception raised when downloaded size does not match content-length |
| 103 | class ContentTooShortError(IOError): |
| 104 | def __init__(self, message, content): |
| 105 | IOError.__init__(self, message) |
| 106 | self.content = content |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 107 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 108 | ftpcache = {} |
| 109 | class URLopener: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 110 | """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 Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 116 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 117 | __tempfiles = None |
Guido van Rossum | 29e7781 | 1996-11-27 19:39:58 +0000 | [diff] [blame] | 118 | |
Guido van Rossum | ba31138 | 2000-08-24 16:18:04 +0000 | [diff] [blame] | 119 | version = "Python-urllib/%s" % __version__ |
| 120 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 121 | # Constructor |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 122 | def __init__(self, proxies=None, **x509): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 123 | if proxies is None: |
| 124 | proxies = getproxies() |
| 125 | assert hasattr(proxies, 'has_key'), "proxies must be a mapping" |
| 126 | self.proxies = proxies |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 127 | self.key_file = x509.get('key_file') |
| 128 | self.cert_file = x509.get('cert_file') |
Georg Brandl | 0619a32 | 2006-07-26 07:40:17 +0000 | [diff] [blame] | 129 | self.addheaders = [('User-Agent', self.version)] |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 130 | 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 Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 144 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 145 | def __del__(self): |
| 146 | self.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 147 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 148 | def close(self): |
| 149 | self.cleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 150 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 151 | 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öwis | 58682b7 | 2001-08-11 15:02:57 +0000 | [diff] [blame] | 159 | except OSError: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 160 | pass |
| 161 | del self.__tempfiles[:] |
| 162 | if self.tempcache: |
| 163 | self.tempcache.clear() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 164 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 165 | def addheader(self, *args): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 166 | """Add a header to be used by the HTTP interface only |
| 167 | e.g. u.addheader('Accept', 'sound/basic')""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 168 | self.addheaders.append(args) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 169 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 170 | # External interface |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 171 | def open(self, fullurl, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 172 | """Use URLopener().open(file) instead of open(file, 'r').""" |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 173 | fullurl = unwrap(toBytes(fullurl)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 174 | if self.tempcache and fullurl in self.tempcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 175 | filename, headers = self.tempcache[fullurl] |
| 176 | fp = open(filename, 'rb') |
| 177 | return addinfourl(fp, headers, fullurl) |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 178 | urltype, url = splittype(fullurl) |
| 179 | if not urltype: |
| 180 | urltype = 'file' |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 181 | if urltype in self.proxies: |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 182 | proxy = self.proxies[urltype] |
| 183 | urltype, proxyhost = splittype(proxy) |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 184 | host, selector = splithost(proxyhost) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 185 | url = (host, fullurl) # Signal special case to open_*() |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 186 | else: |
| 187 | proxy = None |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 188 | name = 'open_' + urltype |
| 189 | self.type = urltype |
Brett Cannon | aaeffaf | 2004-03-23 23:50:17 +0000 | [diff] [blame] | 190 | name = name.replace('-', '_') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 191 | if not hasattr(self, name): |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 192 | if proxy: |
| 193 | return self.open_unknown_proxy(proxy, fullurl, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 194 | 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 Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 203 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 204 | def open_unknown(self, fullurl, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 205 | """Overridable interface to open unknown URL type.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 206 | type, url = splittype(fullurl) |
| 207 | raise IOError, ('url error', 'unknown url type', type) |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 208 | |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 209 | 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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 214 | # External interface |
Sjoerd Mullender | d7b86f0 | 2000-08-25 11:23:36 +0000 | [diff] [blame] | 215 | def retrieve(self, url, filename=None, reporthook=None, data=None): |
Brett Cannon | 7d618c7 | 2003-04-24 02:43:20 +0000 | [diff] [blame] | 216 | """retrieve(url) returns (filename, headers) for a local object |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 217 | or (tempfilename, headers) for a remote object.""" |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 218 | url = unwrap(toBytes(url)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 219 | if self.tempcache and url in self.tempcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 220 | return self.tempcache[url] |
| 221 | type, url1 = splittype(url) |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 222 | if filename is None and (not type or type == 'file'): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 223 | 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 Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 230 | fp = self.open(url, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 231 | headers = fp.info() |
Guido van Rossum | 3b0a329 | 2002-08-09 16:38:32 +0000 | [diff] [blame] | 232 | if filename: |
| 233 | tfp = open(filename, 'wb') |
| 234 | else: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 235 | 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 Rossum | 3b0a329 | 2002-08-09 16:38:32 +0000 | [diff] [blame] | 241 | (fd, filename) = tempfile.mkstemp(suffix) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 242 | self.__tempfiles.append(filename) |
Jeremy Hylton | 3bd6fde | 2002-10-11 14:36:24 +0000 | [diff] [blame] | 243 | tfp = os.fdopen(fd, 'wb') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 244 | result = filename, headers |
| 245 | if self.tempcache is not None: |
| 246 | self.tempcache[url] = result |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 247 | bs = 1024*8 |
| 248 | size = -1 |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 249 | read = 0 |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 250 | blocknum = 0 |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 251 | if reporthook: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 252 | if "content-length" in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 253 | size = int(headers["Content-Length"]) |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 254 | reporthook(blocknum, bs, size) |
| 255 | while 1: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 256 | block = fp.read(bs) |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 257 | if block == "": |
| 258 | break |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 259 | read += len(block) |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 260 | tfp.write(block) |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 261 | blocknum += 1 |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 262 | if reporthook: |
| 263 | reporthook(blocknum, bs, size) |
| 264 | fp.close() |
| 265 | tfp.close() |
| 266 | del fp |
| 267 | del tfp |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 268 | |
| 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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 274 | return result |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 275 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 276 | # Each method named open_<type> knows how to open that type of URL |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 277 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 278 | def open_http(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 279 | """Use HTTP protocol.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 280 | import httplib |
| 281 | user_passwd = None |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 282 | proxy_passwd= None |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 283 | if isinstance(url, str): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 284 | 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öwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 291 | # 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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 294 | urltype, rest = splittype(selector) |
| 295 | url = rest |
| 296 | user_passwd = None |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 297 | if urltype.lower() != 'http': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 298 | 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 Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 305 | if proxy_bypass(realhost): |
| 306 | host = realhost |
| 307 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 308 | #print "proxy via http:", host, selector |
| 309 | if not host: raise IOError, ('http error', 'no host given') |
Tim Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 310 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 311 | if proxy_passwd: |
| 312 | import base64 |
Andrew M. Kuchling | 872dba4 | 2006-10-27 17:11:23 +0000 | [diff] [blame] | 313 | proxy_auth = base64.b64encode(proxy_passwd).strip() |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 314 | else: |
| 315 | proxy_auth = None |
| 316 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 317 | if user_passwd: |
| 318 | import base64 |
Andrew M. Kuchling | 872dba4 | 2006-10-27 17:11:23 +0000 | [diff] [blame] | 319 | auth = base64.b64encode(user_passwd).strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 320 | else: |
| 321 | auth = None |
| 322 | h = httplib.HTTP(host) |
| 323 | if data is not None: |
| 324 | h.putrequest('POST', selector) |
Georg Brandl | 0619a32 | 2006-07-26 07:40:17 +0000 | [diff] [blame] | 325 | h.putheader('Content-Type', 'application/x-www-form-urlencoded') |
| 326 | h.putheader('Content-Length', '%d' % len(data)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 327 | else: |
| 328 | h.putrequest('GET', selector) |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 329 | if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 330 | if auth: h.putheader('Authorization', 'Basic %s' % auth) |
| 331 | if realhost: h.putheader('Host', realhost) |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 332 | for args in self.addheaders: h.putheader(*args) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 333 | h.endheaders() |
| 334 | if data is not None: |
Fred Drake | ec3dfde | 2001-07-04 05:18:29 +0000 | [diff] [blame] | 335 | h.send(data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 336 | errcode, errmsg, headers = h.getreply() |
Neal Norwitz | ce55e21 | 2007-03-20 08:14:57 +0000 | [diff] [blame] | 337 | fp = h.getfile() |
Georg Brandl | f66b603 | 2007-03-14 08:27:52 +0000 | [diff] [blame] | 338 | if errcode == -1: |
Neal Norwitz | ce55e21 | 2007-03-20 08:14:57 +0000 | [diff] [blame] | 339 | if fp: fp.close() |
Georg Brandl | f66b603 | 2007-03-14 08:27:52 +0000 | [diff] [blame] | 340 | # something went wrong with the HTTP status line |
| 341 | raise IOError, ('http protocol error', 0, |
| 342 | 'got a bad status line', None) |
Sean Reifscheider | a1afbf6 | 2007-09-19 07:52:56 +0000 | [diff] [blame^] | 343 | # 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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 346 | return addinfourl(fp, headers, "http:" + url) |
| 347 | else: |
| 348 | if data is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 349 | return self.http_error(url, fp, errcode, errmsg, headers) |
Guido van Rossum | 29aab75 | 1999-03-09 19:31:21 +0000 | [diff] [blame] | 350 | else: |
| 351 | return self.http_error(url, fp, errcode, errmsg, headers, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 352 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 353 | def http_error(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 354 | """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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 357 | # 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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 362 | result = method(url, fp, errcode, errmsg, headers) |
Jeremy Hylton | b30f52a | 1999-02-25 16:14:58 +0000 | [diff] [blame] | 363 | else: |
| 364 | result = method(url, fp, errcode, errmsg, headers, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 365 | if result: return result |
Jeremy Hylton | b30f52a | 1999-02-25 16:14:58 +0000 | [diff] [blame] | 366 | return self.http_error_default(url, fp, errcode, errmsg, headers) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 367 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 368 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 369 | """Default error handler: close the connection and raise IOError.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 370 | void = fp.read() |
| 371 | fp.close() |
| 372 | raise IOError, ('http error', errcode, errmsg, headers) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 373 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 374 | if _have_ssl: |
Andrew M. Kuchling | 141e989 | 2000-04-23 02:53:11 +0000 | [diff] [blame] | 375 | def open_https(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 376 | """Use HTTPS protocol.""" |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 377 | |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 378 | import httplib |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 379 | user_passwd = None |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 380 | proxy_passwd = None |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 381 | if isinstance(url, str): |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 382 | host, selector = splithost(url) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 383 | if host: |
| 384 | user_passwd, host = splituser(host) |
| 385 | host = unquote(host) |
| 386 | realhost = host |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 387 | else: |
| 388 | host, selector = url |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 389 | # here, we determine, whether the proxy contains authorization information |
| 390 | proxy_passwd, host = splituser(host) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 391 | urltype, rest = splittype(selector) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 392 | url = rest |
| 393 | user_passwd = None |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 394 | if urltype.lower() != 'https': |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 395 | realhost = None |
| 396 | else: |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 397 | realhost, rest = splithost(rest) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 398 | if realhost: |
| 399 | user_passwd, realhost = splituser(realhost) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 400 | if user_passwd: |
| 401 | selector = "%s://%s%s" % (urltype, realhost, rest) |
Andrew M. Kuchling | 7ad4792 | 2000-06-10 01:41:48 +0000 | [diff] [blame] | 402 | #print "proxy via https:", host, selector |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 403 | if not host: raise IOError, ('https error', 'no host given') |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 404 | if proxy_passwd: |
| 405 | import base64 |
Andrew M. Kuchling | 872dba4 | 2006-10-27 17:11:23 +0000 | [diff] [blame] | 406 | proxy_auth = base64.b64encode(proxy_passwd).strip() |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 407 | else: |
| 408 | proxy_auth = None |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 409 | if user_passwd: |
| 410 | import base64 |
Andrew M. Kuchling | 872dba4 | 2006-10-27 17:11:23 +0000 | [diff] [blame] | 411 | auth = base64.b64encode(user_passwd).strip() |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 412 | else: |
| 413 | auth = None |
| 414 | h = httplib.HTTPS(host, 0, |
| 415 | key_file=self.key_file, |
| 416 | cert_file=self.cert_file) |
Andrew M. Kuchling | 141e989 | 2000-04-23 02:53:11 +0000 | [diff] [blame] | 417 | if data is not None: |
| 418 | h.putrequest('POST', selector) |
Georg Brandl | 0619a32 | 2006-07-26 07:40:17 +0000 | [diff] [blame] | 419 | h.putheader('Content-Type', |
Andrew M. Kuchling | 141e989 | 2000-04-23 02:53:11 +0000 | [diff] [blame] | 420 | 'application/x-www-form-urlencoded') |
Georg Brandl | 0619a32 | 2006-07-26 07:40:17 +0000 | [diff] [blame] | 421 | h.putheader('Content-Length', '%d' % len(data)) |
Andrew M. Kuchling | 141e989 | 2000-04-23 02:53:11 +0000 | [diff] [blame] | 422 | else: |
| 423 | h.putrequest('GET', selector) |
Andrew M. Kuchling | 5227857 | 2006-12-19 15:11:41 +0000 | [diff] [blame] | 424 | if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth) |
| 425 | if auth: h.putheader('Authorization', 'Basic %s' % auth) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 426 | if realhost: h.putheader('Host', realhost) |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 427 | for args in self.addheaders: h.putheader(*args) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 428 | h.endheaders() |
Andrew M. Kuchling | 43c5af0 | 2000-04-24 14:17:06 +0000 | [diff] [blame] | 429 | if data is not None: |
Fred Drake | ec3dfde | 2001-07-04 05:18:29 +0000 | [diff] [blame] | 430 | h.send(data) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 431 | errcode, errmsg, headers = h.getreply() |
Neal Norwitz | ce55e21 | 2007-03-20 08:14:57 +0000 | [diff] [blame] | 432 | fp = h.getfile() |
Georg Brandl | f66b603 | 2007-03-14 08:27:52 +0000 | [diff] [blame] | 433 | if errcode == -1: |
Neal Norwitz | ce55e21 | 2007-03-20 08:14:57 +0000 | [diff] [blame] | 434 | if fp: fp.close() |
Georg Brandl | f66b603 | 2007-03-14 08:27:52 +0000 | [diff] [blame] | 435 | # something went wrong with the HTTP status line |
| 436 | raise IOError, ('http protocol error', 0, |
| 437 | 'got a bad status line', None) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 438 | if errcode == 200: |
Guido van Rossum | b931bf3 | 2001-12-08 17:09:07 +0000 | [diff] [blame] | 439 | return addinfourl(fp, headers, "https:" + url) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 440 | else: |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 441 | if data is None: |
| 442 | return self.http_error(url, fp, errcode, errmsg, headers) |
| 443 | else: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 444 | return self.http_error(url, fp, errcode, errmsg, headers, |
| 445 | data) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 446 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 447 | def open_file(self, url): |
Neal Norwitz | c5d0dbd | 2006-04-09 04:00:49 +0000 | [diff] [blame] | 448 | """Use local file or FTP depending on form of URL.""" |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 449 | if not isinstance(url, str): |
| 450 | raise IOError, ('file error', 'proxy support for file protocol currently not implemented') |
Jack Jansen | 4ef1103 | 2002-09-12 20:14:04 +0000 | [diff] [blame] | 451 | if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 452 | return self.open_ftp(url) |
| 453 | else: |
| 454 | return self.open_local_file(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 455 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 456 | def open_local_file(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 457 | """Use local file.""" |
Georg Brandl | 5a096e1 | 2007-01-22 19:40:21 +0000 | [diff] [blame] | 458 | import mimetypes, mimetools, email.utils |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 459 | try: |
| 460 | from cStringIO import StringIO |
| 461 | except ImportError: |
| 462 | from StringIO import StringIO |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 463 | host, file = splithost(url) |
| 464 | localname = url2pathname(file) |
Guido van Rossum | a2da305 | 2002-04-15 00:25:01 +0000 | [diff] [blame] | 465 | try: |
| 466 | stats = os.stat(localname) |
| 467 | except OSError, e: |
| 468 | raise IOError(e.errno, e.strerror, e.filename) |
Walter Dörwald | 92b48b7 | 2002-03-22 17:30:38 +0000 | [diff] [blame] | 469 | size = stats.st_size |
Georg Brandl | 5a096e1 | 2007-01-22 19:40:21 +0000 | [diff] [blame] | 470 | modified = email.utils.formatdate(stats.st_mtime, usegmt=True) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 471 | mtype = mimetypes.guess_type(url)[0] |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 472 | headers = mimetools.Message(StringIO( |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 473 | 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % |
| 474 | (mtype or 'text/plain', size, modified))) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 475 | if not host: |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 476 | urlfile = file |
| 477 | if file[:1] == '/': |
| 478 | urlfile = 'file://' + file |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 479 | return addinfourl(open(localname, 'rb'), |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 480 | headers, urlfile) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 481 | host, port = splitport(host) |
| 482 | if not port \ |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 483 | and socket.gethostbyname(host) in (localhost(), thishost()): |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 484 | urlfile = file |
| 485 | if file[:1] == '/': |
| 486 | urlfile = 'file://' + file |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 487 | return addinfourl(open(localname, 'rb'), |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 488 | headers, urlfile) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 489 | raise IOError, ('local file error', 'not on local host') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 490 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 491 | def open_ftp(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 492 | """Use FTP protocol.""" |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 493 | if not isinstance(url, str): |
| 494 | raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented') |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 495 | import mimetypes, mimetools |
| 496 | try: |
| 497 | from cStringIO import StringIO |
| 498 | except ImportError: |
| 499 | from StringIO import StringIO |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 500 | 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 Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 517 | dirs = path.split('/') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 518 | dirs, file = dirs[:-1], dirs[-1] |
| 519 | if dirs and not dirs[0]: dirs = dirs[1:] |
Guido van Rossum | 5e006a3 | 1999-08-18 17:40:33 +0000 | [diff] [blame] | 520 | if dirs and not dirs[0]: dirs[0] = '/' |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 521 | key = user, host, port, '/'.join(dirs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 522 | # 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 Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 531 | if not key in self.ftpcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 532 | 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 Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 538 | if attr.lower() == 'type' and \ |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 539 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 540 | type = value.upper() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 541 | (fp, retrlen) = self.ftpcache[key].retrfile(file, type) |
Guido van Rossum | 88e0b5b | 2001-08-23 13:38:15 +0000 | [diff] [blame] | 542 | mtype = mimetypes.guess_type("ftp:" + url)[0] |
| 543 | headers = "" |
| 544 | if mtype: |
| 545 | headers += "Content-Type: %s\n" % mtype |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 546 | if retrlen is not None and retrlen >= 0: |
Guido van Rossum | 88e0b5b | 2001-08-23 13:38:15 +0000 | [diff] [blame] | 547 | headers += "Content-Length: %d\n" % retrlen |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 548 | headers = mimetools.Message(StringIO(headers)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 549 | return addinfourl(fp, headers, "ftp:" + url) |
| 550 | except ftperrors(), msg: |
| 551 | raise IOError, ('ftp error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 552 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 553 | def open_data(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 554 | """Use "data" URL.""" |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 555 | if not isinstance(url, str): |
| 556 | raise IOError, ('data error', 'proxy support for data protocol currently not implemented') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 557 | # 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 Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 564 | import mimetools |
| 565 | try: |
| 566 | from cStringIO import StringIO |
| 567 | except ImportError: |
| 568 | from StringIO import StringIO |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 569 | try: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 570 | [type, data] = url.split(',', 1) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 571 | except ValueError: |
| 572 | raise IOError, ('data error', 'bad data URL') |
| 573 | if not type: |
| 574 | type = 'text/plain;charset=US-ASCII' |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 575 | semi = type.rfind(';') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 576 | 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 Brandl | 0619a32 | 2006-07-26 07:40:17 +0000 | [diff] [blame] | 590 | msg.append('Content-Length: %d' % len(data)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 591 | msg.append('') |
| 592 | msg.append(data) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 593 | msg = '\n'.join(msg) |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 594 | f = StringIO(msg) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 595 | headers = mimetools.Message(f, 0) |
Georg Brandl | 1f66357 | 2005-11-26 16:50:44 +0000 | [diff] [blame] | 596 | #f.fileno = None # needed for addinfourl |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 597 | return addinfourl(f, headers, url) |
Guido van Rossum | 6d4d1c2 | 1998-03-12 14:32:55 +0000 | [diff] [blame] | 598 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 599 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 600 | class FancyURLopener(URLopener): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 601 | """Derived class with handlers for errors we can handle (perhaps).""" |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 602 | |
Neal Norwitz | 60e04cd | 2002-06-11 13:38:51 +0000 | [diff] [blame] | 603 | def __init__(self, *args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 604 | URLopener.__init__(self, *args, **kwargs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 605 | self.auth_cache = {} |
Skip Montanaro | c3e11d6 | 2001-02-15 16:56:36 +0000 | [diff] [blame] | 606 | self.tries = 0 |
| 607 | self.maxtries = 10 |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 608 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 609 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 610 | """Default error handling -- don't raise an exception.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 611 | return addinfourl(fp, headers, "http:" + url) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 612 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 613 | def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 614 | """Error 302 -- relocated (temporarily).""" |
Skip Montanaro | c3e11d6 | 2001-02-15 16:56:36 +0000 | [diff] [blame] | 615 | 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 Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 630 | if 'location' in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 631 | newurl = headers['location'] |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 632 | elif 'uri' in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 633 | newurl = headers['uri'] |
| 634 | else: |
| 635 | return |
| 636 | void = fp.read() |
| 637 | fp.close() |
Guido van Rossum | 3527f59 | 1999-03-29 20:23:41 +0000 | [diff] [blame] | 638 | # In case the server sent a relative URL, join with original: |
Moshe Zadka | 5d87d47 | 2001-04-09 14:54:21 +0000 | [diff] [blame] | 639 | newurl = basejoin(self.type + ":" + url, newurl) |
Guido van Rossum | fa19f7c | 2003-05-16 01:46:51 +0000 | [diff] [blame] | 640 | return self.open(newurl) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 641 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 642 | def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 643 | """Error 301 -- also relocated (permanently).""" |
| 644 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 645 | |
Raymond Hettinger | 024aaa1 | 2003-04-24 15:32:12 +0000 | [diff] [blame] | 646 | 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 Rossum | fa19f7c | 2003-05-16 01:46:51 +0000 | [diff] [blame] | 650 | 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 Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 657 | def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 658 | """Error 401 -- authentication required. |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 659 | This function supports Basic authentication only.""" |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 660 | if not 'www-authenticate' in headers: |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 661 | URLopener.http_error_default(self, url, fp, |
Fred Drake | c680ae8 | 2001-10-13 18:37:07 +0000 | [diff] [blame] | 662 | errcode, errmsg, headers) |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 663 | stuff = headers['www-authenticate'] |
| 664 | import re |
| 665 | match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 666 | if not match: |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 667 | URLopener.http_error_default(self, url, fp, |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 668 | errcode, errmsg, headers) |
| 669 | scheme, realm = match.groups() |
| 670 | if scheme.lower() != 'basic': |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 671 | URLopener.http_error_default(self, url, fp, |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 672 | 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 Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 678 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 679 | 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 Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 700 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 701 | 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 Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 717 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 718 | 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 Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 734 | |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 735 | def retry_http_basic_auth(self, url, realm, data=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 736 | host, selector = splithost(url) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 737 | i = host.find('@') + 1 |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 738 | host = host[i:] |
| 739 | user, passwd = self.get_user_passwd(host, realm, i) |
| 740 | if not (user or passwd): return None |
Guido van Rossum | afc4f04 | 2001-01-15 18:31:13 +0000 | [diff] [blame] | 741 | host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 742 | newurl = 'http://' + host + selector |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 743 | if data is None: |
| 744 | return self.open(newurl) |
| 745 | else: |
| 746 | return self.open(newurl, data) |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 747 | |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 748 | def retry_https_basic_auth(self, url, realm, data=None): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 749 | 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 Rossum | afc4f04 | 2001-01-15 18:31:13 +0000 | [diff] [blame] | 754 | host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 755 | newurl = 'https://' + host + selector |
| 756 | if data is None: |
| 757 | return self.open(newurl) |
| 758 | else: |
| 759 | return self.open(newurl, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 760 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 761 | def get_user_passwd(self, host, realm, clear_cache = 0): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 762 | key = realm + '@' + host.lower() |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 763 | if key in self.auth_cache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 764 | 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 Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 771 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 772 | def prompt_user_passwd(self, host, realm): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 773 | """Override this in a GUI environment!""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 774 | import getpass |
| 775 | try: |
| 776 | user = raw_input("Enter username for %s at %s: " % (realm, |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 777 | host)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 778 | 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 Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 784 | |
| 785 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 786 | # Utility functions |
| 787 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 788 | _localhost = None |
| 789 | def localhost(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 790 | """Return the IP address of the magic hostname 'localhost'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 791 | global _localhost |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 792 | if _localhost is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 793 | _localhost = socket.gethostbyname('localhost') |
| 794 | return _localhost |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 795 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 796 | _thishost = None |
| 797 | def thishost(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 798 | """Return the IP address of the current host.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 799 | global _thishost |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 800 | if _thishost is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 801 | _thishost = socket.gethostbyname(socket.gethostname()) |
| 802 | return _thishost |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 803 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 804 | _ftperrors = None |
| 805 | def ftperrors(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 806 | """Return the set of errors raised by the FTP class.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 807 | global _ftperrors |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 808 | if _ftperrors is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 809 | import ftplib |
| 810 | _ftperrors = ftplib.all_errors |
| 811 | return _ftperrors |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 812 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 813 | _noheaders = None |
| 814 | def noheaders(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 815 | """Return an empty mimetools.Message object.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 816 | global _noheaders |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 817 | if _noheaders is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 818 | import mimetools |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 819 | try: |
| 820 | from cStringIO import StringIO |
| 821 | except ImportError: |
| 822 | from StringIO import StringIO |
| 823 | _noheaders = mimetools.Message(StringIO(), 0) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 824 | _noheaders.fp.close() # Recycle file descriptor |
| 825 | return _noheaders |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 826 | |
| 827 | |
| 828 | # Utility classes |
| 829 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 830 | class ftpwrapper: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 831 | """Class used by open_ftp() for cache of open FTP connections.""" |
| 832 | |
Facundo Batista | 711a54e | 2007-05-24 17:50:54 +0000 | [diff] [blame] | 833 | def __init__(self, user, passwd, host, port, dirs, timeout=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 834 | self.user = user |
| 835 | self.passwd = passwd |
| 836 | self.host = host |
| 837 | self.port = port |
| 838 | self.dirs = dirs |
Facundo Batista | 711a54e | 2007-05-24 17:50:54 +0000 | [diff] [blame] | 839 | self.timeout = timeout |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 840 | self.init() |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 841 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 842 | def init(self): |
| 843 | import ftplib |
| 844 | self.busy = 0 |
| 845 | self.ftp = ftplib.FTP() |
Facundo Batista | 711a54e | 2007-05-24 17:50:54 +0000 | [diff] [blame] | 846 | self.ftp.connect(self.host, self.port, self.timeout) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 847 | self.ftp.login(self.user, self.passwd) |
| 848 | for dir in self.dirs: |
| 849 | self.ftp.cwd(dir) |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 850 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 851 | 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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 863 | # 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 Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 868 | if str(reason)[:3] != '550': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 869 | 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 Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 880 | self.endtransfer), conn[1]) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 881 | 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 Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 889 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 890 | def close(self): |
| 891 | self.endtransfer() |
| 892 | try: |
| 893 | self.ftp.close() |
| 894 | except ftperrors(): |
| 895 | pass |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 896 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 897 | class addbase: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 898 | """Base class for addinfo and addclosehook.""" |
| 899 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 900 | def __init__(self, fp): |
| 901 | self.fp = fp |
| 902 | self.read = self.fp.read |
| 903 | self.readline = self.fp.readline |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 904 | if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines |
Georg Brandl | 1f66357 | 2005-11-26 16:50:44 +0000 | [diff] [blame] | 905 | if hasattr(self.fp, "fileno"): |
| 906 | self.fileno = self.fp.fileno |
| 907 | else: |
| 908 | self.fileno = lambda: None |
Raymond Hettinger | 42182eb | 2003-03-09 05:33:33 +0000 | [diff] [blame] | 909 | 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 Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 913 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 914 | def __repr__(self): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 915 | return '<%s at %r whose fp = %r>' % (self.__class__.__name__, |
| 916 | id(self), self.fp) |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 917 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 918 | 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 Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 925 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 926 | class addclosehook(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 927 | """Class to add a close hook to an open file.""" |
| 928 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 929 | def __init__(self, fp, closehook, *hookargs): |
| 930 | addbase.__init__(self, fp) |
| 931 | self.closehook = closehook |
| 932 | self.hookargs = hookargs |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 933 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 934 | def close(self): |
Guido van Rossum | c580dae | 2000-05-24 13:21:46 +0000 | [diff] [blame] | 935 | addbase.close(self) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 936 | if self.closehook: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 937 | self.closehook(*self.hookargs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 938 | self.closehook = None |
| 939 | self.hookargs = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 940 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 941 | class addinfo(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 942 | """class to add an info() method to an open file.""" |
| 943 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 944 | def __init__(self, fp, headers): |
| 945 | addbase.__init__(self, fp) |
| 946 | self.headers = headers |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 947 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 948 | def info(self): |
| 949 | return self.headers |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 950 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 951 | class addinfourl(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 952 | """class to add info() and geturl() methods to an open file.""" |
| 953 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 954 | def __init__(self, fp, headers, url): |
| 955 | addbase.__init__(self, fp) |
| 956 | self.headers = headers |
| 957 | self.url = url |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 958 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 959 | def info(self): |
| 960 | return self.headers |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 961 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 962 | def geturl(self): |
| 963 | return self.url |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 964 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 965 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 966 | # Utilities to parse URLs (most of these return None for missing parts): |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 967 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 968 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 969 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 970 | # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' |
| 971 | # splitpasswd('user:passwd') -> 'user', 'passwd' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 972 | # splitport('host:port') --> 'host', 'port' |
| 973 | # splitquery('/path?query') --> '/path', 'query' |
| 974 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 975 | # splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 976 | # '/path', ['attr1=value1', 'attr2=value2', ...] |
| 977 | # splitvalue('attr=value') --> 'attr', 'value' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 978 | # unquote('abc%20def') -> 'abc def' |
| 979 | # quote('abc def') -> 'abc%20def') |
| 980 | |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 981 | try: |
| 982 | unicode |
| 983 | except NameError: |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 984 | def _is_unicode(x): |
| 985 | return 0 |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 986 | else: |
| 987 | def _is_unicode(x): |
| 988 | return isinstance(x, unicode) |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 989 | |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 990 | def toBytes(url): |
| 991 | """toBytes(u"URL") --> 'URL'.""" |
| 992 | # Most URL schemes require ASCII. If that changes, the conversion |
| 993 | # can be relaxed |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 994 | if _is_unicode(url): |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 995 | try: |
| 996 | url = url.encode("ASCII") |
| 997 | except UnicodeError: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 998 | raise UnicodeError("URL " + repr(url) + |
| 999 | " contains non-ASCII characters") |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 1000 | return url |
| 1001 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1002 | def unwrap(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1003 | """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1004 | url = url.strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1005 | if url[:1] == '<' and url[-1:] == '>': |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1006 | url = url[1:-1].strip() |
| 1007 | if url[:4] == 'URL:': url = url[4:].strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1008 | return url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1009 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1010 | _typeprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1011 | def splittype(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1012 | """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1013 | global _typeprog |
| 1014 | if _typeprog is None: |
| 1015 | import re |
| 1016 | _typeprog = re.compile('^([^/:]+):') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1017 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1018 | match = _typeprog.match(url) |
| 1019 | if match: |
| 1020 | scheme = match.group(1) |
Fred Drake | 9e94afd | 2000-07-01 07:03:30 +0000 | [diff] [blame] | 1021 | return scheme.lower(), url[len(scheme) + 1:] |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1022 | return None, url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1023 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1024 | _hostprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1025 | def splithost(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1026 | """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1027 | global _hostprog |
| 1028 | if _hostprog is None: |
| 1029 | import re |
Georg Brandl | 1c168d8 | 2006-03-26 20:59:38 +0000 | [diff] [blame] | 1030 | _hostprog = re.compile('^//([^/?]*)(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1031 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1032 | match = _hostprog.match(url) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1033 | if match: return match.group(1, 2) |
| 1034 | return None, url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1035 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1036 | _userprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1037 | def splituser(host): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1038 | """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1039 | global _userprog |
| 1040 | if _userprog is None: |
| 1041 | import re |
Raymond Hettinger | f2e45dd | 2002-08-18 20:08:56 +0000 | [diff] [blame] | 1042 | _userprog = re.compile('^(.*)@(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1043 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1044 | match = _userprog.match(host) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 1045 | if match: return map(unquote, match.group(1, 2)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1046 | return None, host |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1047 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1048 | _passwdprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1049 | def splitpasswd(user): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1050 | """splitpasswd('user:passwd') -> 'user', 'passwd'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1051 | global _passwdprog |
| 1052 | if _passwdprog is None: |
| 1053 | import re |
| 1054 | _passwdprog = re.compile('^([^:]*):(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1055 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1056 | match = _passwdprog.match(user) |
| 1057 | if match: return match.group(1, 2) |
| 1058 | return user, None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1059 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1060 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1061 | _portprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1062 | def splitport(host): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1063 | """splitport('host:port') --> 'host', 'port'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1064 | global _portprog |
| 1065 | if _portprog is None: |
| 1066 | import re |
| 1067 | _portprog = re.compile('^(.*):([0-9]+)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1068 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1069 | match = _portprog.match(host) |
| 1070 | if match: return match.group(1, 2) |
| 1071 | return host, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1072 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1073 | _nportprog = None |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 1074 | def splitnport(host, defport=-1): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1075 | """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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1079 | global _nportprog |
| 1080 | if _nportprog is None: |
| 1081 | import re |
| 1082 | _nportprog = re.compile('^(.*):(.*)$') |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 1083 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1084 | match = _nportprog.match(host) |
| 1085 | if match: |
| 1086 | host, port = match.group(1, 2) |
| 1087 | try: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1088 | if not port: raise ValueError, "no digits" |
| 1089 | nport = int(port) |
| 1090 | except ValueError: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1091 | nport = None |
| 1092 | return host, nport |
| 1093 | return host, defport |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 1094 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1095 | _queryprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1096 | def splitquery(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1097 | """splitquery('/path?query') --> '/path', 'query'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1098 | global _queryprog |
| 1099 | if _queryprog is None: |
| 1100 | import re |
| 1101 | _queryprog = re.compile('^(.*)\?([^?]*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1102 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1103 | match = _queryprog.match(url) |
| 1104 | if match: return match.group(1, 2) |
| 1105 | return url, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1106 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1107 | _tagprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1108 | def splittag(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1109 | """splittag('/path#tag') --> '/path', 'tag'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1110 | global _tagprog |
| 1111 | if _tagprog is None: |
| 1112 | import re |
| 1113 | _tagprog = re.compile('^(.*)#([^#]*)$') |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 1114 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1115 | match = _tagprog.match(url) |
| 1116 | if match: return match.group(1, 2) |
| 1117 | return url, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1118 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1119 | def splitattr(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1120 | """splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 1121 | '/path', ['attr1=value1', 'attr2=value2', ...].""" |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1122 | words = url.split(';') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1123 | return words[0], words[1:] |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1124 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1125 | _valueprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1126 | def splitvalue(attr): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1127 | """splitvalue('attr=value') --> 'attr', 'value'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1128 | global _valueprog |
| 1129 | if _valueprog is None: |
| 1130 | import re |
| 1131 | _valueprog = re.compile('^([^=]*)=(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1132 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1133 | match = _valueprog.match(attr) |
| 1134 | if match: return match.group(1, 2) |
| 1135 | return attr, None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1136 | |
Raymond Hettinger | 803ce80 | 2005-09-10 06:49:04 +0000 | [diff] [blame] | 1137 | _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 Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1140 | def unquote(s): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1141 | """unquote('abc%20def') -> 'abc def'.""" |
Raymond Hettinger | 803ce80 | 2005-09-10 06:49:04 +0000 | [diff] [blame] | 1142 | 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 Hettinger | 4b0f20d | 2005-10-15 16:41:53 +0000 | [diff] [blame] | 1149 | except UnicodeDecodeError: |
| 1150 | res[i] = unichr(int(item[:2], 16)) + item[2:] |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1151 | return "".join(res) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1152 | |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1153 | def unquote_plus(s): |
Skip Montanaro | 79f1c17 | 2000-08-22 03:00:52 +0000 | [diff] [blame] | 1154 | """unquote('%7e/abc+def') -> '~/abc def'""" |
Brett Cannon | aaeffaf | 2004-03-23 23:50:17 +0000 | [diff] [blame] | 1155 | s = s.replace('+', ' ') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1156 | return unquote(s) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1157 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1158 | always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
Jeremy Hylton | 6102e29 | 2000-08-31 15:48:10 +0000 | [diff] [blame] | 1159 | 'abcdefghijklmnopqrstuvwxyz' |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1160 | '0123456789' '_.-') |
Raymond Hettinger | 199d2f7 | 2005-09-09 22:27:13 +0000 | [diff] [blame] | 1161 | _safemaps = {} |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1162 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1163 | def quote(s, safe = '/'): |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1164 | """quote('abc def') -> 'abc%20def' |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1165 | |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1166 | 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 Hettinger | 199d2f7 | 2005-09-09 22:27:13 +0000 | [diff] [blame] | 1184 | 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 Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1195 | return ''.join(res) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1196 | |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1197 | def quote_plus(s, safe = ''): |
| 1198 | """Quote the query fragment of a URL; replacing ' ' with '+'""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1199 | if ' ' in s: |
Raymond Hettinger | cf6b632 | 2005-09-10 18:17:54 +0000 | [diff] [blame] | 1200 | s = quote(s, safe + ' ') |
| 1201 | return s.replace(' ', '+') |
| 1202 | return quote(s, safe) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1203 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1204 | def urlencode(query,doseq=0): |
| 1205 | """Encode a sequence of two-element tuples or dictionary into a URL query string. |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1206 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1207 | If any values in the query arg are sequences and doseq is true, each |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1208 | sequence element is converted to a separate parameter. |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1209 | |
| 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 Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1213 | """ |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 1214 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1215 | 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 Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1223 | # non-empty strings will fail this |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 1224 | if len(query) and not isinstance(query[0], tuple): |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1225 | 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 Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1234 | l = [] |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1235 | if not doseq: |
| 1236 | # preserve old behavior |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1237 | for k, v in query: |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1238 | k = quote_plus(str(k)) |
| 1239 | v = quote_plus(str(v)) |
| 1240 | l.append(k + '=' + v) |
| 1241 | else: |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1242 | for k, v in query: |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1243 | k = quote_plus(str(k)) |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 1244 | if isinstance(v, str): |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1245 | v = quote_plus(v) |
| 1246 | l.append(k + '=' + v) |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 1247 | elif _is_unicode(v): |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1248 | # 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 Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1265 | return '&'.join(l) |
Guido van Rossum | 810a339 | 1998-07-22 21:33:23 +0000 | [diff] [blame] | 1266 | |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1267 | # Proxy handling |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1268 | def 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 Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1279 | name = name.lower() |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1280 | if value and name[-6:] == '_proxy': |
| 1281 | proxies[name[:-6]] = value |
| 1282 | return proxies |
| 1283 | |
Jack Jansen | 11d9b06 | 2004-07-16 11:45:00 +0000 | [diff] [blame] | 1284 | if sys.platform == 'darwin': |
| 1285 | def getproxies_internetconfig(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1286 | """Return a dictionary of scheme -> proxy server URL mappings. |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1287 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1288 | 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 Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1291 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1292 | """ |
| 1293 | try: |
| 1294 | import ic |
| 1295 | except ImportError: |
| 1296 | return {} |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1297 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1298 | try: |
| 1299 | config = ic.IC() |
| 1300 | except ic.error: |
| 1301 | return {} |
| 1302 | proxies = {} |
| 1303 | # HTTP: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 1304 | if 'UseHTTPProxy' in config and config['UseHTTPProxy']: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1305 | 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 Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1314 | |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1315 | def proxy_bypass(x): |
| 1316 | return 0 |
| 1317 | |
Jack Jansen | 11d9b06 | 2004-07-16 11:45:00 +0000 | [diff] [blame] | 1318 | def getproxies(): |
| 1319 | return getproxies_environment() or getproxies_internetconfig() |
Tim Peters | 182b5ac | 2004-07-18 06:16:08 +0000 | [diff] [blame] | 1320 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1321 | elif os.name == 'nt': |
| 1322 | def getproxies_registry(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1323 | """Return a dictionary of scheme -> proxy server URL mappings. |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1324 | |
| 1325 | Win32 uses the registry to store proxies. |
| 1326 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1327 | """ |
| 1328 | proxies = {} |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1329 | try: |
| 1330 | import _winreg |
| 1331 | except ImportError: |
| 1332 | # Std module, so should be around - but you never know! |
| 1333 | return proxies |
| 1334 | try: |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1335 | internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, |
| 1336 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1337 | 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 Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1343 | if '=' in proxyServer: |
| 1344 | # Per-protocol settings |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1345 | for p in proxyServer.split(';'): |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1346 | protocol, address = p.split('=', 1) |
Guido van Rossum | b955d6c | 2002-03-31 23:38:48 +0000 | [diff] [blame] | 1347 | # See if address has a type:// prefix |
Guido van Rossum | 64e5aa9 | 2002-04-02 14:38:16 +0000 | [diff] [blame] | 1348 | import re |
| 1349 | if not re.match('^([^/:]+)://', address): |
Guido van Rossum | b955d6c | 2002-03-31 23:38:48 +0000 | [diff] [blame] | 1350 | address = '%s://%s' % (protocol, address) |
| 1351 | proxies[protocol] = address |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1352 | 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 Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1359 | 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 Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1365 | return proxies |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1366 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1367 | 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 Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1375 | |
| 1376 | def proxy_bypass(host): |
| 1377 | try: |
| 1378 | import _winreg |
| 1379 | import re |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1380 | 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 Brandl | 1f63670 | 2006-02-18 23:10:23 +0000 | [diff] [blame] | 1396 | rawHost, port = splitport(host) |
| 1397 | host = [rawHost] |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1398 | try: |
Georg Brandl | 1f63670 | 2006-02-18 23:10:23 +0000 | [diff] [blame] | 1399 | addr = socket.gethostbyname(rawHost) |
| 1400 | if addr != rawHost: |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1401 | host.append(addr) |
| 1402 | except socket.error: |
| 1403 | pass |
Georg Brandl | 1f63670 | 2006-02-18 23:10:23 +0000 | [diff] [blame] | 1404 | try: |
| 1405 | fqdn = socket.getfqdn(rawHost) |
| 1406 | if fqdn != rawHost: |
| 1407 | host.append(fqdn) |
| 1408 | except socket.error: |
| 1409 | pass |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1410 | # 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 Peters | ab9ba27 | 2001-08-09 21:40:30 +0000 | [diff] [blame] | 1426 | test = test.replace(".", r"\.") # mask dots |
| 1427 | test = test.replace("*", r".*") # change glob sequence |
| 1428 | test = test.replace("?", r".") # change glob char |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1429 | 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 Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1435 | else: |
| 1436 | # By default use environment variables |
| 1437 | getproxies = getproxies_environment |
| 1438 | |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1439 | def proxy_bypass(host): |
| 1440 | return 0 |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1441 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1442 | # Test and time quote() and unquote() |
| 1443 | def test1(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1444 | 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örwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 1453 | print repr(s) |
| 1454 | print repr(qs) |
| 1455 | print repr(uqs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1456 | print round(t1 - t0, 3), 'sec' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1457 | |
| 1458 | |
Guido van Rossum | 9ab96d4 | 1998-09-28 14:07:00 +0000 | [diff] [blame] | 1459 | def reporthook(blocknum, blocksize, totalsize): |
| 1460 | # Report during remote transfers |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1461 | print "Block number: %d, Block size: %d, Total size: %d" % ( |
| 1462 | blocknum, blocksize, totalsize) |
Guido van Rossum | 9ab96d4 | 1998-09-28 14:07:00 +0000 | [diff] [blame] | 1463 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1464 | # Test program |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1465 | def test(args=[]): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1466 | if not args: |
| 1467 | args = [ |
| 1468 | '/etc/passwd', |
| 1469 | 'file:/etc/passwd', |
| 1470 | 'file://localhost/etc/passwd', |
Collin Winter | 071d1ae | 2007-03-12 01:55:54 +0000 | [diff] [blame] | 1471 | 'ftp://ftp.gnu.org/pub/README', |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1472 | 'http://www.python.org/index.html', |
| 1473 | ] |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 1474 | if hasattr(URLopener, "open_https"): |
| 1475 | args.append('https://synergy.as.cmu.edu/~geek/') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1476 | try: |
| 1477 | for url in args: |
| 1478 | print '-'*10, url, '-'*10 |
| 1479 | fn, h = urlretrieve(url, None, reporthook) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1480 | print fn |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1481 | 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 Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1490 | data = data.translate(table, "\r") |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1491 | print data |
| 1492 | fn, h = None, None |
| 1493 | print '-'*40 |
| 1494 | finally: |
| 1495 | urlcleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1496 | |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1497 | def main(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1498 | 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 Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1523 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1524 | # Run test program when run as a script |
| 1525 | if __name__ == '__main__': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1526 | main() |