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