blob: 52fe62b2e0c4544287137d443e07365bfe7e25bc [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""An extensible library for opening URLs using a variety of protocols
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00002
3The simplest way to use this module is to call the urlopen function,
Tim Peterse1190062001-01-15 03:34:38 +00004which accepts a string containing a URL or a Request object (described
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00005below). It opens the URL and returns the results as file-like
6object; the returned object has some extra methods described below.
7
Jeremy Hyltone1906632002-10-11 17:27:55 +00008The OpenerDirector manages a collection of Handler objects that do
Tim Peterse1190062001-01-15 03:34:38 +00009all the actual work. Each Handler implements a particular protocol or
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000010option. The OpenerDirector is a composite object that invokes the
11Handlers needed to open the requested URL. For example, the
12HTTPHandler performs HTTP GET and POST requests and deals with
13non-error returns. The HTTPRedirectHandler automatically deals with
Raymond Hettinger024aaa12003-04-24 15:32:12 +000014HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15deals with digest authentication.
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000016
17urlopen(url, data=None) -- basic usage is that same as original
18urllib. pass the url and optionally data to post to an HTTP URL, and
Tim Peterse1190062001-01-15 03:34:38 +000019get a file-like object back. One difference is that you can also pass
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000020a Request instance instead of URL. Raises a URLError (subclass of
21IOError); for HTTP errors, raises an HTTPError, which can also be
22treated as a valid response.
23
24build_opener -- function that creates a new OpenerDirector instance.
25will install the default handlers. accepts one or more Handlers as
26arguments, either instances or Handler classes that it will
27instantiate. if one of the argument is a subclass of the default
28handler, the argument will be installed instead of the default.
29
30install_opener -- installs a new opener as the default opener.
31
32objects of interest:
33OpenerDirector --
34
35Request -- an object that encapsulates the state of a request. the
36state can be a simple as the URL. it can also include extra HTTP
37headers, e.g. a User-Agent.
38
39BaseHandler --
40
41exceptions:
42URLError-- a subclass of IOError, individual protocols have their own
43specific subclass
44
Tim Peterse1190062001-01-15 03:34:38 +000045HTTPError-- also a valid HTTP response, so you can treat an HTTP error
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000046as an exceptional event or valid response
47
48internals:
49BaseHandler and parent
50_call_chain conventions
51
52Example usage:
53
54import urllib2
55
56# set up authentication info
57authinfo = urllib2.HTTPBasicAuthHandler()
58authinfo.add_password('realm', 'host', 'username', 'password')
59
Moshe Zadka8a18e992001-03-01 08:40:42 +000060proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
61
Tim Peterse1190062001-01-15 03:34:38 +000062# build a new opener that adds authentication and caching FTP handlers
Moshe Zadka8a18e992001-03-01 08:40:42 +000063opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000064
65# install it
66urllib2.install_opener(opener)
67
68f = urllib2.urlopen('http://www.python.org/')
69
70
71"""
72
73# XXX issues:
74# If an authentication error handler that tries to perform
Fred Draked5214b02001-11-08 17:19:29 +000075# 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 Hylton6d7e47b2000-01-20 18:19:08 +000080
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 Hylton6d7e47b2000-01-20 18:19:08 +000090import socket
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000091import httplib
Jeremy Hylton8b78b992001-10-09 16:18:45 +000092import inspect
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000093import re
94import base64
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000095import urlparse
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +000096import md5
97import mimetypes
98import mimetools
Jeremy Hylton6d8c1aa2001-08-27 20:16:53 +000099import rfc822
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000100import ftplib
101import sys
102import time
Jeremy Hylton6d8c1aa2001-08-27 20:16:53 +0000103import os
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000104import gopherlib
Moshe Zadka8a18e992001-03-01 08:40:42 +0000105import posixpath
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000106
107try:
108 from cStringIO import StringIO
109except ImportError:
110 from StringIO import StringIO
111
112try:
113 import sha
114except ImportError:
115 # need 1.5.2 final
116 sha = None
117
118# not sure how many of these need to be gotten rid of
119from urllib import unwrap, unquote, splittype, splithost, \
120 addinfourl, splitport, splitgophertype, splitquery, \
121 splitattr, ftpwrapper, noheaders
122
123# support for proxies via environment variables
124from urllib import getproxies
125
126# support for FileHandler
Moshe Zadka8a18e992001-03-01 08:40:42 +0000127from urllib import localhost, url2pathname
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000128
129__version__ = "2.0a1"
130
131_opener = None
132def urlopen(url, data=None):
133 global _opener
134 if _opener is None:
135 _opener = build_opener()
136 return _opener.open(url, data)
137
138def install_opener(opener):
139 global _opener
140 _opener = opener
141
142# do these error classes make sense?
Tim Peterse1190062001-01-15 03:34:38 +0000143# make sure all of the IOError stuff is overridden. we just want to be
Fred Drakea87a5212002-08-13 13:59:55 +0000144# subtypes.
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000145
146class 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 Drake13a2c272000-02-10 17:17:14 +0000150 self.reason = reason
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000151
152 def __str__(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000153 return '<urlopen error %s>' % self.reason
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000154
155class HTTPError(URLError, addinfourl):
156 """Raised when HTTP error occurs, but also acts like non-error return"""
Jeremy Hylton73574ee2000-10-12 18:54:18 +0000157 __super_init = addinfourl.__init__
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000158
159 def __init__(self, url, code, msg, hdrs, fp):
Fred Drake13a2c272000-02-10 17:17:14 +0000160 self.code = code
161 self.msg = msg
162 self.hdrs = hdrs
163 self.fp = fp
Fred Drake13a2c272000-02-10 17:17:14 +0000164 self.filename = url
Jeremy Hylton40bbae32002-06-03 16:53:00 +0000165 # 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 Petersc411dba2002-07-16 21:35:23 +0000168 # not initialize the base classes.
Jeremy Hylton40bbae32002-06-03 16:53:00 +0000169 if fp is not None:
170 self.__super_init(fp, hdrs, url)
Tim Peterse1190062001-01-15 03:34:38 +0000171
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000172 def __str__(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000173 return 'HTTP Error %s: %s' % (self.code, self.msg)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000174
175 def __del__(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000176 # XXX is this safe? what if user catches exception, then
177 # extracts fp and discards exception?
Jeremy Hylton73574ee2000-10-12 18:54:18 +0000178 if self.fp:
179 self.fp.close()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000180
181class GopherError(URLError):
182 pass
183
Moshe Zadka8a18e992001-03-01 08:40:42 +0000184
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000185class Request:
Moshe Zadka8a18e992001-03-01 08:40:42 +0000186
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000187 def __init__(self, url, data=None, headers={}):
Fred Drake13a2c272000-02-10 17:17:14 +0000188 # 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 Hylton6d7e47b2000-01-20 18:19:08 +0000194 self.data = data
Fred Drake13a2c272000-02-10 17:17:14 +0000195 self.headers = {}
Brett Cannonc8b188a2003-05-17 19:51:26 +0000196 for key, value in headers.items():
Brett Cannon86503b12003-05-12 07:29:42 +0000197 self.add_header(key, value)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000198
199 def __getattr__(self, attr):
Fred Drake13a2c272000-02-10 17:17:14 +0000200 # XXX this is a fallback mechanism to guard against these
Tim Peterse1190062001-01-15 03:34:38 +0000201 # methods getting called in a non-standard order. this may be
Fred Drake13a2c272000-02-10 17:17:14 +0000202 # 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 Hylton6d7e47b2000-01-20 18:19:08 +0000210
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000211 def get_method(self):
212 if self.has_data():
213 return "POST"
214 else:
215 return "GET"
216
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000217 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 Drake13a2c272000-02-10 17:17:14 +0000230 if self.type is None:
231 self.type, self.__r_type = splittype(self.__original)
Jeremy Hylton78cae612001-05-09 15:49:24 +0000232 if self.type is None:
233 raise ValueError, "unknown url type: %s" % self.__original
Fred Drake13a2c272000-02-10 17:17:14 +0000234 return self.type
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000235
236 def get_host(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000237 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 Hylton6d7e47b2000-01-20 18:19:08 +0000242
243 def get_selector(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000244 return self.__r_host
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000245
Moshe Zadka8a18e992001-03-01 08:40:42 +0000246 def set_proxy(self, host, type):
247 self.host, self.type = host, type
Fred Drake13a2c272000-02-10 17:17:14 +0000248 self.__r_host = self.__original
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000249
250 def add_header(self, key, val):
Fred Drake13a2c272000-02-10 17:17:14 +0000251 # useful for something like authentication
Brett Cannon86503b12003-05-12 07:29:42 +0000252 self.headers[key.capitalize()] = val
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000253
254class OpenerDirector:
255 def __init__(self):
256 server_version = "Python-urllib/%s" % __version__
Brett Cannon783eaf42003-06-17 21:52:34 +0000257 self.addheaders = [('User-agent', server_version)]
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000258 # 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 Hylton8b78b992001-10-09 16:18:45 +0000265 for meth in dir(handler):
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000266 if meth[-5:] == '_open':
267 protocol = meth[:-5]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000268 if protocol in self.handle_open:
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000269 self.handle_open[protocol].append(handler)
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +0000270 self.handle_open[protocol].sort()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000271 else:
272 self.handle_open[protocol] = [handler]
273 added = 1
274 continue
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000275 i = meth.find('_')
276 j = meth[i+1:].find('_') + i + 1
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000277 if j != -1 and meth[i+1:j] == 'error':
278 proto = meth[:i]
279 kind = meth[j+1:]
280 try:
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000281 kind = int(kind)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000282 except ValueError:
283 pass
284 dict = self.handle_error.get(proto, {})
Raymond Hettinger54f02222002-06-01 14:18:47 +0000285 if kind in dict:
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000286 dict[kind].append(handler)
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +0000287 dict[kind].sort()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000288 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 Niemeyer9556fba2003-06-07 17:53:08 +0000295 self.handlers.sort()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000296 handler.add_parent(self)
Tim Peterse1190062001-01-15 03:34:38 +0000297
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000298 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 Hylton73574ee2000-10-12 18:54:18 +0000312
313 result = func(*args)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000314 if result is not None:
315 return result
316
317 def open(self, fullurl, data=None):
Fred Drake13a2c272000-02-10 17:17:14 +0000318 # accept a URL or a Request object
Walter Dörwald65230a22002-06-03 15:58:32 +0000319 if isinstance(fullurl, basestring):
Fred Drake13a2c272000-02-10 17:17:14 +0000320 req = Request(fullurl, data)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000321 else:
322 req = fullurl
323 if data is not None:
324 req.add_data(data)
Tim Peterse1190062001-01-15 03:34:38 +0000325
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000326 result = self._call_chain(self.handle_open, 'default',
Tim Peterse1190062001-01-15 03:34:38 +0000327 'default_open', req)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000328 if result:
329 return result
330
Fred Drake13a2c272000-02-10 17:17:14 +0000331 type_ = req.get_type()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000332 result = self._call_chain(self.handle_open, type_, type_ + \
Jeremy Hylton73574ee2000-10-12 18:54:18 +0000333 '_open', req)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000334 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 Zadka8a18e992001-03-01 08:40:42 +0000341 if proto in ['http', 'https']:
Fred Draked5214b02001-11-08 17:19:29 +0000342 # XXX http[s] protocols are special-cased
343 dict = self.handle_error['http'] # https is not different than http
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000344 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 Hylton73574ee2000-10-12 18:54:18 +0000353 result = self._call_chain(*args)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000354 if result:
355 return result
356
357 if http_err:
358 args = (dict, 'default', 'http_error_default') + orig_args
Jeremy Hylton73574ee2000-10-12 18:54:18 +0000359 return self._call_chain(*args)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000360
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +0000361# 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 Hylton6d7e47b2000-01-20 18:19:08 +0000364
365def 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 Niemeyer9556fba2003-06-07 17:53:08 +0000369 for HTTP and FTP.
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000370
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 Peterse1190062001-01-15 03:34:38 +0000374
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000375 opener = OpenerDirector()
376 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
377 HTTPDefaultErrorHandler, HTTPRedirectHandler,
378 FTPHandler, FileHandler]
Moshe Zadka8a18e992001-03-01 08:40:42 +0000379 if hasattr(httplib, 'HTTPS'):
380 default_classes.append(HTTPSHandler)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000381 skip = []
382 for klass in default_classes:
383 for check in handlers:
Jeremy Hylton8b78b992001-10-09 16:18:45 +0000384 if inspect.isclass(check):
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000385 if issubclass(check, klass):
386 skip.append(klass)
Jeremy Hylton8b78b992001-10-09 16:18:45 +0000387 elif isinstance(check, klass):
388 skip.append(klass)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000389 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 Hylton8b78b992001-10-09 16:18:45 +0000396 if inspect.isclass(h):
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000397 h = h()
398 opener.add_handler(h)
399 return opener
400
401class BaseHandler:
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +0000402 handler_order = 500
403
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000404 def add_parent(self, parent):
405 self.parent = parent
406 def close(self):
407 self.parent = None
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +0000408 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 Petersf545baa2003-06-15 23:26:30 +0000415
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000416
417class HTTPDefaultErrorHandler(BaseHandler):
418 def http_error_default(self, req, fp, code, msg, hdrs):
Fred Drake13a2c272000-02-10 17:17:14 +0000419 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000420
421class HTTPRedirectHandler(BaseHandler):
Jeremy Hylton03892952003-05-05 04:09:13 +0000422 def redirect_request(self, req, fp, code, msg, headers, newurl):
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000423 """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 Hettinger024aaa12003-04-24 15:32:12 +0000430 """
Jeremy Hylton828023b2003-05-04 23:44:49 +0000431 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 Hettinger024aaa12003-04-24 15:32:12 +0000439 return Request(newurl, headers=req.headers)
440 else:
Martin v. Löwise3b67bc2003-06-14 05:51:25 +0000441 raise HTTPError(req.get_full_url(), code, msg, headers, fp)
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000442
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000443 # 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 Hettinger54f02222002-06-01 14:18:47 +0000448 if 'location' in headers:
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000449 newurl = headers['location']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000450 elif 'uri' in headers:
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000451 newurl = headers['uri']
452 else:
453 return
Jeremy Hylton73574ee2000-10-12 18:54:18 +0000454 newurl = urlparse.urljoin(req.get_full_url(), newurl)
455
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000456 # 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 Hylton03892952003-05-05 04:09:13 +0000459 new = self.redirect_request(req, fp, code, msg, headers, newurl)
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000460 if new is None:
461 return
462
463 # loop detection
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000464 new.error_302_dict = {}
465 if hasattr(req, 'error_302_dict'):
Guido van Rossum2d996c02001-04-15 13:08:01 +0000466 if len(req.error_302_dict)>10 or \
Raymond Hettinger54f02222002-06-01 14:18:47 +0000467 newurl in req.error_302_dict:
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000468 raise HTTPError(req.get_full_url(), code,
Jeremy Hylton54e99e82001-08-07 21:12:25 +0000469 self.inf_msg + msg, headers, fp)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000470 new.error_302_dict.update(req.error_302_dict)
471 new.error_302_dict[newurl] = newurl
Jeremy Hylton54e99e82001-08-07 21:12:25 +0000472
473 # Don't close the fp until we are sure that we won't use it
Tim Petersab9ba272001-08-09 21:40:30 +0000474 # with HTTPError.
Jeremy Hylton54e99e82001-08-07 21:12:25 +0000475 fp.read()
476 fp.close()
477
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000478 return self.parent.open(new)
479
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000480 http_error_301 = http_error_303 = http_error_307 = http_error_302
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000481
482 inf_msg = "The HTTP server returned a redirect error that would" \
Thomas Wouters7e474022000-07-16 12:04:32 +0000483 "lead to an infinite loop.\n" \
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000484 "The last 302 error message was:\n"
485
486class ProxyHandler(BaseHandler):
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +0000487 # Proxies must be in front
488 handler_order = 100
489
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000490 def __init__(self, proxies=None):
Fred Drake13a2c272000-02-10 17:17:14 +0000491 if proxies is None:
492 proxies = getproxies()
493 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
494 self.proxies = proxies
Brett Cannondf0d87a2003-05-18 02:25:07 +0000495 for type, url in proxies.items():
Tim Peterse1190062001-01-15 03:34:38 +0000496 setattr(self, '%s_open' % type,
Fred Drake13a2c272000-02-10 17:17:14 +0000497 lambda r, proxy=url, type=type, meth=self.proxy_open: \
498 meth(r, proxy, type))
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000499
500 def proxy_open(self, req, proxy, type):
Fred Drake13a2c272000-02-10 17:17:14 +0000501 orig_type = req.get_type()
Moshe Zadka8a18e992001-03-01 08:40:42 +0000502 type, r_type = splittype(proxy)
503 host, XXX = splithost(r_type)
504 if '@' in host:
505 user_pass, host = host.split('@', 1)
Jeremy Hylton144dea32002-07-07 16:57:35 +0000506 if ':' in user_pass:
507 user, password = user_pass.split(':', 1)
Tim Petersc411dba2002-07-16 21:35:23 +0000508 user_pass = base64.encodestring('%s:%s' % (unquote(user),
Jeremy Hylton144dea32002-07-07 16:57:35 +0000509 unquote(password)))
Brett Cannon783eaf42003-06-17 21:52:34 +0000510 req.add_header('Proxy-authorization', 'Basic ' + user_pass)
Moshe Zadka8a18e992001-03-01 08:40:42 +0000511 host = unquote(host)
512 req.set_proxy(host, type)
Fred Drake13a2c272000-02-10 17:17:14 +0000513 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 Hylton6d7e47b2000-01-20 18:19:08 +0000522
523# feature suggested by Duncan Booth
524# XXX custom is not a good name
525class CustomProxy:
526 # either pass a function to the constructor or override handle
527 def __init__(self, proto, func=None, proxy_addr=None):
Fred Drake13a2c272000-02-10 17:17:14 +0000528 self.proto = proto
529 self.func = func
530 self.addr = proxy_addr
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000531
532 def handle(self, req):
Fred Drake13a2c272000-02-10 17:17:14 +0000533 if self.func and self.func(req):
534 return 1
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000535
536 def get_proxy(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000537 return self.addr
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000538
539class CustomProxyHandler(BaseHandler):
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +0000540 # Proxies must be in front
541 handler_order = 100
542
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000543 def __init__(self, *proxies):
Fred Drake13a2c272000-02-10 17:17:14 +0000544 self.proxies = {}
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000545
546 def proxy_open(self, req):
Fred Drake13a2c272000-02-10 17:17:14 +0000547 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 Hylton6d7e47b2000-01-20 18:19:08 +0000557
558 def do_proxy(self, p, req):
Fred Drake13a2c272000-02-10 17:17:14 +0000559 return self.parent.open(req)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000560
561 def add_proxy(self, cpo):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000562 if cpo.proto in self.proxies:
Fred Drake13a2c272000-02-10 17:17:14 +0000563 self.proxies[cpo.proto].append(cpo)
564 else:
565 self.proxies[cpo.proto] = [cpo]
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000566
567class HTTPPasswordMgr:
568 def __init__(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000569 self.passwd = {}
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000570
571 def add_password(self, realm, uri, user, passwd):
Fred Drake13a2c272000-02-10 17:17:14 +0000572 # uri could be a single URI or a sequence
Walter Dörwald65230a22002-06-03 15:58:32 +0000573 if isinstance(uri, basestring):
Fred Drake13a2c272000-02-10 17:17:14 +0000574 uri = [uri]
575 uri = tuple(map(self.reduce_uri, uri))
Raymond Hettinger54f02222002-06-01 14:18:47 +0000576 if not realm in self.passwd:
Fred Drake13a2c272000-02-10 17:17:14 +0000577 self.passwd[realm] = {}
578 self.passwd[realm][uri] = (user, passwd)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000579
580 def find_user_password(self, realm, authuri):
Fred Drake13a2c272000-02-10 17:17:14 +0000581 domains = self.passwd.get(realm, {})
582 authuri = self.reduce_uri(authuri)
Brett Cannon86503b12003-05-12 07:29:42 +0000583 for uris, authinfo in domains.iteritems():
Fred Drake13a2c272000-02-10 17:17:14 +0000584 for uri in uris:
585 if self.is_suburi(uri, authuri):
586 return authinfo
587 return None, None
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000588
589 def reduce_uri(self, uri):
Fred Drake13a2c272000-02-10 17:17:14 +0000590 """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 Hylton6d7e47b2000-01-20 18:19:08 +0000596
597 def is_suburi(self, base, test):
Fred Drake13a2c272000-02-10 17:17:14 +0000598 """Check if test is below base in a URI tree
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000599
Fred Drake13a2c272000-02-10 17:17:14 +0000600 Both args must be URIs in reduced form.
601 """
602 if base == test:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000603 return True
Fred Drake13a2c272000-02-10 17:17:14 +0000604 if base[0] != test[0]:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000605 return False
Moshe Zadka8a18e992001-03-01 08:40:42 +0000606 common = posixpath.commonprefix((base[1], test[1]))
Fred Drake13a2c272000-02-10 17:17:14 +0000607 if len(common) == len(base[1]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000608 return True
609 return False
Tim Peterse1190062001-01-15 03:34:38 +0000610
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000611
Moshe Zadka8a18e992001-03-01 08:40:42 +0000612class 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
621class AbstractBasicAuthHandler:
622
Neal Norwitz853ddd52002-10-09 23:17:04 +0000623 rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000624
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 Zadka8a18e992001-03-01 08:40:42 +0000629 def __init__(self, password_mgr=None):
630 if password_mgr is None:
631 password_mgr = HTTPPasswordMgr()
632 self.passwd = password_mgr
Fred Drake13a2c272000-02-10 17:17:14 +0000633 self.add_password = self.passwd.add_password
Tim Peterse1190062001-01-15 03:34:38 +0000634
Moshe Zadka8a18e992001-03-01 08:40:42 +0000635 def http_error_auth_reqed(self, authreq, host, req, headers):
636 # XXX could be multiple headers
637 authreq = headers.get(authreq, None)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000638 if authreq:
Moshe Zadka8a18e992001-03-01 08:40:42 +0000639 mo = AbstractBasicAuthHandler.rx.match(authreq)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000640 if mo:
641 scheme, realm = mo.groups()
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000642 if scheme.lower() == 'basic':
Moshe Zadka8a18e992001-03-01 08:40:42 +0000643 return self.retry_http_basic_auth(host, req, realm)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000644
Moshe Zadka8a18e992001-03-01 08:40:42 +0000645 def retry_http_basic_auth(self, host, req, realm):
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000646 user,pw = self.passwd.find_user_password(realm, host)
647 if pw:
Fred Drake13a2c272000-02-10 17:17:14 +0000648 raw = "%s:%s" % (user, pw)
Jeremy Hylton52a17be2001-11-09 16:46:51 +0000649 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 Hylton6d7e47b2000-01-20 18:19:08 +0000654 else:
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000655 return None
656
Moshe Zadka8a18e992001-03-01 08:40:42 +0000657class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000658
Jeremy Hylton52a17be2001-11-09 16:46:51 +0000659 auth_header = 'Authorization'
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000660
Moshe Zadka8a18e992001-03-01 08:40:42 +0000661 def http_error_401(self, req, fp, code, msg, headers):
662 host = urlparse.urlparse(req.get_full_url())[1]
Tim Peters30edd232001-03-16 08:29:48 +0000663 return self.http_error_auth_reqed('www-authenticate',
Moshe Zadka8a18e992001-03-01 08:40:42 +0000664 host, req, headers)
665
666
667class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
668
Brett Cannon783eaf42003-06-17 21:52:34 +0000669 auth_header = 'Proxy-authorization'
Moshe Zadka8a18e992001-03-01 08:40:42 +0000670
671 def http_error_407(self, req, fp, code, msg, headers):
672 host = req.get_host()
Tim Peters30edd232001-03-16 08:29:48 +0000673 return self.http_error_auth_reqed('proxy-authenticate',
Moshe Zadka8a18e992001-03-01 08:40:42 +0000674 host, req, headers)
675
676
677class AbstractDigestAuthHandler:
678
679 def __init__(self, passwd=None):
680 if passwd is None:
Jeremy Hylton54e99e82001-08-07 21:12:25 +0000681 passwd = HTTPPasswordMgr()
Moshe Zadka8a18e992001-03-01 08:40:42 +0000682 self.passwd = passwd
Fred Drake13a2c272000-02-10 17:17:14 +0000683 self.add_password = self.passwd.add_password
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000684
Moshe Zadka8a18e992001-03-01 08:40:42 +0000685 def http_error_auth_reqed(self, authreq, host, req, headers):
Jeremy Hylton52a17be2001-11-09 16:46:51 +0000686 authreq = headers.get(self.auth_header, None)
Fred Drake13a2c272000-02-10 17:17:14 +0000687 if authreq:
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000688 kind = authreq.split()[0]
Fred Drake13a2c272000-02-10 17:17:14 +0000689 if kind == 'Digest':
690 return self.retry_http_digest_auth(req, authreq)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000691
692 def retry_http_digest_auth(self, req, auth):
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000693 token, challenge = auth.split(' ', 1)
Fred Drake13a2c272000-02-10 17:17:14 +0000694 chal = parse_keqv_list(parse_http_list(challenge))
695 auth = self.get_authorization(req, chal)
696 if auth:
Jeremy Hylton52a17be2001-11-09 16:46:51 +0000697 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 Drake13a2c272000-02-10 17:17:14 +0000701 resp = self.parent.open(req)
Fred Drake13a2c272000-02-10 17:17:14 +0000702 return resp
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000703
704 def get_authorization(self, req, chal):
Fred Drake13a2c272000-02-10 17:17:14 +0000705 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 Hylton6d7e47b2000-01-20 18:19:08 +0000714
Fred Drake13a2c272000-02-10 17:17:14 +0000715 H, KD = self.get_algorithm_impls(algorithm)
716 if H is None:
717 return None
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000718
Fred Drake13a2c272000-02-10 17:17:14 +0000719 user, pw = self.passwd.find_user_password(realm,
Tim Peterse1190062001-01-15 03:34:38 +0000720 req.get_full_url())
Fred Drake13a2c272000-02-10 17:17:14 +0000721 if user is None:
722 return None
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000723
Fred Drake13a2c272000-02-10 17:17:14 +0000724 # 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 Hylton6d7e47b2000-01-20 18:19:08 +0000729
Fred Drake13a2c272000-02-10 17:17:14 +0000730 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 Hylton6d7e47b2000-01-20 18:19:08 +0000736
Fred Drake13a2c272000-02-10 17:17:14 +0000737 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 Hylton6d7e47b2000-01-20 18:19:08 +0000747
748 def get_algorithm_impls(self, algorithm):
Fred Drake13a2c272000-02-10 17:17:14 +0000749 # 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 Hylton6d7e47b2000-01-20 18:19:08 +0000757
758 def get_entity_digest(self, data, chal):
Fred Drake13a2c272000-02-10 17:17:14 +0000759 # XXX not implemented yet
760 return None
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000761
Moshe Zadka8a18e992001-03-01 08:40:42 +0000762
763class 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
777class 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 Hylton6d7e47b2000-01-20 18:19:08 +0000786def encode_digest(digest):
787 hexrep = []
788 for c in digest:
Fred Drake13a2c272000-02-10 17:17:14 +0000789 n = (ord(c) >> 4) & 0xf
790 hexrep.append(hex(n)[-1])
791 n = ord(c) & 0xf
792 hexrep.append(hex(n)[-1])
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000793 return ''.join(hexrep)
Tim Peterse1190062001-01-15 03:34:38 +0000794
795
Moshe Zadka8a18e992001-03-01 08:40:42 +0000796class AbstractHTTPHandler(BaseHandler):
797
Jeremy Hylton828023b2003-05-04 23:44:49 +0000798 # XXX Should rewrite do_open() to use the new httplib interface,
799 # would would be a little simpler.
800
Moshe Zadka8a18e992001-03-01 08:40:42 +0000801 def do_open(self, http_class, req):
Moshe Zadka76676802001-04-11 07:44:53 +0000802 host = req.get_host()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000803 if not host:
804 raise URLError('no host given')
805
Jeremy Hylton828023b2003-05-04 23:44:49 +0000806 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 Peterse1190062001-01-15 03:34:38 +0000817
Jeremy Hylton144dea32002-07-07 16:57:35 +0000818 scheme, sel = splittype(req.get_selector())
819 sel_host, sel_path = splithost(sel)
820 h.putheader('Host', sel_host or host)
Brett Cannon783eaf42003-06-17 21:52:34 +0000821 for name, value in self.parent.addheaders:
822 name = name.capitalize()
Jeremy Hylton96f11292002-10-11 17:26:46 +0000823 if name not in req.headers:
Brett Cannon783eaf42003-06-17 21:52:34 +0000824 h.putheader(name, value)
Brett Cannondf0d87a2003-05-18 02:25:07 +0000825 for k, v in req.headers.items():
Fred Drake13a2c272000-02-10 17:17:14 +0000826 h.putheader(k, v)
Jeremy Hyltonf6b444e2003-05-05 01:47:13 +0000827 # httplib will attempt to connect() here. be prepared
828 # to convert a socket error to a URLError.
Jeremy Hylton828023b2003-05-04 23:44:49 +0000829 try:
830 h.endheaders()
831 except socket.error, err:
832 raise URLError(err)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000833 if req.has_data():
Fred Drakeec3dfde2001-07-04 05:18:29 +0000834 h.send(data)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000835
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 Hylton6d7e47b2000-01-20 18:19:08 +0000841 return self.parent.error('http', req, fp, code, msg, hdrs)
842
Moshe Zadka8a18e992001-03-01 08:40:42 +0000843
844class HTTPHandler(AbstractHTTPHandler):
845
846 def http_open(self, req):
847 return self.do_open(httplib.HTTP, req)
848
849
850if 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 Hylton6d7e47b2000-01-20 18:19:08 +0000857class UnknownHandler(BaseHandler):
858 def unknown_open(self, req):
Fred Drake13a2c272000-02-10 17:17:14 +0000859 type = req.get_type()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000860 raise URLError('unknown url type: %s' % type)
861
862def 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. Raymondb08b2d32001-02-09 11:10:16 +0000866 k, v = elt.split('=', 1)
Fred Drake13a2c272000-02-10 17:17:14 +0000867 if v[0] == '"' and v[-1] == '"':
868 v = v[1:-1]
869 parsed[k] = v
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000870 return parsed
871
872def 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 Drake13a2c272000-02-10 17:17:14 +0000887 cur = s[i:]
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000888 c = cur.find(',')
889 q = cur.find('"')
Fred Drake13a2c272000-02-10 17:17:14 +0000890 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 Peterse1190062001-01-15 03:34:38 +0000907 i = i + q
Fred Drake13a2c272000-02-10 17:17:14 +0000908 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. Raymondb08b2d32001-02-09 11:10:16 +0000916 return map(lambda x: x.strip(), list)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000917
918class FileHandler(BaseHandler):
919 # Use local file or FTP depending on form of URL
920 def file_open(self, req):
Fred Drake13a2c272000-02-10 17:17:14 +0000921 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 Hylton6d7e47b2000-01-20 18:19:08 +0000927
928 # names for the localhost
929 names = None
930 def get_names(self):
Fred Drake13a2c272000-02-10 17:17:14 +0000931 if FileHandler.names is None:
Tim Peterse1190062001-01-15 03:34:38 +0000932 FileHandler.names = (socket.gethostbyname('localhost'),
Fred Drake13a2c272000-02-10 17:17:14 +0000933 socket.gethostbyname(socket.gethostname()))
934 return FileHandler.names
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000935
936 # not entirely sure what the rules are here
937 def open_local_file(self, req):
Fred Drake13a2c272000-02-10 17:17:14 +0000938 host = req.get_host()
939 file = req.get_selector()
Jeremy Hylton6d8c1aa2001-08-27 20:16:53 +0000940 localfile = url2pathname(file)
941 stats = os.stat(localfile)
Martin v. Löwis9d3eba82002-03-18 08:37:19 +0000942 size = stats.st_size
943 modified = rfc822.formatdate(stats.st_mtime)
Jeremy Hylton6d8c1aa2001-08-27 20:16:53 +0000944 mtype = mimetypes.guess_type(file)[0]
Jeremy Hylton6d8c1aa2001-08-27 20:16:53 +0000945 headers = mimetools.Message(StringIO(
Brett Cannon783eaf42003-06-17 21:52:34 +0000946 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
Jeremy Hylton6d8c1aa2001-08-27 20:16:53 +0000947 (mtype or 'text/plain', size, modified)))
Fred Drake13a2c272000-02-10 17:17:14 +0000948 if host:
949 host, port = splitport(host)
950 if not host or \
951 (not port and socket.gethostbyname(host) in self.get_names()):
Jeremy Hylton6d8c1aa2001-08-27 20:16:53 +0000952 return addinfourl(open(localfile, 'rb'),
Fred Drake13a2c272000-02-10 17:17:14 +0000953 headers, 'file:'+file)
954 raise URLError('file not on local host')
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +0000955
956class FTPHandler(BaseHandler):
957 def ftp_open(self, req):
Fred Drake13a2c272000-02-10 17:17:14 +0000958 host = req.get_host()
959 if not host:
960 raise IOError, ('ftp error', 'no host given')
961 # XXX handle custom username & password
Jeremy Hylton73574ee2000-10-12 18:54:18 +0000962 try:
963 host = socket.gethostbyname(host)
964 except socket.error, msg:
965 raise URLError(msg)
Fred Drake13a2c272000-02-10 17:17:14 +0000966 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. Raymondb08b2d32001-02-09 11:10:16 +0000971 dirs = path.split('/')
Fred Drake13a2c272000-02-10 17:17:14 +0000972 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. Raymondb08b2d32001-02-09 11:10:16 +0000981 if attr.lower() == 'type' and \
Fred Drake13a2c272000-02-10 17:17:14 +0000982 value in ('a', 'A', 'i', 'I', 'd', 'D'):
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000983 type = value.upper()
Fred Drake13a2c272000-02-10 17:17:14 +0000984 fp, retrlen = fw.retrfile(file, type)
Guido van Rossum833a8d82001-08-24 13:10:13 +0000985 headers = ""
986 mtype = mimetypes.guess_type(req.get_full_url())[0]
987 if mtype:
Brett Cannon783eaf42003-06-17 21:52:34 +0000988 headers += "Content-type: %s\n" % mtype
Fred Drake13a2c272000-02-10 17:17:14 +0000989 if retrlen is not None and retrlen >= 0:
Brett Cannon783eaf42003-06-17 21:52:34 +0000990 headers += "Content-length: %d\n" % retrlen
Guido van Rossum833a8d82001-08-24 13:10:13 +0000991 sf = StringIO(headers)
992 headers = mimetools.Message(sf)
Fred Drake13a2c272000-02-10 17:17:14 +0000993 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 Hylton6d7e47b2000-01-20 18:19:08 +0000996
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
1002class 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 Drake13a2c272000-02-10 17:17:14 +00001010 self.max_conns = 16
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001011
1012 def setTimeout(self, t):
1013 self.delay = t
1014
1015 def setMaxConns(self, m):
Fred Drake13a2c272000-02-10 17:17:14 +00001016 self.max_conns = m
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001017
1018 def connect_ftp(self, user, passwd, host, port, dirs):
1019 key = user, passwd, host, port
Raymond Hettinger54f02222002-06-01 14:18:47 +00001020 if key in self.cache:
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001021 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 Drake13a2c272000-02-10 17:17:14 +00001025 self.check_cache()
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001026 return self.cache[key]
1027
1028 def check_cache(self):
Fred Drake13a2c272000-02-10 17:17:14 +00001029 # first check for old ones
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001030 t = time.time()
1031 if self.soonest <= t:
Raymond Hettinger4ec4fa22003-05-23 08:51:51 +00001032 for k, v in self.timeout.items():
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001033 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 Drake13a2c272000-02-10 17:17:14 +00001040 if len(self.cache) == self.max_conns:
Brett Cannonc8b188a2003-05-17 19:51:26 +00001041 for k, v in self.timeout.items():
Fred Drake13a2c272000-02-10 17:17:14 +00001042 if v == self.soonest:
1043 del self.cache[k]
1044 del self.timeout[k]
1045 break
1046 self.soonest = min(self.timeout.values())
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001047
1048class GopherHandler(BaseHandler):
1049 def gopher_open(self, req):
Fred Drake13a2c272000-02-10 17:17:14 +00001050 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 Hylton6d7e47b2000-01-20 18:19:08 +00001064
1065#bleck! don't use this yet
1066class OpenerFactory:
1067
1068 default_handlers = [UnknownHandler, HTTPHandler,
Tim Peterse1190062001-01-15 03:34:38 +00001069 HTTPDefaultErrorHandler, HTTPRedirectHandler,
Fred Drake13a2c272000-02-10 17:17:14 +00001070 FTPHandler, FileHandler]
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001071 handlers = []
1072 replacement_handlers = []
1073
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001074 def add_handler(self, h):
Fred Drake13a2c272000-02-10 17:17:14 +00001075 self.handlers = self.handlers + [h]
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001076
1077 def replace_handler(self, h):
Fred Drake13a2c272000-02-10 17:17:14 +00001078 pass
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001079
1080 def build_opener(self):
Jeremy Hylton54e99e82001-08-07 21:12:25 +00001081 opener = OpenerDirector()
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +00001082 for ph in self.default_handlers:
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001083 if inspect.isclass(ph):
Fred Drake13a2c272000-02-10 17:17:14 +00001084 ph = ph()
1085 opener.add_handler(ph)
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001086
1087if __name__ == "__main__":
Tim Peterse1190062001-01-15 03:34:38 +00001088 # XXX some of the test code depends on machine configurations that
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001089 # 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 Hylton73574ee2000-10-12 18:54:18 +00001093 elif socket.gethostname() == 'bitdiddle.concentric.net':
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001094 localhost = 'localhost'
1095 else:
1096 localhost = None
1097 urls = [
Fred Drake13a2c272000-02-10 17:17:14 +00001098 # 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 Hylton6d7e47b2000-01-20 18:19:08 +00001101
Fred Drake13a2c272000-02-10 17:17:14 +00001102 'file:/etc/passwd',
1103 'file://nonsensename/etc/passwd',
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001104 'ftp://www.python.org/pub/python/misc/sousa.au',
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001105 'ftp://www.python.org/pub/tmp/blat',
Fred Drake13a2c272000-02-10 17:17:14 +00001106 'http://www.espn.com/', # redirect
1107 'http://www.python.org/Spanish/Inquistion/',
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001108 ('http://www.python.org/cgi-bin/faqw.py',
Fred Drake13a2c272000-02-10 17:17:14 +00001109 'query=pythonistas&querytype=simple&casefold=yes&req=search'),
1110 'http://www.python.org/',
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001111 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC/research-reports/00README-Legal-Rules-Regs',
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001112 ]
1113
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001114## 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 Hylton6d7e47b2000-01-20 18:19:08 +00001121
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001122## 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 Peterse1190062001-01-15 03:34:38 +00001128
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001129
1130 cfh = CacheFTPHandler()
1131 cfh.setTimeout(1)
1132
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001133## # 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 Hylton6d7e47b2000-01-20 18:19:08 +00001141
Jeremy Hylton8b78b992001-10-09 16:18:45 +00001142## install_opener(build_opener(dauth, bauth, cfh, GopherHandler, ph))
1143 install_opener(build_opener(cfh, GopherHandler))
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001144
1145 for url in urls:
Walter Dörwald65230a22002-06-03 15:58:32 +00001146 if isinstance(url, tuple):
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001147 url, req = url
1148 else:
1149 req = None
1150 print url
1151 try:
1152 f = urlopen(url, req)
1153 except IOError, err:
Fred Drake13a2c272000-02-10 17:17:14 +00001154 print "IOError:", err
1155 except socket.error, err:
1156 print "socket.error:", err
Jeremy Hylton6d7e47b2000-01-20 18:19:08 +00001157 else:
1158 buf = f.read()
1159 f.close()
1160 print "read %d bytes" % len(buf)
1161 print
1162 time.sleep(0.1)