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