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 | |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 25 | import httplib |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 26 | import os |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 27 | import socket |
Guido van Rossum | 3c8484e | 1996-11-20 22:02:24 +0000 | [diff] [blame] | 28 | import sys |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 29 | import time |
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", |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +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 |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 49 | else: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 50 | def url2pathname(pathname): |
Georg Brandl | c0b2473 | 2005-12-26 22:53:56 +0000 | [diff] [blame] | 51 | """OS-specific conversion from a relative URL of the 'file' scheme |
| 52 | to a file system path; not recommended for general use.""" |
Guido van Rossum | 367ac80 | 1999-03-12 14:31:10 +0000 | [diff] [blame] | 53 | return unquote(pathname) |
Georg Brandl | c0b2473 | 2005-12-26 22:53:56 +0000 | [diff] [blame] | 54 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 55 | def pathname2url(pathname): |
Georg Brandl | c0b2473 | 2005-12-26 22:53:56 +0000 | [diff] [blame] | 56 | """OS-specific conversion from a file system path to a relative URL |
| 57 | of the 'file' scheme; not recommended for general use.""" |
Guido van Rossum | 367ac80 | 1999-03-12 14:31:10 +0000 | [diff] [blame] | 58 | return quote(pathname) |
Guido van Rossum | 33add0a | 1998-12-18 15:25:22 +0000 | [diff] [blame] | 59 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 60 | # This really consists of two pieces: |
| 61 | # (1) a class which handles opening of all sorts of URLs |
| 62 | # (plus assorted utilities etc.) |
| 63 | # (2) a set of functions for parsing URLs |
| 64 | # XXX Should these be separated out into different modules? |
| 65 | |
| 66 | |
| 67 | # Shortcut for basic usage |
| 68 | _urlopener = None |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 69 | def urlopen(url, data=None, proxies=None): |
Skip Montanaro | 79f1c17 | 2000-08-22 03:00:52 +0000 | [diff] [blame] | 70 | """urlopen(url [, data]) -> open file-like object""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 71 | global _urlopener |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 72 | if proxies is not None: |
| 73 | opener = FancyURLopener(proxies=proxies) |
| 74 | elif not _urlopener: |
| 75 | opener = FancyURLopener() |
| 76 | _urlopener = opener |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 77 | else: |
Fred Drake | df6eca7 | 2002-04-04 20:41:34 +0000 | [diff] [blame] | 78 | opener = _urlopener |
| 79 | if data is None: |
| 80 | return opener.open(url) |
| 81 | else: |
| 82 | return opener.open(url, data) |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 83 | |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 84 | def urlretrieve(url, filename=None, reporthook=None, data=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 85 | global _urlopener |
| 86 | if not _urlopener: |
| 87 | _urlopener = FancyURLopener() |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 88 | return _urlopener.retrieve(url, filename, reporthook, data) |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 89 | |
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 | |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 94 | # exception raised when downloaded size does not match content-length |
| 95 | class ContentTooShortError(IOError): |
| 96 | def __init__(self, message, content): |
| 97 | IOError.__init__(self, message) |
| 98 | self.content = content |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 99 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 100 | ftpcache = {} |
| 101 | class URLopener: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 102 | """Class to open URLs. |
| 103 | This is a class rather than just a subroutine because we may need |
| 104 | more than one set of global protocol-specific options. |
| 105 | Note -- this is a base class for those who don't want the |
| 106 | automatic handling of errors type 302 (relocated) and 401 |
| 107 | (authorization needed).""" |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 108 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 109 | __tempfiles = None |
Guido van Rossum | 29e7781 | 1996-11-27 19:39:58 +0000 | [diff] [blame] | 110 | |
Guido van Rossum | ba31138 | 2000-08-24 16:18:04 +0000 | [diff] [blame] | 111 | version = "Python-urllib/%s" % __version__ |
| 112 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 113 | # Constructor |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 114 | def __init__(self, proxies=None, **x509): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 115 | if proxies is None: |
| 116 | proxies = getproxies() |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 117 | assert hasattr(proxies, 'keys'), "proxies must be a mapping" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 118 | self.proxies = proxies |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 119 | self.key_file = x509.get('key_file') |
| 120 | self.cert_file = x509.get('cert_file') |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 121 | self.addheaders = [('User-Agent', self.version)] |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 122 | self.__tempfiles = [] |
| 123 | self.__unlink = os.unlink # See cleanup() |
| 124 | self.tempcache = None |
| 125 | # Undocumented feature: if you assign {} to tempcache, |
| 126 | # it is used to cache files retrieved with |
| 127 | # self.retrieve(). This is not enabled by default |
| 128 | # since it does not work for changing documents (and I |
| 129 | # haven't got the logic to check expiration headers |
| 130 | # yet). |
| 131 | self.ftpcache = ftpcache |
| 132 | # Undocumented feature: you can use a different |
| 133 | # ftp cache by assigning to the .ftpcache member; |
| 134 | # in case you want logically independent URL openers |
| 135 | # XXX This is not threadsafe. Bah. |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 136 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 137 | def __del__(self): |
| 138 | self.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 139 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 140 | def close(self): |
| 141 | self.cleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 142 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 143 | def cleanup(self): |
| 144 | # This code sometimes runs when the rest of this module |
| 145 | # has already been deleted, so it can't use any globals |
| 146 | # or import anything. |
| 147 | if self.__tempfiles: |
| 148 | for file in self.__tempfiles: |
| 149 | try: |
| 150 | self.__unlink(file) |
Martin v. Löwis | 58682b7 | 2001-08-11 15:02:57 +0000 | [diff] [blame] | 151 | except OSError: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 152 | pass |
| 153 | del self.__tempfiles[:] |
| 154 | if self.tempcache: |
| 155 | self.tempcache.clear() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 156 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 157 | def addheader(self, *args): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 158 | """Add a header to be used by the HTTP interface only |
| 159 | e.g. u.addheader('Accept', 'sound/basic')""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 160 | self.addheaders.append(args) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 161 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 162 | # External interface |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 163 | def open(self, fullurl, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 164 | """Use URLopener().open(file) instead of open(file, 'r').""" |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 165 | fullurl = unwrap(toBytes(fullurl)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 166 | if self.tempcache and fullurl in self.tempcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 167 | filename, headers = self.tempcache[fullurl] |
| 168 | fp = open(filename, 'rb') |
| 169 | return addinfourl(fp, headers, fullurl) |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 170 | urltype, url = splittype(fullurl) |
| 171 | if not urltype: |
| 172 | urltype = 'file' |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 173 | if urltype in self.proxies: |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 174 | proxy = self.proxies[urltype] |
| 175 | urltype, proxyhost = splittype(proxy) |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 176 | host, selector = splithost(proxyhost) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 177 | url = (host, fullurl) # Signal special case to open_*() |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 178 | else: |
| 179 | proxy = None |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 180 | name = 'open_' + urltype |
| 181 | self.type = urltype |
Brett Cannon | aaeffaf | 2004-03-23 23:50:17 +0000 | [diff] [blame] | 182 | name = name.replace('-', '_') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 183 | if not hasattr(self, name): |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 184 | if proxy: |
| 185 | return self.open_unknown_proxy(proxy, fullurl, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 186 | else: |
| 187 | return self.open_unknown(fullurl, data) |
| 188 | try: |
| 189 | if data is None: |
| 190 | return getattr(self, name)(url) |
| 191 | else: |
| 192 | return getattr(self, name)(url, data) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 193 | except socket.error as msg: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 194 | raise IOError, ('socket error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 195 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 196 | def open_unknown(self, fullurl, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 197 | """Overridable interface to open unknown URL type.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 198 | type, url = splittype(fullurl) |
| 199 | raise IOError, ('url error', 'unknown url type', type) |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 200 | |
Jeremy Hylton | d52755f | 2000-10-02 23:04:02 +0000 | [diff] [blame] | 201 | def open_unknown_proxy(self, proxy, fullurl, data=None): |
| 202 | """Overridable interface to open unknown URL type.""" |
| 203 | type, url = splittype(fullurl) |
| 204 | raise IOError, ('url error', 'invalid proxy for %s' % type, proxy) |
| 205 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 206 | # External interface |
Sjoerd Mullender | d7b86f0 | 2000-08-25 11:23:36 +0000 | [diff] [blame] | 207 | def retrieve(self, url, filename=None, reporthook=None, data=None): |
Brett Cannon | 7d618c7 | 2003-04-24 02:43:20 +0000 | [diff] [blame] | 208 | """retrieve(url) returns (filename, headers) for a local object |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 209 | or (tempfilename, headers) for a remote object.""" |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 210 | url = unwrap(toBytes(url)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 211 | if self.tempcache and url in self.tempcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 212 | return self.tempcache[url] |
| 213 | type, url1 = splittype(url) |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 214 | if filename is None and (not type or type == 'file'): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 215 | try: |
| 216 | fp = self.open_local_file(url1) |
| 217 | hdrs = fp.info() |
| 218 | del fp |
| 219 | return url2pathname(splithost(url1)[1]), hdrs |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 220 | except IOError as msg: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 221 | pass |
Fred Drake | 316a793 | 2000-08-24 01:01:26 +0000 | [diff] [blame] | 222 | fp = self.open(url, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 223 | headers = fp.info() |
Guido van Rossum | 3b0a329 | 2002-08-09 16:38:32 +0000 | [diff] [blame] | 224 | if filename: |
| 225 | tfp = open(filename, 'wb') |
| 226 | else: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 227 | import tempfile |
| 228 | garbage, path = splittype(url) |
| 229 | garbage, path = splithost(path or "") |
| 230 | path, garbage = splitquery(path or "") |
| 231 | path, garbage = splitattr(path or "") |
| 232 | suffix = os.path.splitext(path)[1] |
Guido van Rossum | 3b0a329 | 2002-08-09 16:38:32 +0000 | [diff] [blame] | 233 | (fd, filename) = tempfile.mkstemp(suffix) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 234 | self.__tempfiles.append(filename) |
Jeremy Hylton | 3bd6fde | 2002-10-11 14:36:24 +0000 | [diff] [blame] | 235 | tfp = os.fdopen(fd, 'wb') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 236 | result = filename, headers |
| 237 | if self.tempcache is not None: |
| 238 | self.tempcache[url] = result |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 239 | bs = 1024*8 |
| 240 | size = -1 |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 241 | read = 0 |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 242 | blocknum = 0 |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 243 | if reporthook: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 244 | if "content-length" in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 245 | size = int(headers["Content-Length"]) |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 246 | reporthook(blocknum, bs, size) |
| 247 | while 1: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 248 | block = fp.read(bs) |
Guido van Rossum | a098294 | 2007-07-10 08:30:03 +0000 | [diff] [blame] | 249 | if not block: |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 250 | break |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 251 | read += len(block) |
Georg Brandl | 5a650a2 | 2005-08-26 08:51:34 +0000 | [diff] [blame] | 252 | tfp.write(block) |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 253 | blocknum += 1 |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 254 | if reporthook: |
| 255 | reporthook(blocknum, bs, size) |
| 256 | fp.close() |
| 257 | tfp.close() |
| 258 | del fp |
| 259 | del tfp |
Georg Brandl | b925602 | 2005-08-24 18:46:39 +0000 | [diff] [blame] | 260 | |
| 261 | # raise exception if actual size does not match content-length header |
| 262 | if size >= 0 and read < size: |
| 263 | raise ContentTooShortError("retrieval incomplete: got only %i out " |
| 264 | "of %i bytes" % (read, size), result) |
| 265 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 266 | return result |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 267 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 268 | # 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] | 269 | |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 270 | def _open_generic_http(self, connection_factory, url, data): |
| 271 | """Make an HTTP connection using connection_class. |
| 272 | |
| 273 | This is an internal method that should be called from |
| 274 | open_http() or open_https(). |
| 275 | |
| 276 | Arguments: |
| 277 | - connection_factory should take a host name and return an |
| 278 | HTTPConnection instance. |
| 279 | - url is the url to retrieval or a host, relative-path pair. |
| 280 | - data is payload for a POST request or None. |
| 281 | """ |
| 282 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 283 | user_passwd = None |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 284 | proxy_passwd= None |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 285 | if isinstance(url, str): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 286 | host, selector = splithost(url) |
| 287 | if host: |
| 288 | user_passwd, host = splituser(host) |
| 289 | host = unquote(host) |
| 290 | realhost = host |
| 291 | else: |
| 292 | host, selector = url |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 293 | # check whether the proxy contains authorization information |
| 294 | proxy_passwd, host = splituser(host) |
| 295 | # now we proceed with the url we want to obtain |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 296 | urltype, rest = splittype(selector) |
| 297 | url = rest |
| 298 | user_passwd = None |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 299 | if urltype.lower() != 'http': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 300 | realhost = None |
| 301 | else: |
| 302 | realhost, rest = splithost(rest) |
| 303 | if realhost: |
| 304 | user_passwd, realhost = splituser(realhost) |
| 305 | if user_passwd: |
| 306 | selector = "%s://%s%s" % (urltype, realhost, rest) |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 307 | if proxy_bypass(realhost): |
| 308 | host = realhost |
| 309 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 310 | #print "proxy via http:", host, selector |
| 311 | if not host: raise IOError, ('http error', 'no host given') |
Tim Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 312 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 313 | if proxy_passwd: |
| 314 | import base64 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 315 | proxy_auth = base64.b64encode(proxy_passwd).strip() |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 316 | else: |
| 317 | proxy_auth = None |
| 318 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 319 | if user_passwd: |
| 320 | import base64 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 321 | auth = base64.b64encode(user_passwd).strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 322 | else: |
| 323 | auth = None |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 324 | http_conn = connection_factory(host) |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 325 | # XXX We should fix urllib so that it works with HTTP/1.1. |
| 326 | http_conn._http_vsn = 10 |
| 327 | http_conn._http_vsn_str = "HTTP/1.0" |
| 328 | |
| 329 | headers = {} |
| 330 | if proxy_auth: |
| 331 | headers["Proxy-Authorization"] = "Basic %s" % proxy_auth |
| 332 | if auth: |
| 333 | headers["Authorization"] = "Basic %s" % auth |
| 334 | if realhost: |
| 335 | headers["Host"] = realhost |
| 336 | for header, value in self.addheaders: |
| 337 | headers[header] = value |
| 338 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 339 | if data is not None: |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 340 | headers["Content-Type"] = "application/x-www-form-urlencoded" |
| 341 | http_conn.request("POST", selector, data, headers) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 342 | else: |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 343 | http_conn.request("GET", selector, headers=headers) |
| 344 | |
| 345 | try: |
| 346 | response = http_conn.getresponse() |
| 347 | except httplib.BadStatusLine: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 348 | # something went wrong with the HTTP status line |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 349 | raise IOError('http protocol error', 0, |
| 350 | 'got a bad status line', None) |
| 351 | |
| 352 | if response.status == 200: |
| 353 | return addinfourl(response.fp, response.msg, "http:" + url) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 354 | else: |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 355 | return self.http_error( |
| 356 | url, response.fp, |
| 357 | response.status, response.reason, response.msg, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 358 | |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 359 | def open_http(self, url, data=None): |
| 360 | """Use HTTP protocol.""" |
| 361 | return self._open_generic_http(httplib.HTTPConnection, url, data) |
| 362 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 363 | def http_error(self, url, fp, errcode, errmsg, headers, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 364 | """Handle http errors. |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 365 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 366 | Derived class can override this, or provide specific handlers |
| 367 | named http_error_DDD where DDD is the 3-digit error code.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 368 | # First check if there's a specific handler for this error |
| 369 | name = 'http_error_%d' % errcode |
| 370 | if hasattr(self, name): |
| 371 | method = getattr(self, name) |
| 372 | if data is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 373 | result = method(url, fp, errcode, errmsg, headers) |
Jeremy Hylton | b30f52a | 1999-02-25 16:14:58 +0000 | [diff] [blame] | 374 | else: |
| 375 | result = method(url, fp, errcode, errmsg, headers, data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 376 | if result: return result |
Jeremy Hylton | b30f52a | 1999-02-25 16:14:58 +0000 | [diff] [blame] | 377 | return self.http_error_default(url, fp, errcode, errmsg, headers) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 378 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 379 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 380 | """Default error handler: close the connection and raise IOError.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 381 | void = fp.read() |
| 382 | fp.close() |
| 383 | raise IOError, ('http error', errcode, errmsg, headers) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 384 | |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 385 | if hasattr(socket, "ssl"): |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 386 | def _https_connection(self, host): |
| 387 | return httplib.HTTPSConnection(host, |
| 388 | key_file=self.key_file, |
| 389 | cert_file=self.cert_file) |
| 390 | |
Andrew M. Kuchling | 141e989 | 2000-04-23 02:53:11 +0000 | [diff] [blame] | 391 | def open_https(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 392 | """Use HTTPS protocol.""" |
Jeremy Hylton | 5f22af1 | 2007-08-16 17:55:18 +0000 | [diff] [blame] | 393 | return self._open_generic_http(self._https_connection, url, data) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 394 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 395 | def open_file(self, url): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 396 | """Use local file or FTP depending on form of URL.""" |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 397 | if not isinstance(url, str): |
| 398 | raise IOError, ('file error', 'proxy support for file protocol currently not implemented') |
Jack Jansen | 4ef1103 | 2002-09-12 20:14:04 +0000 | [diff] [blame] | 399 | 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] | 400 | return self.open_ftp(url) |
| 401 | else: |
| 402 | return self.open_local_file(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 403 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 404 | def open_local_file(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 405 | """Use local file.""" |
Neal Norwitz | fce59bf | 2007-08-25 19:00:31 +0000 | [diff] [blame] | 406 | import mimetypes, mimetools #, email.utils |
Guido van Rossum | 68937b4 | 2007-05-18 00:51:22 +0000 | [diff] [blame] | 407 | from io import StringIO |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 408 | host, file = splithost(url) |
| 409 | localname = url2pathname(file) |
Guido van Rossum | a2da305 | 2002-04-15 00:25:01 +0000 | [diff] [blame] | 410 | try: |
| 411 | stats = os.stat(localname) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 412 | except OSError as e: |
Guido van Rossum | a2da305 | 2002-04-15 00:25:01 +0000 | [diff] [blame] | 413 | raise IOError(e.errno, e.strerror, e.filename) |
Walter Dörwald | 92b48b7 | 2002-03-22 17:30:38 +0000 | [diff] [blame] | 414 | size = stats.st_size |
Neal Norwitz | fce59bf | 2007-08-25 19:00:31 +0000 | [diff] [blame] | 415 | # XXX(nnorwitz): inline formatdate until it is restored. |
| 416 | #modified = email.utils.formatdate(stats.st_mtime, usegmt=True) |
| 417 | now, zone = time.gmtime(stats.st_mtime), 'GMT' |
| 418 | modified = '%s, %02d %s %04d %02d:%02d:%02d %s' % ( |
| 419 | ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]], |
| 420 | now[2], |
| 421 | ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', |
| 422 | 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1], |
| 423 | now[0], now[3], now[4], now[5], |
| 424 | zone) |
| 425 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 426 | mtype = mimetypes.guess_type(url)[0] |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 427 | headers = mimetools.Message(StringIO( |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 428 | 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % |
| 429 | (mtype or 'text/plain', size, modified))) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 430 | if not host: |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 431 | urlfile = file |
| 432 | if file[:1] == '/': |
| 433 | urlfile = 'file://' + file |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 434 | return addinfourl(open(localname, 'rb'), |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 435 | headers, urlfile) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 436 | host, port = splitport(host) |
| 437 | if not port \ |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 438 | and socket.gethostbyname(host) in (localhost(), thishost()): |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 439 | urlfile = file |
| 440 | if file[:1] == '/': |
| 441 | urlfile = 'file://' + file |
Guido van Rossum | f0713d3 | 2001-08-09 17:43:35 +0000 | [diff] [blame] | 442 | return addinfourl(open(localname, 'rb'), |
Guido van Rossum | 336a201 | 1999-06-24 15:27:36 +0000 | [diff] [blame] | 443 | headers, urlfile) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 444 | raise IOError, ('local file error', 'not on local host') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 445 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 446 | def open_ftp(self, url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 447 | """Use FTP protocol.""" |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 448 | if not isinstance(url, str): |
| 449 | raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented') |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 450 | import mimetypes, mimetools |
Guido van Rossum | 68937b4 | 2007-05-18 00:51:22 +0000 | [diff] [blame] | 451 | from io import StringIO |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 452 | host, path = splithost(url) |
| 453 | if not host: raise IOError, ('ftp error', 'no host given') |
| 454 | host, port = splitport(host) |
| 455 | user, host = splituser(host) |
| 456 | if user: user, passwd = splitpasswd(user) |
| 457 | else: passwd = None |
| 458 | host = unquote(host) |
| 459 | user = unquote(user or '') |
| 460 | passwd = unquote(passwd or '') |
| 461 | host = socket.gethostbyname(host) |
| 462 | if not port: |
| 463 | import ftplib |
| 464 | port = ftplib.FTP_PORT |
| 465 | else: |
| 466 | port = int(port) |
| 467 | path, attrs = splitattr(path) |
| 468 | path = unquote(path) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 469 | dirs = path.split('/') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 470 | dirs, file = dirs[:-1], dirs[-1] |
| 471 | if dirs and not dirs[0]: dirs = dirs[1:] |
Guido van Rossum | 5e006a3 | 1999-08-18 17:40:33 +0000 | [diff] [blame] | 472 | if dirs and not dirs[0]: dirs[0] = '/' |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 473 | key = user, host, port, '/'.join(dirs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 474 | # XXX thread unsafe! |
| 475 | if len(self.ftpcache) > MAXFTPCACHE: |
| 476 | # Prune the cache, rather arbitrarily |
| 477 | for k in self.ftpcache.keys(): |
| 478 | if k != key: |
| 479 | v = self.ftpcache[k] |
| 480 | del self.ftpcache[k] |
| 481 | v.close() |
| 482 | try: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 483 | if not key in self.ftpcache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 484 | self.ftpcache[key] = \ |
| 485 | ftpwrapper(user, passwd, host, port, dirs) |
| 486 | if not file: type = 'D' |
| 487 | else: type = 'I' |
| 488 | for attr in attrs: |
| 489 | attr, value = splitvalue(attr) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 490 | if attr.lower() == 'type' and \ |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 491 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 492 | type = value.upper() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 493 | (fp, retrlen) = self.ftpcache[key].retrfile(file, type) |
Guido van Rossum | 88e0b5b | 2001-08-23 13:38:15 +0000 | [diff] [blame] | 494 | mtype = mimetypes.guess_type("ftp:" + url)[0] |
| 495 | headers = "" |
| 496 | if mtype: |
| 497 | headers += "Content-Type: %s\n" % mtype |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 498 | if retrlen is not None and retrlen >= 0: |
Guido van Rossum | 88e0b5b | 2001-08-23 13:38:15 +0000 | [diff] [blame] | 499 | headers += "Content-Length: %d\n" % retrlen |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 500 | headers = mimetools.Message(StringIO(headers)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 501 | return addinfourl(fp, headers, "ftp:" + url) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 502 | except ftperrors() as msg: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 503 | raise IOError, ('ftp error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 504 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 505 | def open_data(self, url, data=None): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 506 | """Use "data" URL.""" |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 507 | if not isinstance(url, str): |
| 508 | raise IOError, ('data error', 'proxy support for data protocol currently not implemented') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 509 | # ignore POSTed data |
| 510 | # |
| 511 | # syntax of data URLs: |
| 512 | # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data |
| 513 | # mediatype := [ type "/" subtype ] *( ";" parameter ) |
| 514 | # data := *urlchar |
| 515 | # parameter := attribute "=" value |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 516 | import mimetools |
Guido van Rossum | 68937b4 | 2007-05-18 00:51:22 +0000 | [diff] [blame] | 517 | from io import StringIO |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 518 | try: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 519 | [type, data] = url.split(',', 1) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 520 | except ValueError: |
| 521 | raise IOError, ('data error', 'bad data URL') |
| 522 | if not type: |
| 523 | type = 'text/plain;charset=US-ASCII' |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 524 | semi = type.rfind(';') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 525 | if semi >= 0 and '=' not in type[semi:]: |
| 526 | encoding = type[semi+1:] |
| 527 | type = type[:semi] |
| 528 | else: |
| 529 | encoding = '' |
| 530 | msg = [] |
| 531 | msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', |
| 532 | time.gmtime(time.time()))) |
| 533 | msg.append('Content-type: %s' % type) |
| 534 | if encoding == 'base64': |
| 535 | import base64 |
| 536 | data = base64.decodestring(data) |
| 537 | else: |
| 538 | data = unquote(data) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 539 | msg.append('Content-Length: %d' % len(data)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 540 | msg.append('') |
| 541 | msg.append(data) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 542 | msg = '\n'.join(msg) |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 543 | f = StringIO(msg) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 544 | headers = mimetools.Message(f, 0) |
Georg Brandl | 1f66357 | 2005-11-26 16:50:44 +0000 | [diff] [blame] | 545 | #f.fileno = None # needed for addinfourl |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 546 | return addinfourl(f, headers, url) |
Guido van Rossum | 6d4d1c2 | 1998-03-12 14:32:55 +0000 | [diff] [blame] | 547 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 548 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 549 | class FancyURLopener(URLopener): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 550 | """Derived class with handlers for errors we can handle (perhaps).""" |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 551 | |
Neal Norwitz | 60e04cd | 2002-06-11 13:38:51 +0000 | [diff] [blame] | 552 | def __init__(self, *args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 553 | URLopener.__init__(self, *args, **kwargs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 554 | self.auth_cache = {} |
Skip Montanaro | c3e11d6 | 2001-02-15 16:56:36 +0000 | [diff] [blame] | 555 | self.tries = 0 |
| 556 | self.maxtries = 10 |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 557 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 558 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 559 | """Default error handling -- don't raise an exception.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 560 | return addinfourl(fp, headers, "http:" + url) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 561 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 562 | 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] | 563 | """Error 302 -- relocated (temporarily).""" |
Skip Montanaro | c3e11d6 | 2001-02-15 16:56:36 +0000 | [diff] [blame] | 564 | self.tries += 1 |
| 565 | if self.maxtries and self.tries >= self.maxtries: |
| 566 | if hasattr(self, "http_error_500"): |
| 567 | meth = self.http_error_500 |
| 568 | else: |
| 569 | meth = self.http_error_default |
| 570 | self.tries = 0 |
| 571 | return meth(url, fp, 500, |
| 572 | "Internal Server Error: Redirect Recursion", headers) |
| 573 | result = self.redirect_internal(url, fp, errcode, errmsg, headers, |
| 574 | data) |
| 575 | self.tries = 0 |
| 576 | return result |
| 577 | |
| 578 | def redirect_internal(self, url, fp, errcode, errmsg, headers, data): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 579 | if 'location' in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 580 | newurl = headers['location'] |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 581 | elif 'uri' in headers: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 582 | newurl = headers['uri'] |
| 583 | else: |
| 584 | return |
| 585 | void = fp.read() |
| 586 | fp.close() |
Guido van Rossum | 3527f59 | 1999-03-29 20:23:41 +0000 | [diff] [blame] | 587 | # In case the server sent a relative URL, join with original: |
Moshe Zadka | 5d87d47 | 2001-04-09 14:54:21 +0000 | [diff] [blame] | 588 | newurl = basejoin(self.type + ":" + url, newurl) |
Guido van Rossum | fa19f7c | 2003-05-16 01:46:51 +0000 | [diff] [blame] | 589 | return self.open(newurl) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 590 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 591 | 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] | 592 | """Error 301 -- also relocated (permanently).""" |
| 593 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 594 | |
Raymond Hettinger | 024aaa1 | 2003-04-24 15:32:12 +0000 | [diff] [blame] | 595 | def http_error_303(self, url, fp, errcode, errmsg, headers, data=None): |
| 596 | """Error 303 -- also relocated (essentially identical to 302).""" |
| 597 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
| 598 | |
Guido van Rossum | fa19f7c | 2003-05-16 01:46:51 +0000 | [diff] [blame] | 599 | def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): |
| 600 | """Error 307 -- relocated, but turn POST into error.""" |
| 601 | if data is None: |
| 602 | return self.http_error_302(url, fp, errcode, errmsg, headers, data) |
| 603 | else: |
| 604 | return self.http_error_default(url, fp, errcode, errmsg, headers) |
| 605 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 606 | 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] | 607 | """Error 401 -- authentication required. |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 608 | This function supports Basic authentication only.""" |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 609 | if not 'www-authenticate' in headers: |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 610 | URLopener.http_error_default(self, url, fp, |
Fred Drake | c680ae8 | 2001-10-13 18:37:07 +0000 | [diff] [blame] | 611 | errcode, errmsg, headers) |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 612 | stuff = headers['www-authenticate'] |
| 613 | import re |
| 614 | match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 615 | if not match: |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 616 | URLopener.http_error_default(self, url, fp, |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 617 | errcode, errmsg, headers) |
| 618 | scheme, realm = match.groups() |
| 619 | if scheme.lower() != 'basic': |
Tim Peters | 85ba673 | 2001-02-28 08:26:44 +0000 | [diff] [blame] | 620 | URLopener.http_error_default(self, url, fp, |
Moshe Zadka | e99bd17 | 2001-02-27 06:27:04 +0000 | [diff] [blame] | 621 | errcode, errmsg, headers) |
| 622 | name = 'retry_' + self.type + '_basic_auth' |
| 623 | if data is None: |
| 624 | return getattr(self,name)(url, realm) |
| 625 | else: |
| 626 | return getattr(self,name)(url, realm, data) |
Tim Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 627 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 628 | def http_error_407(self, url, fp, errcode, errmsg, headers, data=None): |
| 629 | """Error 407 -- proxy authentication required. |
| 630 | This function supports Basic authentication only.""" |
| 631 | if not 'proxy-authenticate' in headers: |
| 632 | URLopener.http_error_default(self, url, fp, |
| 633 | errcode, errmsg, headers) |
| 634 | stuff = headers['proxy-authenticate'] |
| 635 | import re |
| 636 | match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 637 | if not match: |
| 638 | URLopener.http_error_default(self, url, fp, |
| 639 | errcode, errmsg, headers) |
| 640 | scheme, realm = match.groups() |
| 641 | if scheme.lower() != 'basic': |
| 642 | URLopener.http_error_default(self, url, fp, |
| 643 | errcode, errmsg, headers) |
| 644 | name = 'retry_proxy_' + self.type + '_basic_auth' |
| 645 | if data is None: |
| 646 | return getattr(self,name)(url, realm) |
| 647 | else: |
| 648 | return getattr(self,name)(url, realm, data) |
Tim Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 649 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 650 | def retry_proxy_http_basic_auth(self, url, realm, data=None): |
| 651 | host, selector = splithost(url) |
| 652 | newurl = 'http://' + host + selector |
| 653 | proxy = self.proxies['http'] |
| 654 | urltype, proxyhost = splittype(proxy) |
| 655 | proxyhost, proxyselector = splithost(proxyhost) |
| 656 | i = proxyhost.find('@') + 1 |
| 657 | proxyhost = proxyhost[i:] |
| 658 | user, passwd = self.get_user_passwd(proxyhost, realm, i) |
| 659 | if not (user or passwd): return None |
| 660 | proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost |
| 661 | self.proxies['http'] = 'http://' + proxyhost + proxyselector |
| 662 | if data is None: |
| 663 | return self.open(newurl) |
| 664 | else: |
| 665 | return self.open(newurl, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 666 | |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 667 | def retry_proxy_https_basic_auth(self, url, realm, data=None): |
| 668 | host, selector = splithost(url) |
| 669 | newurl = 'https://' + host + selector |
| 670 | proxy = self.proxies['https'] |
| 671 | urltype, proxyhost = splittype(proxy) |
| 672 | proxyhost, proxyselector = splithost(proxyhost) |
| 673 | i = proxyhost.find('@') + 1 |
| 674 | proxyhost = proxyhost[i:] |
| 675 | user, passwd = self.get_user_passwd(proxyhost, realm, i) |
| 676 | if not (user or passwd): return None |
| 677 | proxyhost = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + proxyhost |
| 678 | self.proxies['https'] = 'https://' + proxyhost + proxyselector |
| 679 | if data is None: |
| 680 | return self.open(newurl) |
| 681 | else: |
| 682 | return self.open(newurl, data) |
Tim Peters | 92037a1 | 2006-01-24 22:44:08 +0000 | [diff] [blame] | 683 | |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 684 | def retry_http_basic_auth(self, url, realm, data=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 685 | host, selector = splithost(url) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 686 | i = host.find('@') + 1 |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 687 | host = host[i:] |
| 688 | user, passwd = self.get_user_passwd(host, realm, i) |
| 689 | if not (user or passwd): return None |
Guido van Rossum | afc4f04 | 2001-01-15 18:31:13 +0000 | [diff] [blame] | 690 | host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 691 | newurl = 'http://' + host + selector |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 692 | if data is None: |
| 693 | return self.open(newurl) |
| 694 | else: |
| 695 | return self.open(newurl, data) |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 696 | |
Guido van Rossum | 3c8baed | 2000-02-01 23:36:55 +0000 | [diff] [blame] | 697 | def retry_https_basic_auth(self, url, realm, data=None): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 698 | host, selector = splithost(url) |
| 699 | i = host.find('@') + 1 |
| 700 | host = host[i:] |
| 701 | user, passwd = self.get_user_passwd(host, realm, i) |
| 702 | if not (user or passwd): return None |
Guido van Rossum | afc4f04 | 2001-01-15 18:31:13 +0000 | [diff] [blame] | 703 | host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host |
Martin v. Löwis | 3e86595 | 2006-01-24 15:51:21 +0000 | [diff] [blame] | 704 | newurl = 'https://' + host + selector |
| 705 | if data is None: |
| 706 | return self.open(newurl) |
| 707 | else: |
| 708 | return self.open(newurl, data) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 709 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 710 | def get_user_passwd(self, host, realm, clear_cache = 0): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 711 | key = realm + '@' + host.lower() |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 712 | if key in self.auth_cache: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 713 | if clear_cache: |
| 714 | del self.auth_cache[key] |
| 715 | else: |
| 716 | return self.auth_cache[key] |
| 717 | user, passwd = self.prompt_user_passwd(host, realm) |
| 718 | if user or passwd: self.auth_cache[key] = (user, passwd) |
| 719 | return user, passwd |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 720 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 721 | def prompt_user_passwd(self, host, realm): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 722 | """Override this in a GUI environment!""" |
Guido van Rossum | 7cba850 | 2007-03-19 22:23:59 +0000 | [diff] [blame] | 723 | import getpass |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 724 | try: |
Guido van Rossum | 7cba850 | 2007-03-19 22:23:59 +0000 | [diff] [blame] | 725 | user = input("Enter username for %s at %s: " % (realm, host)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 726 | passwd = getpass.getpass("Enter password for %s in %s at %s: " % |
| 727 | (user, realm, host)) |
| 728 | return user, passwd |
| 729 | except KeyboardInterrupt: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 730 | print() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 731 | return None, None |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 732 | |
| 733 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 734 | # Utility functions |
| 735 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 736 | _localhost = None |
| 737 | def localhost(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 738 | """Return the IP address of the magic hostname 'localhost'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 739 | global _localhost |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 740 | if _localhost is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 741 | _localhost = socket.gethostbyname('localhost') |
| 742 | return _localhost |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 743 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 744 | _thishost = None |
| 745 | def thishost(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 746 | """Return the IP address of the current host.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 747 | global _thishost |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 748 | if _thishost is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 749 | _thishost = socket.gethostbyname(socket.gethostname()) |
| 750 | return _thishost |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 751 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 752 | _ftperrors = None |
| 753 | def ftperrors(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 754 | """Return the set of errors raised by the FTP class.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 755 | global _ftperrors |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 756 | if _ftperrors is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 757 | import ftplib |
| 758 | _ftperrors = ftplib.all_errors |
| 759 | return _ftperrors |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 760 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 761 | _noheaders = None |
| 762 | def noheaders(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 763 | """Return an empty mimetools.Message object.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 764 | global _noheaders |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 765 | if _noheaders is None: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 766 | import mimetools |
Guido van Rossum | 68937b4 | 2007-05-18 00:51:22 +0000 | [diff] [blame] | 767 | from io import StringIO |
Raymond Hettinger | a617271 | 2004-12-31 19:15:26 +0000 | [diff] [blame] | 768 | _noheaders = mimetools.Message(StringIO(), 0) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 769 | _noheaders.fp.close() # Recycle file descriptor |
| 770 | return _noheaders |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 771 | |
| 772 | |
| 773 | # Utility classes |
| 774 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 775 | class ftpwrapper: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 776 | """Class used by open_ftp() for cache of open FTP connections.""" |
| 777 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 778 | def __init__(self, user, passwd, host, port, dirs, timeout=None): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 779 | self.user = user |
| 780 | self.passwd = passwd |
| 781 | self.host = host |
| 782 | self.port = port |
| 783 | self.dirs = dirs |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 784 | self.timeout = timeout |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 785 | self.init() |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 786 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 787 | def init(self): |
| 788 | import ftplib |
| 789 | self.busy = 0 |
| 790 | self.ftp = ftplib.FTP() |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 791 | self.ftp.connect(self.host, self.port, self.timeout) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 792 | self.ftp.login(self.user, self.passwd) |
| 793 | for dir in self.dirs: |
| 794 | self.ftp.cwd(dir) |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 795 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 796 | def retrfile(self, file, type): |
| 797 | import ftplib |
| 798 | self.endtransfer() |
| 799 | if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 |
| 800 | else: cmd = 'TYPE ' + type; isdir = 0 |
| 801 | try: |
| 802 | self.ftp.voidcmd(cmd) |
| 803 | except ftplib.all_errors: |
| 804 | self.init() |
| 805 | self.ftp.voidcmd(cmd) |
| 806 | conn = None |
| 807 | if file and not isdir: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 808 | # Try to retrieve as a file |
| 809 | try: |
| 810 | cmd = 'RETR ' + file |
| 811 | conn = self.ftp.ntransfercmd(cmd) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 812 | except ftplib.error_perm as reason: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 813 | if str(reason)[:3] != '550': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 814 | raise IOError, ('ftp error', reason), sys.exc_info()[2] |
| 815 | if not conn: |
| 816 | # Set transfer mode to ASCII! |
| 817 | self.ftp.voidcmd('TYPE A') |
| 818 | # Try a directory listing |
| 819 | if file: cmd = 'LIST ' + file |
| 820 | else: cmd = 'LIST' |
| 821 | conn = self.ftp.ntransfercmd(cmd) |
| 822 | self.busy = 1 |
| 823 | # Pass back both a suitably decorated object and a retrieval length |
| 824 | return (addclosehook(conn[0].makefile('rb'), |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 825 | self.endtransfer), conn[1]) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 826 | def endtransfer(self): |
| 827 | if not self.busy: |
| 828 | return |
| 829 | self.busy = 0 |
| 830 | try: |
| 831 | self.ftp.voidresp() |
| 832 | except ftperrors(): |
| 833 | pass |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 834 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 835 | def close(self): |
| 836 | self.endtransfer() |
| 837 | try: |
| 838 | self.ftp.close() |
| 839 | except ftperrors(): |
| 840 | pass |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 841 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 842 | class addbase: |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 843 | """Base class for addinfo and addclosehook.""" |
| 844 | |
Jeremy Hylton | 39b198d | 2007-08-04 19:22:00 +0000 | [diff] [blame] | 845 | # XXX Add a method to expose the timeout on the underlying socket? |
| 846 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 847 | def __init__(self, fp): |
| 848 | self.fp = fp |
| 849 | self.read = self.fp.read |
| 850 | self.readline = self.fp.readline |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 851 | if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines |
Georg Brandl | 1f66357 | 2005-11-26 16:50:44 +0000 | [diff] [blame] | 852 | if hasattr(self.fp, "fileno"): |
| 853 | self.fileno = self.fp.fileno |
| 854 | else: |
| 855 | self.fileno = lambda: None |
Raymond Hettinger | 42182eb | 2003-03-09 05:33:33 +0000 | [diff] [blame] | 856 | if hasattr(self.fp, "__iter__"): |
| 857 | self.__iter__ = self.fp.__iter__ |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 858 | if hasattr(self.fp, "__next__"): |
| 859 | self.__next__ = self.fp.__next__ |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 860 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 861 | def __repr__(self): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 862 | return '<%s at %r whose fp = %r>' % (self.__class__.__name__, |
| 863 | id(self), self.fp) |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 864 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 865 | def close(self): |
| 866 | self.read = None |
| 867 | self.readline = None |
| 868 | self.readlines = None |
| 869 | self.fileno = None |
| 870 | if self.fp: self.fp.close() |
| 871 | self.fp = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 872 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 873 | class addclosehook(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 874 | """Class to add a close hook to an open file.""" |
| 875 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 876 | def __init__(self, fp, closehook, *hookargs): |
| 877 | addbase.__init__(self, fp) |
| 878 | self.closehook = closehook |
| 879 | self.hookargs = hookargs |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 880 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 881 | def close(self): |
Guido van Rossum | c580dae | 2000-05-24 13:21:46 +0000 | [diff] [blame] | 882 | addbase.close(self) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 883 | if self.closehook: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 884 | self.closehook(*self.hookargs) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 885 | self.closehook = None |
| 886 | self.hookargs = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 887 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 888 | class addinfo(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 889 | """class to add an info() method to an open file.""" |
| 890 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 891 | def __init__(self, fp, headers): |
| 892 | addbase.__init__(self, fp) |
| 893 | self.headers = headers |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 894 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 895 | def info(self): |
| 896 | return self.headers |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 897 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 898 | class addinfourl(addbase): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 899 | """class to add info() and geturl() methods to an open file.""" |
| 900 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 901 | def __init__(self, fp, headers, url): |
| 902 | addbase.__init__(self, fp) |
| 903 | self.headers = headers |
| 904 | self.url = url |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 905 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 906 | def info(self): |
| 907 | return self.headers |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 908 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 909 | def geturl(self): |
| 910 | return self.url |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 911 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 912 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 913 | # Utilities to parse URLs (most of these return None for missing parts): |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 914 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 915 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 916 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 917 | # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' |
| 918 | # splitpasswd('user:passwd') -> 'user', 'passwd' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 919 | # splitport('host:port') --> 'host', 'port' |
| 920 | # splitquery('/path?query') --> '/path', 'query' |
| 921 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 922 | # splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 923 | # '/path', ['attr1=value1', 'attr2=value2', ...] |
| 924 | # splitvalue('attr=value') --> 'attr', 'value' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 925 | # unquote('abc%20def') -> 'abc def' |
| 926 | # quote('abc def') -> 'abc%20def') |
| 927 | |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 928 | try: |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 929 | str |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 930 | except NameError: |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 931 | def _is_unicode(x): |
| 932 | return 0 |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 933 | else: |
| 934 | def _is_unicode(x): |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 935 | return isinstance(x, str) |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 936 | |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 937 | def toBytes(url): |
| 938 | """toBytes(u"URL") --> 'URL'.""" |
| 939 | # Most URL schemes require ASCII. If that changes, the conversion |
| 940 | # can be relaxed |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 941 | if _is_unicode(url): |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 942 | try: |
| 943 | url = url.encode("ASCII") |
| 944 | except UnicodeError: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 945 | raise UnicodeError("URL " + repr(url) + |
| 946 | " contains non-ASCII characters") |
Martin v. Löwis | 1d99433 | 2000-12-03 18:30:10 +0000 | [diff] [blame] | 947 | return url |
| 948 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 949 | def unwrap(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 950 | """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" |
Guido van Rossum | a098294 | 2007-07-10 08:30:03 +0000 | [diff] [blame] | 951 | url = str(url).strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 952 | if url[:1] == '<' and url[-1:] == '>': |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 953 | url = url[1:-1].strip() |
| 954 | if url[:4] == 'URL:': url = url[4:].strip() |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 955 | return url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 956 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 957 | _typeprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 958 | def splittype(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 959 | """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 960 | global _typeprog |
| 961 | if _typeprog is None: |
| 962 | import re |
| 963 | _typeprog = re.compile('^([^/:]+):') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 964 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 965 | match = _typeprog.match(url) |
| 966 | if match: |
| 967 | scheme = match.group(1) |
Fred Drake | 9e94afd | 2000-07-01 07:03:30 +0000 | [diff] [blame] | 968 | return scheme.lower(), url[len(scheme) + 1:] |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 969 | return None, url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 970 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 971 | _hostprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 972 | def splithost(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 973 | """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 974 | global _hostprog |
| 975 | if _hostprog is None: |
| 976 | import re |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 977 | _hostprog = re.compile('^//([^/?]*)(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 978 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 979 | match = _hostprog.match(url) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 980 | if match: return match.group(1, 2) |
| 981 | return None, url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 982 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 983 | _userprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 984 | def splituser(host): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 985 | """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 986 | global _userprog |
| 987 | if _userprog is None: |
| 988 | import re |
Raymond Hettinger | f2e45dd | 2002-08-18 20:08:56 +0000 | [diff] [blame] | 989 | _userprog = re.compile('^(.*)@(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 990 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 991 | match = _userprog.match(host) |
Fred Drake | 567ca8e | 2000-08-21 21:42:42 +0000 | [diff] [blame] | 992 | if match: return map(unquote, match.group(1, 2)) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 993 | return None, host |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 994 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 995 | _passwdprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 996 | def splitpasswd(user): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 997 | """splitpasswd('user:passwd') -> 'user', 'passwd'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 998 | global _passwdprog |
| 999 | if _passwdprog is None: |
| 1000 | import re |
| 1001 | _passwdprog = re.compile('^([^:]*):(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1002 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1003 | match = _passwdprog.match(user) |
| 1004 | if match: return match.group(1, 2) |
| 1005 | return user, None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1006 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1007 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1008 | _portprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1009 | def splitport(host): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1010 | """splitport('host:port') --> 'host', 'port'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1011 | global _portprog |
| 1012 | if _portprog is None: |
| 1013 | import re |
| 1014 | _portprog = re.compile('^(.*):([0-9]+)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1015 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1016 | match = _portprog.match(host) |
| 1017 | if match: return match.group(1, 2) |
| 1018 | return host, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1019 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1020 | _nportprog = None |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 1021 | def splitnport(host, defport=-1): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1022 | """Split host and port, returning numeric port. |
| 1023 | Return given default port if no ':' found; defaults to -1. |
| 1024 | Return numerical port if a valid number are found after ':'. |
| 1025 | Return None if ':' but not a valid number.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1026 | global _nportprog |
| 1027 | if _nportprog is None: |
| 1028 | import re |
| 1029 | _nportprog = re.compile('^(.*):(.*)$') |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 1030 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1031 | match = _nportprog.match(host) |
| 1032 | if match: |
| 1033 | host, port = match.group(1, 2) |
| 1034 | try: |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1035 | if not port: raise ValueError, "no digits" |
| 1036 | nport = int(port) |
| 1037 | except ValueError: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1038 | nport = None |
| 1039 | return host, nport |
| 1040 | return host, defport |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 1041 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1042 | _queryprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1043 | def splitquery(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1044 | """splitquery('/path?query') --> '/path', 'query'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1045 | global _queryprog |
| 1046 | if _queryprog is None: |
| 1047 | import re |
| 1048 | _queryprog = re.compile('^(.*)\?([^?]*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1049 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1050 | match = _queryprog.match(url) |
| 1051 | if match: return match.group(1, 2) |
| 1052 | return url, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1053 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1054 | _tagprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1055 | def splittag(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1056 | """splittag('/path#tag') --> '/path', 'tag'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1057 | global _tagprog |
| 1058 | if _tagprog is None: |
| 1059 | import re |
| 1060 | _tagprog = re.compile('^(.*)#([^#]*)$') |
Guido van Rossum | 7e7ca0b | 1998-03-26 21:01:39 +0000 | [diff] [blame] | 1061 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1062 | match = _tagprog.match(url) |
| 1063 | if match: return match.group(1, 2) |
| 1064 | return url, None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1065 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1066 | def splitattr(url): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1067 | """splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 1068 | '/path', ['attr1=value1', 'attr2=value2', ...].""" |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1069 | words = url.split(';') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1070 | return words[0], words[1:] |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1071 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1072 | _valueprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1073 | def splitvalue(attr): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1074 | """splitvalue('attr=value') --> 'attr', 'value'.""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1075 | global _valueprog |
| 1076 | if _valueprog is None: |
| 1077 | import re |
| 1078 | _valueprog = re.compile('^([^=]*)=(.*)$') |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 1079 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1080 | match = _valueprog.match(attr) |
| 1081 | if match: return match.group(1, 2) |
| 1082 | return attr, None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1083 | |
Raymond Hettinger | 803ce80 | 2005-09-10 06:49:04 +0000 | [diff] [blame] | 1084 | _hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) |
| 1085 | _hextochr.update(('%02X' % i, chr(i)) for i in range(256)) |
| 1086 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1087 | def unquote(s): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1088 | """unquote('abc%20def') -> 'abc def'.""" |
Raymond Hettinger | 803ce80 | 2005-09-10 06:49:04 +0000 | [diff] [blame] | 1089 | res = s.split('%') |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1090 | for i in range(1, len(res)): |
Raymond Hettinger | 803ce80 | 2005-09-10 06:49:04 +0000 | [diff] [blame] | 1091 | item = res[i] |
| 1092 | try: |
| 1093 | res[i] = _hextochr[item[:2]] + item[2:] |
| 1094 | except KeyError: |
| 1095 | res[i] = '%' + item |
Raymond Hettinger | 4b0f20d | 2005-10-15 16:41:53 +0000 | [diff] [blame] | 1096 | except UnicodeDecodeError: |
Guido van Rossum | 84fc66d | 2007-05-03 17:18:26 +0000 | [diff] [blame] | 1097 | res[i] = chr(int(item[:2], 16)) + item[2:] |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1098 | return "".join(res) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1099 | |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1100 | def unquote_plus(s): |
Skip Montanaro | 79f1c17 | 2000-08-22 03:00:52 +0000 | [diff] [blame] | 1101 | """unquote('%7e/abc+def') -> '~/abc def'""" |
Brett Cannon | aaeffaf | 2004-03-23 23:50:17 +0000 | [diff] [blame] | 1102 | s = s.replace('+', ' ') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1103 | return unquote(s) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1104 | |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1105 | always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
Jeremy Hylton | 6102e29 | 2000-08-31 15:48:10 +0000 | [diff] [blame] | 1106 | 'abcdefghijklmnopqrstuvwxyz' |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1107 | '0123456789' '_.-') |
Guido van Rossum | c0f2d2d | 2007-08-03 19:19:24 +0000 | [diff] [blame] | 1108 | _safe_quoters= {} |
| 1109 | |
| 1110 | class Quoter: |
| 1111 | def __init__(self, safe): |
| 1112 | self.cache = {} |
| 1113 | self.safe = safe + always_safe |
| 1114 | |
| 1115 | def __call__(self, c): |
| 1116 | try: |
| 1117 | return self.cache[c] |
| 1118 | except KeyError: |
| 1119 | if ord(c) < 256: |
| 1120 | res = (c in self.safe) and c or ('%%%02X' % ord(c)) |
| 1121 | self.cache[c] = res |
| 1122 | return res |
| 1123 | else: |
| 1124 | return "".join(['%%%02X' % i for i in c.encode("utf-8")]) |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1125 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 1126 | def quote(s, safe = '/'): |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1127 | """quote('abc def') -> 'abc%20def' |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1128 | |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1129 | Each part of a URL, e.g. the path info, the query, etc., has a |
| 1130 | different set of reserved characters that must be quoted. |
| 1131 | |
| 1132 | RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists |
| 1133 | the following reserved characters. |
| 1134 | |
| 1135 | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | |
| 1136 | "$" | "," |
| 1137 | |
| 1138 | Each of these characters is reserved in some component of a URL, |
| 1139 | but not necessarily in all of them. |
| 1140 | |
| 1141 | By default, the quote function is intended for quoting the path |
| 1142 | section of a URL. Thus, it will not encode '/'. This character |
| 1143 | is reserved, but in typical usage the quote function is being |
| 1144 | called on a path where the existing slash characters are used as |
| 1145 | reserved characters. |
| 1146 | """ |
Raymond Hettinger | 199d2f7 | 2005-09-09 22:27:13 +0000 | [diff] [blame] | 1147 | cachekey = (safe, always_safe) |
| 1148 | try: |
Guido van Rossum | c0f2d2d | 2007-08-03 19:19:24 +0000 | [diff] [blame] | 1149 | quoter = _safe_quoters[cachekey] |
Raymond Hettinger | 199d2f7 | 2005-09-09 22:27:13 +0000 | [diff] [blame] | 1150 | except KeyError: |
Guido van Rossum | c0f2d2d | 2007-08-03 19:19:24 +0000 | [diff] [blame] | 1151 | quoter = Quoter(safe) |
| 1152 | _safe_quoters[cachekey] = quoter |
| 1153 | res = map(quoter, s) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1154 | return ''.join(res) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1155 | |
Jeremy Hylton | 7ae51bf | 2000-09-14 16:59:07 +0000 | [diff] [blame] | 1156 | def quote_plus(s, safe = ''): |
| 1157 | """Quote the query fragment of a URL; replacing ' ' with '+'""" |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1158 | if ' ' in s: |
Raymond Hettinger | cf6b632 | 2005-09-10 18:17:54 +0000 | [diff] [blame] | 1159 | s = quote(s, safe + ' ') |
| 1160 | return s.replace(' ', '+') |
| 1161 | return quote(s, safe) |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 1162 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1163 | def urlencode(query,doseq=0): |
| 1164 | """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] | 1165 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1166 | 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] | 1167 | sequence element is converted to a separate parameter. |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1168 | |
| 1169 | If the query arg is a sequence of two-element tuples, the order of the |
| 1170 | parameters in the output will match the order of parameters in the |
| 1171 | input. |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1172 | """ |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 1173 | |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1174 | if hasattr(query,"items"): |
| 1175 | # mapping objects |
| 1176 | query = query.items() |
| 1177 | else: |
| 1178 | # it's a bother at times that strings and string-like objects are |
| 1179 | # sequences... |
| 1180 | try: |
| 1181 | # non-sequence items should not work with len() |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1182 | # non-empty strings will fail this |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 1183 | if len(query) and not isinstance(query[0], tuple): |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1184 | raise TypeError |
| 1185 | # zero-length sequences of all types will get here and succeed, |
| 1186 | # but that's a minor nit - since the original implementation |
| 1187 | # allowed empty dicts that type of behavior probably should be |
| 1188 | # preserved for consistency |
| 1189 | except TypeError: |
| 1190 | ty,va,tb = sys.exc_info() |
| 1191 | raise TypeError, "not a valid non-string sequence or mapping object", tb |
| 1192 | |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1193 | l = [] |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1194 | if not doseq: |
| 1195 | # preserve old behavior |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1196 | for k, v in query: |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1197 | k = quote_plus(str(k)) |
| 1198 | v = quote_plus(str(v)) |
| 1199 | l.append(k + '=' + v) |
| 1200 | else: |
Skip Montanaro | 14f1ad4 | 2001-01-28 21:11:12 +0000 | [diff] [blame] | 1201 | for k, v in query: |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1202 | k = quote_plus(str(k)) |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 1203 | if isinstance(v, str): |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1204 | v = quote_plus(v) |
| 1205 | l.append(k + '=' + v) |
Guido van Rossum | 4b46c0a | 2002-05-24 17:58:05 +0000 | [diff] [blame] | 1206 | elif _is_unicode(v): |
Skip Montanaro | a5d23a1 | 2001-01-20 15:56:39 +0000 | [diff] [blame] | 1207 | # is there a reasonable way to convert to ASCII? |
| 1208 | # encode generates a string, but "replace" or "ignore" |
| 1209 | # lose information and "strict" can raise UnicodeError |
| 1210 | v = quote_plus(v.encode("ASCII","replace")) |
| 1211 | l.append(k + '=' + v) |
| 1212 | else: |
| 1213 | try: |
| 1214 | # is this a sufficient test for sequence-ness? |
| 1215 | x = len(v) |
| 1216 | except TypeError: |
| 1217 | # not a sequence |
| 1218 | v = quote_plus(str(v)) |
| 1219 | l.append(k + '=' + v) |
| 1220 | else: |
| 1221 | # loop over the sequence |
| 1222 | for elt in v: |
| 1223 | l.append(k + '=' + quote_plus(str(elt))) |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1224 | return '&'.join(l) |
Guido van Rossum | 810a339 | 1998-07-22 21:33:23 +0000 | [diff] [blame] | 1225 | |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1226 | # Proxy handling |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1227 | def getproxies_environment(): |
| 1228 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 1229 | |
| 1230 | Scan the environment for variables named <scheme>_proxy; |
| 1231 | this seems to be the standard convention. If you need a |
| 1232 | different way, you can pass a proxies dictionary to the |
| 1233 | [Fancy]URLopener constructor. |
| 1234 | |
| 1235 | """ |
| 1236 | proxies = {} |
| 1237 | for name, value in os.environ.items(): |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1238 | name = name.lower() |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1239 | if value and name[-6:] == '_proxy': |
| 1240 | proxies[name[:-6]] = value |
| 1241 | return proxies |
| 1242 | |
Jack Jansen | 11d9b06 | 2004-07-16 11:45:00 +0000 | [diff] [blame] | 1243 | if sys.platform == 'darwin': |
| 1244 | def getproxies_internetconfig(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1245 | """Return a dictionary of scheme -> proxy server URL mappings. |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1246 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1247 | By convention the mac uses Internet Config to store |
| 1248 | proxies. An HTTP proxy, for instance, is stored under |
| 1249 | the HttpProxy key. |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1250 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1251 | """ |
| 1252 | try: |
| 1253 | import ic |
| 1254 | except ImportError: |
| 1255 | return {} |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1256 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1257 | try: |
| 1258 | config = ic.IC() |
| 1259 | except ic.error: |
| 1260 | return {} |
| 1261 | proxies = {} |
| 1262 | # HTTP: |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 1263 | if 'UseHTTPProxy' in config and config['UseHTTPProxy']: |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1264 | try: |
| 1265 | value = config['HTTPProxyHost'] |
| 1266 | except ic.error: |
| 1267 | pass |
| 1268 | else: |
| 1269 | proxies['http'] = 'http://%s' % value |
| 1270 | # FTP: XXXX To be done. |
| 1271 | # Gopher: XXXX To be done. |
| 1272 | return proxies |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1273 | |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1274 | def proxy_bypass(x): |
| 1275 | return 0 |
| 1276 | |
Jack Jansen | 11d9b06 | 2004-07-16 11:45:00 +0000 | [diff] [blame] | 1277 | def getproxies(): |
| 1278 | return getproxies_environment() or getproxies_internetconfig() |
Tim Peters | 182b5ac | 2004-07-18 06:16:08 +0000 | [diff] [blame] | 1279 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1280 | elif os.name == 'nt': |
| 1281 | def getproxies_registry(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1282 | """Return a dictionary of scheme -> proxy server URL mappings. |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1283 | |
| 1284 | Win32 uses the registry to store proxies. |
| 1285 | |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1286 | """ |
| 1287 | proxies = {} |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1288 | try: |
| 1289 | import _winreg |
| 1290 | except ImportError: |
| 1291 | # Std module, so should be around - but you never know! |
| 1292 | return proxies |
| 1293 | try: |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1294 | internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, |
| 1295 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1296 | proxyEnable = _winreg.QueryValueEx(internetSettings, |
| 1297 | 'ProxyEnable')[0] |
| 1298 | if proxyEnable: |
| 1299 | # Returned as Unicode but problems if not converted to ASCII |
| 1300 | proxyServer = str(_winreg.QueryValueEx(internetSettings, |
| 1301 | 'ProxyServer')[0]) |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1302 | if '=' in proxyServer: |
| 1303 | # Per-protocol settings |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1304 | for p in proxyServer.split(';'): |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1305 | protocol, address = p.split('=', 1) |
Guido van Rossum | b955d6c | 2002-03-31 23:38:48 +0000 | [diff] [blame] | 1306 | # See if address has a type:// prefix |
Guido van Rossum | 64e5aa9 | 2002-04-02 14:38:16 +0000 | [diff] [blame] | 1307 | import re |
| 1308 | if not re.match('^([^/:]+)://', address): |
Guido van Rossum | b955d6c | 2002-03-31 23:38:48 +0000 | [diff] [blame] | 1309 | address = '%s://%s' % (protocol, address) |
| 1310 | proxies[protocol] = address |
Fredrik Lundh | b49f88b | 2000-09-24 18:51:25 +0000 | [diff] [blame] | 1311 | else: |
| 1312 | # Use one setting for all protocols |
| 1313 | if proxyServer[:5] == 'http:': |
| 1314 | proxies['http'] = proxyServer |
| 1315 | else: |
| 1316 | proxies['http'] = 'http://%s' % proxyServer |
| 1317 | proxies['ftp'] = 'ftp://%s' % proxyServer |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1318 | internetSettings.Close() |
| 1319 | except (WindowsError, ValueError, TypeError): |
| 1320 | # Either registry key not found etc, or the value in an |
| 1321 | # unexpected format. |
| 1322 | # proxies already set up to be empty so nothing to do |
| 1323 | pass |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1324 | return proxies |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1325 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1326 | def getproxies(): |
| 1327 | """Return a dictionary of scheme -> proxy server URL mappings. |
| 1328 | |
| 1329 | Returns settings gathered from the environment, if specified, |
| 1330 | or the registry. |
| 1331 | |
| 1332 | """ |
| 1333 | return getproxies_environment() or getproxies_registry() |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1334 | |
| 1335 | def proxy_bypass(host): |
| 1336 | try: |
| 1337 | import _winreg |
| 1338 | import re |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1339 | except ImportError: |
| 1340 | # Std modules, so should be around - but you never know! |
| 1341 | return 0 |
| 1342 | try: |
| 1343 | internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, |
| 1344 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') |
| 1345 | proxyEnable = _winreg.QueryValueEx(internetSettings, |
| 1346 | 'ProxyEnable')[0] |
| 1347 | proxyOverride = str(_winreg.QueryValueEx(internetSettings, |
| 1348 | 'ProxyOverride')[0]) |
| 1349 | # ^^^^ Returned as Unicode but problems if not converted to ASCII |
| 1350 | except WindowsError: |
| 1351 | return 0 |
| 1352 | if not proxyEnable or not proxyOverride: |
| 1353 | return 0 |
| 1354 | # try to make a host list from name and IP address. |
Georg Brandl | 1f63670 | 2006-02-18 23:10:23 +0000 | [diff] [blame] | 1355 | rawHost, port = splitport(host) |
| 1356 | host = [rawHost] |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1357 | try: |
Georg Brandl | 1f63670 | 2006-02-18 23:10:23 +0000 | [diff] [blame] | 1358 | addr = socket.gethostbyname(rawHost) |
| 1359 | if addr != rawHost: |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1360 | host.append(addr) |
| 1361 | except socket.error: |
| 1362 | pass |
Georg Brandl | 1f63670 | 2006-02-18 23:10:23 +0000 | [diff] [blame] | 1363 | try: |
| 1364 | fqdn = socket.getfqdn(rawHost) |
| 1365 | if fqdn != rawHost: |
| 1366 | host.append(fqdn) |
| 1367 | except socket.error: |
| 1368 | pass |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1369 | # make a check value list from the registry entry: replace the |
| 1370 | # '<local>' string by the localhost entry and the corresponding |
| 1371 | # canonical entry. |
| 1372 | proxyOverride = proxyOverride.split(';') |
| 1373 | i = 0 |
| 1374 | while i < len(proxyOverride): |
| 1375 | if proxyOverride[i] == '<local>': |
| 1376 | proxyOverride[i:i+1] = ['localhost', |
| 1377 | '127.0.0.1', |
| 1378 | socket.gethostname(), |
| 1379 | socket.gethostbyname( |
| 1380 | socket.gethostname())] |
| 1381 | i += 1 |
| 1382 | # print proxyOverride |
| 1383 | # now check if we match one of the registry values. |
| 1384 | for test in proxyOverride: |
Tim Peters | ab9ba27 | 2001-08-09 21:40:30 +0000 | [diff] [blame] | 1385 | test = test.replace(".", r"\.") # mask dots |
| 1386 | test = test.replace("*", r".*") # change glob sequence |
| 1387 | test = test.replace("?", r".") # change glob char |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1388 | for val in host: |
| 1389 | # print "%s <--> %s" %( test, val ) |
| 1390 | if re.match(test, val, re.I): |
| 1391 | return 1 |
| 1392 | return 0 |
| 1393 | |
Mark Hammond | 4f570b9 | 2000-07-26 07:04:38 +0000 | [diff] [blame] | 1394 | else: |
| 1395 | # By default use environment variables |
| 1396 | getproxies = getproxies_environment |
| 1397 | |
Tim Peters | 55c12d4 | 2001-08-09 18:04:14 +0000 | [diff] [blame] | 1398 | def proxy_bypass(host): |
| 1399 | return 0 |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 1400 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1401 | # Test and time quote() and unquote() |
| 1402 | def test1(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1403 | s = '' |
| 1404 | for i in range(256): s = s + chr(i) |
| 1405 | s = s*4 |
| 1406 | t0 = time.time() |
| 1407 | qs = quote(s) |
| 1408 | uqs = unquote(qs) |
| 1409 | t1 = time.time() |
| 1410 | if uqs != s: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1411 | print('Wrong!') |
| 1412 | print(repr(s)) |
| 1413 | print(repr(qs)) |
| 1414 | print(repr(uqs)) |
| 1415 | print(round(t1 - t0, 3), 'sec') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1416 | |
| 1417 | |
Guido van Rossum | 9ab96d4 | 1998-09-28 14:07:00 +0000 | [diff] [blame] | 1418 | def reporthook(blocknum, blocksize, totalsize): |
| 1419 | # Report during remote transfers |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1420 | print("Block number: %d, Block size: %d, Total size: %d" % ( |
| 1421 | blocknum, blocksize, totalsize)) |
Guido van Rossum | 9ab96d4 | 1998-09-28 14:07:00 +0000 | [diff] [blame] | 1422 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1423 | # Test program |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1424 | def test(args=[]): |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1425 | import string |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1426 | if not args: |
| 1427 | args = [ |
| 1428 | '/etc/passwd', |
| 1429 | 'file:/etc/passwd', |
| 1430 | 'file://localhost/etc/passwd', |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1431 | 'ftp://ftp.gnu.org/pub/README', |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1432 | 'http://www.python.org/index.html', |
| 1433 | ] |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 1434 | if hasattr(URLopener, "open_https"): |
| 1435 | args.append('https://synergy.as.cmu.edu/~geek/') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1436 | try: |
| 1437 | for url in args: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1438 | print('-'*10, url, '-'*10) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1439 | fn, h = urlretrieve(url, None, reporthook) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1440 | print(fn) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1441 | if h: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1442 | print('======') |
| 1443 | for k in h.keys(): print(k + ':', h[k]) |
| 1444 | print('======') |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1445 | fp = open(fn, 'rb') |
| 1446 | data = fp.read() |
| 1447 | del fp |
| 1448 | if '\r' in data: |
| 1449 | table = string.maketrans("", "") |
Guido van Rossum | b2493f8 | 2000-12-15 15:01:37 +0000 | [diff] [blame] | 1450 | data = data.translate(table, "\r") |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1451 | print(data) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1452 | fn, h = None, None |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1453 | print('-'*40) |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1454 | finally: |
| 1455 | urlcleanup() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1456 | |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1457 | def main(): |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1458 | import getopt, sys |
| 1459 | try: |
| 1460 | opts, args = getopt.getopt(sys.argv[1:], "th") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1461 | except getopt.error as msg: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1462 | print(msg) |
| 1463 | print("Use -h for help") |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1464 | return |
| 1465 | t = 0 |
| 1466 | for o, a in opts: |
| 1467 | if o == '-t': |
| 1468 | t = t + 1 |
| 1469 | if o == '-h': |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1470 | print("Usage: python urllib.py [-t] [url ...]") |
| 1471 | print("-t runs self-test;", end=' ') |
| 1472 | print("otherwise, contents of urls are printed") |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1473 | return |
| 1474 | if t: |
| 1475 | if t > 1: |
| 1476 | test1() |
| 1477 | test(args) |
| 1478 | else: |
| 1479 | if not args: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1480 | print("Use -h for help") |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1481 | for url in args: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1482 | print(urlopen(url).read(), end=' ') |
Guido van Rossum | 2349015 | 1998-06-25 02:39:00 +0000 | [diff] [blame] | 1483 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1484 | # Run test program when run as a script |
| 1485 | if __name__ == '__main__': |
Jeremy Hylton | f90b002 | 1999-02-25 16:12:12 +0000 | [diff] [blame] | 1486 | main() |