ยปCore Development>Code coverage>Lib/urllib2.py

Python code coverage for Lib/urllib2.py

#countcontent
1n/a"""An extensible library for opening URLs using a variety of protocols
2n/a
3n/aThe simplest way to use this module is to call the urlopen function,
4n/awhich accepts a string containing a URL or a Request object (described
5n/abelow). It opens the URL and returns the results as file-like
6n/aobject; the returned object has some extra methods described below.
7n/a
8n/aThe OpenerDirector manages a collection of Handler objects that do
9n/aall the actual work. Each Handler implements a particular protocol or
10n/aoption. The OpenerDirector is a composite object that invokes the
11n/aHandlers needed to open the requested URL. For example, the
12n/aHTTPHandler performs HTTP GET and POST requests and deals with
13n/anon-error returns. The HTTPRedirectHandler automatically deals with
14n/aHTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15n/adeals with digest authentication.
16n/a
17n/aurlopen(url, data=None) -- Basic usage is the same as original
18n/aurllib. pass the url and optionally data to post to an HTTP URL, and
19n/aget a file-like object back. One difference is that you can also pass
20n/aa Request instance instead of URL. Raises a URLError (subclass of
21n/aIOError); for HTTP errors, raises an HTTPError, which can also be
22n/atreated as a valid response.
23n/a
24n/abuild_opener -- Function that creates a new OpenerDirector instance.
25n/aWill install the default handlers. Accepts one or more Handlers as
26n/aarguments, either instances or Handler classes that it will
27n/ainstantiate. If one of the argument is a subclass of the default
28n/ahandler, the argument will be installed instead of the default.
29n/a
30n/ainstall_opener -- Installs a new opener as the default opener.
31n/a
32n/aobjects of interest:
33n/a
34n/aOpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
35n/athe Handler classes, while dealing with requests and responses.
36n/a
37n/aRequest -- An object that encapsulates the state of a request. The
38n/astate can be as simple as the URL. It can also include extra HTTP
39n/aheaders, e.g. a User-Agent.
40n/a
41n/aBaseHandler --
42n/a
43n/aexceptions:
44n/aURLError -- A subclass of IOError, individual protocols have their own
45n/aspecific subclass.
46n/a
47n/aHTTPError -- Also a valid HTTP response, so you can treat an HTTP error
48n/aas an exceptional event or valid response.
49n/a
50n/ainternals:
51n/aBaseHandler and parent
52n/a_call_chain conventions
53n/a
54n/aExample usage:
55n/a
56n/aimport urllib2
57n/a
58n/a# set up authentication info
59n/aauthinfo = urllib2.HTTPBasicAuthHandler()
60n/aauthinfo.add_password(realm='PDQ Application',
61n/a uri='https://mahler:8092/site-updates.py',
62n/a user='klem',
63n/a passwd='geheim$parole')
64n/a
65n/aproxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
66n/a
67n/a# build a new opener that adds authentication and caching FTP handlers
68n/aopener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
69n/a
70n/a# install it
71n/aurllib2.install_opener(opener)
72n/a
73n/af = urllib2.urlopen('http://www.python.org/')
74n/a
75n/a
761"""
77n/a
78n/a# XXX issues:
79n/a# If an authentication error handler that tries to perform
80n/a# authentication for some reason but fails, how should the error be
81n/a# signalled? The client needs to know the HTTP error code. But if
82n/a# the handler knows that the problem was, e.g., that it didn't know
83n/a# that hash algo that requested in the challenge, it would be good to
84n/a# pass that information along to the client, too.
85n/a# ftp errors aren't handled cleanly
86n/a# check digest against correct (i.e. non-apache) implementation
87n/a
88n/a# Possible extensions:
89n/a# complex proxies XXX not sure what exactly was meant by this
90n/a# abstract factory for opener
91n/a
921import base64
931import hashlib
941import httplib
951import mimetools
961import os
971import posixpath
981import random
991import re
1001import socket
1011import sys
1021import time
1031import urlparse
1041import bisect
105n/a
1061try:
1071 from cStringIO import StringIO
1080except ImportError:
1090 from StringIO import StringIO
110n/a
1111from urllib import (unwrap, unquote, splittype, splithost, quote,
112n/a addinfourl, splitport,
113n/a splitattr, ftpwrapper, splituser, splitpasswd, splitvalue)
114n/a
115n/a# support for FileHandler, proxies via environment variables
1161from urllib import localhost, url2pathname, getproxies, proxy_bypass
117n/a
118n/a# used in User-Agent header sent
1191__version__ = sys.version[:3]
120n/a
1211_opener = None
1221def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
123n/a global _opener
12435 if _opener is None:
1251 _opener = build_opener()
12635 return _opener.open(url, data, timeout)
127n/a
1281def install_opener(opener):
129n/a global _opener
1300 _opener = opener
131n/a
132n/a# do these error classes make sense?
133n/a# make sure all of the IOError stuff is overridden. we just want to be
134n/a# subtypes.
135n/a
1362class URLError(IOError):
137n/a # URLError is a sub-type of IOError, but it doesn't share any of
138n/a # the implementation. need to override __init__ and __str__.
139n/a # It sets self.args for compatibility with other EnvironmentError
140n/a # subclasses, but args doesn't have the typical format with errno in
141n/a # slot 0 and strerror in slot 1. This may be better than nothing.
1421 def __init__(self, reason):
14319 self.args = reason,
14419 self.reason = reason
145n/a
1461 def __str__(self):
1471 return '<urlopen error %s>' % self.reason
148n/a
1492class HTTPError(URLError, addinfourl):
1501 """Raised when HTTP error occurs, but also acts like non-error return"""
1511 __super_init = addinfourl.__init__
152n/a
1531 def __init__(self, url, code, msg, hdrs, fp):
1546 self.code = code
1556 self.msg = msg
1566 self.hdrs = hdrs
1576 self.fp = fp
1586 self.filename = url
159n/a # The addinfourl classes depend on fp being a valid file
160n/a # object. In some cases, the HTTPError may not have a valid
161n/a # file object. If this happens, the simplest workaround is to
162n/a # not initialize the base classes.
1636 if fp is not None:
1645 self.__super_init(fp, hdrs, url, code)
165n/a
1661 def __str__(self):
1670 return 'HTTP Error %s: %s' % (self.code, self.msg)
168n/a
169n/a# copied from cookielib.py
1701_cut_port_re = re.compile(r":\d+$")
1711def request_host(request):
172n/a """Return request-host, as defined by RFC 2965.
173n/a
174n/a Variation from RFC: returned value is lowercased, for convenient
175n/a comparison.
176n/a
177n/a """
178323 url = request.get_full_url()
179323 host = urlparse.urlparse(url)[1]
180323 if host == "":
1819 host = request.get_header("Host", "")
182n/a
183n/a # remove port, if present
184323 host = _cut_port_re.sub("", host, 1)
185323 return host.lower()
186n/a
1872class Request:
188n/a
1891 def __init__(self, url, data=None, headers={},
1901 origin_req_host=None, unverifiable=False):
191n/a # unwrap('<URL:type://host/path>') --> 'type://host/path'
192350 self.__original = unwrap(url)
193350 self.type = None
194n/a # self.__r_type is what's left after doing the splittype
195350 self.host = None
196350 self.port = None
197350 self._tunnel_host = None
198350 self.data = data
199350 self.headers = {}
200391 for key, value in headers.items():
20141 self.add_header(key, value)
202350 self.unredirected_hdrs = {}
203350 if origin_req_host is None:
204323 origin_req_host = request_host(self)
205350 self.origin_req_host = origin_req_host
206350 self.unverifiable = unverifiable
207n/a
2081 def __getattr__(self, attr):
209n/a # XXX this is a fallback mechanism to guard against these
210n/a # methods getting called in a non-standard order. this may be
211n/a # too complicated and/or unnecessary.
212n/a # XXX should the __r_XXX attributes be public?
213142 if attr[:12] == '_Request__r_':
21475 name = attr[12:]
21575 if hasattr(Request, 'get_' + name):
21675 getattr(self, 'get_' + name)()
21775 return getattr(self, attr)
21867 raise AttributeError, attr
219n/a
2201 def get_method(self):
22192 if self.has_data():
22210 return "POST"
223n/a else:
22482 return "GET"
225n/a
226n/a # XXX these helper methods are lame
227n/a
2281 def add_data(self, data):
2291 self.data = data
230n/a
2311 def has_data(self):
232155 return self.data is not None
233n/a
2341 def get_data(self):
23511 return self.data
236n/a
2371 def get_full_url(self):
2381100 return self.__original
239n/a
2401 def get_type(self):
241247 if self.type is None:
242127 self.type, self.__r_type = splittype(self.__original)
243127 if self.type is None:
2441 raise ValueError, "unknown url type: %s" % self.__original
245246 return self.type
246n/a
2471 def get_host(self):
248199 if self.host is None:
249105 self.host, self.__r_host = splithost(self.__r_type)
250105 if self.host:
25197 self.host = unquote(self.host)
252199 return self.host
253n/a
2541 def get_selector(self):
255116 return self.__r_host
256n/a
2571 def set_proxy(self, host, type):
25823 if self.type == 'https' and not self._tunnel_host:
2592 self._tunnel_host = self.host
260n/a else:
26121 self.type = type
26221 self.__r_host = self.__original
263n/a
26423 self.host = host
265n/a
2661 def has_proxy(self):
26755 return self.__r_host == self.__original
268n/a
2691 def get_origin_req_host(self):
27027 return self.origin_req_host
271n/a
2721 def is_unverifiable(self):
273244 return self.unverifiable
274n/a
2751 def add_header(self, key, val):
276n/a # useful for something like authentication
27756 self.headers[key.capitalize()] = val
278n/a
2791 def add_unredirected_header(self, key, val):
280n/a # will not be added to a redirected request
281205 self.unredirected_hdrs[key.capitalize()] = val
282n/a
2831 def has_header(self, header_name):
284307 return (header_name in self.headers or
285306 header_name in self.unredirected_hdrs)
286n/a
2871 def get_header(self, header_name, default=None):
288167 return self.headers.get(
289167 header_name,
290167 self.unredirected_hdrs.get(header_name, default))
291n/a
2921 def header_items(self):
2932 hdrs = self.unredirected_hdrs.copy()
2942 hdrs.update(self.headers)
2952 return hdrs.items()
296n/a
2972class OpenerDirector:
2981 def __init__(self):
29930 client_version = "Python-urllib/%s" % __version__
30030 self.addheaders = [('User-agent', client_version)]
301n/a # manage the individual handlers
30230 self.handlers = []
30330 self.handle_open = {}
30430 self.handle_error = {}
30530 self.process_response = {}
30630 self.process_request = {}
307n/a
3081 def add_handler(self, handler):
309174 if not hasattr(handler, "add_parent"):
3101 raise TypeError("expected BaseHandler instance, got %r" %
3111 type(handler))
312n/a
313173 added = False
3142019 for meth in dir(handler):
3151846 if meth in ["redirect_request", "do_open", "proxy_open"]:
316n/a # oops, coincidental match
31767 continue
318n/a
3191779 i = meth.find("_")
3201779 protocol = meth[:i]
3211779 condition = meth[i+1:]
322n/a
3231779 if condition.startswith("error"):
32499 j = condition.find("_") + i + 1
32599 kind = meth[j+1:]
32699 try:
32799 kind = int(kind)
32825 except ValueError:
32925 pass
33099 lookup = self.handle_error.get(protocol, {})
33199 self.handle_error[protocol] = lookup
3321680 elif condition == "open":
333104 kind = protocol
334104 lookup = self.handle_open
3351576 elif condition == "response":
33632 kind = protocol
33732 lookup = self.process_response
3381544 elif condition == "request":
33933 kind = protocol
34033 lookup = self.process_request
341n/a else:
3420 continue
343n/a
344268 handlers = lookup.setdefault(kind, [])
345268 if handlers:
34621 bisect.insort(handlers, handler)
347n/a else:
348247 handlers.append(handler)
349268 added = True
350n/a
351173 if added:
352n/a # the handlers must work in an specific order, the order
353n/a # is specified in a Handler attribute
354161 bisect.insort(self.handlers, handler)
355161 handler.add_parent(self)
356n/a
3571 def close(self):
358n/a # Only exists for backwards compatibility.
3590 pass
360n/a
3611 def _call_chain(self, chain, kind, meth_name, *args):
362n/a # Handlers raise an exception if no one else should try to handle
363n/a # the request, or return None if they can't but another handler
364n/a # could. Otherwise, they return the response.
365204 handlers = chain.get(kind, ())
366238 for handler in handlers:
367125 func = getattr(handler, meth_name)
368n/a
369125 result = func(*args)
370104 if result is not None:
37170 return result
372n/a
3731 def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
374n/a # accept a URL or a Request object
37583 if isinstance(fullurl, basestring):
37660 req = Request(fullurl, data)
377n/a else:
37823 req = fullurl
37923 if data is not None:
3800 req.add_data(data)
381n/a
38283 req.timeout = timeout
38383 protocol = req.get_type()
384n/a
385n/a # pre-process request
38682 meth_name = protocol+"_request"
387127 for processor in self.process_request.get(protocol, []):
38845 meth = getattr(processor, meth_name)
38945 req = meth(req)
390n/a
39182 response = self._open(req, data)
392n/a
393n/a # post-process response
39471 meth_name = protocol+"_response"
395105 for processor in self.process_response.get(protocol, []):
39644 meth = getattr(processor, meth_name)
39744 response = meth(req, response)
398n/a
39961 return response
400n/a
4011 def _open(self, req, data=None):
40282 result = self._call_chain(self.handle_open, 'default',
40382 'default_open', req)
40482 if result:
4050 return result
406n/a
40782 protocol = req.get_type()
40882 result = self._call_chain(self.handle_open, protocol, protocol +
40982 '_open', req)
41074 if result:
41163 return result
412n/a
41311 return self._call_chain(self.handle_open, 'unknown',
41411 'unknown_open', req)
415n/a
4161 def error(self, proto, *args):
41722 if proto in ('http', 'https'):
418n/a # XXX http[s] protocols are special-cased
41922 dict = self.handle_error['http'] # https is not different than http
42022 proto = args[2] # YUCK!
42122 meth_name = 'http_error_%s' % proto
42222 http_err = 1
42322 orig_args = args
424n/a else:
4250 dict = self.handle_error
4260 meth_name = proto + '_error'
4270 http_err = 0
42822 args = (dict, proto, meth_name) + args
42922 result = self._call_chain(*args)
43014 if result:
4317 return result
432n/a
4337 if http_err:
4347 args = (dict, 'default', 'http_error_default') + orig_args
4357 return self._call_chain(*args)
436n/a
437n/a# XXX probably also want an abstract factory that knows when it makes
438n/a# sense to skip a superclass in favor of a subclass and when it might
439n/a# make sense to include both
440n/a
4411def build_opener(*handlers):
442n/a """Create an opener object from a list of handlers.
443n/a
444n/a The opener will use several default handlers, including support
445n/a for HTTP, FTP and when applicable, HTTPS.
446n/a
447n/a If any of the handlers passed as arguments are subclasses of the
448n/a default handlers, the default handlers will not be used.
449n/a """
45014 import types
45114 def isclass(obj):
452190 return isinstance(obj, (types.ClassType, type))
453n/a
45414 opener = OpenerDirector()
45514 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
45614 HTTPDefaultErrorHandler, HTTPRedirectHandler,
45714 FTPHandler, FileHandler, HTTPErrorProcessor]
45814 if hasattr(httplib, 'HTTPS'):
45914 default_classes.append(HTTPSHandler)
46014 skip = set()
461140 for klass in default_classes:
462297 for check in handlers:
463171 if isclass(check):
46463 if issubclass(check, klass):
4654 skip.add(klass)
466108 elif isinstance(check, klass):
4677 skip.add(klass)
46824 for klass in skip:
46910 default_classes.remove(klass)
470n/a
471130 for klass in default_classes:
472116 opener.add_handler(klass())
473n/a
47433 for h in handlers:
47519 if isclass(h):
4767 h = h()
47719 opener.add_handler(h)
47814 return opener
479n/a
4802class BaseHandler:
4811 handler_order = 500
482n/a
4831 def add_parent(self, parent):
484145 self.parent = parent
485n/a
4861 def close(self):
487n/a # Only exists for backwards compatibility
4880 pass
489n/a
4901 def __lt__(self, other):
491256 if not hasattr(other, "handler_order"):
492n/a # Try to preserve the old behavior of having custom classes
493n/a # inserted after default ones (works only for custom user
494n/a # classes which are not aware of handler_order).
4950 return True
496256 return self.handler_order < other.handler_order
497n/a
498n/a
4992class HTTPErrorProcessor(BaseHandler):
5001 """Process HTTP error responses."""
5011 handler_order = 1000 # after all other processing
502n/a
5031 def http_response(self, request, response):
50444 code, msg, hdrs = response.code, response.msg, response.info()
505n/a
506n/a # According to RFC 2616, "2xx" code indicates that the client's
507n/a # request was successfully received, understood, and accepted.
50844 if not (200 <= code < 300):
50913 response = self.parent.error(
51013 'http', request, response, code, msg, hdrs)
511n/a
51234 return response
513n/a
5141 https_response = http_response
515n/a
5162class HTTPDefaultErrorHandler(BaseHandler):
5171 def http_error_default(self, req, fp, code, msg, hdrs):
5182 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
519n/a
5202class HTTPRedirectHandler(BaseHandler):
521n/a # maximum number of redirections to any single URL
522n/a # this is needed because of the state that cookies introduce
5231 max_repeats = 4
524n/a # maximum total number of redirections (regardless of URL) before
525n/a # assuming we're in a loop
5261 max_redirections = 10
527n/a
5281 def redirect_request(self, req, fp, code, msg, headers, newurl):
529n/a """Return a Request or None in response to a redirect.
530n/a
531n/a This is called by the http_error_30x methods when a
532n/a redirection response is received. If a redirection should
533n/a take place, return a new Request to allow http_error_30x to
534n/a perform the redirect. Otherwise, raise HTTPError if no-one
535n/a else should try to handle this url. Return None if you can't
536n/a but another Handler might.
537n/a """
53826 m = req.get_method()
53926 if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
5404 or code in (301, 302, 303) and m == "POST"):
541n/a # Strictly (according to RFC 2616), 301 or 302 in response
542n/a # to a POST MUST NOT cause a redirection without confirmation
543n/a # from the user (of urllib2, in this case). In practice,
544n/a # essentially all clients do redirect in this case, so we
545n/a # do the same.
546n/a # be conciliant with URIs containing a space
54725 newurl = newurl.replace(' ', '%20')
54860 newheaders = dict((k,v) for k,v in req.headers.items()
54910 if k.lower() not in ("content-length", "content-type")
550n/a )
55125 return Request(newurl,
55225 headers=newheaders,
55325 origin_req_host=req.get_origin_req_host(),
55425 unverifiable=True)
555n/a else:
5561 raise HTTPError(req.get_full_url(), code, msg, headers, fp)
557n/a
558n/a # Implementation note: To avoid the server sending us into an
559n/a # infinite loop, the request object needs to track what URLs we
560n/a # have already seen. Do this by adding a handler-specific
561n/a # attribute to the Request object.
5621 def http_error_302(self, req, fp, code, msg, headers):
563n/a # Some servers (incorrectly) return multiple Location headers
564n/a # (so probably same goes for URI). Use first header.
56526 if 'location' in headers:
56626 newurl = headers.getheaders('location')[0]
5670 elif 'uri' in headers:
5680 newurl = headers.getheaders('uri')[0]
569n/a else:
5700 return
571n/a
572n/a # fix a possible malformed URL
57326 urlparts = urlparse.urlparse(newurl)
57426 if not urlparts.path:
5750 urlparts = list(urlparts)
5760 urlparts[2] = "/"
57726 newurl = urlparse.urlunparse(urlparts)
578n/a
57926 newurl = urlparse.urljoin(req.get_full_url(), newurl)
580n/a
581n/a # XXX Probably want to forget about the state of the current
582n/a # request, although that might interact poorly with other
583n/a # handlers that also use handler-specific request attributes
58426 new = self.redirect_request(req, fp, code, msg, headers, newurl)
58525 if new is None:
5860 return
587n/a
588n/a # loop detection
589n/a # .redirect_dict has a key url if url was previously visited.
59025 if hasattr(req, 'redirect_dict'):
59114 visited = new.redirect_dict = req.redirect_dict
59214 if (visited.get(newurl, 0) >= self.max_repeats or
59313 len(visited) >= self.max_redirections):
5942 raise HTTPError(req.get_full_url(), code,
5952 self.inf_msg + msg, headers, fp)
596n/a else:
59711 visited = new.redirect_dict = req.redirect_dict = {}
59823 visited[newurl] = visited.get(newurl, 0) + 1
599n/a
600n/a # Don't close the fp until we are sure that we won't use it
601n/a # with HTTPError.
60223 fp.read()
60323 fp.close()
604n/a
60523 return self.parent.open(new, timeout=req.timeout)
606n/a
6071 http_error_301 = http_error_303 = http_error_307 = http_error_302
608n/a
6091 inf_msg = "The HTTP server returned a redirect error that would " \
610n/a "lead to an infinite loop.\n" \
611n/a "The last 30x error message was:\n"
612n/a
613n/a
6141def _parse_proxy(proxy):
615n/a """Return (scheme, user, password, host/port) given a URL or an authority.
616n/a
617n/a If a URL is supplied, it must have an authority (host:port) component.
618n/a According to RFC 3986, having an authority component means the URL must
619n/a have two slashes after the scheme:
620n/a
621n/a >>> _parse_proxy('file:/ftp.example.com/')
622n/a Traceback (most recent call last):
623n/a ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
624n/a
625n/a The first three items of the returned tuple may be None.
626n/a
627n/a Examples of authority parsing:
628n/a
629n/a >>> _parse_proxy('proxy.example.com')
630n/a (None, None, None, 'proxy.example.com')
631n/a >>> _parse_proxy('proxy.example.com:3128')
632n/a (None, None, None, 'proxy.example.com:3128')
633n/a
634n/a The authority component may optionally include userinfo (assumed to be
635n/a username:password):
636n/a
637n/a >>> _parse_proxy('joe:password@proxy.example.com')
638n/a (None, 'joe', 'password', 'proxy.example.com')
639n/a >>> _parse_proxy('joe:password@proxy.example.com:3128')
640n/a (None, 'joe', 'password', 'proxy.example.com:3128')
641n/a
642n/a Same examples, but with URLs instead:
643n/a
644n/a >>> _parse_proxy('http://proxy.example.com/')
645n/a ('http', None, None, 'proxy.example.com')
646n/a >>> _parse_proxy('http://proxy.example.com:3128/')
647n/a ('http', None, None, 'proxy.example.com:3128')
648n/a >>> _parse_proxy('http://joe:password@proxy.example.com/')
649n/a ('http', 'joe', 'password', 'proxy.example.com')
650n/a >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
651n/a ('http', 'joe', 'password', 'proxy.example.com:3128')
652n/a
653n/a Everything after the authority is ignored:
654n/a
655n/a >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
656n/a ('ftp', 'joe', 'password', 'proxy.example.com')
657n/a
658n/a Test for no trailing '/' case:
659n/a
660n/a >>> _parse_proxy('http://joe:password@proxy.example.com')
661n/a ('http', 'joe', 'password', 'proxy.example.com')
662n/a
663n/a """
66430 scheme, r_scheme = splittype(proxy)
66530 if not r_scheme.startswith("/"):
666n/a # authority
66712 scheme = None
66812 authority = proxy
669n/a else:
670n/a # URL
67118 if not r_scheme.startswith("//"):
6721 raise ValueError("proxy URL with no authority: %r" % proxy)
673n/a # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
674n/a # and 3.3.), path is empty or starts with '/'
67517 end = r_scheme.find("/", 2)
67617 if end == -1:
67713 end = None
67817 authority = r_scheme[2:end]
67929 userinfo, hostport = splituser(authority)
68029 if userinfo is not None:
6816 user, password = splitpasswd(userinfo)
682n/a else:
68323 user = password = None
68429 return scheme, user, password, hostport
685n/a
6862class ProxyHandler(BaseHandler):
687n/a # Proxies must be in front
6881 handler_order = 100
689n/a
6901 def __init__(self, proxies=None):
69119 if proxies is None:
69210 proxies = getproxies()
69319 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
69419 self.proxies = proxies
69528 for type, url in proxies.items():
6969 setattr(self, '%s_open' % type,
6979 lambda r, proxy=url, type=type, meth=self.proxy_open: \
69819 meth(r, proxy, type))
699n/a
7001 def proxy_open(self, req, proxy, type):
70119 orig_type = req.get_type()
70219 proxy_type, user, password, hostport = _parse_proxy(proxy)
703n/a
70419 if proxy_type is None:
7058 proxy_type = orig_type
706n/a
70719 if req.host and proxy_bypass(req.host):
7081 return None
709n/a
71018 if user and password:
7110 user_pass = '%s:%s' % (unquote(user), unquote(password))
7120 creds = base64.b64encode(user_pass).strip()
7130 req.add_header('Proxy-authorization', 'Basic ' + creds)
71418 hostport = unquote(hostport)
71518 req.set_proxy(hostport, proxy_type)
716n/a
71718 if orig_type == proxy_type or orig_type == 'https':
718n/a # let other handlers take care of it
71918 return None
720n/a else:
721n/a # need to start over, because the other handlers don't
722n/a # grok the proxy's URL type
723n/a # e.g. if we have a constructor arg proxies like so:
724n/a # {'http': 'ftp://proxy.example.com'}, we may end up turning
725n/a # a request for http://acme.example.com/a into one for
726n/a # ftp://proxy.example.com/a
7270 return self.parent.open(req, timeout=req.timeout)
728n/a
7292class HTTPPasswordMgr:
730n/a
7311 def __init__(self):
73211 self.passwd = {}
733n/a
7341 def add_password(self, realm, uri, user, passwd):
735n/a # uri could be a single URI or a sequence
73620 if isinstance(uri, basestring):
73720 uri = [uri]
73820 if not realm in self.passwd:
73914 self.passwd[realm] = {}
74060 for default_port in True, False:
74140 reduced_uri = tuple(
74280 [self.reduce_uri(u, default_port) for u in uri])
74340 self.passwd[realm][reduced_uri] = (user, passwd)
744n/a
7451 def find_user_password(self, realm, authuri):
74640 domains = self.passwd.get(realm, {})
74759 for default_port in True, False:
74850 reduced_authuri = self.reduce_uri(authuri, default_port)
749130 for uris, authinfo in domains.iteritems():
750191 for uri in uris:
751111 if self.is_suburi(uri, reduced_authuri):
75231 return authinfo
7539 return None, None
754n/a
7551 def reduce_uri(self, uri, default_port=True):
756n/a """Accept authority or URI and extract only the authority and path."""
757n/a # note HTTP URLs do not have a userinfo component
75890 parts = urlparse.urlsplit(uri)
75990 if parts[1]:
760n/a # URI
76157 scheme = parts[0]
76257 authority = parts[1]
76357 path = parts[2] or '/'
764n/a else:
765n/a # host or host:port
76633 scheme = None
76733 authority = uri
76833 path = '/'
76990 host, port = splitport(authority)
77090 if default_port and port is None and scheme is not None:
77131 dport = {"http": 80,
77231 "https": 443,
77331 }.get(scheme)
77431 if dport is not None:
77531 authority = "%s:%d" % (host, dport)
77690 return authority, path
777n/a
7781 def is_suburi(self, base, test):
779n/a """Check if test is below base in a URI tree
780n/a
781n/a Both args must be URIs in reduced form.
782n/a """
783111 if base == test:
78429 return True
78582 if base[0] != test[0]:
78675 return False
7877 common = posixpath.commonprefix((base[1], test[1]))
7887 if len(common) == len(base[1]):
7892 return True
7905 return False
791n/a
792n/a
7932class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
794n/a
7951 def find_user_password(self, realm, authuri):
7960 user, password = HTTPPasswordMgr.find_user_password(self, realm,
7970 authuri)
7980 if user is not None:
7990 return user, password
8000 return HTTPPasswordMgr.find_user_password(self, None, authuri)
801n/a
802n/a
8032class AbstractBasicAuthHandler:
804n/a
805n/a # XXX this allows for multiple auth-schemes, but will stupidly pick
806n/a # the last one with a realm specified.
807n/a
808n/a # allow for double- and single-quoted realm values
809n/a # (single quotes are a violation of the RFC, but appear in the wild)
8101 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
8111 'realm=(["\'])(.*?)\\2', re.I)
812n/a
813n/a # XXX could pre-emptively send auth info already accepted (RFC 2617,
814n/a # end of section 2, and section 1.2 immediately after "credentials"
815n/a # production).
816n/a
8171 def __init__(self, password_mgr=None):
8189 if password_mgr is None:
8192 password_mgr = HTTPPasswordMgr()
8209 self.passwd = password_mgr
8219 self.add_password = self.passwd.add_password
8229 self.retried = 0
823n/a
8241 def http_error_auth_reqed(self, authreq, host, req, headers):
825n/a # host may be an authority (without userinfo) or a URL with an
826n/a # authority
827n/a # XXX could be multiple headers
8288 authreq = headers.get(authreq, None)
829n/a
8308 if self.retried > 5:
831n/a # retry sending the username:password 5 times before failing.
8320 raise HTTPError(req.get_full_url(), 401, "basic auth failed",
8330 headers, None)
834n/a else:
8358 self.retried += 1
836n/a
8378 if authreq:
8388 mo = AbstractBasicAuthHandler.rx.search(authreq)
8398 if mo:
8408 scheme, quote, realm = mo.groups()
8418 if scheme.lower() == 'basic':
8428 return self.retry_http_basic_auth(host, req, realm)
843n/a
8441 def retry_http_basic_auth(self, host, req, realm):
8458 user, pw = self.passwd.find_user_password(realm, host)
8468 if pw is not None:
8474 raw = "%s:%s" % (user, pw)
8484 auth = 'Basic %s' % base64.b64encode(raw).strip()
8494 if req.headers.get(self.auth_header, None) == auth:
8500 return None
8514 req.add_unredirected_header(self.auth_header, auth)
8524 return self.parent.open(req, timeout=req.timeout)
853n/a else:
8544 return None
855n/a
856n/a
8572class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
858n/a
8591 auth_header = 'Authorization'
860n/a
8611 def http_error_401(self, req, fp, code, msg, headers):
8626 url = req.get_full_url()
8636 return self.http_error_auth_reqed('www-authenticate',
8646 url, req, headers)
865n/a
866n/a
8672class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
868n/a
8691 auth_header = 'Proxy-authorization'
870n/a
8711 def http_error_407(self, req, fp, code, msg, headers):
872n/a # http_error_auth_reqed requires that there is no userinfo component in
873n/a # authority. Assume there isn't one, since urllib2 does not (and
874n/a # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
875n/a # userinfo.
8762 authority = req.get_host()
8772 return self.http_error_auth_reqed('proxy-authenticate',
8782 authority, req, headers)
879n/a
880n/a
8811def randombytes(n):
882n/a """Return n random bytes."""
883n/a # Use /dev/urandom if it is available. Fall back to random module
884n/a # if not. It might be worthwhile to extend this function to use
885n/a # other platform-specific mechanisms for getting random bytes.
8867 if os.path.exists("/dev/urandom"):
8877 f = open("/dev/urandom")
8887 s = f.read(n)
8897 f.close()
8907 return s
891n/a else:
8920 L = [chr(random.randrange(0, 256)) for i in range(n)]
8930 return "".join(L)
894n/a
8952class AbstractDigestAuthHandler:
896n/a # Digest authentication is specified in RFC 2617.
897n/a
898n/a # XXX The client does not inspect the Authentication-Info header
899n/a # in a successful response.
900n/a
901n/a # XXX It should be possible to test this implementation against
902n/a # a mock server that just generates a static set of challenges.
903n/a
904n/a # XXX qop="auth-int" supports is shaky
905n/a
9061 def __init__(self, passwd=None):
9075 if passwd is None:
9084 passwd = HTTPPasswordMgr()
9095 self.passwd = passwd
9105 self.add_password = self.passwd.add_password
9115 self.retried = 0
9125 self.nonce_count = 0
9135 self.last_nonce = None
914n/a
9151 def reset_retry_count(self):
9164 self.retried = 0
917n/a
9181 def http_error_auth_reqed(self, auth_header, host, req, headers):
91912 authreq = headers.get(auth_header, None)
92012 if self.retried > 5:
921n/a # Don't fail endlessly - if we failed once, we'll probably
922n/a # fail a second time. Hm. Unless the Password Manager is
923n/a # prompting for the information. Crap. This isn't great
924n/a # but it's better than the current 'repeat until recursion
925n/a # depth exceeded' approach <wink>
9261 raise HTTPError(req.get_full_url(), 401, "digest auth failed",
9271 headers, None)
928n/a else:
92911 self.retried += 1
93011 if authreq:
93111 scheme = authreq.split()[0]
93211 if scheme.lower() == 'digest':
9339 return self.retry_http_digest_auth(req, authreq)
934n/a
9351 def retry_http_digest_auth(self, req, auth):
9369 token, challenge = auth.split(' ', 1)
9379 chal = parse_keqv_list(parse_http_list(challenge))
9389 auth = self.get_authorization(req, chal)
9398 if auth:
9407 auth_val = 'Digest %s' % auth
9417 if req.headers.get(self.auth_header, None) == auth_val:
9420 return None
9437 req.add_unredirected_header(self.auth_header, auth_val)
9447 resp = self.parent.open(req, timeout=req.timeout)
9451 return resp
946n/a
9471 def get_cnonce(self, nonce):
948n/a # The cnonce-value is an opaque
949n/a # quoted string value provided by the client and used by both client
950n/a # and server to avoid chosen plaintext attacks, to provide mutual
951n/a # authentication, and to provide some message integrity protection.
952n/a # This isn't a fabulous effort, but it's probably Good Enough.
9537 dig = hashlib.sha1("%s:%s:%s:%s" % (self.nonce_count, nonce, time.ctime(),
9547 randombytes(8))).hexdigest()
9557 return dig[:16]
956n/a
9571 def get_authorization(self, req, chal):
9589 try:
9599 realm = chal['realm']
9609 nonce = chal['nonce']
9619 qop = chal.get('qop')
9629 algorithm = chal.get('algorithm', 'MD5')
963n/a # mod_digest doesn't send an opaque, even though it isn't
964n/a # supposed to be optional
9659 opaque = chal.get('opaque', None)
9660 except KeyError:
9670 return None
968n/a
9699 H, KD = self.get_algorithm_impls(algorithm)
9709 if H is None:
9710 return None
972n/a
9739 user, pw = self.passwd.find_user_password(realm, req.get_full_url())
9749 if user is None:
9751 return None
976n/a
977n/a # XXX not implemented yet
9788 if req.has_data():
9790 entdig = self.get_entity_digest(req.get_data(), chal)
980n/a else:
9818 entdig = None
982n/a
9838 A1 = "%s:%s:%s" % (user, realm, pw)
9848 A2 = "%s:%s" % (req.get_method(),
985n/a # XXX selector: what about proxies and full urls
9868 req.get_selector())
9878 if qop == 'auth':
9887 if nonce == self.last_nonce:
9890 self.nonce_count += 1
990n/a else:
9917 self.nonce_count = 1
9927 self.last_nonce = nonce
993n/a
9947 ncvalue = '%08x' % self.nonce_count
9957 cnonce = self.get_cnonce(nonce)
9967 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
9977 respdig = KD(H(A1), noncebit)
9981 elif qop is None:
9990 respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
1000n/a else:
1001n/a # XXX handle auth-int.
10021 raise URLError("qop '%s' is not supported." % qop)
1003n/a
1004n/a # XXX should the partial digests be encoded too?
1005n/a
10067 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
10077 'response="%s"' % (user, realm, nonce, req.get_selector(),
10087 respdig)
10097 if opaque:
10100 base += ', opaque="%s"' % opaque
10117 if entdig:
10120 base += ', digest="%s"' % entdig
10137 base += ', algorithm="%s"' % algorithm
10147 if qop:
10157 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
10167 return base
1017n/a
10181 def get_algorithm_impls(self, algorithm):
1019n/a # algorithm should be case-insensitive according to RFC2617
10209 algorithm = algorithm.upper()
1021n/a # lambdas assume digest modules are imported at the top level
10229 if algorithm == 'MD5':
102330 H = lambda x: hashlib.md5(x).hexdigest()
10240 elif algorithm == 'SHA':
10250 H = lambda x: hashlib.sha1(x).hexdigest()
1026n/a # XXX MD5-sess
102716 KD = lambda s, d: H("%s:%s" % (s, d))
10289 return H, KD
1029n/a
10301 def get_entity_digest(self, data, chal):
1031n/a # XXX not implemented yet
10320 return None
1033n/a
1034n/a
10352class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1036n/a """An authentication protocol defined by RFC 2069
1037n/a
1038n/a Digest authentication improves on basic authentication because it
1039n/a does not transmit passwords in the clear.
10401 """
1041n/a
10421 auth_header = 'Authorization'
10431 handler_order = 490 # before Basic auth
1044n/a
10451 def http_error_401(self, req, fp, code, msg, headers):
10462 host = urlparse.urlparse(req.get_full_url())[1]
10472 retry = self.http_error_auth_reqed('www-authenticate',
10482 host, req, headers)
10492 self.reset_retry_count()
10502 return retry
1051n/a
1052n/a
10532class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1054n/a
10551 auth_header = 'Proxy-Authorization'
10561 handler_order = 490 # before Basic auth
1057n/a
10581 def http_error_407(self, req, fp, code, msg, headers):
105910 host = req.get_host()
106010 retry = self.http_error_auth_reqed('proxy-authenticate',
106110 host, req, headers)
10622 self.reset_retry_count()
10632 return retry
1064n/a
10652class AbstractHTTPHandler(BaseHandler):
1066n/a
10671 def __init__(self, debuglevel=0):
106832 self._debuglevel = debuglevel
1069n/a
10701 def set_http_debuglevel(self, level):
10710 self._debuglevel = level
1072n/a
10731 def do_request_(self, request):
107453 host = request.get_host()
107553 if not host:
10760 raise URLError('no host given')
1077n/a
107853 if request.has_data(): # POST
107911 data = request.get_data()
108011 if not request.has_header('Content-type'):
10816 request.add_unredirected_header(
10826 'Content-type',
10836 'application/x-www-form-urlencoded')
108411 if not request.has_header('Content-length'):
10856 request.add_unredirected_header(
10866 'Content-length', '%d' % len(data))
1087n/a
108853 sel_host = host
108953 if request.has_proxy():
109011 scheme, sel = splittype(request.get_selector())
109111 sel_host, sel_path = splithost(sel)
1092n/a
109353 if not request.has_header('Host'):
109440 request.add_unredirected_header('Host', sel_host)
109598 for name, value in self.parent.addheaders:
109645 name = name.capitalize()
109745 if not request.has_header(name):
109836 request.add_unredirected_header(name, value)
1099n/a
110053 return request
1101n/a
11021 def do_open(self, http_class, req):
1103n/a """Return an addinfourl object for the request, using http_class.
1104n/a
1105n/a http_class must implement the HTTPConnection API from httplib.
1106n/a The addinfourl return value is a file-like object. It also
1107n/a has methods and attributes including:
1108n/a - info(): return a mimetools.Message object for the headers
1109n/a - geturl(): return the original request URL
1110n/a - code: HTTP status code
1111n/a """
111245 host = req.get_host()
111345 if not host:
11140 raise URLError('no host given')
1115n/a
111645 h = http_class(host, timeout=req.timeout) # will parse host:port
111745 h.set_debuglevel(self._debuglevel)
1118n/a
111945 headers = dict(req.headers)
112045 headers.update(req.unredirected_hdrs)
1121n/a # We want to make an HTTP/1.1 request, but the addinfourl
1122n/a # class isn't prepared to deal with a persistent connection.
1123n/a # It will try to read all remaining data from the socket,
1124n/a # which will block while the server waits for the next request.
1125n/a # So make sure the connection gets closed after the (only)
1126n/a # request.
112745 headers["Connection"] = "close"
112845 headers = dict(
1129235 (name.title(), val) for name, val in headers.items())
1130n/a
113145 if req._tunnel_host:
11321 tunnel_headers = {}
11331 proxy_auth_hdr = "Proxy-Authorization"
11341 if proxy_auth_hdr in headers:
11351 tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1136n/a # Proxy-Authorization should not be sent to origin
1137n/a # server.
11381 del headers[proxy_auth_hdr]
11391 h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
1140n/a
114145 try:
114245 h.request(req.get_method(), req.get_selector(), req.data, headers)
114343 try:
114443 r = h.getresponse(buffering=True)
11453 except TypeError: #buffering kw not supported
11463 r = h.getresponse()
11472 except socket.error, err: # XXX what error?
11482 raise URLError(err)
1149n/a
1150n/a # Pick apart the HTTPResponse object to get the addinfourl
1151n/a # object initialized properly.
1152n/a
1153n/a # Wrap the HTTPResponse object in socket's file object adapter
1154n/a # for Windows. That adapter calls recv(), so delegate recv()
1155n/a # to read(). This weird wrapping allows the returned object to
1156n/a # have readline() and readlines() methods.
1157n/a
1158n/a # XXX It might be better to extract the read buffering code
1159n/a # out of socket._fileobject() and into a base class.
1160n/a
116143 r.recv = r.read
116243 fp = socket._fileobject(r, close=True)
1163n/a
116443 resp = addinfourl(fp, r.msg, req.get_full_url())
116543 resp.code = r.status
116643 resp.msg = r.reason
116743 return resp
1168n/a
1169n/a
11702class HTTPHandler(AbstractHTTPHandler):
1171n/a
11721 def http_open(self, req):
117341 return self.do_open(httplib.HTTPConnection, req)
1174n/a
11751 http_request = AbstractHTTPHandler.do_request_
1176n/a
11771if hasattr(httplib, 'HTTPS'):
11782 class HTTPSHandler(AbstractHTTPHandler):
1179n/a
11801 def https_open(self, req):
11810 return self.do_open(httplib.HTTPSConnection, req)
1182n/a
11831 https_request = AbstractHTTPHandler.do_request_
1184n/a
11852class HTTPCookieProcessor(BaseHandler):
11861 def __init__(self, cookiejar=None):
11872 import cookielib
11882 if cookiejar is None:
11890 cookiejar = cookielib.CookieJar()
11902 self.cookiejar = cookiejar
1191n/a
11921 def http_request(self, request):
11933 self.cookiejar.add_cookie_header(request)
11943 return request
1195n/a
11961 def http_response(self, request, response):
11973 self.cookiejar.extract_cookies(response, request)
11983 return response
1199n/a
12001 https_request = http_request
12011 https_response = http_response
1202n/a
12032class UnknownHandler(BaseHandler):
12041 def unknown_open(self, req):
12053 type = req.get_type()
12063 raise URLError('unknown url type: %s' % type)
1207n/a
12081def parse_keqv_list(l):
1209n/a """Parse list of key=value strings where keys are not duplicated."""
12109 parsed = {}
121136 for elt in l:
121227 k, v = elt.split('=', 1)
121327 if v[0] == '"' and v[-1] == '"':
121427 v = v[1:-1]
121527 parsed[k] = v
12169 return parsed
1217n/a
12181def parse_http_list(s):
1219n/a """Parse lists as described by RFC 2068 Section 2.
1220n/a
1221n/a In particular, parse comma-separated lists where the elements of
1222n/a the list may include quoted-strings. A quoted-string could
1223n/a contain a comma. A non-quoted string could have quotes in the
1224n/a middle. Neither commas nor quotes count if they are escaped.
1225n/a Only double-quotes count, not single-quotes.
1226n/a """
122713 res = []
122813 part = ''
1229n/a
123013 escape = quote = False
1231742 for cur in s:
1232729 if escape:
12333 part += cur
12343 escape = False
12353 continue
1236726 if quote:
1237462 if cur == '\\':
12383 escape = True
12393 continue
1240459 elif cur == '"':
124135 quote = False
1242459 part += cur
1243459 continue
1244n/a
1245264 if cur == ',':
124638 res.append(part)
124738 part = ''
124838 continue
1249n/a
1250226 if cur == '"':
125135 quote = True
1252n/a
1253226 part += cur
1254n/a
1255n/a # append last part
125613 if part:
12574 res.append(part)
1258n/a
125955 return [part.strip() for part in res]
1260n/a
12612class FileHandler(BaseHandler):
1262n/a # Use local file or FTP depending on form of URL
12631 def file_open(self, req):
126416 url = req.get_selector()
126516 if url[:2] == '//' and url[2:3] != '/':
12661 req.type = 'ftp'
12671 return self.parent.open(req)
1268n/a else:
126915 return self.open_local_file(req)
1270n/a
1271n/a # names for the localhost
12721 names = None
12731 def get_names(self):
12744 if FileHandler.names is None:
12751 try:
12761 FileHandler.names = tuple(
12771 socket.gethostbyname_ex('localhost')[2] +
12781 socket.gethostbyname_ex(socket.gethostname())[2])
12790 except socket.gaierror:
12800 FileHandler.names = (socket.gethostbyname('localhost'),)
12814 return FileHandler.names
1282n/a
1283n/a # not entirely sure what the rules are here
12841 def open_local_file(self, req):
128515 import email.utils
128615 import mimetypes
128715 host = req.get_host()
128815 filename = req.get_selector()
128915 localfile = url2pathname(filename)
129015 try:
129115 stats = os.stat(localfile)
12929 size = stats.st_size
12939 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
12949 mtype = mimetypes.guess_type(filename)[0]
12959 headers = mimetools.Message(StringIO(
12969 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
12979 (mtype or 'text/plain', size, modified)))
12989 if host:
12996 host, port = splitport(host)
13009 if not host or \
13016 (not port and socket.gethostbyname(host) in self.get_names()):
13026 if host:
13033 origurl = 'file://' + host + filename
1304n/a else:
13053 origurl = 'file://' + filename
13066 return addinfourl(open(localfile, 'rb'), headers, origurl)
13076 except OSError, msg:
1308n/a # urllib2 users shouldn't expect OSErrors coming from urlopen()
13096 raise URLError(msg)
13103 raise URLError('file not on local host')
1311n/a
13122class FTPHandler(BaseHandler):
13131 def ftp_open(self, req):
131412 import ftplib
131512 import mimetypes
131612 host = req.get_host()
131712 if not host:
13180 raise URLError('ftp error: no host given')
131912 host, port = splitport(host)
132012 if port is None:
132111 port = ftplib.FTP_PORT
1322n/a else:
13231 port = int(port)
1324n/a
1325n/a # username/password handling
132612 user, host = splituser(host)
132712 if user:
13280 user, passwd = splitpasswd(user)
1329n/a else:
133012 passwd = None
133112 host = unquote(host)
133212 user = unquote(user or '')
133312 passwd = unquote(passwd or '')
1334n/a
133512 try:
133612 host = socket.gethostbyname(host)
13370 except socket.error, msg:
13380 raise URLError(msg)
133912 path, attrs = splitattr(req.get_selector())
134012 dirs = path.split('/')
134112 dirs = map(unquote, dirs)
134212 dirs, file = dirs[:-1], dirs[-1]
134312 if dirs and not dirs[0]:
134412 dirs = dirs[1:]
134512 try:
134612 fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
134712 type = file and 'I' or 'D'
134813 for attr in attrs:
13491 attr, value = splitvalue(attr)
13501 if attr.lower() == 'type' and \
13511 value in ('a', 'A', 'i', 'I', 'd', 'D'):
13521 type = value.upper()
135312 fp, retrlen = fw.retrfile(file, type)
13549 headers = ""
13559 mtype = mimetypes.guess_type(req.get_full_url())[0]
13569 if mtype:
13571 headers += "Content-type: %s\n" % mtype
13589 if retrlen is not None and retrlen >= 0:
13595 headers += "Content-length: %d\n" % retrlen
13609 sf = StringIO(headers)
13619 headers = mimetools.Message(sf)
13629 return addinfourl(fp, headers, req.get_full_url())
13633 except ftplib.all_errors, msg:
13643 raise URLError, ('ftp error: %s' % msg), sys.exc_info()[2]
1365n/a
13661 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
13674 fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
1368n/a## fw.ftp.set_debuglevel(1)
13694 return fw
1370n/a
13712class CacheFTPHandler(FTPHandler):
1372n/a # XXX would be nice to have pluggable cache strategies
1373n/a # XXX this stuff is definitely not thread safe
13741 def __init__(self):
13752 self.cache = {}
13762 self.timeout = {}
13772 self.soonest = 0
13782 self.delay = 60
13792 self.max_conns = 16
1380n/a
13811 def setTimeout(self, t):
13822 self.delay = t
1383n/a
13841 def setMaxConns(self, m):
13850 self.max_conns = m
1386n/a
13871 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
13885 key = user, host, port, '/'.join(dirs), timeout
13895 if key in self.cache:
13903 self.timeout[key] = time.time() + self.delay
1391n/a else:
13922 self.cache[key] = ftpwrapper(user, passwd, host, port, dirs, timeout)
13932 self.timeout[key] = time.time() + self.delay
13945 self.check_cache()
13955 return self.cache[key]
1396n/a
13971 def check_cache(self):
1398n/a # first check for old ones
13995 t = time.time()
14005 if self.soonest <= t:
14015 for k, v in self.timeout.items():
14023 if v < t:
14031 self.cache[k].close()
14041 del self.cache[k]
14051 del self.timeout[k]
14065 self.soonest = min(self.timeout.values())
1407n/a
1408n/a # then check the size
14095 if len(self.cache) == self.max_conns:
14100 for k, v in self.timeout.items():
14110 if v == self.soonest:
14120 del self.cache[k]
14130 del self.timeout[k]
14140 break
14150 self.soonest = min(self.timeout.values())