/Lib/urllib2.py

http://unladen-swallow.googlecode.com/ · Python · 1384 lines · 1049 code · 133 blank · 202 comment · 127 complexity · 5240841504a50c106cc228fe2b8e4e59 MD5 · raw file

  1. """An extensible library for opening URLs using a variety of protocols
  2. The simplest way to use this module is to call the urlopen function,
  3. which accepts a string containing a URL or a Request object (described
  4. below). It opens the URL and returns the results as file-like
  5. object; the returned object has some extra methods described below.
  6. The OpenerDirector manages a collection of Handler objects that do
  7. all the actual work. Each Handler implements a particular protocol or
  8. option. The OpenerDirector is a composite object that invokes the
  9. Handlers needed to open the requested URL. For example, the
  10. HTTPHandler performs HTTP GET and POST requests and deals with
  11. non-error returns. The HTTPRedirectHandler automatically deals with
  12. HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
  13. deals with digest authentication.
  14. urlopen(url, data=None) -- Basic usage is the same as original
  15. urllib. pass the url and optionally data to post to an HTTP URL, and
  16. get a file-like object back. One difference is that you can also pass
  17. a Request instance instead of URL. Raises a URLError (subclass of
  18. IOError); for HTTP errors, raises an HTTPError, which can also be
  19. treated as a valid response.
  20. build_opener -- Function that creates a new OpenerDirector instance.
  21. Will install the default handlers. Accepts one or more Handlers as
  22. arguments, either instances or Handler classes that it will
  23. instantiate. If one of the argument is a subclass of the default
  24. handler, the argument will be installed instead of the default.
  25. install_opener -- Installs a new opener as the default opener.
  26. objects of interest:
  27. OpenerDirector --
  28. Request -- An object that encapsulates the state of a request. The
  29. state can be as simple as the URL. It can also include extra HTTP
  30. headers, e.g. a User-Agent.
  31. BaseHandler --
  32. exceptions:
  33. URLError -- A subclass of IOError, individual protocols have their own
  34. specific subclass.
  35. HTTPError -- Also a valid HTTP response, so you can treat an HTTP error
  36. as an exceptional event or valid response.
  37. internals:
  38. BaseHandler and parent
  39. _call_chain conventions
  40. Example usage:
  41. import urllib2
  42. # set up authentication info
  43. authinfo = urllib2.HTTPBasicAuthHandler()
  44. authinfo.add_password(realm='PDQ Application',
  45. uri='https://mahler:8092/site-updates.py',
  46. user='klem',
  47. passwd='geheim$parole')
  48. proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
  49. # build a new opener that adds authentication and caching FTP handlers
  50. opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
  51. # install it
  52. urllib2.install_opener(opener)
  53. f = urllib2.urlopen('http://www.python.org/')
  54. """
  55. # XXX issues:
  56. # If an authentication error handler that tries to perform
  57. # authentication for some reason but fails, how should the error be
  58. # signalled? The client needs to know the HTTP error code. But if
  59. # the handler knows that the problem was, e.g., that it didn't know
  60. # that hash algo that requested in the challenge, it would be good to
  61. # pass that information along to the client, too.
  62. # ftp errors aren't handled cleanly
  63. # check digest against correct (i.e. non-apache) implementation
  64. # Possible extensions:
  65. # complex proxies XXX not sure what exactly was meant by this
  66. # abstract factory for opener
  67. import base64
  68. import hashlib
  69. import httplib
  70. import mimetools
  71. import os
  72. import posixpath
  73. import random
  74. import re
  75. import socket
  76. import sys
  77. import time
  78. import urlparse
  79. import bisect
  80. try:
  81. from cStringIO import StringIO
  82. except ImportError:
  83. from StringIO import StringIO
  84. from urllib import (unwrap, unquote, splittype, splithost, quote,
  85. addinfourl, splitport,
  86. splitattr, ftpwrapper, splituser, splitpasswd, splitvalue)
  87. # support for FileHandler, proxies via environment variables
  88. from urllib import localhost, url2pathname, getproxies, proxy_bypass
  89. # used in User-Agent header sent
  90. __version__ = sys.version[:3]
  91. _opener = None
  92. def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  93. global _opener
  94. if _opener is None:
  95. _opener = build_opener()
  96. return _opener.open(url, data, timeout)
  97. def install_opener(opener):
  98. global _opener
  99. _opener = opener
  100. # do these error classes make sense?
  101. # make sure all of the IOError stuff is overridden. we just want to be
  102. # subtypes.
  103. class URLError(IOError):
  104. # URLError is a sub-type of IOError, but it doesn't share any of
  105. # the implementation. need to override __init__ and __str__.
  106. # It sets self.args for compatibility with other EnvironmentError
  107. # subclasses, but args doesn't have the typical format with errno in
  108. # slot 0 and strerror in slot 1. This may be better than nothing.
  109. def __init__(self, reason):
  110. self.args = reason,
  111. self.reason = reason
  112. def __str__(self):
  113. return '<urlopen error %s>' % self.reason
  114. class HTTPError(URLError, addinfourl):
  115. """Raised when HTTP error occurs, but also acts like non-error return"""
  116. __super_init = addinfourl.__init__
  117. def __init__(self, url, code, msg, hdrs, fp):
  118. self.code = code
  119. self.msg = msg
  120. self.hdrs = hdrs
  121. self.fp = fp
  122. self.filename = url
  123. # The addinfourl classes depend on fp being a valid file
  124. # object. In some cases, the HTTPError may not have a valid
  125. # file object. If this happens, the simplest workaround is to
  126. # not initialize the base classes.
  127. if fp is not None:
  128. self.__super_init(fp, hdrs, url, code)
  129. def __str__(self):
  130. return 'HTTP Error %s: %s' % (self.code, self.msg)
  131. # copied from cookielib.py
  132. _cut_port_re = re.compile(r":\d+$")
  133. def request_host(request):
  134. """Return request-host, as defined by RFC 2965.
  135. Variation from RFC: returned value is lowercased, for convenient
  136. comparison.
  137. """
  138. url = request.get_full_url()
  139. host = urlparse.urlparse(url)[1]
  140. if host == "":
  141. host = request.get_header("Host", "")
  142. # remove port, if present
  143. host = _cut_port_re.sub("", host, 1)
  144. return host.lower()
  145. class Request:
  146. def __init__(self, url, data=None, headers={},
  147. origin_req_host=None, unverifiable=False):
  148. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  149. self.__original = unwrap(url)
  150. self.type = None
  151. # self.__r_type is what's left after doing the splittype
  152. self.host = None
  153. self.port = None
  154. self._tunnel_host = None
  155. self.data = data
  156. self.headers = {}
  157. for key, value in headers.items():
  158. self.add_header(key, value)
  159. self.unredirected_hdrs = {}
  160. if origin_req_host is None:
  161. origin_req_host = request_host(self)
  162. self.origin_req_host = origin_req_host
  163. self.unverifiable = unverifiable
  164. def __getattr__(self, attr):
  165. # XXX this is a fallback mechanism to guard against these
  166. # methods getting called in a non-standard order. this may be
  167. # too complicated and/or unnecessary.
  168. # XXX should the __r_XXX attributes be public?
  169. if attr[:12] == '_Request__r_':
  170. name = attr[12:]
  171. if hasattr(Request, 'get_' + name):
  172. getattr(self, 'get_' + name)()
  173. return getattr(self, attr)
  174. raise AttributeError, attr
  175. def get_method(self):
  176. if self.has_data():
  177. return "POST"
  178. else:
  179. return "GET"
  180. # XXX these helper methods are lame
  181. def add_data(self, data):
  182. self.data = data
  183. def has_data(self):
  184. return self.data is not None
  185. def get_data(self):
  186. return self.data
  187. def get_full_url(self):
  188. return self.__original
  189. def get_type(self):
  190. if self.type is None:
  191. self.type, self.__r_type = splittype(self.__original)
  192. if self.type is None:
  193. raise ValueError, "unknown url type: %s" % self.__original
  194. return self.type
  195. def get_host(self):
  196. if self.host is None:
  197. self.host, self.__r_host = splithost(self.__r_type)
  198. if self.host:
  199. self.host = unquote(self.host)
  200. return self.host
  201. def get_selector(self):
  202. return self.__r_host
  203. def set_proxy(self, host, type):
  204. if self.type == 'https' and not self._tunnel_host:
  205. self._tunnel_host = self.host
  206. else:
  207. self.type = type
  208. self.__r_host = self.__original
  209. self.host = host
  210. def has_proxy(self):
  211. return self.__r_host == self.__original
  212. def get_origin_req_host(self):
  213. return self.origin_req_host
  214. def is_unverifiable(self):
  215. return self.unverifiable
  216. def add_header(self, key, val):
  217. # useful for something like authentication
  218. self.headers[key.capitalize()] = val
  219. def add_unredirected_header(self, key, val):
  220. # will not be added to a redirected request
  221. self.unredirected_hdrs[key.capitalize()] = val
  222. def has_header(self, header_name):
  223. return (header_name in self.headers or
  224. header_name in self.unredirected_hdrs)
  225. def get_header(self, header_name, default=None):
  226. return self.headers.get(
  227. header_name,
  228. self.unredirected_hdrs.get(header_name, default))
  229. def header_items(self):
  230. hdrs = self.unredirected_hdrs.copy()
  231. hdrs.update(self.headers)
  232. return hdrs.items()
  233. class OpenerDirector:
  234. def __init__(self):
  235. client_version = "Python-urllib/%s" % __version__
  236. self.addheaders = [('User-agent', client_version)]
  237. # manage the individual handlers
  238. self.handlers = []
  239. self.handle_open = {}
  240. self.handle_error = {}
  241. self.process_response = {}
  242. self.process_request = {}
  243. def add_handler(self, handler):
  244. if not hasattr(handler, "add_parent"):
  245. raise TypeError("expected BaseHandler instance, got %r" %
  246. type(handler))
  247. added = False
  248. for meth in dir(handler):
  249. if meth in ["redirect_request", "do_open", "proxy_open"]:
  250. # oops, coincidental match
  251. continue
  252. i = meth.find("_")
  253. protocol = meth[:i]
  254. condition = meth[i+1:]
  255. if condition.startswith("error"):
  256. j = condition.find("_") + i + 1
  257. kind = meth[j+1:]
  258. try:
  259. kind = int(kind)
  260. except ValueError:
  261. pass
  262. lookup = self.handle_error.get(protocol, {})
  263. self.handle_error[protocol] = lookup
  264. elif condition == "open":
  265. kind = protocol
  266. lookup = self.handle_open
  267. elif condition == "response":
  268. kind = protocol
  269. lookup = self.process_response
  270. elif condition == "request":
  271. kind = protocol
  272. lookup = self.process_request
  273. else:
  274. continue
  275. handlers = lookup.setdefault(kind, [])
  276. if handlers:
  277. bisect.insort(handlers, handler)
  278. else:
  279. handlers.append(handler)
  280. added = True
  281. if added:
  282. # the handlers must work in an specific order, the order
  283. # is specified in a Handler attribute
  284. bisect.insort(self.handlers, handler)
  285. handler.add_parent(self)
  286. def close(self):
  287. # Only exists for backwards compatibility.
  288. pass
  289. def _call_chain(self, chain, kind, meth_name, *args):
  290. # Handlers raise an exception if no one else should try to handle
  291. # the request, or return None if they can't but another handler
  292. # could. Otherwise, they return the response.
  293. handlers = chain.get(kind, ())
  294. for handler in handlers:
  295. func = getattr(handler, meth_name)
  296. result = func(*args)
  297. if result is not None:
  298. return result
  299. def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  300. # accept a URL or a Request object
  301. if isinstance(fullurl, basestring):
  302. req = Request(fullurl, data)
  303. else:
  304. req = fullurl
  305. if data is not None:
  306. req.add_data(data)
  307. req.timeout = timeout
  308. protocol = req.get_type()
  309. # pre-process request
  310. meth_name = protocol+"_request"
  311. for processor in self.process_request.get(protocol, []):
  312. meth = getattr(processor, meth_name)
  313. req = meth(req)
  314. response = self._open(req, data)
  315. # post-process response
  316. meth_name = protocol+"_response"
  317. for processor in self.process_response.get(protocol, []):
  318. meth = getattr(processor, meth_name)
  319. response = meth(req, response)
  320. return response
  321. def _open(self, req, data=None):
  322. result = self._call_chain(self.handle_open, 'default',
  323. 'default_open', req)
  324. if result:
  325. return result
  326. protocol = req.get_type()
  327. result = self._call_chain(self.handle_open, protocol, protocol +
  328. '_open', req)
  329. if result:
  330. return result
  331. return self._call_chain(self.handle_open, 'unknown',
  332. 'unknown_open', req)
  333. def error(self, proto, *args):
  334. if proto in ('http', 'https'):
  335. # XXX http[s] protocols are special-cased
  336. dict = self.handle_error['http'] # https is not different than http
  337. proto = args[2] # YUCK!
  338. meth_name = 'http_error_%s' % proto
  339. http_err = 1
  340. orig_args = args
  341. else:
  342. dict = self.handle_error
  343. meth_name = proto + '_error'
  344. http_err = 0
  345. args = (dict, proto, meth_name) + args
  346. result = self._call_chain(*args)
  347. if result:
  348. return result
  349. if http_err:
  350. args = (dict, 'default', 'http_error_default') + orig_args
  351. return self._call_chain(*args)
  352. # XXX probably also want an abstract factory that knows when it makes
  353. # sense to skip a superclass in favor of a subclass and when it might
  354. # make sense to include both
  355. def build_opener(*handlers):
  356. """Create an opener object from a list of handlers.
  357. The opener will use several default handlers, including support
  358. for HTTP and FTP.
  359. If any of the handlers passed as arguments are subclasses of the
  360. default handlers, the default handlers will not be used.
  361. """
  362. import types
  363. def isclass(obj):
  364. return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")
  365. opener = OpenerDirector()
  366. default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
  367. HTTPDefaultErrorHandler, HTTPRedirectHandler,
  368. FTPHandler, FileHandler, HTTPErrorProcessor]
  369. if hasattr(httplib, 'HTTPS'):
  370. default_classes.append(HTTPSHandler)
  371. skip = set()
  372. for klass in default_classes:
  373. for check in handlers:
  374. if isclass(check):
  375. if issubclass(check, klass):
  376. skip.add(klass)
  377. elif isinstance(check, klass):
  378. skip.add(klass)
  379. for klass in skip:
  380. default_classes.remove(klass)
  381. for klass in default_classes:
  382. opener.add_handler(klass())
  383. for h in handlers:
  384. if isclass(h):
  385. h = h()
  386. opener.add_handler(h)
  387. return opener
  388. class BaseHandler:
  389. handler_order = 500
  390. def add_parent(self, parent):
  391. self.parent = parent
  392. def close(self):
  393. # Only exists for backwards compatibility
  394. pass
  395. def __lt__(self, other):
  396. if not hasattr(other, "handler_order"):
  397. # Try to preserve the old behavior of having custom classes
  398. # inserted after default ones (works only for custom user
  399. # classes which are not aware of handler_order).
  400. return True
  401. return self.handler_order < other.handler_order
  402. class HTTPErrorProcessor(BaseHandler):
  403. """Process HTTP error responses."""
  404. handler_order = 1000 # after all other processing
  405. def http_response(self, request, response):
  406. code, msg, hdrs = response.code, response.msg, response.info()
  407. # According to RFC 2616, "2xx" code indicates that the client's
  408. # request was successfully received, understood, and accepted.
  409. if not (200 <= code < 300):
  410. response = self.parent.error(
  411. 'http', request, response, code, msg, hdrs)
  412. return response
  413. https_response = http_response
  414. class HTTPDefaultErrorHandler(BaseHandler):
  415. def http_error_default(self, req, fp, code, msg, hdrs):
  416. raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
  417. class HTTPRedirectHandler(BaseHandler):
  418. # maximum number of redirections to any single URL
  419. # this is needed because of the state that cookies introduce
  420. max_repeats = 4
  421. # maximum total number of redirections (regardless of URL) before
  422. # assuming we're in a loop
  423. max_redirections = 10
  424. def redirect_request(self, req, fp, code, msg, headers, newurl):
  425. """Return a Request or None in response to a redirect.
  426. This is called by the http_error_30x methods when a
  427. redirection response is received. If a redirection should
  428. take place, return a new Request to allow http_error_30x to
  429. perform the redirect. Otherwise, raise HTTPError if no-one
  430. else should try to handle this url. Return None if you can't
  431. but another Handler might.
  432. """
  433. m = req.get_method()
  434. if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
  435. or code in (301, 302, 303) and m == "POST"):
  436. # Strictly (according to RFC 2616), 301 or 302 in response
  437. # to a POST MUST NOT cause a redirection without confirmation
  438. # from the user (of urllib2, in this case). In practice,
  439. # essentially all clients do redirect in this case, so we
  440. # do the same.
  441. # be conciliant with URIs containing a space
  442. newurl = newurl.replace(' ', '%20')
  443. newheaders = dict((k,v) for k,v in req.headers.items()
  444. if k.lower() not in ("content-length", "content-type")
  445. )
  446. return Request(newurl,
  447. headers=newheaders,
  448. origin_req_host=req.get_origin_req_host(),
  449. unverifiable=True)
  450. else:
  451. raise HTTPError(req.get_full_url(), code, msg, headers, fp)
  452. # Implementation note: To avoid the server sending us into an
  453. # infinite loop, the request object needs to track what URLs we
  454. # have already seen. Do this by adding a handler-specific
  455. # attribute to the Request object.
  456. def http_error_302(self, req, fp, code, msg, headers):
  457. # Some servers (incorrectly) return multiple Location headers
  458. # (so probably same goes for URI). Use first header.
  459. if 'location' in headers:
  460. newurl = headers.getheaders('location')[0]
  461. elif 'uri' in headers:
  462. newurl = headers.getheaders('uri')[0]
  463. else:
  464. return
  465. # fix a possible malformed URL
  466. urlparts = urlparse.urlparse(newurl)
  467. if not urlparts.path:
  468. urlparts = list(urlparts)
  469. urlparts[2] = "/"
  470. newurl = urlparse.urlunparse(urlparts)
  471. newurl = urlparse.urljoin(req.get_full_url(), newurl)
  472. # XXX Probably want to forget about the state of the current
  473. # request, although that might interact poorly with other
  474. # handlers that also use handler-specific request attributes
  475. new = self.redirect_request(req, fp, code, msg, headers, newurl)
  476. if new is None:
  477. return
  478. # loop detection
  479. # .redirect_dict has a key url if url was previously visited.
  480. if hasattr(req, 'redirect_dict'):
  481. visited = new.redirect_dict = req.redirect_dict
  482. if (visited.get(newurl, 0) >= self.max_repeats or
  483. len(visited) >= self.max_redirections):
  484. raise HTTPError(req.get_full_url(), code,
  485. self.inf_msg + msg, headers, fp)
  486. else:
  487. visited = new.redirect_dict = req.redirect_dict = {}
  488. visited[newurl] = visited.get(newurl, 0) + 1
  489. # Don't close the fp until we are sure that we won't use it
  490. # with HTTPError.
  491. fp.read()
  492. fp.close()
  493. return self.parent.open(new, timeout=req.timeout)
  494. http_error_301 = http_error_303 = http_error_307 = http_error_302
  495. inf_msg = "The HTTP server returned a redirect error that would " \
  496. "lead to an infinite loop.\n" \
  497. "The last 30x error message was:\n"
  498. def _parse_proxy(proxy):
  499. """Return (scheme, user, password, host/port) given a URL or an authority.
  500. If a URL is supplied, it must have an authority (host:port) component.
  501. According to RFC 3986, having an authority component means the URL must
  502. have two slashes after the scheme:
  503. >>> _parse_proxy('file:/ftp.example.com/')
  504. Traceback (most recent call last):
  505. ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
  506. The first three items of the returned tuple may be None.
  507. Examples of authority parsing:
  508. >>> _parse_proxy('proxy.example.com')
  509. (None, None, None, 'proxy.example.com')
  510. >>> _parse_proxy('proxy.example.com:3128')
  511. (None, None, None, 'proxy.example.com:3128')
  512. The authority component may optionally include userinfo (assumed to be
  513. username:password):
  514. >>> _parse_proxy('joe:password@proxy.example.com')
  515. (None, 'joe', 'password', 'proxy.example.com')
  516. >>> _parse_proxy('joe:password@proxy.example.com:3128')
  517. (None, 'joe', 'password', 'proxy.example.com:3128')
  518. Same examples, but with URLs instead:
  519. >>> _parse_proxy('http://proxy.example.com/')
  520. ('http', None, None, 'proxy.example.com')
  521. >>> _parse_proxy('http://proxy.example.com:3128/')
  522. ('http', None, None, 'proxy.example.com:3128')
  523. >>> _parse_proxy('http://joe:password@proxy.example.com/')
  524. ('http', 'joe', 'password', 'proxy.example.com')
  525. >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
  526. ('http', 'joe', 'password', 'proxy.example.com:3128')
  527. Everything after the authority is ignored:
  528. >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
  529. ('ftp', 'joe', 'password', 'proxy.example.com')
  530. Test for no trailing '/' case:
  531. >>> _parse_proxy('http://joe:password@proxy.example.com')
  532. ('http', 'joe', 'password', 'proxy.example.com')
  533. """
  534. scheme, r_scheme = splittype(proxy)
  535. if not r_scheme.startswith("/"):
  536. # authority
  537. scheme = None
  538. authority = proxy
  539. else:
  540. # URL
  541. if not r_scheme.startswith("//"):
  542. raise ValueError("proxy URL with no authority: %r" % proxy)
  543. # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
  544. # and 3.3.), path is empty or starts with '/'
  545. end = r_scheme.find("/", 2)
  546. if end == -1:
  547. end = None
  548. authority = r_scheme[2:end]
  549. userinfo, hostport = splituser(authority)
  550. if userinfo is not None:
  551. user, password = splitpasswd(userinfo)
  552. else:
  553. user = password = None
  554. return scheme, user, password, hostport
  555. class ProxyHandler(BaseHandler):
  556. # Proxies must be in front
  557. handler_order = 100
  558. def __init__(self, proxies=None):
  559. if proxies is None:
  560. proxies = getproxies()
  561. assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  562. self.proxies = proxies
  563. for type, url in proxies.items():
  564. setattr(self, '%s_open' % type,
  565. lambda r, proxy=url, type=type, meth=self.proxy_open: \
  566. meth(r, proxy, type))
  567. def proxy_open(self, req, proxy, type):
  568. orig_type = req.get_type()
  569. proxy_type, user, password, hostport = _parse_proxy(proxy)
  570. if proxy_type is None:
  571. proxy_type = orig_type
  572. if req.host and proxy_bypass(req.host):
  573. return None
  574. if user and password:
  575. user_pass = '%s:%s' % (unquote(user), unquote(password))
  576. creds = base64.b64encode(user_pass).strip()
  577. req.add_header('Proxy-authorization', 'Basic ' + creds)
  578. hostport = unquote(hostport)
  579. req.set_proxy(hostport, proxy_type)
  580. if orig_type == proxy_type or orig_type == 'https':
  581. # let other handlers take care of it
  582. return None
  583. else:
  584. # need to start over, because the other handlers don't
  585. # grok the proxy's URL type
  586. # e.g. if we have a constructor arg proxies like so:
  587. # {'http': 'ftp://proxy.example.com'}, we may end up turning
  588. # a request for http://acme.example.com/a into one for
  589. # ftp://proxy.example.com/a
  590. return self.parent.open(req, timeout=req.timeout)
  591. class HTTPPasswordMgr:
  592. def __init__(self):
  593. self.passwd = {}
  594. def add_password(self, realm, uri, user, passwd):
  595. # uri could be a single URI or a sequence
  596. if isinstance(uri, basestring):
  597. uri = [uri]
  598. if not realm in self.passwd:
  599. self.passwd[realm] = {}
  600. for default_port in True, False:
  601. reduced_uri = tuple(
  602. [self.reduce_uri(u, default_port) for u in uri])
  603. self.passwd[realm][reduced_uri] = (user, passwd)
  604. def find_user_password(self, realm, authuri):
  605. domains = self.passwd.get(realm, {})
  606. for default_port in True, False:
  607. reduced_authuri = self.reduce_uri(authuri, default_port)
  608. for uris, authinfo in domains.iteritems():
  609. for uri in uris:
  610. if self.is_suburi(uri, reduced_authuri):
  611. return authinfo
  612. return None, None
  613. def reduce_uri(self, uri, default_port=True):
  614. """Accept authority or URI and extract only the authority and path."""
  615. # note HTTP URLs do not have a userinfo component
  616. parts = urlparse.urlsplit(uri)
  617. if parts[1]:
  618. # URI
  619. scheme = parts[0]
  620. authority = parts[1]
  621. path = parts[2] or '/'
  622. else:
  623. # host or host:port
  624. scheme = None
  625. authority = uri
  626. path = '/'
  627. host, port = splitport(authority)
  628. if default_port and port is None and scheme is not None:
  629. dport = {"http": 80,
  630. "https": 443,
  631. }.get(scheme)
  632. if dport is not None:
  633. authority = "%s:%d" % (host, dport)
  634. return authority, path
  635. def is_suburi(self, base, test):
  636. """Check if test is below base in a URI tree
  637. Both args must be URIs in reduced form.
  638. """
  639. if base == test:
  640. return True
  641. if base[0] != test[0]:
  642. return False
  643. common = posixpath.commonprefix((base[1], test[1]))
  644. if len(common) == len(base[1]):
  645. return True
  646. return False
  647. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  648. def find_user_password(self, realm, authuri):
  649. user, password = HTTPPasswordMgr.find_user_password(self, realm,
  650. authuri)
  651. if user is not None:
  652. return user, password
  653. return HTTPPasswordMgr.find_user_password(self, None, authuri)
  654. class AbstractBasicAuthHandler:
  655. # XXX this allows for multiple auth-schemes, but will stupidly pick
  656. # the last one with a realm specified.
  657. # allow for double- and single-quoted realm values
  658. # (single quotes are a violation of the RFC, but appear in the wild)
  659. rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
  660. 'realm=(["\'])(.*?)\\2', re.I)
  661. # XXX could pre-emptively send auth info already accepted (RFC 2617,
  662. # end of section 2, and section 1.2 immediately after "credentials"
  663. # production).
  664. def __init__(self, password_mgr=None):
  665. if password_mgr is None:
  666. password_mgr = HTTPPasswordMgr()
  667. self.passwd = password_mgr
  668. self.add_password = self.passwd.add_password
  669. def http_error_auth_reqed(self, authreq, host, req, headers):
  670. # host may be an authority (without userinfo) or a URL with an
  671. # authority
  672. # XXX could be multiple headers
  673. authreq = headers.get(authreq, None)
  674. if authreq:
  675. mo = AbstractBasicAuthHandler.rx.search(authreq)
  676. if mo:
  677. scheme, quote, realm = mo.groups()
  678. if scheme.lower() == 'basic':
  679. return self.retry_http_basic_auth(host, req, realm)
  680. def retry_http_basic_auth(self, host, req, realm):
  681. user, pw = self.passwd.find_user_password(realm, host)
  682. if pw is not None:
  683. raw = "%s:%s" % (user, pw)
  684. auth = 'Basic %s' % base64.b64encode(raw).strip()
  685. if req.headers.get(self.auth_header, None) == auth:
  686. return None
  687. req.add_header(self.auth_header, auth)
  688. return self.parent.open(req, timeout=req.timeout)
  689. else:
  690. return None
  691. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  692. auth_header = 'Authorization'
  693. def http_error_401(self, req, fp, code, msg, headers):
  694. url = req.get_full_url()
  695. return self.http_error_auth_reqed('www-authenticate',
  696. url, req, headers)
  697. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  698. auth_header = 'Proxy-authorization'
  699. def http_error_407(self, req, fp, code, msg, headers):
  700. # http_error_auth_reqed requires that there is no userinfo component in
  701. # authority. Assume there isn't one, since urllib2 does not (and
  702. # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
  703. # userinfo.
  704. authority = req.get_host()
  705. return self.http_error_auth_reqed('proxy-authenticate',
  706. authority, req, headers)
  707. def randombytes(n):
  708. """Return n random bytes."""
  709. # Use /dev/urandom if it is available. Fall back to random module
  710. # if not. It might be worthwhile to extend this function to use
  711. # other platform-specific mechanisms for getting random bytes.
  712. if os.path.exists("/dev/urandom"):
  713. f = open("/dev/urandom")
  714. s = f.read(n)
  715. f.close()
  716. return s
  717. else:
  718. L = [chr(random.randrange(0, 256)) for i in range(n)]
  719. return "".join(L)
  720. class AbstractDigestAuthHandler:
  721. # Digest authentication is specified in RFC 2617.
  722. # XXX The client does not inspect the Authentication-Info header
  723. # in a successful response.
  724. # XXX It should be possible to test this implementation against
  725. # a mock server that just generates a static set of challenges.
  726. # XXX qop="auth-int" supports is shaky
  727. def __init__(self, passwd=None):
  728. if passwd is None:
  729. passwd = HTTPPasswordMgr()
  730. self.passwd = passwd
  731. self.add_password = self.passwd.add_password
  732. self.retried = 0
  733. self.nonce_count = 0
  734. def reset_retry_count(self):
  735. self.retried = 0
  736. def http_error_auth_reqed(self, auth_header, host, req, headers):
  737. authreq = headers.get(auth_header, None)
  738. if self.retried > 5:
  739. # Don't fail endlessly - if we failed once, we'll probably
  740. # fail a second time. Hm. Unless the Password Manager is
  741. # prompting for the information. Crap. This isn't great
  742. # but it's better than the current 'repeat until recursion
  743. # depth exceeded' approach <wink>
  744. raise HTTPError(req.get_full_url(), 401, "digest auth failed",
  745. headers, None)
  746. else:
  747. self.retried += 1
  748. if authreq:
  749. scheme = authreq.split()[0]
  750. if scheme.lower() == 'digest':
  751. return self.retry_http_digest_auth(req, authreq)
  752. def retry_http_digest_auth(self, req, auth):
  753. token, challenge = auth.split(' ', 1)
  754. chal = parse_keqv_list(parse_http_list(challenge))
  755. auth = self.get_authorization(req, chal)
  756. if auth:
  757. auth_val = 'Digest %s' % auth
  758. if req.headers.get(self.auth_header, None) == auth_val:
  759. return None
  760. req.add_unredirected_header(self.auth_header, auth_val)
  761. resp = self.parent.open(req, timeout=req.timeout)
  762. return resp
  763. def get_cnonce(self, nonce):
  764. # The cnonce-value is an opaque
  765. # quoted string value provided by the client and used by both client
  766. # and server to avoid chosen plaintext attacks, to provide mutual
  767. # authentication, and to provide some message integrity protection.
  768. # This isn't a fabulous effort, but it's probably Good Enough.
  769. dig = hashlib.sha1("%s:%s:%s:%s" % (self.nonce_count, nonce, time.ctime(),
  770. randombytes(8))).hexdigest()
  771. return dig[:16]
  772. def get_authorization(self, req, chal):
  773. try:
  774. realm = chal['realm']
  775. nonce = chal['nonce']
  776. qop = chal.get('qop')
  777. algorithm = chal.get('algorithm', 'MD5')
  778. # mod_digest doesn't send an opaque, even though it isn't
  779. # supposed to be optional
  780. opaque = chal.get('opaque', None)
  781. except KeyError:
  782. return None
  783. H, KD = self.get_algorithm_impls(algorithm)
  784. if H is None:
  785. return None
  786. user, pw = self.passwd.find_user_password(realm, req.get_full_url())
  787. if user is None:
  788. return None
  789. # XXX not implemented yet
  790. if req.has_data():
  791. entdig = self.get_entity_digest(req.get_data(), chal)
  792. else:
  793. entdig = None
  794. A1 = "%s:%s:%s" % (user, realm, pw)
  795. A2 = "%s:%s" % (req.get_method(),
  796. # XXX selector: what about proxies and full urls
  797. req.get_selector())
  798. if qop == 'auth':
  799. self.nonce_count += 1
  800. ncvalue = '%08x' % self.nonce_count
  801. cnonce = self.get_cnonce(nonce)
  802. noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
  803. respdig = KD(H(A1), noncebit)
  804. elif qop is None:
  805. respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
  806. else:
  807. # XXX handle auth-int.
  808. raise URLError("qop '%s' is not supported." % qop)
  809. # XXX should the partial digests be encoded too?
  810. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  811. 'response="%s"' % (user, realm, nonce, req.get_selector(),
  812. respdig)
  813. if opaque:
  814. base += ', opaque="%s"' % opaque
  815. if entdig:
  816. base += ', digest="%s"' % entdig
  817. base += ', algorithm="%s"' % algorithm
  818. if qop:
  819. base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  820. return base
  821. def get_algorithm_impls(self, algorithm):
  822. # algorithm should be case-insensitive according to RFC2617
  823. algorithm = algorithm.upper()
  824. # lambdas assume digest modules are imported at the top level
  825. if algorithm == 'MD5':
  826. H = lambda x: hashlib.md5(x).hexdigest()
  827. elif algorithm == 'SHA':
  828. H = lambda x: hashlib.sha1(x).hexdigest()
  829. # XXX MD5-sess
  830. KD = lambda s, d: H("%s:%s" % (s, d))
  831. return H, KD
  832. def get_entity_digest(self, data, chal):
  833. # XXX not implemented yet
  834. return None
  835. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  836. """An authentication protocol defined by RFC 2069
  837. Digest authentication improves on basic authentication because it
  838. does not transmit passwords in the clear.
  839. """
  840. auth_header = 'Authorization'
  841. handler_order = 490 # before Basic auth
  842. def http_error_401(self, req, fp, code, msg, headers):
  843. host = urlparse.urlparse(req.get_full_url())[1]
  844. retry = self.http_error_auth_reqed('www-authenticate',
  845. host, req, headers)
  846. self.reset_retry_count()
  847. return retry
  848. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  849. auth_header = 'Proxy-Authorization'
  850. handler_order = 490 # before Basic auth
  851. def http_error_407(self, req, fp, code, msg, headers):
  852. host = req.get_host()
  853. retry = self.http_error_auth_reqed('proxy-authenticate',
  854. host, req, headers)
  855. self.reset_retry_count()
  856. return retry
  857. class AbstractHTTPHandler(BaseHandler):
  858. def __init__(self, debuglevel=0):
  859. self._debuglevel = debuglevel
  860. def set_http_debuglevel(self, level):
  861. self._debuglevel = level
  862. def do_request_(self, request):
  863. host = request.get_host()
  864. if not host:
  865. raise URLError('no host given')
  866. if request.has_data(): # POST
  867. data = request.get_data()
  868. if not request.has_header('Content-type'):
  869. request.add_unredirected_header(
  870. 'Content-type',
  871. 'application/x-www-form-urlencoded')
  872. if not request.has_header('Content-length'):
  873. request.add_unredirected_header(
  874. 'Content-length', '%d' % len(data))
  875. sel_host = host
  876. if request.has_proxy():
  877. scheme, sel = splittype(request.get_selector())
  878. sel_host, sel_path = splithost(sel)
  879. if not request.has_header('Host'):
  880. request.add_unredirected_header('Host', sel_host)
  881. for name, value in self.parent.addheaders:
  882. name = name.capitalize()
  883. if not request.has_header(name):
  884. request.add_unredirected_header(name, value)
  885. return request
  886. def do_open(self, http_class, req):
  887. """Return an addinfourl object for the request, using http_class.
  888. http_class must implement the HTTPConnection API from httplib.
  889. The addinfourl return value is a file-like object. It also
  890. has methods and attributes including:
  891. - info(): return a mimetools.Message object for the headers
  892. - geturl(): return the original request URL
  893. - code: HTTP status code
  894. """
  895. host = req.get_host()
  896. if not host:
  897. raise URLError('no host given')
  898. h = http_class(host, timeout=req.timeout) # will parse host:port
  899. h.set_debuglevel(self._debuglevel)
  900. headers = dict(req.headers)
  901. headers.update(req.unredirected_hdrs)
  902. # We want to make an HTTP/1.1 request, but the addinfourl
  903. # class isn't prepared to deal with a persistent connection.
  904. # It will try to read all remaining data from the socket,
  905. # which will block while the server waits for the next request.
  906. # So make sure the connection gets closed after the (only)
  907. # request.
  908. headers["Connection"] = "close"
  909. headers = dict(
  910. (name.title(), val) for name, val in headers.items())
  911. if req._tunnel_host:
  912. h._set_tunnel(req._tunnel_host)
  913. try:
  914. h.request(req.get_method(), req.get_selector(), req.data, headers)
  915. r = h.getresponse()
  916. except socket.error, err: # XXX what error?
  917. raise URLError(err)
  918. # Pick apart the HTTPResponse object to get the addinfourl
  919. # object initialized properly.
  920. # Wrap the HTTPResponse object in socket's file object adapter
  921. # for Windows. That adapter calls recv(), so delegate recv()
  922. # to read(). This weird wrapping allows the returned object to
  923. # have readline() and readlines() methods.
  924. # XXX It might be better to extract the read buffering code
  925. # out of socket._fileobject() and into a base class.
  926. r.recv = r.read
  927. fp = socket._fileobject(r, close=True)
  928. resp = addinfourl(fp, r.msg, req.get_full_url())
  929. resp.code = r.status
  930. resp.msg = r.reason
  931. return resp
  932. class HTTPHandler(AbstractHTTPHandler):
  933. def http_open(self, req):
  934. return self.do_open(httplib.HTTPConnection, req)
  935. http_request = AbstractHTTPHandler.do_request_
  936. if hasattr(httplib, 'HTTPS'):
  937. class HTTPSHandler(AbstractHTTPHandler):
  938. def https_open(self, req):
  939. return self.do_open(httplib.HTTPSConnection, req)
  940. https_request = AbstractHTTPHandler.do_request_
  941. class HTTPCookieProcessor(BaseHandler):
  942. def __init__(self, cookiejar=None):
  943. import cookielib
  944. if cookiejar is None:
  945. cookiejar = cookielib.CookieJar()
  946. self.cookiejar = cookiejar
  947. def http_request(self, request):
  948. self.cookiejar.add_cookie_header(request)
  949. return request
  950. def http_response(self, request, response):
  951. self.cookiejar.extract_cookies(response, request)
  952. return response
  953. https_request = http_request
  954. https_response = http_response
  955. class UnknownHandler(BaseHandler):
  956. def unknown_open(self, req):
  957. type = req.get_type()
  958. raise URLError('unknown url type: %s' % type)
  959. def parse_keqv_list(l):
  960. """Parse list of key=value strings where keys are not duplicated."""
  961. parsed = {}
  962. for elt in l:
  963. k, v = elt.split('=', 1)
  964. if v[0] == '"' and v[-1] == '"':
  965. v = v[1:-1]
  966. parsed[k] = v
  967. return parsed
  968. def parse_http_list(s):
  969. """Parse lists as described by RFC 2068 Section 2.
  970. In particular, parse comma-separated lists where the elements of
  971. the list may include quoted-strings. A quoted-string could
  972. contain a comma. A non-quoted string could have quotes in the
  973. middle. Neither commas nor quotes count if they are escaped.
  974. Only double-quotes count, not single-quotes.
  975. """
  976. res = []
  977. part = ''
  978. escape = quote = False
  979. for cur in s:
  980. if escape:
  981. part += cur
  982. escape = False
  983. continue
  984. if quote:
  985. if cur == '\\':
  986. escape = True
  987. continue
  988. elif cur == '"':
  989. quote = False
  990. part += cur
  991. continue
  992. if cur == ',':
  993. res.append(part)
  994. part = ''
  995. continue
  996. if cur == '"':
  997. quote = True
  998. part += cur
  999. # append last part
  1000. if part:
  1001. res.append(part)
  1002. return [part.strip() for part in res]
  1003. class FileHandler(BaseHandler):
  1004. # Use local file or FTP depending on form of URL
  1005. def file_open(self, req):
  1006. url = req.get_selector()
  1007. if url[:2] == '//' and url[2:3] != '/':
  1008. req.type = 'ftp'
  1009. return self.parent.open(req)
  1010. else:
  1011. return self.open_local_file(req)
  1012. # names for the localhost
  1013. names = None
  1014. def get_names(self):
  1015. if FileHandler.names is None:
  1016. try:
  1017. FileHandler.names = (socket.gethostbyname('localhost'),
  1018. socket.gethostbyname(socket.gethostname()))
  1019. except socket.gaierror:
  1020. FileHandler.names = (socket.gethostbyname('localhost'),)
  1021. return FileHandler.names
  1022. # not entirely sure what the rules are here
  1023. def open_local_file(self, req):
  1024. import email.utils
  1025. import mimetypes
  1026. host = req.get_host()
  1027. file = req.get_selector()
  1028. localfile = url2pathname(file)
  1029. try:
  1030. stats = os.stat(localfile)
  1031. size = stats.st_size
  1032. modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
  1033. mtype = mimetypes.guess_type(file)[0]
  1034. headers = mimetools.Message(StringIO(
  1035. 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
  1036. (mtype or 'text/plain', size, modified)))
  1037. if host:
  1038. host, port = splitport(host)
  1039. if not host or \
  1040. (not port and socket.gethostbyname(host) in self.get_names()):
  1041. return addinfourl(open(localfile, 'rb'),
  1042. headers, 'file:'+file)
  1043. except OSError, msg:
  1044. # urllib2 users shouldn't expect OSErrors coming from urlopen()
  1045. raise URLError(msg)
  1046. raise URLError('file not on local host')
  1047. class FTPHandler(BaseHandler):
  1048. def ftp_open(self, req):
  1049. import ftplib
  1050. import mimetypes
  1051. host = req.get_host()
  1052. if not host:
  1053. raise URLError('ftp error: no host given')
  1054. host, port = splitport(host)
  1055. if port is None:
  1056. port = ftplib.FTP_PORT
  1057. else:
  1058. port = int(port)
  1059. # username/password handling
  1060. user, host = splituser(host)
  1061. if user:
  1062. user, passwd = splitpasswd(user)
  1063. else:
  1064. passwd = None
  1065. host = unquote(host)
  1066. user = unquote(user or '')
  1067. passwd = unquote(passwd or '')
  1068. try:
  1069. host = socket.gethostbyname(host)
  1070. except socket.error, msg:
  1071. raise URLError(msg)
  1072. path, attrs = splitattr(req.get_selector())
  1073. dirs = path.split('/')
  1074. dirs = map(unquote, dirs)
  1075. dirs, file = dirs[:-1], dirs[-1]
  1076. if dirs and not dirs[0]:
  1077. dirs = dirs[1:]
  1078. try:
  1079. fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
  1080. type = file and 'I' or 'D'
  1081. for attr in attrs:
  1082. attr, value = splitvalue(attr)
  1083. if attr.lower() == 'type' and \
  1084. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1085. type = value.upper()
  1086. fp, retrlen = fw.retrfile(file, type)
  1087. headers = ""
  1088. mtype = mimetypes.guess_type(req.get_full_url())[0]
  1089. if mtype:
  1090. headers += "Content-type: %s\n" % mtype
  1091. if retrlen is not None and retrlen >= 0:
  1092. headers += "Content-length: %d\n" % retrlen
  1093. sf = StringIO(headers)
  1094. headers = mimetools.Message(sf)
  1095. return addinfourl(fp, headers, req.get_full_url())
  1096. except ftplib.all_errors, msg:
  1097. raise URLError, ('ftp error: %s' % msg), sys.exc_info()[2]
  1098. def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1099. fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
  1100. ## fw.ftp.set_debuglevel(1)
  1101. return fw
  1102. class CacheFTPHandler(FTPHandler):
  1103. # XXX would be nice to have pluggable cache strategies
  1104. # XXX this stuff is definitely not thread safe
  1105. def __init__(self):
  1106. self.cache = {}
  1107. self.timeout = {}
  1108. self.soonest = 0
  1109. self.delay = 60
  1110. self.max_conns = 16
  1111. def setTimeout(self, t):
  1112. self.delay = t
  1113. def setMaxConns(self, m):
  1114. self.max_conns = m
  1115. def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1116. key = user, host, port, '/'.join(dirs), timeout
  1117. if key in self.cache:
  1118. self.timeout[key] = time.time() + self.delay
  1119. else:
  1120. self.cache[key] = ftpwrapper(user, passwd, host, port, dirs, timeout)
  1121. self.timeout[key] = time.time() + self.delay
  1122. self.check_cache()
  1123. return self.cache[key]
  1124. def check_cache(self):
  1125. # first check for old ones
  1126. t = time.time()
  1127. if self.soonest <= t:
  1128. for k, v in self.timeout.items():
  1129. if v < t:
  1130. self.cache[k].close()
  1131. del self.cache[k]
  1132. del self.timeout[k]
  1133. self.soonest = min(self.timeout.values())
  1134. # then check the size
  1135. if len(self.cache) == self.max_conns:
  1136. for k, v in self.timeout.items():
  1137. if v == self.soonest:
  1138. del self.cache[k]
  1139. del self.timeout[k]
  1140. break
  1141. self.soonest = min(self.timeout.values())