Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """An extensible library for opening URLs using a variety of protocols |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 2 | |
| 3 | The simplest way to use this module is to call the urlopen function, |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 4 | which accepts a string containing a URL or a Request object (described |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 5 | below). It opens the URL and returns the results as file-like |
| 6 | object; the returned object has some extra methods described below. |
| 7 | |
| 8 | The OpenerDirectory manages a collection of Handler objects that do |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 9 | all the actual work. Each Handler implements a particular protocol or |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 10 | option. The OpenerDirector is a composite object that invokes the |
| 11 | Handlers needed to open the requested URL. For example, the |
| 12 | HTTPHandler performs HTTP GET and POST requests and deals with |
| 13 | non-error returns. The HTTPRedirectHandler automatically deals with |
| 14 | HTTP 301 & 302 redirect errors, and the HTTPDigestAuthHandler deals |
| 15 | with digest authentication. |
| 16 | |
| 17 | urlopen(url, data=None) -- basic usage is that same as original |
| 18 | urllib. pass the url and optionally data to post to an HTTP URL, and |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 19 | get a file-like object back. One difference is that you can also pass |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 20 | a Request instance instead of URL. Raises a URLError (subclass of |
| 21 | IOError); for HTTP errors, raises an HTTPError, which can also be |
| 22 | treated as a valid response. |
| 23 | |
| 24 | build_opener -- function that creates a new OpenerDirector instance. |
| 25 | will install the default handlers. accepts one or more Handlers as |
| 26 | arguments, either instances or Handler classes that it will |
| 27 | instantiate. if one of the argument is a subclass of the default |
| 28 | handler, the argument will be installed instead of the default. |
| 29 | |
| 30 | install_opener -- installs a new opener as the default opener. |
| 31 | |
| 32 | objects of interest: |
| 33 | OpenerDirector -- |
| 34 | |
| 35 | Request -- an object that encapsulates the state of a request. the |
| 36 | state can be a simple as the URL. it can also include extra HTTP |
| 37 | headers, e.g. a User-Agent. |
| 38 | |
| 39 | BaseHandler -- |
| 40 | |
| 41 | exceptions: |
| 42 | URLError-- a subclass of IOError, individual protocols have their own |
| 43 | specific subclass |
| 44 | |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 45 | HTTPError-- also a valid HTTP response, so you can treat an HTTP error |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 46 | as an exceptional event or valid response |
| 47 | |
| 48 | internals: |
| 49 | BaseHandler and parent |
| 50 | _call_chain conventions |
| 51 | |
| 52 | Example usage: |
| 53 | |
| 54 | import urllib2 |
| 55 | |
| 56 | # set up authentication info |
| 57 | authinfo = urllib2.HTTPBasicAuthHandler() |
| 58 | authinfo.add_password('realm', 'host', 'username', 'password') |
| 59 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 60 | proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"}) |
| 61 | |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 62 | # build a new opener that adds authentication and caching FTP handlers |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 63 | opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 64 | |
| 65 | # install it |
| 66 | urllib2.install_opener(opener) |
| 67 | |
| 68 | f = urllib2.urlopen('http://www.python.org/') |
| 69 | |
| 70 | |
| 71 | """ |
| 72 | |
| 73 | # XXX issues: |
| 74 | # If an authentication error handler that tries to perform |
Fred Drake | d5214b0 | 2001-11-08 17:19:29 +0000 | [diff] [blame] | 75 | # authentication for some reason but fails, how should the error be |
| 76 | # signalled? The client needs to know the HTTP error code. But if |
| 77 | # the handler knows that the problem was, e.g., that it didn't know |
| 78 | # that hash algo that requested in the challenge, it would be good to |
| 79 | # pass that information along to the client, too. |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 80 | |
| 81 | # XXX to do: |
| 82 | # name! |
| 83 | # documentation (getting there) |
| 84 | # complex proxies |
| 85 | # abstract factory for opener |
| 86 | # ftp errors aren't handled cleanly |
| 87 | # gopher can return a socket.error |
| 88 | # check digest against correct (i.e. non-apache) implementation |
| 89 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 90 | import socket |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 91 | import httplib |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 92 | import inspect |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 93 | import re |
| 94 | import base64 |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 95 | import urlparse |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 96 | import md5 |
| 97 | import mimetypes |
| 98 | import mimetools |
Jeremy Hylton | 6d8c1aa | 2001-08-27 20:16:53 +0000 | [diff] [blame] | 99 | import rfc822 |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 100 | import ftplib |
| 101 | import sys |
| 102 | import time |
Jeremy Hylton | 6d8c1aa | 2001-08-27 20:16:53 +0000 | [diff] [blame] | 103 | import os |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 104 | import gopherlib |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 105 | import posixpath |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 106 | |
| 107 | try: |
| 108 | from cStringIO import StringIO |
| 109 | except ImportError: |
| 110 | from StringIO import StringIO |
| 111 | |
| 112 | try: |
| 113 | import sha |
| 114 | except ImportError: |
| 115 | # need 1.5.2 final |
| 116 | sha = None |
| 117 | |
| 118 | # not sure how many of these need to be gotten rid of |
| 119 | from urllib import unwrap, unquote, splittype, splithost, \ |
| 120 | addinfourl, splitport, splitgophertype, splitquery, \ |
| 121 | splitattr, ftpwrapper, noheaders |
| 122 | |
| 123 | # support for proxies via environment variables |
| 124 | from urllib import getproxies |
| 125 | |
| 126 | # support for FileHandler |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 127 | from urllib import localhost, url2pathname |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 128 | |
| 129 | __version__ = "2.0a1" |
| 130 | |
| 131 | _opener = None |
| 132 | def urlopen(url, data=None): |
| 133 | global _opener |
| 134 | if _opener is None: |
| 135 | _opener = build_opener() |
| 136 | return _opener.open(url, data) |
| 137 | |
| 138 | def install_opener(opener): |
| 139 | global _opener |
| 140 | _opener = opener |
| 141 | |
| 142 | # do these error classes make sense? |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 143 | # make sure all of the IOError stuff is overridden. we just want to be |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 144 | # subtypes. |
| 145 | |
| 146 | class URLError(IOError): |
| 147 | # URLError is a sub-type of IOError, but it doesn't share any of |
| 148 | # the implementation. need to override __init__ and __str__ |
| 149 | def __init__(self, reason): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 150 | self.reason = reason |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 151 | |
| 152 | def __str__(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 153 | return '<urlopen error %s>' % self.reason |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 154 | |
| 155 | class HTTPError(URLError, addinfourl): |
| 156 | """Raised when HTTP error occurs, but also acts like non-error return""" |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 157 | __super_init = addinfourl.__init__ |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 158 | |
| 159 | def __init__(self, url, code, msg, hdrs, fp): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 160 | self.code = code |
| 161 | self.msg = msg |
| 162 | self.hdrs = hdrs |
| 163 | self.fp = fp |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 164 | self.filename = url |
Jeremy Hylton | 40bbae3 | 2002-06-03 16:53:00 +0000 | [diff] [blame] | 165 | # The addinfourl classes depend on fp being a valid file |
| 166 | # object. In some cases, the HTTPError may not have a valid |
| 167 | # file object. If this happens, the simplest workaround is to |
| 168 | # not initialize the base classes. |
| 169 | if fp is not None: |
| 170 | self.__super_init(fp, hdrs, url) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 171 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 172 | def __str__(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 173 | return 'HTTP Error %s: %s' % (self.code, self.msg) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 174 | |
| 175 | def __del__(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 176 | # XXX is this safe? what if user catches exception, then |
| 177 | # extracts fp and discards exception? |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 178 | if self.fp: |
| 179 | self.fp.close() |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 180 | |
| 181 | class GopherError(URLError): |
| 182 | pass |
| 183 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 184 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 185 | class Request: |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 186 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 187 | def __init__(self, url, data=None, headers={}): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 188 | # unwrap('<URL:type://host/path>') --> 'type://host/path' |
| 189 | self.__original = unwrap(url) |
| 190 | self.type = None |
| 191 | # self.__r_type is what's left after doing the splittype |
| 192 | self.host = None |
| 193 | self.port = None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 194 | self.data = data |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 195 | self.headers = {} |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 196 | self.headers.update(headers) |
| 197 | |
| 198 | def __getattr__(self, attr): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 199 | # XXX this is a fallback mechanism to guard against these |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 200 | # methods getting called in a non-standard order. this may be |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 201 | # too complicated and/or unnecessary. |
| 202 | # XXX should the __r_XXX attributes be public? |
| 203 | if attr[:12] == '_Request__r_': |
| 204 | name = attr[12:] |
| 205 | if hasattr(Request, 'get_' + name): |
| 206 | getattr(self, 'get_' + name)() |
| 207 | return getattr(self, attr) |
| 208 | raise AttributeError, attr |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 209 | |
| 210 | def add_data(self, data): |
| 211 | self.data = data |
| 212 | |
| 213 | def has_data(self): |
| 214 | return self.data is not None |
| 215 | |
| 216 | def get_data(self): |
| 217 | return self.data |
| 218 | |
| 219 | def get_full_url(self): |
| 220 | return self.__original |
| 221 | |
| 222 | def get_type(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 223 | if self.type is None: |
| 224 | self.type, self.__r_type = splittype(self.__original) |
Jeremy Hylton | 78cae61 | 2001-05-09 15:49:24 +0000 | [diff] [blame] | 225 | if self.type is None: |
| 226 | raise ValueError, "unknown url type: %s" % self.__original |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 227 | return self.type |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 228 | |
| 229 | def get_host(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 230 | if self.host is None: |
| 231 | self.host, self.__r_host = splithost(self.__r_type) |
| 232 | if self.host: |
| 233 | self.host = unquote(self.host) |
| 234 | return self.host |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 235 | |
| 236 | def get_selector(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 237 | return self.__r_host |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 238 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 239 | def set_proxy(self, host, type): |
| 240 | self.host, self.type = host, type |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 241 | self.__r_host = self.__original |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 242 | |
| 243 | def add_header(self, key, val): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 244 | # useful for something like authentication |
| 245 | self.headers[key] = val |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 246 | |
| 247 | class OpenerDirector: |
| 248 | def __init__(self): |
| 249 | server_version = "Python-urllib/%s" % __version__ |
| 250 | self.addheaders = [('User-agent', server_version)] |
| 251 | # manage the individual handlers |
| 252 | self.handlers = [] |
| 253 | self.handle_open = {} |
| 254 | self.handle_error = {} |
| 255 | |
| 256 | def add_handler(self, handler): |
| 257 | added = 0 |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 258 | for meth in dir(handler): |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 259 | if meth[-5:] == '_open': |
| 260 | protocol = meth[:-5] |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 261 | if protocol in self.handle_open: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 262 | self.handle_open[protocol].append(handler) |
| 263 | else: |
| 264 | self.handle_open[protocol] = [handler] |
| 265 | added = 1 |
| 266 | continue |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 267 | i = meth.find('_') |
| 268 | j = meth[i+1:].find('_') + i + 1 |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 269 | if j != -1 and meth[i+1:j] == 'error': |
| 270 | proto = meth[:i] |
| 271 | kind = meth[j+1:] |
| 272 | try: |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 273 | kind = int(kind) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 274 | except ValueError: |
| 275 | pass |
| 276 | dict = self.handle_error.get(proto, {}) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 277 | if kind in dict: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 278 | dict[kind].append(handler) |
| 279 | else: |
| 280 | dict[kind] = [handler] |
| 281 | self.handle_error[proto] = dict |
| 282 | added = 1 |
| 283 | continue |
| 284 | if added: |
| 285 | self.handlers.append(handler) |
| 286 | handler.add_parent(self) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 287 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 288 | def __del__(self): |
| 289 | self.close() |
| 290 | |
| 291 | def close(self): |
| 292 | for handler in self.handlers: |
| 293 | handler.close() |
| 294 | self.handlers = [] |
| 295 | |
| 296 | def _call_chain(self, chain, kind, meth_name, *args): |
| 297 | # XXX raise an exception if no one else should try to handle |
| 298 | # this url. return None if you can't but someone else could. |
| 299 | handlers = chain.get(kind, ()) |
| 300 | for handler in handlers: |
| 301 | func = getattr(handler, meth_name) |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 302 | |
| 303 | result = func(*args) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 304 | if result is not None: |
| 305 | return result |
| 306 | |
| 307 | def open(self, fullurl, data=None): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 308 | # accept a URL or a Request object |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 309 | if isinstance(fullurl, basestring): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 310 | req = Request(fullurl, data) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 311 | else: |
| 312 | req = fullurl |
| 313 | if data is not None: |
| 314 | req.add_data(data) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 315 | assert isinstance(req, Request) # really only care about interface |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 316 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 317 | result = self._call_chain(self.handle_open, 'default', |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 318 | 'default_open', req) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 319 | if result: |
| 320 | return result |
| 321 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 322 | type_ = req.get_type() |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 323 | result = self._call_chain(self.handle_open, type_, type_ + \ |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 324 | '_open', req) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 325 | if result: |
| 326 | return result |
| 327 | |
| 328 | return self._call_chain(self.handle_open, 'unknown', |
| 329 | 'unknown_open', req) |
| 330 | |
| 331 | def error(self, proto, *args): |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 332 | if proto in ['http', 'https']: |
Fred Drake | d5214b0 | 2001-11-08 17:19:29 +0000 | [diff] [blame] | 333 | # XXX http[s] protocols are special-cased |
| 334 | dict = self.handle_error['http'] # https is not different than http |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 335 | proto = args[2] # YUCK! |
| 336 | meth_name = 'http_error_%d' % proto |
| 337 | http_err = 1 |
| 338 | orig_args = args |
| 339 | else: |
| 340 | dict = self.handle_error |
| 341 | meth_name = proto + '_error' |
| 342 | http_err = 0 |
| 343 | args = (dict, proto, meth_name) + args |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 344 | result = self._call_chain(*args) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 345 | if result: |
| 346 | return result |
| 347 | |
| 348 | if http_err: |
| 349 | args = (dict, 'default', 'http_error_default') + orig_args |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 350 | return self._call_chain(*args) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 351 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 352 | # XXX probably also want an abstract factory that knows things like |
| 353 | # the fact that a ProxyHandler needs to get inserted first. |
| 354 | # would also know when it makes sense to skip a superclass in favor of |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 355 | # a subclass and when it might make sense to include both |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 356 | |
| 357 | def build_opener(*handlers): |
| 358 | """Create an opener object from a list of handlers. |
| 359 | |
| 360 | The opener will use several default handlers, including support |
| 361 | for HTTP and FTP. If there is a ProxyHandler, it must be at the |
| 362 | front of the list of handlers. (Yuck.) |
| 363 | |
| 364 | If any of the handlers passed as arguments are subclasses of the |
| 365 | default handlers, the default handlers will not be used. |
| 366 | """ |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 367 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 368 | opener = OpenerDirector() |
| 369 | default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, |
| 370 | HTTPDefaultErrorHandler, HTTPRedirectHandler, |
| 371 | FTPHandler, FileHandler] |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 372 | if hasattr(httplib, 'HTTPS'): |
| 373 | default_classes.append(HTTPSHandler) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 374 | skip = [] |
| 375 | for klass in default_classes: |
| 376 | for check in handlers: |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 377 | if inspect.isclass(check): |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 378 | if issubclass(check, klass): |
| 379 | skip.append(klass) |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 380 | elif isinstance(check, klass): |
| 381 | skip.append(klass) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 382 | for klass in skip: |
| 383 | default_classes.remove(klass) |
| 384 | |
| 385 | for klass in default_classes: |
| 386 | opener.add_handler(klass()) |
| 387 | |
| 388 | for h in handlers: |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 389 | if inspect.isclass(h): |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 390 | h = h() |
| 391 | opener.add_handler(h) |
| 392 | return opener |
| 393 | |
| 394 | class BaseHandler: |
| 395 | def add_parent(self, parent): |
| 396 | self.parent = parent |
| 397 | def close(self): |
| 398 | self.parent = None |
| 399 | |
| 400 | class HTTPDefaultErrorHandler(BaseHandler): |
| 401 | def http_error_default(self, req, fp, code, msg, hdrs): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 402 | raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 403 | |
| 404 | class HTTPRedirectHandler(BaseHandler): |
| 405 | # Implementation note: To avoid the server sending us into an |
| 406 | # infinite loop, the request object needs to track what URLs we |
| 407 | # have already seen. Do this by adding a handler-specific |
| 408 | # attribute to the Request object. |
| 409 | def http_error_302(self, req, fp, code, msg, headers): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 410 | if 'location' in headers: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 411 | newurl = headers['location'] |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 412 | elif 'uri' in headers: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 413 | newurl = headers['uri'] |
| 414 | else: |
| 415 | return |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 416 | newurl = urlparse.urljoin(req.get_full_url(), newurl) |
| 417 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 418 | # XXX Probably want to forget about the state of the current |
| 419 | # request, although that might interact poorly with other |
| 420 | # handlers that also use handler-specific request attributes |
Greg Ward | 2e250b4 | 2002-02-11 20:46:10 +0000 | [diff] [blame] | 421 | new = Request(newurl, req.get_data(), req.headers) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 422 | new.error_302_dict = {} |
| 423 | if hasattr(req, 'error_302_dict'): |
Guido van Rossum | 2d996c0 | 2001-04-15 13:08:01 +0000 | [diff] [blame] | 424 | if len(req.error_302_dict)>10 or \ |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 425 | newurl in req.error_302_dict: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 426 | raise HTTPError(req.get_full_url(), code, |
Jeremy Hylton | 54e99e8 | 2001-08-07 21:12:25 +0000 | [diff] [blame] | 427 | self.inf_msg + msg, headers, fp) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 428 | new.error_302_dict.update(req.error_302_dict) |
| 429 | new.error_302_dict[newurl] = newurl |
Jeremy Hylton | 54e99e8 | 2001-08-07 21:12:25 +0000 | [diff] [blame] | 430 | |
| 431 | # Don't close the fp until we are sure that we won't use it |
Tim Peters | ab9ba27 | 2001-08-09 21:40:30 +0000 | [diff] [blame] | 432 | # with HTTPError. |
Jeremy Hylton | 54e99e8 | 2001-08-07 21:12:25 +0000 | [diff] [blame] | 433 | fp.read() |
| 434 | fp.close() |
| 435 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 436 | return self.parent.open(new) |
| 437 | |
| 438 | http_error_301 = http_error_302 |
| 439 | |
| 440 | inf_msg = "The HTTP server returned a redirect error that would" \ |
Thomas Wouters | 7e47402 | 2000-07-16 12:04:32 +0000 | [diff] [blame] | 441 | "lead to an infinite loop.\n" \ |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 442 | "The last 302 error message was:\n" |
| 443 | |
| 444 | class ProxyHandler(BaseHandler): |
| 445 | def __init__(self, proxies=None): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 446 | if proxies is None: |
| 447 | proxies = getproxies() |
| 448 | assert hasattr(proxies, 'has_key'), "proxies must be a mapping" |
| 449 | self.proxies = proxies |
| 450 | for type, url in proxies.items(): |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 451 | setattr(self, '%s_open' % type, |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 452 | lambda r, proxy=url, type=type, meth=self.proxy_open: \ |
| 453 | meth(r, proxy, type)) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 454 | |
| 455 | def proxy_open(self, req, proxy, type): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 456 | orig_type = req.get_type() |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 457 | type, r_type = splittype(proxy) |
| 458 | host, XXX = splithost(r_type) |
| 459 | if '@' in host: |
| 460 | user_pass, host = host.split('@', 1) |
Moshe Zadka | d3f193f | 2001-03-20 13:14:28 +0000 | [diff] [blame] | 461 | user_pass = base64.encodestring(unquote(user_pass)).strip() |
| 462 | req.add_header('Proxy-Authorization', 'Basic '+user_pass) |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 463 | host = unquote(host) |
| 464 | req.set_proxy(host, type) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 465 | if orig_type == type: |
| 466 | # let other handlers take care of it |
| 467 | # XXX this only makes sense if the proxy is before the |
| 468 | # other handlers |
| 469 | return None |
| 470 | else: |
| 471 | # need to start over, because the other handlers don't |
| 472 | # grok the proxy's URL type |
| 473 | return self.parent.open(req) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 474 | |
| 475 | # feature suggested by Duncan Booth |
| 476 | # XXX custom is not a good name |
| 477 | class CustomProxy: |
| 478 | # either pass a function to the constructor or override handle |
| 479 | def __init__(self, proto, func=None, proxy_addr=None): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 480 | self.proto = proto |
| 481 | self.func = func |
| 482 | self.addr = proxy_addr |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 483 | |
| 484 | def handle(self, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 485 | if self.func and self.func(req): |
| 486 | return 1 |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 487 | |
| 488 | def get_proxy(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 489 | return self.addr |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 490 | |
| 491 | class CustomProxyHandler(BaseHandler): |
| 492 | def __init__(self, *proxies): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 493 | self.proxies = {} |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 494 | |
| 495 | def proxy_open(self, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 496 | proto = req.get_type() |
| 497 | try: |
| 498 | proxies = self.proxies[proto] |
| 499 | except KeyError: |
| 500 | return None |
| 501 | for p in proxies: |
| 502 | if p.handle(req): |
| 503 | req.set_proxy(p.get_proxy()) |
| 504 | return self.parent.open(req) |
| 505 | return None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 506 | |
| 507 | def do_proxy(self, p, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 508 | return self.parent.open(req) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 509 | |
| 510 | def add_proxy(self, cpo): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 511 | if cpo.proto in self.proxies: |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 512 | self.proxies[cpo.proto].append(cpo) |
| 513 | else: |
| 514 | self.proxies[cpo.proto] = [cpo] |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 515 | |
| 516 | class HTTPPasswordMgr: |
| 517 | def __init__(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 518 | self.passwd = {} |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 519 | |
| 520 | def add_password(self, realm, uri, user, passwd): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 521 | # uri could be a single URI or a sequence |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 522 | if isinstance(uri, basestring): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 523 | uri = [uri] |
| 524 | uri = tuple(map(self.reduce_uri, uri)) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 525 | if not realm in self.passwd: |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 526 | self.passwd[realm] = {} |
| 527 | self.passwd[realm][uri] = (user, passwd) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 528 | |
| 529 | def find_user_password(self, realm, authuri): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 530 | domains = self.passwd.get(realm, {}) |
| 531 | authuri = self.reduce_uri(authuri) |
| 532 | for uris, authinfo in domains.items(): |
| 533 | for uri in uris: |
| 534 | if self.is_suburi(uri, authuri): |
| 535 | return authinfo |
| 536 | return None, None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 537 | |
| 538 | def reduce_uri(self, uri): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 539 | """Accept netloc or URI and extract only the netloc and path""" |
| 540 | parts = urlparse.urlparse(uri) |
| 541 | if parts[1]: |
| 542 | return parts[1], parts[2] or '/' |
| 543 | else: |
| 544 | return parts[2], '/' |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 545 | |
| 546 | def is_suburi(self, base, test): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 547 | """Check if test is below base in a URI tree |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 548 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 549 | Both args must be URIs in reduced form. |
| 550 | """ |
| 551 | if base == test: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 552 | return True |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 553 | if base[0] != test[0]: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 554 | return False |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 555 | common = posixpath.commonprefix((base[1], test[1])) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 556 | if len(common) == len(base[1]): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 557 | return True |
| 558 | return False |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 559 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 560 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 561 | class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): |
| 562 | |
| 563 | def find_user_password(self, realm, authuri): |
| 564 | user, password = HTTPPasswordMgr.find_user_password(self,realm,authuri) |
| 565 | if user is not None: |
| 566 | return user, password |
| 567 | return HTTPPasswordMgr.find_user_password(self, None, authuri) |
| 568 | |
| 569 | |
| 570 | class AbstractBasicAuthHandler: |
| 571 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 572 | rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"') |
| 573 | |
| 574 | # XXX there can actually be multiple auth-schemes in a |
| 575 | # www-authenticate header. should probably be a lot more careful |
| 576 | # in parsing them to extract multiple alternatives |
| 577 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 578 | def __init__(self, password_mgr=None): |
| 579 | if password_mgr is None: |
| 580 | password_mgr = HTTPPasswordMgr() |
| 581 | self.passwd = password_mgr |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 582 | self.add_password = self.passwd.add_password |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 583 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 584 | def http_error_auth_reqed(self, authreq, host, req, headers): |
| 585 | # XXX could be multiple headers |
| 586 | authreq = headers.get(authreq, None) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 587 | if authreq: |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 588 | mo = AbstractBasicAuthHandler.rx.match(authreq) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 589 | if mo: |
| 590 | scheme, realm = mo.groups() |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 591 | if scheme.lower() == 'basic': |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 592 | return self.retry_http_basic_auth(host, req, realm) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 593 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 594 | def retry_http_basic_auth(self, host, req, realm): |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 595 | user,pw = self.passwd.find_user_password(realm, host) |
| 596 | if pw: |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 597 | raw = "%s:%s" % (user, pw) |
Jeremy Hylton | 52a17be | 2001-11-09 16:46:51 +0000 | [diff] [blame] | 598 | auth = 'Basic %s' % base64.encodestring(raw).strip() |
| 599 | if req.headers.get(self.auth_header, None) == auth: |
| 600 | return None |
| 601 | req.add_header(self.auth_header, auth) |
| 602 | return self.parent.open(req) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 603 | else: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 604 | return None |
| 605 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 606 | class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 607 | |
Jeremy Hylton | 52a17be | 2001-11-09 16:46:51 +0000 | [diff] [blame] | 608 | auth_header = 'Authorization' |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 609 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 610 | def http_error_401(self, req, fp, code, msg, headers): |
| 611 | host = urlparse.urlparse(req.get_full_url())[1] |
Tim Peters | 30edd23 | 2001-03-16 08:29:48 +0000 | [diff] [blame] | 612 | return self.http_error_auth_reqed('www-authenticate', |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 613 | host, req, headers) |
| 614 | |
| 615 | |
| 616 | class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): |
| 617 | |
Jeremy Hylton | 52a17be | 2001-11-09 16:46:51 +0000 | [diff] [blame] | 618 | auth_header = 'Proxy-Authorization' |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 619 | |
| 620 | def http_error_407(self, req, fp, code, msg, headers): |
| 621 | host = req.get_host() |
Tim Peters | 30edd23 | 2001-03-16 08:29:48 +0000 | [diff] [blame] | 622 | return self.http_error_auth_reqed('proxy-authenticate', |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 623 | host, req, headers) |
| 624 | |
| 625 | |
| 626 | class AbstractDigestAuthHandler: |
| 627 | |
| 628 | def __init__(self, passwd=None): |
| 629 | if passwd is None: |
Jeremy Hylton | 54e99e8 | 2001-08-07 21:12:25 +0000 | [diff] [blame] | 630 | passwd = HTTPPasswordMgr() |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 631 | self.passwd = passwd |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 632 | self.add_password = self.passwd.add_password |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 633 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 634 | def http_error_auth_reqed(self, authreq, host, req, headers): |
Jeremy Hylton | 52a17be | 2001-11-09 16:46:51 +0000 | [diff] [blame] | 635 | authreq = headers.get(self.auth_header, None) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 636 | if authreq: |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 637 | kind = authreq.split()[0] |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 638 | if kind == 'Digest': |
| 639 | return self.retry_http_digest_auth(req, authreq) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 640 | |
| 641 | def retry_http_digest_auth(self, req, auth): |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 642 | token, challenge = auth.split(' ', 1) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 643 | chal = parse_keqv_list(parse_http_list(challenge)) |
| 644 | auth = self.get_authorization(req, chal) |
| 645 | if auth: |
Jeremy Hylton | 52a17be | 2001-11-09 16:46:51 +0000 | [diff] [blame] | 646 | auth_val = 'Digest %s' % auth |
| 647 | if req.headers.get(self.auth_header, None) == auth_val: |
| 648 | return None |
| 649 | req.add_header(self.auth_header, auth_val) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 650 | resp = self.parent.open(req) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 651 | return resp |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 652 | |
| 653 | def get_authorization(self, req, chal): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 654 | try: |
| 655 | realm = chal['realm'] |
| 656 | nonce = chal['nonce'] |
| 657 | algorithm = chal.get('algorithm', 'MD5') |
| 658 | # mod_digest doesn't send an opaque, even though it isn't |
| 659 | # supposed to be optional |
| 660 | opaque = chal.get('opaque', None) |
| 661 | except KeyError: |
| 662 | return None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 663 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 664 | H, KD = self.get_algorithm_impls(algorithm) |
| 665 | if H is None: |
| 666 | return None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 667 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 668 | user, pw = self.passwd.find_user_password(realm, |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 669 | req.get_full_url()) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 670 | if user is None: |
| 671 | return None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 672 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 673 | # XXX not implemented yet |
| 674 | if req.has_data(): |
| 675 | entdig = self.get_entity_digest(req.get_data(), chal) |
| 676 | else: |
| 677 | entdig = None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 678 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 679 | A1 = "%s:%s:%s" % (user, realm, pw) |
| 680 | A2 = "%s:%s" % (req.has_data() and 'POST' or 'GET', |
| 681 | # XXX selector: what about proxies and full urls |
| 682 | req.get_selector()) |
| 683 | respdig = KD(H(A1), "%s:%s" % (nonce, H(A2))) |
| 684 | # XXX should the partial digests be encoded too? |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 685 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 686 | base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ |
| 687 | 'response="%s"' % (user, realm, nonce, req.get_selector(), |
| 688 | respdig) |
| 689 | if opaque: |
| 690 | base = base + ', opaque="%s"' % opaque |
| 691 | if entdig: |
| 692 | base = base + ', digest="%s"' % entdig |
| 693 | if algorithm != 'MD5': |
| 694 | base = base + ', algorithm="%s"' % algorithm |
| 695 | return base |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 696 | |
| 697 | def get_algorithm_impls(self, algorithm): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 698 | # lambdas assume digest modules are imported at the top level |
| 699 | if algorithm == 'MD5': |
| 700 | H = lambda x, e=encode_digest:e(md5.new(x).digest()) |
| 701 | elif algorithm == 'SHA': |
| 702 | H = lambda x, e=encode_digest:e(sha.new(x).digest()) |
| 703 | # XXX MD5-sess |
| 704 | KD = lambda s, d, H=H: H("%s:%s" % (s, d)) |
| 705 | return H, KD |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 706 | |
| 707 | def get_entity_digest(self, data, chal): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 708 | # XXX not implemented yet |
| 709 | return None |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 710 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 711 | |
| 712 | class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): |
| 713 | """An authentication protocol defined by RFC 2069 |
| 714 | |
| 715 | Digest authentication improves on basic authentication because it |
| 716 | does not transmit passwords in the clear. |
| 717 | """ |
| 718 | |
| 719 | header = 'Authorization' |
| 720 | |
| 721 | def http_error_401(self, req, fp, code, msg, headers): |
| 722 | host = urlparse.urlparse(req.get_full_url())[1] |
| 723 | self.http_error_auth_reqed('www-authenticate', host, req, headers) |
| 724 | |
| 725 | |
| 726 | class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): |
| 727 | |
| 728 | header = 'Proxy-Authorization' |
| 729 | |
| 730 | def http_error_407(self, req, fp, code, msg, headers): |
| 731 | host = req.get_host() |
| 732 | self.http_error_auth_reqed('proxy-authenticate', host, req, headers) |
| 733 | |
| 734 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 735 | def encode_digest(digest): |
| 736 | hexrep = [] |
| 737 | for c in digest: |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 738 | n = (ord(c) >> 4) & 0xf |
| 739 | hexrep.append(hex(n)[-1]) |
| 740 | n = ord(c) & 0xf |
| 741 | hexrep.append(hex(n)[-1]) |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 742 | return ''.join(hexrep) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 743 | |
| 744 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 745 | class AbstractHTTPHandler(BaseHandler): |
| 746 | |
| 747 | def do_open(self, http_class, req): |
Moshe Zadka | 7667680 | 2001-04-11 07:44:53 +0000 | [diff] [blame] | 748 | host = req.get_host() |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 749 | if not host: |
| 750 | raise URLError('no host given') |
| 751 | |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 752 | try: |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 753 | h = http_class(host) # will parse host:port |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 754 | if req.has_data(): |
| 755 | data = req.get_data() |
| 756 | h.putrequest('POST', req.get_selector()) |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 757 | if not 'Content-type' in req.headers: |
Moshe Zadka | d3f193f | 2001-03-20 13:14:28 +0000 | [diff] [blame] | 758 | h.putheader('Content-type', |
| 759 | 'application/x-www-form-urlencoded') |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 760 | if not 'Content-length' in req.headers: |
Moshe Zadka | d3f193f | 2001-03-20 13:14:28 +0000 | [diff] [blame] | 761 | h.putheader('Content-length', '%d' % len(data)) |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 762 | else: |
| 763 | h.putrequest('GET', req.get_selector()) |
| 764 | except socket.error, err: |
| 765 | raise URLError(err) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 766 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 767 | h.putheader('Host', host) |
| 768 | for args in self.parent.addheaders: |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 769 | h.putheader(*args) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 770 | for k, v in req.headers.items(): |
| 771 | h.putheader(k, v) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 772 | h.endheaders() |
| 773 | if req.has_data(): |
Fred Drake | ec3dfde | 2001-07-04 05:18:29 +0000 | [diff] [blame] | 774 | h.send(data) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 775 | |
| 776 | code, msg, hdrs = h.getreply() |
| 777 | fp = h.getfile() |
| 778 | if code == 200: |
| 779 | return addinfourl(fp, hdrs, req.get_full_url()) |
| 780 | else: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 781 | return self.parent.error('http', req, fp, code, msg, hdrs) |
| 782 | |
Moshe Zadka | 8a18e99 | 2001-03-01 08:40:42 +0000 | [diff] [blame] | 783 | |
| 784 | class HTTPHandler(AbstractHTTPHandler): |
| 785 | |
| 786 | def http_open(self, req): |
| 787 | return self.do_open(httplib.HTTP, req) |
| 788 | |
| 789 | |
| 790 | if hasattr(httplib, 'HTTPS'): |
| 791 | class HTTPSHandler(AbstractHTTPHandler): |
| 792 | |
| 793 | def https_open(self, req): |
| 794 | return self.do_open(httplib.HTTPS, req) |
| 795 | |
| 796 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 797 | class UnknownHandler(BaseHandler): |
| 798 | def unknown_open(self, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 799 | type = req.get_type() |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 800 | raise URLError('unknown url type: %s' % type) |
| 801 | |
| 802 | def parse_keqv_list(l): |
| 803 | """Parse list of key=value strings where keys are not duplicated.""" |
| 804 | parsed = {} |
| 805 | for elt in l: |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 806 | k, v = elt.split('=', 1) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 807 | if v[0] == '"' and v[-1] == '"': |
| 808 | v = v[1:-1] |
| 809 | parsed[k] = v |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 810 | return parsed |
| 811 | |
| 812 | def parse_http_list(s): |
| 813 | """Parse lists as described by RFC 2068 Section 2. |
| 814 | |
| 815 | In particular, parse comman-separated lists where the elements of |
| 816 | the list may include quoted-strings. A quoted-string could |
| 817 | contain a comma. |
| 818 | """ |
| 819 | # XXX this function could probably use more testing |
| 820 | |
| 821 | list = [] |
| 822 | end = len(s) |
| 823 | i = 0 |
| 824 | inquote = 0 |
| 825 | start = 0 |
| 826 | while i < end: |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 827 | cur = s[i:] |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 828 | c = cur.find(',') |
| 829 | q = cur.find('"') |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 830 | if c == -1: |
| 831 | list.append(s[start:]) |
| 832 | break |
| 833 | if q == -1: |
| 834 | if inquote: |
| 835 | raise ValueError, "unbalanced quotes" |
| 836 | else: |
| 837 | list.append(s[start:i+c]) |
| 838 | i = i + c + 1 |
| 839 | continue |
| 840 | if inquote: |
| 841 | if q < c: |
| 842 | list.append(s[start:i+c]) |
| 843 | i = i + c + 1 |
| 844 | start = i |
| 845 | inquote = 0 |
| 846 | else: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 847 | i = i + q |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 848 | else: |
| 849 | if c < q: |
| 850 | list.append(s[start:i+c]) |
| 851 | i = i + c + 1 |
| 852 | start = i |
| 853 | else: |
| 854 | inquote = 1 |
| 855 | i = i + q + 1 |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 856 | return map(lambda x: x.strip(), list) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 857 | |
| 858 | class FileHandler(BaseHandler): |
| 859 | # Use local file or FTP depending on form of URL |
| 860 | def file_open(self, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 861 | url = req.get_selector() |
| 862 | if url[:2] == '//' and url[2:3] != '/': |
| 863 | req.type = 'ftp' |
| 864 | return self.parent.open(req) |
| 865 | else: |
| 866 | return self.open_local_file(req) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 867 | |
| 868 | # names for the localhost |
| 869 | names = None |
| 870 | def get_names(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 871 | if FileHandler.names is None: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 872 | FileHandler.names = (socket.gethostbyname('localhost'), |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 873 | socket.gethostbyname(socket.gethostname())) |
| 874 | return FileHandler.names |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 875 | |
| 876 | # not entirely sure what the rules are here |
| 877 | def open_local_file(self, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 878 | host = req.get_host() |
| 879 | file = req.get_selector() |
Jeremy Hylton | 6d8c1aa | 2001-08-27 20:16:53 +0000 | [diff] [blame] | 880 | localfile = url2pathname(file) |
| 881 | stats = os.stat(localfile) |
Martin v. Löwis | 9d3eba8 | 2002-03-18 08:37:19 +0000 | [diff] [blame] | 882 | size = stats.st_size |
| 883 | modified = rfc822.formatdate(stats.st_mtime) |
Jeremy Hylton | 6d8c1aa | 2001-08-27 20:16:53 +0000 | [diff] [blame] | 884 | mtype = mimetypes.guess_type(file)[0] |
Jeremy Hylton | 6d8c1aa | 2001-08-27 20:16:53 +0000 | [diff] [blame] | 885 | headers = mimetools.Message(StringIO( |
| 886 | 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % |
| 887 | (mtype or 'text/plain', size, modified))) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 888 | if host: |
| 889 | host, port = splitport(host) |
| 890 | if not host or \ |
| 891 | (not port and socket.gethostbyname(host) in self.get_names()): |
Jeremy Hylton | 6d8c1aa | 2001-08-27 20:16:53 +0000 | [diff] [blame] | 892 | return addinfourl(open(localfile, 'rb'), |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 893 | headers, 'file:'+file) |
| 894 | raise URLError('file not on local host') |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 895 | |
| 896 | class FTPHandler(BaseHandler): |
| 897 | def ftp_open(self, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 898 | host = req.get_host() |
| 899 | if not host: |
| 900 | raise IOError, ('ftp error', 'no host given') |
| 901 | # XXX handle custom username & password |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 902 | try: |
| 903 | host = socket.gethostbyname(host) |
| 904 | except socket.error, msg: |
| 905 | raise URLError(msg) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 906 | host, port = splitport(host) |
| 907 | if port is None: |
| 908 | port = ftplib.FTP_PORT |
| 909 | path, attrs = splitattr(req.get_selector()) |
| 910 | path = unquote(path) |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 911 | dirs = path.split('/') |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 912 | dirs, file = dirs[:-1], dirs[-1] |
| 913 | if dirs and not dirs[0]: |
| 914 | dirs = dirs[1:] |
| 915 | user = passwd = '' # XXX |
| 916 | try: |
| 917 | fw = self.connect_ftp(user, passwd, host, port, dirs) |
| 918 | type = file and 'I' or 'D' |
| 919 | for attr in attrs: |
| 920 | attr, value = splitattr(attr) |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 921 | if attr.lower() == 'type' and \ |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 922 | value in ('a', 'A', 'i', 'I', 'd', 'D'): |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 923 | type = value.upper() |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 924 | fp, retrlen = fw.retrfile(file, type) |
Guido van Rossum | 833a8d8 | 2001-08-24 13:10:13 +0000 | [diff] [blame] | 925 | headers = "" |
| 926 | mtype = mimetypes.guess_type(req.get_full_url())[0] |
| 927 | if mtype: |
| 928 | headers += "Content-Type: %s\n" % mtype |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 929 | if retrlen is not None and retrlen >= 0: |
Guido van Rossum | 833a8d8 | 2001-08-24 13:10:13 +0000 | [diff] [blame] | 930 | headers += "Content-Length: %d\n" % retrlen |
| 931 | sf = StringIO(headers) |
| 932 | headers = mimetools.Message(sf) |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 933 | return addinfourl(fp, headers, req.get_full_url()) |
| 934 | except ftplib.all_errors, msg: |
| 935 | raise IOError, ('ftp error', msg), sys.exc_info()[2] |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 936 | |
| 937 | def connect_ftp(self, user, passwd, host, port, dirs): |
| 938 | fw = ftpwrapper(user, passwd, host, port, dirs) |
| 939 | ## fw.ftp.set_debuglevel(1) |
| 940 | return fw |
| 941 | |
| 942 | class CacheFTPHandler(FTPHandler): |
| 943 | # XXX would be nice to have pluggable cache strategies |
| 944 | # XXX this stuff is definitely not thread safe |
| 945 | def __init__(self): |
| 946 | self.cache = {} |
| 947 | self.timeout = {} |
| 948 | self.soonest = 0 |
| 949 | self.delay = 60 |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 950 | self.max_conns = 16 |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 951 | |
| 952 | def setTimeout(self, t): |
| 953 | self.delay = t |
| 954 | |
| 955 | def setMaxConns(self, m): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 956 | self.max_conns = m |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 957 | |
| 958 | def connect_ftp(self, user, passwd, host, port, dirs): |
| 959 | key = user, passwd, host, port |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 960 | if key in self.cache: |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 961 | self.timeout[key] = time.time() + self.delay |
| 962 | else: |
| 963 | self.cache[key] = ftpwrapper(user, passwd, host, port, dirs) |
| 964 | self.timeout[key] = time.time() + self.delay |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 965 | self.check_cache() |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 966 | return self.cache[key] |
| 967 | |
| 968 | def check_cache(self): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 969 | # first check for old ones |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 970 | t = time.time() |
| 971 | if self.soonest <= t: |
| 972 | for k, v in self.timeout.items(): |
| 973 | if v < t: |
| 974 | self.cache[k].close() |
| 975 | del self.cache[k] |
| 976 | del self.timeout[k] |
| 977 | self.soonest = min(self.timeout.values()) |
| 978 | |
| 979 | # then check the size |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 980 | if len(self.cache) == self.max_conns: |
| 981 | for k, v in self.timeout.items(): |
| 982 | if v == self.soonest: |
| 983 | del self.cache[k] |
| 984 | del self.timeout[k] |
| 985 | break |
| 986 | self.soonest = min(self.timeout.values()) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 987 | |
| 988 | class GopherHandler(BaseHandler): |
| 989 | def gopher_open(self, req): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 990 | host = req.get_host() |
| 991 | if not host: |
| 992 | raise GopherError('no host given') |
| 993 | host = unquote(host) |
| 994 | selector = req.get_selector() |
| 995 | type, selector = splitgophertype(selector) |
| 996 | selector, query = splitquery(selector) |
| 997 | selector = unquote(selector) |
| 998 | if query: |
| 999 | query = unquote(query) |
| 1000 | fp = gopherlib.send_query(selector, query, host) |
| 1001 | else: |
| 1002 | fp = gopherlib.send_selector(selector, host) |
| 1003 | return addinfourl(fp, noheaders(), req.get_full_url()) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1004 | |
| 1005 | #bleck! don't use this yet |
| 1006 | class OpenerFactory: |
| 1007 | |
| 1008 | default_handlers = [UnknownHandler, HTTPHandler, |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 1009 | HTTPDefaultErrorHandler, HTTPRedirectHandler, |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1010 | FTPHandler, FileHandler] |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1011 | proxy_handlers = [ProxyHandler] |
| 1012 | handlers = [] |
| 1013 | replacement_handlers = [] |
| 1014 | |
| 1015 | def add_proxy_handler(self, ph): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1016 | self.proxy_handlers = self.proxy_handlers + [ph] |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1017 | |
| 1018 | def add_handler(self, h): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1019 | self.handlers = self.handlers + [h] |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1020 | |
| 1021 | def replace_handler(self, h): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1022 | pass |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1023 | |
| 1024 | def build_opener(self): |
Jeremy Hylton | 54e99e8 | 2001-08-07 21:12:25 +0000 | [diff] [blame] | 1025 | opener = OpenerDirector() |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1026 | for ph in self.proxy_handlers: |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1027 | if inspect.isclass(ph): |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1028 | ph = ph() |
| 1029 | opener.add_handler(ph) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1030 | |
| 1031 | if __name__ == "__main__": |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 1032 | # XXX some of the test code depends on machine configurations that |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1033 | # are internal to CNRI. Need to set up a public server with the |
| 1034 | # right authentication configuration for test purposes. |
| 1035 | if socket.gethostname() == 'bitdiddle': |
| 1036 | localhost = 'bitdiddle.cnri.reston.va.us' |
Jeremy Hylton | 73574ee | 2000-10-12 18:54:18 +0000 | [diff] [blame] | 1037 | elif socket.gethostname() == 'bitdiddle.concentric.net': |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1038 | localhost = 'localhost' |
| 1039 | else: |
| 1040 | localhost = None |
| 1041 | urls = [ |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1042 | # Thanks to Fred for finding these! |
| 1043 | 'gopher://gopher.lib.ncsu.edu/11/library/stacks/Alex', |
| 1044 | 'gopher://gopher.vt.edu:10010/10/33', |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1045 | |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1046 | 'file:/etc/passwd', |
| 1047 | 'file://nonsensename/etc/passwd', |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1048 | 'ftp://www.python.org/pub/python/misc/sousa.au', |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1049 | 'ftp://www.python.org/pub/tmp/blat', |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1050 | 'http://www.espn.com/', # redirect |
| 1051 | 'http://www.python.org/Spanish/Inquistion/', |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1052 | ('http://www.python.org/cgi-bin/faqw.py', |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1053 | 'query=pythonistas&querytype=simple&casefold=yes&req=search'), |
| 1054 | 'http://www.python.org/', |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1055 | 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC/research-reports/00README-Legal-Rules-Regs', |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1056 | ] |
| 1057 | |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1058 | ## if localhost is not None: |
| 1059 | ## urls = urls + [ |
| 1060 | ## 'file://%s/etc/passwd' % localhost, |
| 1061 | ## 'http://%s/simple/' % localhost, |
| 1062 | ## 'http://%s/digest/' % localhost, |
| 1063 | ## 'http://%s/not/found.h' % localhost, |
| 1064 | ## ] |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1065 | |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1066 | ## bauth = HTTPBasicAuthHandler() |
| 1067 | ## bauth.add_password('basic_test_realm', localhost, 'jhylton', |
| 1068 | ## 'password') |
| 1069 | ## dauth = HTTPDigestAuthHandler() |
| 1070 | ## dauth.add_password('digest_test_realm', localhost, 'jhylton', |
| 1071 | ## 'password') |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 1072 | |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1073 | |
| 1074 | cfh = CacheFTPHandler() |
| 1075 | cfh.setTimeout(1) |
| 1076 | |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1077 | ## # XXX try out some custom proxy objects too! |
| 1078 | ## def at_cnri(req): |
| 1079 | ## host = req.get_host() |
| 1080 | ## print host |
| 1081 | ## if host[-18:] == '.cnri.reston.va.us': |
| 1082 | ## return 1 |
| 1083 | ## p = CustomProxy('http', at_cnri, 'proxy.cnri.reston.va.us') |
| 1084 | ## ph = CustomProxyHandler(p) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1085 | |
Jeremy Hylton | 8b78b99 | 2001-10-09 16:18:45 +0000 | [diff] [blame] | 1086 | ## install_opener(build_opener(dauth, bauth, cfh, GopherHandler, ph)) |
| 1087 | install_opener(build_opener(cfh, GopherHandler)) |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1088 | |
| 1089 | for url in urls: |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 1090 | if isinstance(url, tuple): |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1091 | url, req = url |
| 1092 | else: |
| 1093 | req = None |
| 1094 | print url |
| 1095 | try: |
| 1096 | f = urlopen(url, req) |
| 1097 | except IOError, err: |
Fred Drake | 13a2c27 | 2000-02-10 17:17:14 +0000 | [diff] [blame] | 1098 | print "IOError:", err |
| 1099 | except socket.error, err: |
| 1100 | print "socket.error:", err |
Jeremy Hylton | 6d7e47b | 2000-01-20 18:19:08 +0000 | [diff] [blame] | 1101 | else: |
| 1102 | buf = f.read() |
| 1103 | f.close() |
| 1104 | print "read %d bytes" % len(buf) |
| 1105 | print |
| 1106 | time.sleep(0.1) |