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