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