home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 December / CHIP_CD_2004-12.iso / bonus / oo / OOo_1.1.3_ru_RU_infra_WinIntel_install.exe / $PLUGINSDIR / f_0372 / python-core-2.2.2 / lib / urllib2.py < prev    next >
Text File  |  2004-10-09  |  37KB  |  1,111 lines

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