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