Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 1 | # Open an arbitrary URL |
| 2 | # |
Guido van Rossum | 838cb28 | 1997-02-10 17:51:56 +0000 | [diff] [blame] | 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) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 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() |
| 19 | # and close() methods work like those of open files. |
Guido van Rossum | 838cb28 | 1997-02-10 17:51:56 +0000 | [diff] [blame] | 20 | # The info() method returns a mimetools.Message object which can be |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 21 | # used to query various info about the object, if available. |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 22 | # (mimetools.Message objects are queried with the getheader() method.) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 23 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 24 | import string |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 25 | import socket |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 26 | import os |
Guido van Rossum | 3c8484e | 1996-11-20 22:02:24 +0000 | [diff] [blame] | 27 | import sys |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 28 | |
| 29 | |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 30 | __version__ = '1.9' |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 31 | |
| 32 | MAXFTPCACHE = 10 # Trim the ftp cache beyond this size |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 33 | |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 34 | # Helper for non-unix systems |
| 35 | if os.name == 'mac': |
Guido van Rossum | 71ac945 | 1996-03-21 16:31:41 +0000 | [diff] [blame] | 36 | from macurl2path import url2pathname, pathname2url |
Guido van Rossum | 2281d35 | 1996-06-26 19:47:37 +0000 | [diff] [blame] | 37 | elif os.name == 'nt': |
| 38 | from nturl2path import url2pathname, pathname2url |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 39 | else: |
Jack Jansen | e8ea21b | 1995-12-21 15:43:53 +0000 | [diff] [blame] | 40 | def url2pathname(pathname): |
Jack Jansen | dc3e3f6 | 1995-12-15 13:22:13 +0000 | [diff] [blame] | 41 | return pathname |
Jack Jansen | e8ea21b | 1995-12-21 15:43:53 +0000 | [diff] [blame] | 42 | def pathname2url(pathname): |
| 43 | return pathname |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 44 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 45 | # This really consists of two pieces: |
| 46 | # (1) a class which handles opening of all sorts of URLs |
| 47 | # (plus assorted utilities etc.) |
| 48 | # (2) a set of functions for parsing URLs |
| 49 | # XXX Should these be separated out into different modules? |
| 50 | |
| 51 | |
| 52 | # Shortcut for basic usage |
| 53 | _urlopener = None |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 54 | def urlopen(url, data=None): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 55 | global _urlopener |
| 56 | if not _urlopener: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 57 | _urlopener = FancyURLopener() |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 58 | if data is None: |
| 59 | return _urlopener.open(url) |
| 60 | else: |
| 61 | return _urlopener.open(url, data) |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 62 | def urlretrieve(url, filename=None): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 63 | global _urlopener |
| 64 | if not _urlopener: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 65 | _urlopener = FancyURLopener() |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 66 | if filename: |
| 67 | return _urlopener.retrieve(url, filename) |
| 68 | else: |
| 69 | return _urlopener.retrieve(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 70 | def urlcleanup(): |
| 71 | if _urlopener: |
| 72 | _urlopener.cleanup() |
| 73 | |
| 74 | |
| 75 | # Class to open URLs. |
| 76 | # This is a class rather than just a subroutine because we may need |
| 77 | # more than one set of global protocol-specific options. |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 78 | # Note -- this is a base class for those who don't want the |
| 79 | # automatic handling of errors type 302 (relocated) and 401 |
| 80 | # (authorization needed). |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 81 | ftpcache = {} |
| 82 | class URLopener: |
| 83 | |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 84 | __tempfiles = None |
Guido van Rossum | 29e7781 | 1996-11-27 19:39:58 +0000 | [diff] [blame] | 85 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 86 | # Constructor |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 87 | def __init__(self, proxies=None): |
| 88 | if proxies is None: |
| 89 | proxies = getproxies() |
| 90 | self.proxies = proxies |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 91 | server_version = "Python-urllib/%s" % __version__ |
| 92 | self.addheaders = [('User-agent', server_version)] |
Guido van Rossum | 1049932 | 1997-09-08 02:16:33 +0000 | [diff] [blame] | 93 | self.__tempfiles = [] |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 94 | self.__unlink = os.unlink # See cleanup() |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 95 | self.tempcache = None |
| 96 | # Undocumented feature: if you assign {} to tempcache, |
| 97 | # it is used to cache files retrieved with |
| 98 | # self.retrieve(). This is not enabled by default |
| 99 | # since it does not work for changing documents (and I |
| 100 | # haven't got the logic to check expiration headers |
| 101 | # yet). |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 102 | self.ftpcache = ftpcache |
| 103 | # Undocumented feature: you can use a different |
| 104 | # ftp cache by assigning to the .ftpcache member; |
| 105 | # in case you want logically independent URL openers |
| 106 | |
| 107 | def __del__(self): |
| 108 | self.close() |
| 109 | |
| 110 | def close(self): |
| 111 | self.cleanup() |
| 112 | |
| 113 | def cleanup(self): |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 114 | # This code sometimes runs when the rest of this module |
| 115 | # has already been deleted, so it can't use any globals |
| 116 | # or import anything. |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 117 | if self.__tempfiles: |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 118 | for file in self.__tempfiles: |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 119 | try: |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 120 | self.__unlink(file) |
| 121 | except: |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 122 | pass |
Guido van Rossum | 036309b | 1997-10-27 18:56:19 +0000 | [diff] [blame] | 123 | del self.__tempfiles[:] |
| 124 | if self.tempcache: |
| 125 | self.tempcache.clear() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 126 | |
| 127 | # Add a header to be used by the HTTP interface only |
| 128 | # e.g. u.addheader('Accept', 'sound/basic') |
| 129 | def addheader(self, *args): |
| 130 | self.addheaders.append(args) |
| 131 | |
| 132 | # External interface |
| 133 | # Use URLopener().open(file) instead of open(file, 'r') |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 134 | def open(self, fullurl, data=None): |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 135 | fullurl = unwrap(fullurl) |
| 136 | type, url = splittype(fullurl) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 137 | if not type: type = 'file' |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 138 | self.openedurl = '%s:%s' % (type, url) |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 139 | if self.proxies.has_key(type): |
| 140 | proxy = self.proxies[type] |
| 141 | type, proxy = splittype(proxy) |
| 142 | host, selector = splithost(proxy) |
| 143 | url = (host, fullurl) # Signal special case to open_*() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 144 | name = 'open_' + type |
| 145 | if '-' in name: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 146 | # replace - with _ |
| 147 | name = string.join(string.split(name, '-'), '_') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 148 | if not hasattr(self, name): |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 149 | if data is None: |
| 150 | return self.open_unknown(fullurl) |
| 151 | else: |
| 152 | return self.open_unknown(fullurl, data) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 153 | try: |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 154 | if data is None: |
| 155 | return getattr(self, name)(url) |
| 156 | else: |
| 157 | return getattr(self, name)(url, data) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 158 | except socket.error, msg: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 159 | raise IOError, ('socket error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 160 | |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 161 | # Overridable interface to open unknown URL type |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 162 | def open_unknown(self, fullurl, data=None): |
Guido van Rossum | ca44540 | 1995-08-29 19:19:12 +0000 | [diff] [blame] | 163 | type, url = splittype(fullurl) |
| 164 | raise IOError, ('url error', 'unknown url type', type) |
| 165 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 166 | # External interface |
| 167 | # retrieve(url) returns (filename, None) for a local object |
| 168 | # or (tempfilename, headers) for a remote object |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 169 | def retrieve(self, url, filename=None): |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 170 | if self.tempcache and self.tempcache.has_key(url): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 171 | return self.tempcache[url] |
| 172 | url1 = unwrap(url) |
Guido van Rossum | 5b1b33c | 1996-10-22 13:28:37 +0000 | [diff] [blame] | 173 | self.openedurl = url1 |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 174 | if self.tempcache and self.tempcache.has_key(url1): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 175 | self.tempcache[url] = self.tempcache[url1] |
| 176 | return self.tempcache[url1] |
| 177 | type, url1 = splittype(url1) |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 178 | if not filename and (not type or type == 'file'): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 179 | try: |
| 180 | fp = self.open_local_file(url1) |
| 181 | del fp |
Jack Jansen | e8ea21b | 1995-12-21 15:43:53 +0000 | [diff] [blame] | 182 | return url2pathname(splithost(url1)[1]), None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 183 | except IOError, msg: |
| 184 | pass |
| 185 | fp = self.open(url) |
| 186 | headers = fp.info() |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 187 | if not filename: |
| 188 | import tempfile |
| 189 | filename = tempfile.mktemp() |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 190 | self.__tempfiles.append(filename) |
Guido van Rossum | a7e4b28 | 1996-06-11 00:16:27 +0000 | [diff] [blame] | 191 | result = filename, headers |
Guido van Rossum | 7aeb4b9 | 1994-08-23 13:32:20 +0000 | [diff] [blame] | 192 | if self.tempcache is not None: |
Guido van Rossum | fa59e83 | 1994-09-21 11:36:19 +0000 | [diff] [blame] | 193 | self.tempcache[url] = result |
Guido van Rossum | c511aee | 1997-04-11 19:01:48 +0000 | [diff] [blame] | 194 | tfp = open(filename, 'wb') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 195 | bs = 1024*8 |
| 196 | block = fp.read(bs) |
| 197 | while block: |
| 198 | tfp.write(block) |
| 199 | block = fp.read(bs) |
Guido van Rossum | ab0abdc | 1997-08-26 19:06:40 +0000 | [diff] [blame] | 200 | fp.close() |
| 201 | tfp.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 202 | del fp |
| 203 | del tfp |
| 204 | return result |
| 205 | |
| 206 | # Each method named open_<type> knows how to open that type of URL |
| 207 | |
| 208 | # Use HTTP protocol |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 209 | def open_http(self, url, data=None): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 210 | import httplib |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 211 | if type(url) is type(""): |
| 212 | host, selector = splithost(url) |
Guido van Rossum | 78c9637 | 1996-08-26 18:09:59 +0000 | [diff] [blame] | 213 | user_passwd, host = splituser(host) |
Guido van Rossum | c24751b | 1997-06-03 14:34:19 +0000 | [diff] [blame] | 214 | realhost = host |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 215 | else: |
| 216 | host, selector = url |
Guido van Rossum | 78c9637 | 1996-08-26 18:09:59 +0000 | [diff] [blame] | 217 | urltype, rest = splittype(selector) |
Guido van Rossum | fd79566 | 1997-04-02 05:46:35 +0000 | [diff] [blame] | 218 | user_passwd = None |
Guido van Rossum | c24751b | 1997-06-03 14:34:19 +0000 | [diff] [blame] | 219 | if string.lower(urltype) != 'http': |
| 220 | realhost = None |
| 221 | else: |
Guido van Rossum | 78c9637 | 1996-08-26 18:09:59 +0000 | [diff] [blame] | 222 | realhost, rest = splithost(rest) |
| 223 | user_passwd, realhost = splituser(realhost) |
| 224 | if user_passwd: |
| 225 | selector = "%s://%s%s" % (urltype, |
| 226 | realhost, rest) |
Guido van Rossum | fd79566 | 1997-04-02 05:46:35 +0000 | [diff] [blame] | 227 | #print "proxy via http:", host, selector |
Guido van Rossum | 590b289 | 1994-04-18 09:39:56 +0000 | [diff] [blame] | 228 | if not host: raise IOError, ('http error', 'no host given') |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 229 | if user_passwd: |
| 230 | import base64 |
| 231 | auth = string.strip(base64.encodestring(user_passwd)) |
| 232 | else: |
| 233 | auth = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 234 | h = httplib.HTTP(host) |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 235 | if data is not None: |
| 236 | h.putrequest('POST', selector) |
| 237 | h.putheader('Content-type', |
| 238 | 'application/x-www-form-urlencoded') |
| 239 | h.putheader('Content-length', '%d' % len(data)) |
| 240 | else: |
| 241 | h.putrequest('GET', selector) |
Guido van Rossum | c5d7e80 | 1996-11-11 19:01:17 +0000 | [diff] [blame] | 242 | if auth: h.putheader('Authorization', 'Basic %s' % auth) |
Guido van Rossum | c24751b | 1997-06-03 14:34:19 +0000 | [diff] [blame] | 243 | if realhost: h.putheader('Host', realhost) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 244 | for args in self.addheaders: apply(h.putheader, args) |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 245 | h.endheaders() |
Guido van Rossum | bd01374 | 1996-12-10 16:00:28 +0000 | [diff] [blame] | 246 | if data is not None: |
| 247 | h.send(data + '\r\n') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 248 | errcode, errmsg, headers = h.getreply() |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 249 | fp = h.getfile() |
| 250 | if errcode == 200: |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 251 | return addinfourl(fp, headers, self.openedurl) |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 252 | else: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 253 | return self.http_error(url, |
| 254 | fp, errcode, errmsg, headers) |
| 255 | |
| 256 | # Handle http errors. |
| 257 | # Derived class can override this, or provide specific handlers |
| 258 | # named http_error_DDD where DDD is the 3-digit error code |
| 259 | def http_error(self, url, fp, errcode, errmsg, headers): |
| 260 | # First check if there's a specific handler for this error |
| 261 | name = 'http_error_%d' % errcode |
| 262 | if hasattr(self, name): |
| 263 | method = getattr(self, name) |
| 264 | result = method(url, fp, errcode, errmsg, headers) |
| 265 | if result: return result |
| 266 | return self.http_error_default( |
| 267 | url, fp, errcode, errmsg, headers) |
| 268 | |
| 269 | # Default http error handler: close the connection and raises IOError |
| 270 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
| 271 | void = fp.read() |
| 272 | fp.close() |
| 273 | raise IOError, ('http error', errcode, errmsg, headers) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 274 | |
| 275 | # Use Gopher protocol |
| 276 | def open_gopher(self, url): |
| 277 | import gopherlib |
| 278 | host, selector = splithost(url) |
Guido van Rossum | 590b289 | 1994-04-18 09:39:56 +0000 | [diff] [blame] | 279 | if not host: raise IOError, ('gopher error', 'no host given') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 280 | type, selector = splitgophertype(selector) |
| 281 | selector, query = splitquery(selector) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 282 | selector = unquote(selector) |
| 283 | if query: |
| 284 | query = unquote(query) |
| 285 | fp = gopherlib.send_query(selector, query, host) |
| 286 | else: |
| 287 | fp = gopherlib.send_selector(selector, host) |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 288 | return addinfourl(fp, noheaders(), self.openedurl) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 289 | |
| 290 | # Use local file or FTP depending on form of URL |
| 291 | def open_file(self, url): |
Guido van Rossum | b6784dc | 1997-08-20 23:34:01 +0000 | [diff] [blame] | 292 | if url[:2] == '//' and url[2:3] != '/': |
| 293 | return self.open_ftp(url) |
| 294 | else: |
| 295 | return self.open_local_file(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 296 | |
| 297 | # Use local file |
| 298 | def open_local_file(self, url): |
| 299 | host, file = splithost(url) |
Guido van Rossum | b030bc0 | 1996-10-10 16:01:16 +0000 | [diff] [blame] | 300 | if not host: |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 301 | return addinfourl( |
| 302 | open(url2pathname(file), 'rb'), |
| 303 | noheaders(), 'file:'+file) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 304 | host, port = splitport(host) |
| 305 | if not port and socket.gethostbyname(host) in ( |
| 306 | localhost(), thishost()): |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 307 | file = unquote(file) |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 308 | return addinfourl( |
| 309 | open(url2pathname(file), 'rb'), |
| 310 | noheaders(), 'file:'+file) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 311 | raise IOError, ('local file error', 'not on local host') |
| 312 | |
| 313 | # Use FTP protocol |
| 314 | def open_ftp(self, url): |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 315 | host, path = splithost(url) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 316 | if not host: raise IOError, ('ftp error', 'no host given') |
| 317 | host, port = splitport(host) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 318 | user, host = splituser(host) |
| 319 | if user: user, passwd = splitpasswd(user) |
| 320 | else: passwd = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 321 | host = socket.gethostbyname(host) |
| 322 | if not port: |
| 323 | import ftplib |
| 324 | port = ftplib.FTP_PORT |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 325 | path, attrs = splitattr(path) |
| 326 | dirs = string.splitfields(path, '/') |
| 327 | dirs, file = dirs[:-1], dirs[-1] |
| 328 | if dirs and not dirs[0]: dirs = dirs[1:] |
| 329 | key = (user, host, port, string.joinfields(dirs, '/')) |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 330 | if len(self.ftpcache) > MAXFTPCACHE: |
| 331 | # Prune the cache, rather arbitrarily |
| 332 | for k in self.ftpcache.keys(): |
| 333 | if k != key: |
| 334 | v = self.ftpcache[k] |
| 335 | del self.ftpcache[k] |
| 336 | v.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 337 | try: |
| 338 | if not self.ftpcache.has_key(key): |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 339 | self.ftpcache[key] = \ |
| 340 | ftpwrapper(user, passwd, |
| 341 | host, port, dirs) |
| 342 | if not file: type = 'D' |
| 343 | else: type = 'I' |
| 344 | for attr in attrs: |
| 345 | attr, value = splitvalue(attr) |
| 346 | if string.lower(attr) == 'type' and \ |
| 347 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
| 348 | type = string.upper(value) |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 349 | return addinfourl( |
| 350 | self.ftpcache[key].retrfile(file, type), |
| 351 | noheaders(), self.openedurl) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 352 | except ftperrors(), msg: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 353 | raise IOError, ('ftp error', msg), sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 354 | |
| 355 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 356 | # Derived class with handlers for errors we can handle (perhaps) |
| 357 | class FancyURLopener(URLopener): |
| 358 | |
| 359 | def __init__(self, *args): |
| 360 | apply(URLopener.__init__, (self,) + args) |
| 361 | self.auth_cache = {} |
| 362 | |
| 363 | # Default error handling -- don't raise an exception |
| 364 | def http_error_default(self, url, fp, errcode, errmsg, headers): |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 365 | return addinfourl(fp, headers, self.openedurl) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 366 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 367 | # Error 302 -- relocated (temporarily) |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 368 | def http_error_302(self, url, fp, errcode, errmsg, headers): |
| 369 | # XXX The server can force infinite recursion here! |
| 370 | if headers.has_key('location'): |
| 371 | newurl = headers['location'] |
| 372 | elif headers.has_key('uri'): |
| 373 | newurl = headers['uri'] |
| 374 | else: |
| 375 | return |
| 376 | void = fp.read() |
| 377 | fp.close() |
| 378 | return self.open(newurl) |
| 379 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 380 | # Error 301 -- also relocated (permanently) |
| 381 | http_error_301 = http_error_302 |
| 382 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 383 | # Error 401 -- authentication required |
| 384 | # See this URL for a description of the basic authentication scheme: |
| 385 | # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt |
| 386 | def http_error_401(self, url, fp, errcode, errmsg, headers): |
| 387 | if headers.has_key('www-authenticate'): |
| 388 | stuff = headers['www-authenticate'] |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 389 | import re |
| 390 | match = re.match( |
| 391 | '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) |
| 392 | if match: |
| 393 | scheme, realm = match.group() |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 394 | if string.lower(scheme) == 'basic': |
| 395 | return self.retry_http_basic_auth( |
| 396 | url, realm) |
| 397 | |
| 398 | def retry_http_basic_auth(self, url, realm): |
| 399 | host, selector = splithost(url) |
| 400 | i = string.find(host, '@') + 1 |
| 401 | host = host[i:] |
| 402 | user, passwd = self.get_user_passwd(host, realm, i) |
| 403 | if not (user or passwd): return None |
| 404 | host = user + ':' + passwd + '@' + host |
| 405 | newurl = '//' + host + selector |
| 406 | return self.open_http(newurl) |
| 407 | |
| 408 | def get_user_passwd(self, host, realm, clear_cache = 0): |
| 409 | key = realm + '@' + string.lower(host) |
| 410 | if self.auth_cache.has_key(key): |
| 411 | if clear_cache: |
| 412 | del self.auth_cache[key] |
| 413 | else: |
| 414 | return self.auth_cache[key] |
| 415 | user, passwd = self.prompt_user_passwd(host, realm) |
| 416 | if user or passwd: self.auth_cache[key] = (user, passwd) |
| 417 | return user, passwd |
| 418 | |
| 419 | def prompt_user_passwd(self, host, realm): |
| 420 | # Override this in a GUI environment! |
| 421 | try: |
| 422 | user = raw_input("Enter username for %s at %s: " % |
| 423 | (realm, host)) |
| 424 | self.echo_off() |
| 425 | try: |
| 426 | passwd = raw_input( |
| 427 | "Enter password for %s in %s at %s: " % |
| 428 | (user, realm, host)) |
| 429 | finally: |
| 430 | self.echo_on() |
| 431 | return user, passwd |
| 432 | except KeyboardInterrupt: |
| 433 | return None, None |
| 434 | |
| 435 | def echo_off(self): |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 436 | os.system("stty -echo") |
| 437 | |
| 438 | def echo_on(self): |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 439 | print |
| 440 | os.system("stty echo") |
| 441 | |
| 442 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 443 | # Utility functions |
| 444 | |
| 445 | # Return the IP address of the magic hostname 'localhost' |
| 446 | _localhost = None |
| 447 | def localhost(): |
| 448 | global _localhost |
| 449 | if not _localhost: |
| 450 | _localhost = socket.gethostbyname('localhost') |
| 451 | return _localhost |
| 452 | |
| 453 | # Return the IP address of the current host |
| 454 | _thishost = None |
| 455 | def thishost(): |
| 456 | global _thishost |
| 457 | if not _thishost: |
| 458 | _thishost = socket.gethostbyname(socket.gethostname()) |
| 459 | return _thishost |
| 460 | |
| 461 | # Return the set of errors raised by the FTP class |
| 462 | _ftperrors = None |
| 463 | def ftperrors(): |
| 464 | global _ftperrors |
| 465 | if not _ftperrors: |
| 466 | import ftplib |
Guido van Rossum | 2966b32 | 1997-06-06 17:44:07 +0000 | [diff] [blame] | 467 | _ftperrors = ftplib.all_errors |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 468 | return _ftperrors |
| 469 | |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 470 | # Return an empty mimetools.Message object |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 471 | _noheaders = None |
| 472 | def noheaders(): |
| 473 | global _noheaders |
| 474 | if not _noheaders: |
Guido van Rossum | bbb0a05 | 1995-08-04 04:29:05 +0000 | [diff] [blame] | 475 | import mimetools |
| 476 | import StringIO |
| 477 | _noheaders = mimetools.Message(StringIO.StringIO(), 0) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 478 | _noheaders.fp.close() # Recycle file descriptor |
| 479 | return _noheaders |
| 480 | |
| 481 | |
| 482 | # Utility classes |
| 483 | |
| 484 | # Class used by open_ftp() for cache of open FTP connections |
| 485 | class ftpwrapper: |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 486 | def __init__(self, user, passwd, host, port, dirs): |
| 487 | self.user = unquote(user or '') |
| 488 | self.passwd = unquote(passwd or '') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 489 | self.host = host |
| 490 | self.port = port |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 491 | self.dirs = [] |
| 492 | for dir in dirs: |
| 493 | self.dirs.append(unquote(dir)) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 494 | self.init() |
| 495 | def init(self): |
| 496 | import ftplib |
| 497 | self.ftp = ftplib.FTP() |
| 498 | self.ftp.connect(self.host, self.port) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 499 | self.ftp.login(self.user, self.passwd) |
| 500 | for dir in self.dirs: |
| 501 | self.ftp.cwd(dir) |
| 502 | def retrfile(self, file, type): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 503 | import ftplib |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 504 | if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 |
| 505 | else: cmd = 'TYPE ' + type; isdir = 0 |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 506 | try: |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 507 | self.ftp.voidcmd(cmd) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 508 | except ftplib.all_errors: |
| 509 | self.init() |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 510 | self.ftp.voidcmd(cmd) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 511 | conn = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 512 | if file and not isdir: |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 513 | try: |
| 514 | cmd = 'RETR ' + file |
| 515 | conn = self.ftp.transfercmd(cmd) |
| 516 | except ftplib.error_perm, reason: |
| 517 | if reason[:3] != '550': |
Guido van Rossum | 3c8484e | 1996-11-20 22:02:24 +0000 | [diff] [blame] | 518 | raise IOError, ('ftp error', reason), \ |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 519 | sys.exc_info()[2] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 520 | if not conn: |
| 521 | # Try a directory listing |
| 522 | if file: cmd = 'LIST ' + file |
| 523 | else: cmd = 'LIST' |
| 524 | conn = self.ftp.transfercmd(cmd) |
Guido van Rossum | f668d17 | 1997-06-06 21:11:11 +0000 | [diff] [blame] | 525 | return addclosehook(conn.makefile('rb'), self.endtransfer) |
| 526 | def endtransfer(self): |
| 527 | try: |
| 528 | self.ftp.voidresp() |
| 529 | except ftperrors(): |
| 530 | pass |
| 531 | def close(self): |
| 532 | try: |
| 533 | self.ftp.close() |
| 534 | except ftperrors(): |
| 535 | pass |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 536 | |
| 537 | # Base class for addinfo and addclosehook |
| 538 | class addbase: |
| 539 | def __init__(self, fp): |
| 540 | self.fp = fp |
| 541 | self.read = self.fp.read |
| 542 | self.readline = self.fp.readline |
| 543 | self.readlines = self.fp.readlines |
| 544 | self.fileno = self.fp.fileno |
| 545 | def __repr__(self): |
| 546 | return '<%s at %s whose fp = %s>' % ( |
| 547 | self.__class__.__name__, `id(self)`, `self.fp`) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 548 | def close(self): |
| 549 | self.read = None |
| 550 | self.readline = None |
| 551 | self.readlines = None |
| 552 | self.fileno = None |
Guido van Rossum | 6cb15a0 | 1995-06-22 19:00:13 +0000 | [diff] [blame] | 553 | if self.fp: self.fp.close() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 554 | self.fp = None |
| 555 | |
| 556 | # Class to add a close hook to an open file |
| 557 | class addclosehook(addbase): |
| 558 | def __init__(self, fp, closehook, *hookargs): |
| 559 | addbase.__init__(self, fp) |
| 560 | self.closehook = closehook |
| 561 | self.hookargs = hookargs |
| 562 | def close(self): |
| 563 | if self.closehook: |
| 564 | apply(self.closehook, self.hookargs) |
| 565 | self.closehook = None |
| 566 | self.hookargs = None |
| 567 | addbase.close(self) |
| 568 | |
| 569 | # class to add an info() method to an open file |
| 570 | class addinfo(addbase): |
| 571 | def __init__(self, fp, headers): |
| 572 | addbase.__init__(self, fp) |
| 573 | self.headers = headers |
| 574 | def info(self): |
| 575 | return self.headers |
| 576 | |
Guido van Rossum | e6ad891 | 1996-09-10 17:02:56 +0000 | [diff] [blame] | 577 | # class to add info() and geturl() methods to an open file |
| 578 | class addinfourl(addbase): |
| 579 | def __init__(self, fp, headers, url): |
| 580 | addbase.__init__(self, fp) |
| 581 | self.headers = headers |
| 582 | self.url = url |
| 583 | def info(self): |
| 584 | return self.headers |
| 585 | def geturl(self): |
| 586 | return self.url |
| 587 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 588 | |
| 589 | # Utility to combine a URL with a base URL to form a new URL |
| 590 | |
| 591 | def basejoin(base, url): |
| 592 | type, path = splittype(url) |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 593 | if type: |
| 594 | # if url is complete (i.e., it contains a type), return it |
| 595 | return url |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 596 | host, path = splithost(path) |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 597 | type, basepath = splittype(base) # inherit type from base |
| 598 | if host: |
| 599 | # if url contains host, just inherit type |
| 600 | if type: return type + '://' + host + path |
| 601 | else: |
| 602 | # no type inherited, so url must have started with // |
| 603 | # just return it |
| 604 | return url |
| 605 | host, basepath = splithost(basepath) # inherit host |
| 606 | basepath, basetag = splittag(basepath) # remove extraneuous cruft |
| 607 | basepath, basequery = splitquery(basepath) # idem |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 608 | if path[:1] != '/': |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 609 | # non-absolute path name |
| 610 | if path[:1] in ('#', '?'): |
| 611 | # path is just a tag or query, attach to basepath |
| 612 | i = len(basepath) |
| 613 | else: |
| 614 | # else replace last component |
| 615 | i = string.rfind(basepath, '/') |
| 616 | if i < 0: |
| 617 | # basepath not absolute |
| 618 | if host: |
| 619 | # host present, make absolute |
| 620 | basepath = '/' |
| 621 | else: |
| 622 | # else keep non-absolute |
| 623 | basepath = '' |
| 624 | else: |
| 625 | # remove last file component |
| 626 | basepath = basepath[:i+1] |
Guido van Rossum | 54a1d0b | 1997-04-11 19:09:51 +0000 | [diff] [blame] | 627 | # Interpret ../ (important because of symlinks) |
| 628 | while basepath and path[:3] == '../': |
| 629 | path = path[3:] |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 630 | i = string.rfind(basepath[:-1], '/') |
Guido van Rossum | 54a1d0b | 1997-04-11 19:09:51 +0000 | [diff] [blame] | 631 | if i > 0: |
Guido van Rossum | 2b3fd76 | 1997-09-03 22:36:15 +0000 | [diff] [blame] | 632 | basepath = basepath[:i+1] |
| 633 | elif i == 0: |
| 634 | basepath = '/' |
| 635 | break |
| 636 | else: |
| 637 | basepath = '' |
Guido van Rossum | 54a1d0b | 1997-04-11 19:09:51 +0000 | [diff] [blame] | 638 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 639 | path = basepath + path |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 640 | if type and host: return type + '://' + host + path |
| 641 | elif type: return type + ':' + path |
| 642 | elif host: return '//' + host + path # don't know what this means |
| 643 | else: return path |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 644 | |
| 645 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 646 | # Utilities to parse URLs (most of these return None for missing parts): |
Sjoerd Mullender | e0371b8 | 1995-11-10 10:36:07 +0000 | [diff] [blame] | 647 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 648 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 649 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 650 | # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' |
| 651 | # splitpasswd('user:passwd') -> 'user', 'passwd' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 652 | # splitport('host:port') --> 'host', 'port' |
| 653 | # splitquery('/path?query') --> '/path', 'query' |
| 654 | # splittag('/path#tag') --> '/path', 'tag' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 655 | # splitattr('/path;attr1=value1;attr2=value2;...') -> |
| 656 | # '/path', ['attr1=value1', 'attr2=value2', ...] |
| 657 | # splitvalue('attr=value') --> 'attr', 'value' |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 658 | # splitgophertype('/Xselector') --> 'X', 'selector' |
| 659 | # unquote('abc%20def') -> 'abc def' |
| 660 | # quote('abc def') -> 'abc%20def') |
| 661 | |
| 662 | def unwrap(url): |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 663 | url = string.strip(url) |
| 664 | if url[:1] == '<' and url[-1:] == '>': |
| 665 | url = string.strip(url[1:-1]) |
| 666 | if url[:4] == 'URL:': url = string.strip(url[4:]) |
| 667 | return url |
| 668 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 669 | _typeprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 670 | def splittype(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 671 | global _typeprog |
| 672 | if _typeprog is None: |
| 673 | import re |
| 674 | _typeprog = re.compile('^([^/:]+):') |
| 675 | |
| 676 | match = _typeprog.match(url) |
| 677 | if match: |
| 678 | scheme = match.group(1) |
Guido van Rossum | ab0d1af | 1997-04-16 15:17:06 +0000 | [diff] [blame] | 679 | return scheme, url[len(scheme) + 1:] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 680 | return None, url |
| 681 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 682 | _hostprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 683 | def splithost(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 684 | global _hostprog |
| 685 | if _hostprog is None: |
| 686 | import re |
| 687 | _hostprog = re.compile('^//([^/]+)(.*)$') |
| 688 | |
| 689 | match = _hostprog.match(url) |
| 690 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 691 | return None, url |
| 692 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 693 | _userprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 694 | def splituser(host): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 695 | global _userprog |
| 696 | if _userprog is None: |
| 697 | import re |
| 698 | _userprog = re.compile('^([^@]*)@(.*)$') |
| 699 | |
| 700 | match = _userprog.match(host) |
| 701 | if match: return match.group(1, 2) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 702 | return None, host |
| 703 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 704 | _passwdprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 705 | def splitpasswd(user): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 706 | global _passwdprog |
| 707 | if _passwdprog is None: |
| 708 | import re |
| 709 | _passwdprog = re.compile('^([^:]*):(.*)$') |
| 710 | |
Fred Drake | 654451d | 1997-10-14 13:30:57 +0000 | [diff] [blame] | 711 | match = _passwdprog.match(user) |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 712 | if match: return match.group(1, 2) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 713 | return user, None |
| 714 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 715 | _portprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 716 | def splitport(host): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 717 | global _portprog |
| 718 | if _portprog is None: |
| 719 | import re |
| 720 | _portprog = re.compile('^(.*):([0-9]+)$') |
| 721 | |
| 722 | match = _portprog.match(host) |
| 723 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 724 | return host, None |
| 725 | |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 726 | # Split host and port, returning numeric port. |
| 727 | # Return given default port if no ':' found; defaults to -1. |
Guido van Rossum | 84a00a8 | 1996-06-17 17:11:40 +0000 | [diff] [blame] | 728 | # Return numerical port if a valid number are found after ':'. |
| 729 | # Return None if ':' but not a valid number. |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 730 | _nportprog = None |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 731 | def splitnport(host, defport=-1): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 732 | global _nportprog |
| 733 | if _nportprog is None: |
| 734 | import re |
| 735 | _nportprog = re.compile('^(.*):(.*)$') |
| 736 | |
| 737 | match = _nportprog.match(host) |
| 738 | if match: |
| 739 | host, port = match.group(1, 2) |
Guido van Rossum | 84a00a8 | 1996-06-17 17:11:40 +0000 | [diff] [blame] | 740 | try: |
| 741 | if not port: raise string.atoi_error, "no digits" |
| 742 | nport = string.atoi(port) |
| 743 | except string.atoi_error: |
| 744 | nport = None |
Guido van Rossum | 53725a2 | 1996-06-13 19:12:35 +0000 | [diff] [blame] | 745 | return host, nport |
| 746 | return host, defport |
| 747 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 748 | _queryprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 749 | def splitquery(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 750 | global _queryprog |
| 751 | if _queryprog is None: |
| 752 | import re |
| 753 | _queryprog = re.compile('^(.*)\?([^?]*)$') |
| 754 | |
| 755 | match = _queryprog.match(url) |
| 756 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 757 | return url, None |
| 758 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 759 | _tagprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 760 | def splittag(url): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 761 | global _tagprog |
| 762 | if _tagprog is None: |
| 763 | import re |
| 764 | _tagprog = re.compile('^(.*)#([^#]*)$') |
| 765 | |
| 766 | match = _tagprog.match(url) |
| 767 | if match: return match.group(1, 2) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 768 | return url, None |
| 769 | |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 770 | def splitattr(url): |
| 771 | words = string.splitfields(url, ';') |
| 772 | return words[0], words[1:] |
| 773 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 774 | _valueprog = None |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 775 | def splitvalue(attr): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 776 | global _valueprog |
| 777 | if _valueprog is None: |
| 778 | import re |
| 779 | _valueprog = re.compile('^([^=]*)=(.*)$') |
| 780 | |
| 781 | match = _valueprog.match(attr) |
| 782 | if match: return match.group(1, 2) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 783 | return attr, None |
| 784 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 785 | def splitgophertype(selector): |
| 786 | if selector[:1] == '/' and selector[1:2]: |
| 787 | return selector[1], selector[2:] |
| 788 | return None, selector |
| 789 | |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 790 | _quoteprog = None |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 791 | def unquote(s): |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 792 | global _quoteprog |
| 793 | if _quoteprog is None: |
| 794 | import re |
| 795 | _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]') |
| 796 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 797 | i = 0 |
| 798 | n = len(s) |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 799 | res = [] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 800 | while 0 <= i < n: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 801 | match = _quoteprog.search(s, i) |
| 802 | if not match: |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 803 | res.append(s[i:]) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 804 | break |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 805 | j = match.start(0) |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 806 | res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16))) |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 807 | i = j+3 |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 808 | return string.joinfields(res, '') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 809 | |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 810 | def unquote_plus(s): |
| 811 | if '+' in s: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 812 | # replace '+' with ' ' |
| 813 | s = string.join(string.split(s, '+'), ' ') |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 814 | return unquote(s) |
| 815 | |
Guido van Rossum | 3bb5448 | 1994-08-29 10:52:58 +0000 | [diff] [blame] | 816 | always_safe = string.letters + string.digits + '_,.-' |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 817 | def quote(s, safe = '/'): |
| 818 | safe = always_safe + safe |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 819 | res = [] |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 820 | for c in s: |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 821 | if c in safe: |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 822 | res.append(c) |
Guido van Rossum | 7c395db | 1994-07-04 22:14:49 +0000 | [diff] [blame] | 823 | else: |
Guido van Rossum | f8abb38 | 1996-08-26 15:56:12 +0000 | [diff] [blame] | 824 | res.append('%%%02x' % ord(c)) |
| 825 | return string.joinfields(res, '') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 826 | |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 827 | def quote_plus(s, safe = '/'): |
| 828 | if ' ' in s: |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 829 | # replace ' ' with '+' |
| 830 | s = string.join(string.split(s, ' '), '+') |
Guido van Rossum | 0564e12 | 1996-12-13 14:47:36 +0000 | [diff] [blame] | 831 | return quote(s, safe + '+') |
| 832 | else: |
| 833 | return quote(s, safe) |
| 834 | |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 835 | |
| 836 | # Proxy handling |
| 837 | def getproxies(): |
| 838 | """Return a dictionary of protocol scheme -> proxy server URL mappings. |
| 839 | |
| 840 | Scan the environment for variables named <scheme>_proxy; |
| 841 | this seems to be the standard convention. If you need a |
| 842 | different way, you can pass a proxies dictionary to the |
| 843 | [Fancy]URLopener constructor. |
| 844 | |
| 845 | """ |
| 846 | proxies = {} |
| 847 | for name, value in os.environ.items(): |
Guido van Rossum | 1aec3f0 | 1997-05-28 15:37:19 +0000 | [diff] [blame] | 848 | name = string.lower(name) |
Guido van Rossum | 442e720 | 1996-03-20 15:33:11 +0000 | [diff] [blame] | 849 | if value and name[-6:] == '_proxy': |
| 850 | proxies[name[:-6]] = value |
| 851 | return proxies |
| 852 | |
| 853 | |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 854 | # Test and time quote() and unquote() |
| 855 | def test1(): |
| 856 | import time |
| 857 | s = '' |
| 858 | for i in range(256): s = s + chr(i) |
| 859 | s = s*4 |
| 860 | t0 = time.time() |
| 861 | qs = quote(s) |
| 862 | uqs = unquote(qs) |
| 863 | t1 = time.time() |
| 864 | if uqs != s: |
| 865 | print 'Wrong!' |
| 866 | print `s` |
| 867 | print `qs` |
| 868 | print `uqs` |
| 869 | print round(t1 - t0, 3), 'sec' |
| 870 | |
| 871 | |
| 872 | # Test program |
| 873 | def test(): |
| 874 | import sys |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 875 | args = sys.argv[1:] |
| 876 | if not args: |
| 877 | args = [ |
| 878 | '/etc/passwd', |
| 879 | 'file:/etc/passwd', |
| 880 | 'file://localhost/etc/passwd', |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 881 | 'ftp://ftp.python.org/etc/passwd', |
| 882 | 'gopher://gopher.micro.umn.edu/1/', |
| 883 | 'http://www.python.org/index.html', |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 884 | ] |
| 885 | try: |
| 886 | for url in args: |
| 887 | print '-'*10, url, '-'*10 |
| 888 | fn, h = urlretrieve(url) |
| 889 | print fn, h |
| 890 | if h: |
| 891 | print '======' |
| 892 | for k in h.keys(): print k + ':', h[k] |
| 893 | print '======' |
Guido van Rossum | c511aee | 1997-04-11 19:01:48 +0000 | [diff] [blame] | 894 | fp = open(fn, 'rb') |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 895 | data = fp.read() |
| 896 | del fp |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 897 | if '\r' in data: |
| 898 | table = string.maketrans("", "") |
| 899 | data = string.translate(data, table, "\r") |
| 900 | print data |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 901 | fn, h = None, None |
| 902 | print '-'*40 |
| 903 | finally: |
| 904 | urlcleanup() |
| 905 | |
| 906 | # Run test program when run as a script |
| 907 | if __name__ == '__main__': |
Guido van Rossum | 332e144 | 1997-09-29 23:23:46 +0000 | [diff] [blame] | 908 | test1() |
Guido van Rossum | 7c6ebb5 | 1994-03-22 12:05:32 +0000 | [diff] [blame] | 909 | test() |