PageRenderTime 41ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/httplib2plus/__init__.py

https://github.com/fffonion/RoameBot
Python | 1685 lines | 1655 code | 7 blank | 23 comment | 17 complexity | 121995b36a4f425e7c3566e66997c677 MD5 | raw file
  1. from __future__ import generators
  2. """
  3. httplib2plus
  4. A caching http interface that supports ETags and gzip
  5. to conserve bandwidth.
  6. Requires Python 2.3 or later
  7. Changelog:
  8. 2007-08-18, Rick: Modified so it's able to use a socks proxy if needed.
  9. """
  10. __author__ = "Joe Gregorio (joe@bitworking.org)"
  11. __copyright__ = "Copyright 2006, Joe Gregorio"
  12. __contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)",
  13. "James Antill",
  14. "Xavier Verges Farrero",
  15. "Jonathan Feinberg",
  16. "Blair Zajac",
  17. "Sam Ruby",
  18. "Louis Nyffenegger"]
  19. __license__ = "MIT"
  20. __version__ = "0.8"
  21. import re
  22. import sys
  23. import email
  24. import email.Utils
  25. import email.Message
  26. import email.FeedParser
  27. import StringIO
  28. import gzip
  29. import zlib
  30. import httplib
  31. import urlparse
  32. import urllib
  33. import base64
  34. import os
  35. import copy
  36. import calendar
  37. import time
  38. import random
  39. import errno
  40. try:
  41. from hashlib import sha1 as _sha, md5 as _md5
  42. except ImportError:
  43. # prior to Python 2.5, these were separate modules
  44. import sha
  45. import md5
  46. _sha = sha.new
  47. _md5 = md5.new
  48. import hmac
  49. from gettext import gettext as _
  50. import socket
  51. try:
  52. from httplib2 import socks
  53. except ImportError:
  54. try:
  55. import socks
  56. except (ImportError, AttributeError):
  57. socks = None
  58. # Build the appropriate socket wrapper for ssl
  59. try:
  60. import ssl # python 2.6
  61. ssl_SSLError = ssl.SSLError
  62. def _ssl_wrap_socket(sock, key_file, cert_file,
  63. disable_validation, ca_certs):
  64. if disable_validation:
  65. cert_reqs = ssl.CERT_NONE
  66. else:
  67. cert_reqs = ssl.CERT_REQUIRED
  68. # We should be specifying SSL version 3 or TLS v1, but the ssl module
  69. # doesn't expose the necessary knobs. So we need to go with the default
  70. # of SSLv23.
  71. return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file,
  72. cert_reqs=cert_reqs, ca_certs=ca_certs)
  73. except (AttributeError, ImportError):
  74. ssl_SSLError = None
  75. def _ssl_wrap_socket(sock, key_file, cert_file,
  76. disable_validation, ca_certs):
  77. if not disable_validation:
  78. raise CertificateValidationUnsupported(
  79. "SSL certificate validation is not supported without "
  80. "the ssl module installed. To avoid this error, install "
  81. "the ssl module, or explicity disable validation.")
  82. ssl_sock = socket.ssl(sock, key_file, cert_file)
  83. return httplib.FakeSocket(sock, ssl_sock)
  84. if sys.version_info >= (2,3):
  85. from iri2uri import iri2uri
  86. else:
  87. def iri2uri(uri):
  88. return uri
  89. def has_timeout(timeout): # python 2.6
  90. if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'):
  91. return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT)
  92. return (timeout is not None)
  93. __all__ = [
  94. 'Http', 'Response', 'ProxyInfo', 'HttpLib2Error', 'RedirectMissingLocation',
  95. 'RedirectLimit', 'FailedToDecompressContent',
  96. 'UnimplementedDigestAuthOptionError',
  97. 'UnimplementedHmacDigestAuthOptionError',
  98. 'debuglevel', 'ProxiesUnavailableError']
  99. # The httplib debug level, set to a non-zero value to get debug output
  100. debuglevel = 0
  101. # A request will be tried 'RETRIES' times if it fails at the socket/connection level.
  102. RETRIES = 2
  103. # Python 2.3 support
  104. if sys.version_info < (2,4):
  105. def sorted(seq):
  106. seq.sort()
  107. return seq
  108. # Python 2.3 support
  109. def HTTPResponse__getheaders(self):
  110. """Return list of (header, value) tuples."""
  111. if self.msg is None:
  112. raise httplib.ResponseNotReady()
  113. return self.msg.items()
  114. if not hasattr(httplib.HTTPResponse, 'getheaders'):
  115. httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
  116. # All exceptions raised here derive from HttpLib2Error
  117. class HttpLib2Error(Exception): pass
  118. # Some exceptions can be caught and optionally
  119. # be turned back into responses.
  120. class HttpLib2ErrorWithResponse(HttpLib2Error):
  121. def __init__(self, desc, response, content):
  122. self.response = response
  123. self.content = content
  124. HttpLib2Error.__init__(self, desc)
  125. class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass
  126. class RedirectLimit(HttpLib2ErrorWithResponse): pass
  127. class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass
  128. class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
  129. class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
  130. class MalformedHeader(HttpLib2Error): pass
  131. class RelativeURIError(HttpLib2Error): pass
  132. class ServerNotFoundError(HttpLib2Error): pass
  133. class ProxiesUnavailableError(HttpLib2Error): pass
  134. class CertificateValidationUnsupported(HttpLib2Error): pass
  135. class SSLHandshakeError(HttpLib2Error): pass
  136. class NotSupportedOnThisPlatform(HttpLib2Error): pass
  137. class CertificateHostnameMismatch(SSLHandshakeError):
  138. def __init__(self, desc, host, cert):
  139. HttpLib2Error.__init__(self, desc)
  140. self.host = host
  141. self.cert = cert
  142. # Open Items:
  143. # -----------
  144. # Proxy support
  145. # Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
  146. # Pluggable cache storage (supports storing the cache in
  147. # flat files by default. We need a plug-in architecture
  148. # that can support Berkeley DB and Squid)
  149. # == Known Issues ==
  150. # Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
  151. # Does not handle Cache-Control: max-stale
  152. # Does not use Age: headers when calculating cache freshness.
  153. # The number of redirections to follow before giving up.
  154. # Note that only GET redirects are automatically followed.
  155. # Will also honor 301 requests by saving that info and never
  156. # requesting that URI again.
  157. DEFAULT_MAX_REDIRECTS = 5
  158. try:
  159. # Users can optionally provide a module that tells us where the CA_CERTS
  160. # are located.
  161. import ca_certs_locater
  162. CA_CERTS = ca_certs_locater.get()
  163. except ImportError:
  164. # Default CA certificates file bundled with httplib2.
  165. CA_CERTS = os.path.join(
  166. os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt")
  167. # Which headers are hop-by-hop headers by default
  168. HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade']
  169. def _get_end2end_headers(response):
  170. hopbyhop = list(HOP_BY_HOP)
  171. hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')])
  172. return [header for header in response.keys() if header not in hopbyhop]
  173. URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
  174. def parse_uri(uri):
  175. """Parses a URI using the regex given in Appendix B of RFC 3986.
  176. (scheme, authority, path, query, fragment) = parse_uri(uri)
  177. """
  178. groups = URI.match(uri).groups()
  179. return (groups[1], groups[3], groups[4], groups[6], groups[8])
  180. def urlnorm(uri):
  181. (scheme, authority, path, query, fragment) = parse_uri(uri)
  182. if not scheme or not authority:
  183. raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
  184. authority = authority.lower()
  185. scheme = scheme.lower()
  186. if not path:
  187. path = "/"
  188. # Could do syntax based normalization of the URI before
  189. # computing the digest. See Section 6.2.2 of Std 66.
  190. request_uri = query and "?".join([path, query]) or path
  191. scheme = scheme.lower()
  192. defrag_uri = scheme + "://" + authority + request_uri
  193. return scheme, authority, request_uri, defrag_uri
  194. # Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
  195. re_url_scheme = re.compile(r'^\w+://')
  196. re_slash = re.compile(r'[?/:|]+')
  197. def safename(filename):
  198. """Return a filename suitable for the cache.
  199. Strips dangerous and common characters to create a filename we
  200. can use to store the cache in.
  201. """
  202. try:
  203. if re_url_scheme.match(filename):
  204. if isinstance(filename,str):
  205. filename = filename.decode('utf-8')
  206. filename = filename.encode('idna')
  207. else:
  208. filename = filename.encode('idna')
  209. except UnicodeError:
  210. pass
  211. if isinstance(filename,unicode):
  212. filename=filename.encode('utf-8')
  213. filemd5 = _md5(filename).hexdigest()
  214. filename = re_url_scheme.sub("", filename)
  215. filename = re_slash.sub(",", filename)
  216. # limit length of filename
  217. if len(filename)>200:
  218. filename=filename[:200]
  219. return ",".join((filename, filemd5))
  220. NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+')
  221. def _normalize_headers(headers):
  222. return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()])
  223. def _parse_cache_control(headers):
  224. retval = {}
  225. if headers.has_key('cache-control'):
  226. parts = headers['cache-control'].split(',')
  227. parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")]
  228. parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")]
  229. retval = dict(parts_with_args + parts_wo_args)
  230. return retval
  231. # Whether to use a strict mode to parse WWW-Authenticate headers
  232. # Might lead to bad results in case of ill-formed header value,
  233. # so disabled by default, falling back to relaxed parsing.
  234. # Set to true to turn on, usefull for testing servers.
  235. USE_WWW_AUTH_STRICT_PARSING = 0
  236. # In regex below:
  237. # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
  238. # "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
  239. # Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
  240. # \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
  241. WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$")
  242. WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$")
  243. UNQUOTE_PAIRS = re.compile(r'\\(.)')
  244. def _parse_www_authenticate(headers, headername='www-authenticate'):
  245. """Returns a dictionary of dictionaries, one dict
  246. per auth_scheme."""
  247. retval = {}
  248. if headers.has_key(headername):
  249. try:
  250. authenticate = headers[headername].strip()
  251. www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
  252. while authenticate:
  253. # Break off the scheme at the beginning of the line
  254. if headername == 'authentication-info':
  255. (auth_scheme, the_rest) = ('digest', authenticate)
  256. else:
  257. (auth_scheme, the_rest) = authenticate.split(" ", 1)
  258. # Now loop over all the key value pairs that come after the scheme,
  259. # being careful not to roll into the next scheme
  260. match = www_auth.search(the_rest)
  261. auth_params = {}
  262. while match:
  263. if match and len(match.groups()) == 3:
  264. (key, value, the_rest) = match.groups()
  265. auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
  266. match = www_auth.search(the_rest)
  267. retval[auth_scheme.lower()] = auth_params
  268. authenticate = the_rest.strip()
  269. except ValueError:
  270. raise MalformedHeader("WWW-Authenticate")
  271. return retval
  272. def _entry_disposition(response_headers, request_headers):
  273. """Determine freshness from the Date, Expires and Cache-Control headers.
  274. We don't handle the following:
  275. 1. Cache-Control: max-stale
  276. 2. Age: headers are not used in the calculations.
  277. Not that this algorithm is simpler than you might think
  278. because we are operating as a private (non-shared) cache.
  279. This lets us ignore 's-maxage'. We can also ignore
  280. 'proxy-invalidate' since we aren't a proxy.
  281. We will never return a stale document as
  282. fresh as a design decision, and thus the non-implementation
  283. of 'max-stale'. This also lets us safely ignore 'must-revalidate'
  284. since we operate as if every server has sent 'must-revalidate'.
  285. Since we are private we get to ignore both 'public' and
  286. 'private' parameters. We also ignore 'no-transform' since
  287. we don't do any transformations.
  288. The 'no-store' parameter is handled at a higher level.
  289. So the only Cache-Control parameters we look at are:
  290. no-cache
  291. only-if-cached
  292. max-age
  293. min-fresh
  294. """
  295. retval = "STALE"
  296. cc = _parse_cache_control(request_headers)
  297. cc_response = _parse_cache_control(response_headers)
  298. if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1:
  299. retval = "TRANSPARENT"
  300. if 'cache-control' not in request_headers:
  301. request_headers['cache-control'] = 'no-cache'
  302. elif cc.has_key('no-cache'):
  303. retval = "TRANSPARENT"
  304. elif cc_response.has_key('no-cache'):
  305. retval = "STALE"
  306. elif cc.has_key('only-if-cached'):
  307. retval = "FRESH"
  308. elif response_headers.has_key('date'):
  309. date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date']))
  310. now = time.time()
  311. current_age = max(0, now - date)
  312. if cc_response.has_key('max-age'):
  313. try:
  314. freshness_lifetime = int(cc_response['max-age'])
  315. except ValueError:
  316. freshness_lifetime = 0
  317. elif response_headers.has_key('expires'):
  318. expires = email.Utils.parsedate_tz(response_headers['expires'])
  319. if None == expires:
  320. freshness_lifetime = 0
  321. else:
  322. freshness_lifetime = max(0, calendar.timegm(expires) - date)
  323. else:
  324. freshness_lifetime = 0
  325. if cc.has_key('max-age'):
  326. try:
  327. freshness_lifetime = int(cc['max-age'])
  328. except ValueError:
  329. freshness_lifetime = 0
  330. if cc.has_key('min-fresh'):
  331. try:
  332. min_fresh = int(cc['min-fresh'])
  333. except ValueError:
  334. min_fresh = 0
  335. current_age += min_fresh
  336. if freshness_lifetime > current_age:
  337. retval = "FRESH"
  338. return retval
  339. def _decompressContent(response, new_content):
  340. content = new_content
  341. try:
  342. encoding = response.get('content-encoding', None)
  343. if encoding in ['gzip', 'deflate']:
  344. if encoding == 'gzip':
  345. content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
  346. if encoding == 'deflate':
  347. content = zlib.decompress(content)
  348. response['content-length'] = str(len(content))
  349. # Record the historical presence of the encoding in a way the won't interfere.
  350. response['-content-encoding'] = response['content-encoding']
  351. del response['content-encoding']
  352. except IOError:
  353. content = ""
  354. raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content)
  355. return content
  356. def _updateCache(request_headers, response_headers, content, cache, cachekey):
  357. if cachekey:
  358. cc = _parse_cache_control(request_headers)
  359. cc_response = _parse_cache_control(response_headers)
  360. if cc.has_key('no-store') or cc_response.has_key('no-store'):
  361. cache.delete(cachekey)
  362. else:
  363. info = email.Message.Message()
  364. for key, value in response_headers.iteritems():
  365. if key not in ['status','content-encoding','transfer-encoding']:
  366. info[key] = value
  367. # Add annotations to the cache to indicate what headers
  368. # are variant for this request.
  369. vary = response_headers.get('vary', None)
  370. if vary:
  371. vary_headers = vary.lower().replace(' ', '').split(',')
  372. for header in vary_headers:
  373. key = '-varied-%s' % header
  374. try:
  375. info[key] = request_headers[header]
  376. except KeyError:
  377. pass
  378. status = response_headers.status
  379. if status == 304:
  380. status = 200
  381. status_header = 'status: %d\r\n' % status
  382. header_str = info.as_string()
  383. header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
  384. text = "".join([status_header, header_str, content])
  385. cache.set(cachekey, text)
  386. def _cnonce():
  387. dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest()
  388. return dig[:16]
  389. def _wsse_username_token(cnonce, iso_now, password):
  390. return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip()
  391. # For credentials we need two things, first
  392. # a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
  393. # Then we also need a list of URIs that have already demanded authentication
  394. # That list is tricky since sub-URIs can take the same auth, or the
  395. # auth scheme may change as you descend the tree.
  396. # So we also need each Auth instance to be able to tell us
  397. # how close to the 'top' it is.
  398. class Authentication(object):
  399. def __init__(self, credentials, host, request_uri, headers, response, content, http):
  400. (scheme, authority, path, query, fragment) = parse_uri(request_uri)
  401. self.path = path
  402. self.host = host
  403. self.credentials = credentials
  404. self.http = http
  405. def depth(self, request_uri):
  406. (scheme, authority, path, query, fragment) = parse_uri(request_uri)
  407. return request_uri[len(self.path):].count("/")
  408. def inscope(self, host, request_uri):
  409. # XXX Should we normalize the request_uri?
  410. (scheme, authority, path, query, fragment) = parse_uri(request_uri)
  411. return (host == self.host) and path.startswith(self.path)
  412. def request(self, method, request_uri, headers, content):
  413. """Modify the request headers to add the appropriate
  414. Authorization header. Over-ride this in sub-classes."""
  415. pass
  416. def response(self, response, content):
  417. """Gives us a chance to update with new nonces
  418. or such returned from the last authorized response.
  419. Over-rise this in sub-classes if necessary.
  420. Return TRUE is the request is to be retried, for
  421. example Digest may return stale=true.
  422. """
  423. return False
  424. class BasicAuthentication(Authentication):
  425. def __init__(self, credentials, host, request_uri, headers, response, content, http):
  426. Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
  427. def request(self, method, request_uri, headers, content):
  428. """Modify the request headers to add the appropriate
  429. Authorization header."""
  430. headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip()
  431. class DigestAuthentication(Authentication):
  432. """Only do qop='auth' and MD5, since that
  433. is all Apache currently implements"""
  434. def __init__(self, credentials, host, request_uri, headers, response, content, http):
  435. Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
  436. challenge = _parse_www_authenticate(response, 'www-authenticate')
  437. self.challenge = challenge['digest']
  438. qop = self.challenge.get('qop', 'auth')
  439. self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None
  440. if self.challenge['qop'] is None:
  441. raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop))
  442. self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper()
  443. if self.challenge['algorithm'] != 'MD5':
  444. raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
  445. self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]])
  446. self.challenge['nc'] = 1
  447. def request(self, method, request_uri, headers, content, cnonce = None):
  448. """Modify the request headers"""
  449. H = lambda x: _md5(x).hexdigest()
  450. KD = lambda s, d: H("%s:%s" % (s, d))
  451. A2 = "".join([method, ":", request_uri])
  452. self.challenge['cnonce'] = cnonce or _cnonce()
  453. request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (
  454. self.challenge['nonce'],
  455. '%08x' % self.challenge['nc'],
  456. self.challenge['cnonce'],
  457. self.challenge['qop'], H(A2)))
  458. headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % (
  459. self.credentials[0],
  460. self.challenge['realm'],
  461. self.challenge['nonce'],
  462. request_uri,
  463. self.challenge['algorithm'],
  464. request_digest,
  465. self.challenge['qop'],
  466. self.challenge['nc'],
  467. self.challenge['cnonce'])
  468. if self.challenge.get('opaque'):
  469. headers['authorization'] += ', opaque="%s"' % self.challenge['opaque']
  470. self.challenge['nc'] += 1
  471. def response(self, response, content):
  472. if not response.has_key('authentication-info'):
  473. challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {})
  474. if 'true' == challenge.get('stale'):
  475. self.challenge['nonce'] = challenge['nonce']
  476. self.challenge['nc'] = 1
  477. return True
  478. else:
  479. updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {})
  480. if updated_challenge.has_key('nextnonce'):
  481. self.challenge['nonce'] = updated_challenge['nextnonce']
  482. self.challenge['nc'] = 1
  483. return False
  484. class HmacDigestAuthentication(Authentication):
  485. """Adapted from Robert Sayre's code and DigestAuthentication above."""
  486. __author__ = "Thomas Broyer (t.broyer@ltgt.net)"
  487. def __init__(self, credentials, host, request_uri, headers, response, content, http):
  488. Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
  489. challenge = _parse_www_authenticate(response, 'www-authenticate')
  490. self.challenge = challenge['hmacdigest']
  491. # TODO: self.challenge['domain']
  492. self.challenge['reason'] = self.challenge.get('reason', 'unauthorized')
  493. if self.challenge['reason'] not in ['unauthorized', 'integrity']:
  494. self.challenge['reason'] = 'unauthorized'
  495. self.challenge['salt'] = self.challenge.get('salt', '')
  496. if not self.challenge.get('snonce'):
  497. raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty."))
  498. self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1')
  499. if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']:
  500. raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
  501. self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1')
  502. if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']:
  503. raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm']))
  504. if self.challenge['algorithm'] == 'HMAC-MD5':
  505. self.hashmod = _md5
  506. else:
  507. self.hashmod = _sha
  508. if self.challenge['pw-algorithm'] == 'MD5':
  509. self.pwhashmod = _md5
  510. else:
  511. self.pwhashmod = _sha
  512. self.key = "".join([self.credentials[0], ":",
  513. self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(),
  514. ":", self.challenge['realm']])
  515. self.key = self.pwhashmod.new(self.key).hexdigest().lower()
  516. def request(self, method, request_uri, headers, content):
  517. """Modify the request headers"""
  518. keys = _get_end2end_headers(headers)
  519. keylist = "".join(["%s " % k for k in keys])
  520. headers_val = "".join([headers[k] for k in keys])
  521. created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
  522. cnonce = _cnonce()
  523. request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
  524. request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
  525. headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
  526. self.credentials[0],
  527. self.challenge['realm'],
  528. self.challenge['snonce'],
  529. cnonce,
  530. request_uri,
  531. created,
  532. request_digest,
  533. keylist)
  534. def response(self, response, content):
  535. challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {})
  536. if challenge.get('reason') in ['integrity', 'stale']:
  537. return True
  538. return False
  539. class WsseAuthentication(Authentication):
  540. """This is thinly tested and should not be relied upon.
  541. At this time there isn't any third party server to test against.
  542. Blogger and TypePad implemented this algorithm at one point
  543. but Blogger has since switched to Basic over HTTPS and
  544. TypePad has implemented it wrong, by never issuing a 401
  545. challenge but instead requiring your client to telepathically know that
  546. their endpoint is expecting WSSE profile="UsernameToken"."""
  547. def __init__(self, credentials, host, request_uri, headers, response, content, http):
  548. Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
  549. def request(self, method, request_uri, headers, content):
  550. """Modify the request headers to add the appropriate
  551. Authorization header."""
  552. headers['authorization'] = 'WSSE profile="UsernameToken"'
  553. iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
  554. cnonce = _cnonce()
  555. password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
  556. headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (
  557. self.credentials[0],
  558. password_digest,
  559. cnonce,
  560. iso_now)
  561. class GoogleLoginAuthentication(Authentication):
  562. def __init__(self, credentials, host, request_uri, headers, response, content, http):
  563. from urllib import urlencode
  564. Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
  565. challenge = _parse_www_authenticate(response, 'www-authenticate')
  566. service = challenge['googlelogin'].get('service', 'xapi')
  567. # Bloggger actually returns the service in the challenge
  568. # For the rest we guess based on the URI
  569. if service == 'xapi' and request_uri.find("calendar") > 0:
  570. service = "cl"
  571. # No point in guessing Base or Spreadsheet
  572. #elif request_uri.find("spreadsheets") > 0:
  573. # service = "wise"
  574. auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent'])
  575. resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'})
  576. lines = content.split('\n')
  577. d = dict([tuple(line.split("=", 1)) for line in lines if line])
  578. if resp.status == 403:
  579. self.Auth = ""
  580. else:
  581. self.Auth = d['Auth']
  582. def request(self, method, request_uri, headers, content):
  583. """Modify the request headers to add the appropriate
  584. Authorization header."""
  585. headers['authorization'] = 'GoogleLogin Auth=' + self.Auth
  586. AUTH_SCHEME_CLASSES = {
  587. "basic": BasicAuthentication,
  588. "wsse": WsseAuthentication,
  589. "digest": DigestAuthentication,
  590. "hmacdigest": HmacDigestAuthentication,
  591. "googlelogin": GoogleLoginAuthentication
  592. }
  593. AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
  594. class FileCache(object):
  595. """Uses a local directory as a store for cached files.
  596. Not really safe to use if multiple threads or processes are going to
  597. be running on the same cache.
  598. """
  599. def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
  600. self.cache = cache
  601. self.safe = safe
  602. if not os.path.exists(cache):
  603. os.makedirs(self.cache)
  604. def get(self, key):
  605. retval = None
  606. cacheFullPath = os.path.join(self.cache, self.safe(key))
  607. try:
  608. f = file(cacheFullPath, "rb")
  609. retval = f.read()
  610. f.close()
  611. except IOError:
  612. pass
  613. return retval
  614. def set(self, key, value):
  615. cacheFullPath = os.path.join(self.cache, self.safe(key))
  616. f = file(cacheFullPath, "wb")
  617. f.write(value)
  618. f.close()
  619. def delete(self, key):
  620. cacheFullPath = os.path.join(self.cache, self.safe(key))
  621. if os.path.exists(cacheFullPath):
  622. os.remove(cacheFullPath)
  623. class Credentials(object):
  624. def __init__(self):
  625. self.credentials = []
  626. def add(self, name, password, domain=""):
  627. self.credentials.append((domain.lower(), name, password))
  628. def clear(self):
  629. self.credentials = []
  630. def iter(self, domain):
  631. for (cdomain, name, password) in self.credentials:
  632. if cdomain == "" or domain == cdomain:
  633. yield (name, password)
  634. class KeyCerts(Credentials):
  635. """Identical to Credentials except that
  636. name/password are mapped to key/cert."""
  637. pass
  638. class AllHosts(object):
  639. pass
  640. class ProxyInfo(object):
  641. """Collect information required to use a proxy."""
  642. bypass_hosts = ()
  643. def __init__(self, proxy_type, proxy_host, proxy_port,
  644. proxy_rdns=None, proxy_user=None, proxy_pass=None):
  645. """The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX
  646. constants. For example:
  647. p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP,
  648. proxy_host='localhost', proxy_port=8000)
  649. """
  650. self.proxy_type = proxy_type
  651. self.proxy_host = proxy_host
  652. self.proxy_port = proxy_port
  653. self.proxy_rdns = proxy_rdns
  654. self.proxy_user = proxy_user
  655. self.proxy_pass = proxy_pass
  656. def astuple(self):
  657. return (self.proxy_type, self.proxy_host, self.proxy_port,
  658. self.proxy_rdns, self.proxy_user, self.proxy_pass)
  659. def isgood(self):
  660. return (self.proxy_host != None) and (self.proxy_port != None)
  661. def applies_to(self, hostname):
  662. return not self.bypass_host(hostname)
  663. def bypass_host(self, hostname):
  664. """Has this host been excluded from the proxy config"""
  665. if self.bypass_hosts is AllHosts:
  666. return True
  667. bypass = False
  668. for domain in self.bypass_hosts:
  669. if hostname.endswith(domain):
  670. bypass = True
  671. return bypass
  672. def proxy_info_from_environment(method='http'):
  673. """
  674. Read proxy info from the environment variables.
  675. """
  676. if method not in ['http', 'https']:
  677. return
  678. #env_var = method + '_proxy'
  679. url = urllib.getproxies()
  680. if not url:
  681. return
  682. else:url=url[method]
  683. pi = proxy_info_from_url(url, method)
  684. #pi=urllib.getproxies()
  685. no_proxy = os.environ.get('no_proxy', os.environ.get('NO_PROXY', ''))
  686. bypass_hosts = []
  687. if no_proxy:
  688. bypass_hosts = no_proxy.split(',')
  689. # special case, no_proxy=* means all hosts bypassed
  690. if no_proxy == '*':
  691. bypass_hosts = AllHosts
  692. pi.bypass_hosts = bypass_hosts
  693. return pi
  694. def proxy_info_from_url(url, method='http'):
  695. """
  696. Construct a ProxyInfo from a URL (such as http_proxy env var)
  697. """
  698. url = urlparse.urlparse(url)
  699. username = None
  700. password = None
  701. port = None
  702. if '@' in url[1]:
  703. ident, host_port = url[1].split('@', 1)
  704. if ':' in ident:
  705. username, password = ident.split(':', 1)
  706. else:
  707. password = ident
  708. else:
  709. host_port = url[1]
  710. if ':' in host_port:
  711. host, port = host_port.split(':', 1)
  712. else:
  713. host = host_port
  714. if port:
  715. port = int(port)
  716. else:
  717. port = dict(https=443, http=80)[method]
  718. if method=='http':proxy_type = 4 # socks.PROXY_TYPE_HTTP_NO_TUNNEL
  719. elif method=='https':proxy_type = 3 # socks.PROXY_TYPE_HTTP, will use CONNECT tunnel
  720. return ProxyInfo(
  721. proxy_type = proxy_type,
  722. proxy_host = host,
  723. proxy_port = port,
  724. proxy_user = username or None,
  725. proxy_pass = password or None,
  726. )
  727. class HTTPConnectionWithTimeout(httplib.HTTPConnection):
  728. """
  729. HTTPConnection subclass that supports timeouts
  730. All timeouts are in seconds. If None is passed for timeout then
  731. Python's default timeout for sockets will be used. See for example
  732. the docs of socket.setdefaulttimeout():
  733. http://docs.python.org/library/socket.html#socket.setdefaulttimeout
  734. """
  735. def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
  736. httplib.HTTPConnection.__init__(self, host, port, strict)
  737. self.timeout = timeout
  738. self.proxy_info = proxy_info
  739. def connect(self):
  740. """Connect to the host and port specified in __init__."""
  741. # Mostly verbatim from httplib.py.
  742. if self.proxy_info and socks is None:
  743. raise ProxiesUnavailableError(
  744. 'Proxy support missing but proxy use was requested!')
  745. msg = "getaddrinfo returns an empty list"
  746. if self.proxy_info and self.proxy_info.isgood():
  747. use_proxy = True
  748. proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass = self.proxy_info.astuple()
  749. else:
  750. use_proxy = False
  751. if use_proxy and proxy_rdns:
  752. host = proxy_host
  753. port = proxy_port
  754. else:
  755. host = self.host
  756. port = self.port
  757. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  758. af, socktype, proto, canonname, sa = res
  759. try:
  760. if use_proxy:
  761. self.sock = socks.socksocket(af, socktype, proto)
  762. self.sock.setproxy(proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)
  763. else:
  764. self.sock = socket.socket(af, socktype, proto)
  765. self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  766. # Different from httplib: support timeouts.
  767. if has_timeout(self.timeout):
  768. self.sock.settimeout(self.timeout)
  769. # End of difference from httplib.
  770. if self.debuglevel > 0:
  771. print "connect: (%s, %s) ************" % (self.host, self.port)
  772. if use_proxy:
  773. print "proxy: %s ************" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
  774. self.sock.connect((self.host, self.port) + sa[2:])
  775. except socket.error, msg:
  776. if self.debuglevel > 0:
  777. print "connect fail: (%s, %s)" % (self.host, self.port)
  778. if use_proxy:
  779. print "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
  780. if self.sock:
  781. self.sock.close()
  782. self.sock = None
  783. continue
  784. break
  785. if not self.sock:
  786. raise socket.error, msg
  787. class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
  788. """
  789. This class allows communication via SSL.
  790. All timeouts are in seconds. If None is passed for timeout then
  791. Python's default timeout for sockets will be used. See for example
  792. the docs of socket.setdefaulttimeout():
  793. http://docs.python.org/library/socket.html#socket.setdefaulttimeout
  794. """
  795. def __init__(self, host, port=None, key_file=None, cert_file=None,
  796. strict=None, timeout=None, proxy_info=None,
  797. ca_certs=None, disable_ssl_certificate_validation=False):
  798. httplib.HTTPSConnection.__init__(self, host, port=port,
  799. key_file=key_file,
  800. cert_file=cert_file, strict=strict)
  801. self.timeout = timeout
  802. self.proxy_info = proxy_info
  803. if ca_certs is None:
  804. ca_certs = CA_CERTS
  805. self.ca_certs = ca_certs
  806. self.disable_ssl_certificate_validation = \
  807. disable_ssl_certificate_validation
  808. # The following two methods were adapted from https_wrapper.py, released
  809. # with the Google Appengine SDK at
  810. # http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
  811. # under the following license:
  812. #
  813. # Copyright 2007 Google Inc.
  814. #
  815. # Licensed under the Apache License, Version 2.0 (the "License");
  816. # you may not use this file except in compliance with the License.
  817. # You may obtain a copy of the License at
  818. #
  819. # http://www.apache.org/licenses/LICENSE-2.0
  820. #
  821. # Unless required by applicable law or agreed to in writing, software
  822. # distributed under the License is distributed on an "AS IS" BASIS,
  823. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  824. # See the License for the specific language governing permissions and
  825. # limitations under the License.
  826. #
  827. def _GetValidHostsForCert(self, cert):
  828. """Returns a list of valid host globs for an SSL certificate.
  829. Args:
  830. cert: A dictionary representing an SSL certificate.
  831. Returns:
  832. list: A list of valid host globs.
  833. """
  834. if 'subjectAltName' in cert:
  835. return [x[1] for x in cert['subjectAltName']
  836. if x[0].lower() == 'dns']
  837. else:
  838. return [x[0][1] for x in cert['subject']
  839. if x[0][0].lower() == 'commonname']
  840. def _ValidateCertificateHostname(self, cert, hostname):
  841. """Validates that a given hostname is valid for an SSL certificate.
  842. Args:
  843. cert: A dictionary representing an SSL certificate.
  844. hostname: The hostname to test.
  845. Returns:
  846. bool: Whether or not the hostname is valid for this certificate.
  847. """
  848. hosts = self._GetValidHostsForCert(cert)
  849. for host in hosts:
  850. host_re = host.replace('.', '\.').replace('*', '[^.]*')
  851. if re.search('^%s$' % (host_re,), hostname, re.I):
  852. return True
  853. return False
  854. def connect(self):
  855. "Connect to a host on a given (SSL) port."
  856. msg = "getaddrinfo returns an empty list"
  857. if self.proxy_info and self.proxy_info.isgood():
  858. use_proxy = True
  859. proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass = self.proxy_info.astuple()
  860. else:
  861. use_proxy = False
  862. if use_proxy and proxy_rdns:
  863. host = proxy_host
  864. port = proxy_port
  865. else:
  866. host = self.host
  867. port = self.port
  868. address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  869. for family, socktype, proto, canonname, sockaddr in address_info:
  870. try:
  871. if use_proxy:
  872. sock = socks.socksocket(family, socktype, proto)
  873. sock.setproxy(proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)
  874. else:
  875. sock = socket.socket(family, socktype, proto)
  876. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  877. if has_timeout(self.timeout):
  878. sock.settimeout(self.timeout)
  879. sock.connect((self.host, self.port))
  880. self.sock =_ssl_wrap_socket(
  881. sock, self.key_file, self.cert_file,
  882. self.disable_ssl_certificate_validation, self.ca_certs)
  883. if self.debuglevel > 0:
  884. print "connect: (%s, %s)" % (self.host, self.port)
  885. if use_proxy:
  886. print "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
  887. if not self.disable_ssl_certificate_validation:
  888. cert = self.sock.getpeercert()
  889. hostname = self.host.split(':', 0)[0]
  890. if not self._ValidateCertificateHostname(cert, hostname):
  891. raise CertificateHostnameMismatch(
  892. 'Server presented certificate that does not match '
  893. 'host %s: %s' % (hostname, cert), hostname, cert)
  894. except ssl_SSLError, e:
  895. if sock:
  896. sock.close()
  897. if self.sock:
  898. self.sock.close()
  899. self.sock = None
  900. # Unfortunately the ssl module doesn't seem to provide any way
  901. # to get at more detailed error information, in particular
  902. # whether the error is due to certificate validation or
  903. # something else (such as SSL protocol mismatch).
  904. if e.errno == ssl.SSL_ERROR_SSL:
  905. raise SSLHandshakeError(e)
  906. else:
  907. raise
  908. except (socket.timeout, socket.gaierror):
  909. raise
  910. except socket.error, msg:
  911. if self.debuglevel > 0:
  912. print "connect fail: (%s, %s)" % (self.host, self.port)
  913. if use_proxy:
  914. print "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
  915. if self.sock:
  916. self.sock.close()
  917. self.sock = None
  918. continue
  919. break
  920. if not self.sock:
  921. raise socket.error, msg
  922. SCHEME_TO_CONNECTION = {
  923. 'http': HTTPConnectionWithTimeout,
  924. 'https': HTTPSConnectionWithTimeout
  925. }
  926. # Use a different connection object for Google App Engine
  927. try:
  928. try:
  929. from google.appengine.api import apiproxy_stub_map
  930. if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
  931. raise ImportError # Bail out; we're not actually running on App Engine.
  932. from google.appengine.api.urlfetch import fetch
  933. from google.appengine.api.urlfetch import InvalidURLError
  934. except (ImportError, AttributeError):
  935. from google3.apphosting.api import apiproxy_stub_map
  936. if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
  937. raise ImportError # Bail out; we're not actually running on App Engine.
  938. from google3.apphosting.api.urlfetch import fetch
  939. from google3.apphosting.api.urlfetch import InvalidURLError
  940. def _new_fixed_fetch(validate_certificate):
  941. def fixed_fetch(url, payload=None, method="GET", headers={},
  942. allow_truncated=False, follow_redirects=True,
  943. deadline=5):
  944. return fetch(url, payload=payload, method=method, headers=headers,
  945. allow_truncated=allow_truncated,
  946. follow_redirects=follow_redirects, deadline=deadline,
  947. validate_certificate=validate_certificate)
  948. return fixed_fetch
  949. class AppEngineHttpConnection(httplib.HTTPConnection):
  950. """Use httplib on App Engine, but compensate for its weirdness.
  951. The parameters key_file, cert_file, proxy_info, ca_certs, and
  952. disable_ssl_certificate_validation are all dropped on the ground.
  953. """
  954. def __init__(self, host, port=None, key_file=None, cert_file=None,
  955. strict=None, timeout=None, proxy_info=None, ca_certs=None,
  956. disable_ssl_certificate_validation=False):
  957. httplib.HTTPConnection.__init__(self, host, port=port,
  958. strict=strict, timeout=timeout)
  959. class AppEngineHttpsConnection(httplib.HTTPSConnection):
  960. """Same as AppEngineHttpConnection, but for HTTPS URIs."""
  961. def __init__(self, host, port=None, key_file=None, cert_file=None,
  962. strict=None, timeout=None, proxy_info=None, ca_certs=None,
  963. disable_ssl_certificate_validation=False):
  964. httplib.HTTPSConnection.__init__(self, host, port=port,
  965. key_file=key_file,
  966. cert_file=cert_file, strict=strict,
  967. timeout=timeout)
  968. self._fetch = _new_fixed_fetch(
  969. not disable_ssl_certificate_validation)
  970. # Update the connection classes to use the Googel App Engine specific ones.
  971. SCHEME_TO_CONNECTION = {
  972. 'http': AppEngineHttpConnection,
  973. 'https': AppEngineHttpsConnection
  974. }
  975. except (ImportError, AttributeError):
  976. pass
  977. class Http(object):
  978. """An HTTP client that handles:
  979. - all methods
  980. - caching
  981. - ETags
  982. - compression,
  983. - HTTPS
  984. - Basic
  985. - Digest
  986. - WSSE
  987. and more.
  988. """
  989. def __init__(self, cache=None, timeout=None,
  990. proxy_info=proxy_info_from_environment,
  991. ca_certs=None, disable_ssl_certificate_validation=False,callback_hook=None,chunk_size=0):
  992. """If 'cache' is a string then it is used as a directory name for
  993. a disk cache. Otherwise it must be an object that supports the
  994. same interface as FileCache.
  995. All timeouts are in seconds. If None is passed for timeout
  996. then Python's default timeout for sockets will be used. See
  997. for example the docs of socket.setdefaulttimeout():
  998. http://docs.python.org/library/socket.html#socket.setdefaulttimeout
  999. `proxy_info` may be:
  1000. - a callable that takes the http scheme ('http' or 'https') and
  1001. returns a ProxyInfo instance per request. By default, uses
  1002. proxy_nfo_from_environment.
  1003. - a ProxyInfo instance (static proxy config).
  1004. - None (proxy disabled).
  1005. ca_certs is the path of a file containing root CA certificates for SSL
  1006. server certificate validation. By default, a CA cert file bundled with
  1007. httplib2 is used.
  1008. If disable_ssl_certificate_validation is true, SSL cert validation will
  1009. not be performed.
  1010. """
  1011. self.proxy_info = proxy_info
  1012. self.ca_certs = ca_certs
  1013. self.disable_ssl_certificate_validation = \
  1014. disable_ssl_certificate_validation
  1015. self.chunk_size=chunk_size
  1016. self.callback_hook=callback_hook
  1017. # Map domain name to an httplib connection
  1018. self.connections = {}
  1019. # The location of the cache, for now a directory
  1020. # where cached responses are held.
  1021. if cache and isinstance(cache, basestring):
  1022. self.cache = FileCache(cache)
  1023. else:
  1024. self.cache = cache
  1025. # Name/password
  1026. self.credentials = Credentials()
  1027. # Key/cert
  1028. self.certificates = KeyCerts()
  1029. # authorization objects
  1030. self.authorizations = []
  1031. # If set to False then no redirects are followed, even safe ones.
  1032. self.follow_redirects = True
  1033. # Which HTTP methods do we apply optimistic concurrency to, i.e.
  1034. # which methods get an "if-match:" etag header added to them.
  1035. self.optimistic_concurrency_methods = ["PUT", "PATCH"]
  1036. # If 'follow_redirects' is True, and this is set to True then
  1037. # all redirecs are followed, including unsafe ones.
  1038. self.follow_all_redirects = False
  1039. self.ignore_etag = False
  1040. self.force_exception_to_status_code = False
  1041. self.timeout = timeout
  1042. # Keep Authorization: headers on a redirect.
  1043. self.forward_authorization_headers = False
  1044. def __getstate__(self):
  1045. state_dict = copy.copy(self.__dict__)
  1046. # In case request is augmented by some foreign object such as
  1047. # credentials which handle auth
  1048. if 'request' in state_dict:
  1049. del state_dict['request']
  1050. if 'connections' in state_dict:
  1051. del state_dict['connections']
  1052. return state_dict
  1053. def __setstate__(self, state):
  1054. self.__dict__.update(state)
  1055. self.connections = {}
  1056. def _auth_from_challenge(self, host, request_uri, headers, response, content):
  1057. """A generator that creates Authorization objects
  1058. that can be applied to requests.
  1059. """
  1060. challenges = _parse_www_authenticate(response, 'www-authenticate')
  1061. for cred in self.credentials.iter(host):
  1062. for scheme in AUTH_SCHEME_ORDER:
  1063. if challenges.has_key(scheme):
  1064. yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self)
  1065. def add_credentials(self, name, password, domain=""):
  1066. """Add a name and password that will be used
  1067. any time a request requires authentication."""
  1068. self.credentials.add(name, password, domain)
  1069. def add_certificate(self, key, cert, domain):
  1070. """Add a key and cert that will be used
  1071. any time a request requires authentication."""
  1072. self.certificates.add(key, cert, domain)
  1073. def clear_credentials(self):
  1074. """Remove all the names and passwords
  1075. that are used for authentication"""
  1076. self.credentials.clear()
  1077. self.authorizations = []
  1078. def _conn_request(self, conn, request_uri, method, body, headers):
  1079. i = 0
  1080. seen_bad_status_line = False
  1081. while i < RETRIES:
  1082. i += 1
  1083. try:
  1084. if hasattr(conn, 'sock') and conn.sock is None:
  1085. conn.connect()
  1086. conn.request(method, request_uri, body, headers)
  1087. except socket.timeout:
  1088. raise
  1089. except socket.gaierror:
  1090. conn.close()
  1091. raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
  1092. except ssl_SSLError:
  1093. conn.close()
  1094. raise
  1095. except socket.error, e:
  1096. err = 0
  1097. if hasattr(e, 'args'):
  1098. err = getattr(e, 'args')[0]
  1099. else:
  1100. err = e.errno
  1101. if err == errno.ECONNREFUSED: # Connection refused
  1102. raise
  1103. except httplib.HTTPException:
  1104. # Just because the server closed the connection doesn't apparently mean
  1105. # that the server didn't send a response.
  1106. if hasattr(conn, 'sock') and conn.sock is None:
  1107. if i < RETRIES-1:
  1108. conn.close()
  1109. conn.connect()
  1110. continue
  1111. else:
  1112. conn.close()
  1113. raise
  1114. if i < RETRIES-1:
  1115. conn.close()
  1116. conn.connect()
  1117. continue
  1118. try:
  1119. response = conn.getresponse()
  1120. except httplib.BadStatusLine:
  1121. # If we get a BadStatusLine on the first try then that means
  1122. # the connection just went stale, so retry regardless of the
  1123. # number of RETRIES set.
  1124. if not seen_bad_status_line and i == 1:
  1125. i = 0
  1126. seen_bad_status_line = True
  1127. conn.close()
  1128. conn.connect()
  1129. continue
  1130. else:
  1131. conn.close()
  1132. raise
  1133. except (socket.error, httplib.HTTPException):
  1134. if i < RETRIES-1:
  1135. conn.close()
  1136. conn.connect()
  1137. continue
  1138. else:
  1139. conn.close()
  1140. raise
  1141. else:
  1142. content = ""
  1143. if method == "HEAD":
  1144. conn.close()
  1145. else:
  1146. if self.callback_hook:#!= None:
  1147. while 1:
  1148. chunk= response.read(self.chunk_size)
  1149. content +=chunk
  1150. if not chunk:break
  1151. self.callback_hook(len(chunk),len(content))
  1152. else:
  1153. content = response.read()
  1154. response = Response(response)
  1155. if method != "HEAD":
  1156. content = _decompressContent(response, content)
  1157. break
  1158. return (response, content)
  1159. def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
  1160. """Do the actual request using the connection object
  1161. and also follow one level of redirects if necessary"""
  1162. auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
  1163. auth = auths and sorted(auths)[0][1] or None
  1164. if auth:
  1165. auth.request(method, request_uri, headers, body)
  1166. (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  1167. if auth:
  1168. if auth.response(response, body):
  1169. auth.request(method, request_uri, headers, body)
  1170. (response, content) = self._conn_request(conn, request_uri, method, body, headers )
  1171. response._stale_digest = 1
  1172. if response.status == 401:
  1173. for authorization in self._auth_from_challenge(host, request_uri, headers, response, content):
  1174. authorization.request(method, request_uri, headers, body)
  1175. (response, content) = self._conn_request(conn, request_uri, method, body, headers, )
  1176. if response.status != 401:
  1177. self.authorizations.append(authorization)
  1178. authorization.response(response, body)
  1179. break
  1180. if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303):
  1181. if self.follow_redirects and response.status in [300, 301, 302, 303, 307]:
  1182. # Pick out the location header and basically start from the beginning
  1183. # remembering first to strip the ETag header and decrement our 'depth'
  1184. if redirections:
  1185. if not response.has_key('location') and response.status != 300:
  1186. raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content)
  1187. # Fix-up relative redirects (which violate an RFC 2616 MUST)
  1188. if response.has_key('location'):
  1189. location = response['location']
  1190. (scheme, authority, path, query, fragment) = parse_uri(location)
  1191. if authority == None:
  1192. response['location'] = urlparse.urljoin(absolute_uri, location)
  1193. if response.status == 301 and method in ["GET", "HEAD"]:
  1194. response['-x-permanent-redirect-url'] = response['location']
  1195. if not response.has_key('content-location'):
  1196. response['content-location'] = absolute_uri
  1197. _updateCache(headers, response, content, self.cache, cachekey)
  1198. if headers.has_key('if-none-match'):
  1199. del headers['if-none-match']
  1200. if headers.has_key('if-modified-since'):
  1201. del headers['if-modified-since']
  1202. if 'authorization' in headers and not self.forward_authorization_headers:
  1203. del headers['authorization']
  1204. if response.has_key('location'):
  1205. location = response['location']
  1206. old_response = copy.deepcopy(response)
  1207. if not old_response.has_key('content-location'):
  1208. old_response['content-location'] = absolute_uri
  1209. redirect_method = method
  1210. if response.status in [302, 303]:
  1211. redirect_method = "GET"
  1212. body = None
  1213. (response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1)
  1214. response.previous = old_response
  1215. else:
  1216. raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content)
  1217. elif response.status in [200, 203] and method in ["GET", "HEAD"]:
  1218. # Don't cache 206's since we aren't going to handle byte range requests
  1219. if not response.has_key('content-location'):
  1220. response['content-location'] = absolute_uri
  1221. _updateCache(headers, response, content, self.cache, cachekey)
  1222. return (response, content)
  1223. def _normalize_headers(self, headers):
  1224. return _normalize_headers(headers)
  1225. # Need to catch and rebrand some exceptions
  1226. # Then need to optionally turn all exceptions into status codes
  1227. # including all socket.* and httplib.* exceptions.
  1228. def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
  1229. """ Performs a single HTTP request.
  1230. The 'uri' is the URI of the HTTP resource and can begin with either
  1231. 'http' or 'https'. The value of 'uri' must be an absolute URI.
  1232. The 'method' is the HTTP method to perform, such as GET, POST, DELETE,
  1233. etc. There is no restriction on the methods allowed.
  1234. The 'body' is the entity body to be sent with the request. It is a
  1235. string object.
  1236. Any extra headers that are to be sent with the request should be
  1237. provided in the 'headers' dictionary.
  1238. The maximum number of redirect to follow before raising an
  1239. exception is 'redirections. The default is 5.
  1240. The return value is a tuple of (response, content), the first
  1241. being and instance of the 'Response' class, the second being
  1242. a string that contains the response entity body.
  1243. """
  1244. try:
  1245. if headers is None:
  1246. headers = {}
  1247. else:
  1248. headers = self._normalize_headers(headers)
  1249. if not headers.has_key('user-agent'):
  1250. headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__
  1251. uri = iri2uri(uri)
  1252. (scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
  1253. domain_port = authority.split(":")[0:2]
  1254. if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http':
  1255. scheme = 'https'
  1256. authority = domain_port[0]
  1257. proxy_info = self._get_proxy_info(scheme, authority)
  1258. conn_key = scheme+":"+authority
  1259. if conn_key in self.connections:
  1260. conn = self.connections[conn_key]
  1261. else:
  1262. if not connection_type:
  1263. connection_type = SCHEME_TO_CONNECTION[scheme]
  1264. certs = list(self.certificates.iter(authority))
  1265. if scheme == 'https':
  1266. if certs:
  1267. conn = self.connections[conn_key] = connection_type(
  1268. authority, key_file=certs[0][0],
  1269. cert_file=certs[0][1], timeout=self.timeout,
  1270. proxy_info=proxy_info,
  1271. ca_certs=self.ca_certs,
  1272. disable_ssl_certificate_validation=
  1273. self.disable_ssl_certificate_validation)
  1274. else:
  1275. conn = self.connections[conn_key] = connection_type(
  1276. authority, timeout=self.timeout,
  1277. proxy_info=proxy_info,
  1278. ca_certs=self.ca_certs,
  1279. disable_ssl_certificate_validation=
  1280. self.disable_ssl_certificate_validation)
  1281. else:
  1282. conn = self.connections[conn_key] = connection_type(
  1283. authority, timeout=self.timeout,
  1284. proxy_info=proxy_info)
  1285. conn.set_debuglevel(debuglevel)
  1286. if 'range' not in headers and 'accept-encoding' not in headers:
  1287. headers['accept-encoding'] = 'gzip, deflate'
  1288. info = email.Message.Message()
  1289. cached_value = None
  1290. if self.cache:
  1291. cachekey = defrag_uri
  1292. cached_value = self.cache.get(cachekey)
  1293. if cached_value:
  1294. # info = email.message_from_string(cached_value)
  1295. #
  1296. # Need to replace the line above with the kludge below
  1297. # to fix the non-existent bug not fixed in this
  1298. # bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
  1299. try:
  1300. info, content = cached_value.split('\r\n\r\n', 1)
  1301. feedparser = email.FeedParser.FeedParser()
  1302. feedparser.feed(info)
  1303. info = feedparser.close()
  1304. feedparser._parse = None
  1305. except (IndexError, ValueError):
  1306. self.cache.delete(cachekey)
  1307. cachekey = None
  1308. cached_value = None
  1309. else:
  1310. cachekey = None
  1311. if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers:
  1312. # http://www.w3.org/1999/04/Editing/
  1313. headers['if-match'] = info['etag']
  1314. if method not in ["GET", "HEAD"] and self.cache and cachekey:
  1315. # RFC 2616 Section 13.10
  1316. self.cache.delete(cachekey)
  1317. # Check the vary header in the cache to see if this request
  1318. # matches what varies in the cache.
  1319. if method in ['GET', 'HEAD'] and 'vary' in info:
  1320. vary = info['vary']
  1321. vary_headers = vary.lower().replace(' ', '').split(',')
  1322. for header in vary_headers:
  1323. key = '-varied-%s' % header
  1324. value = info[key]
  1325. if headers.get(header, None) != value:
  1326. cached_value = None
  1327. break
  1328. if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers:
  1329. if info.has_key('-x-permanent-redirect-url'):
  1330. # Should cached permanent redirects be counted in our redirection count? For now, yes.
  1331. if redirections <= 0:
  1332. raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "")
  1333. (response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1)
  1334. response.previous = Response(info)
  1335. response.previous.fromcache = True
  1336. else:
  1337. # Determine our course of action:
  1338. # Is the cached entry fresh or stale?
  1339. # Has the client requested a non-cached response?
  1340. #
  1341. # There seems to be three possible answers:
  1342. # 1. [FRESH] Return the cache entry w/o doing a GET
  1343. # 2. [STALE] Do the GET (but add in cache validators if available)
  1344. # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
  1345. entry_disposition = _entry_disposition(info, headers)
  1346. if entry_disposition == "FRESH":
  1347. if not cached_value:
  1348. info['status'] = '504'
  1349. content = ""
  1350. response = Response(info)
  1351. if cached_value:
  1352. response.fromcache = True
  1353. return (response, content)
  1354. if entry_disposition == "STALE":
  1355. if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers:
  1356. headers['if-none-match'] = info['etag']
  1357. if info.has_key('last-modified') and not 'last-modified' in headers:
  1358. headers['if-modified-since'] = info['last-modified']
  1359. elif entry_disposition == "TRANSPARENT":
  1360. pass
  1361. (response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  1362. if response.status == 304 and method == "GET":
  1363. # Rewrite the cache entry with the new end-to-end headers
  1364. # Take all headers that are in response
  1365. # and overwrite their values in info.
  1366. # unless they are hop-by-hop, or are listed in the connection header.
  1367. for key in _get_end2end_headers(response):
  1368. info[key] = response[key]
  1369. merged_response = Response(info)
  1370. if hasattr(response, "_stale_digest"):
  1371. merged_response._stale_digest = response._stale_digest
  1372. _updateCache(headers, merged_response, content, self.cache, cachekey)
  1373. response = merged_response
  1374. response.status = 200
  1375. response.fromcache = True
  1376. elif response.status == 200:
  1377. content = new_content
  1378. else:
  1379. self.cache.delete(cachekey)
  1380. content = new_content
  1381. else:
  1382. cc = _parse_cache_control(headers)
  1383. if cc.has_key('only-if-cached'):
  1384. info['status'] = '504'
  1385. response = Response(info)
  1386. content = ""
  1387. else:
  1388. (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  1389. except Exception, e:
  1390. if self.force_exception_to_status_code:
  1391. if isinstance(e, HttpLib2ErrorWithResponse):
  1392. response = e.response
  1393. content = e.content
  1394. response.status = 500
  1395. response.reason = str(e)
  1396. elif isinstance(e, socket.timeout):
  1397. content = "Request Timeout"
  1398. response = Response({
  1399. "content-type": "text/plain",
  1400. "status": "408",
  1401. "content-length": len(content)
  1402. })
  1403. response.reason = "Request Timeout"
  1404. else:
  1405. content = str(e)
  1406. response = Response({
  1407. "content-type": "text/plain",
  1408. "status": "400",
  1409. "content-length": len(content)
  1410. })
  1411. response.reason = "Bad Request"
  1412. else:
  1413. raise
  1414. return (response, content)
  1415. def _get_proxy_info(self, scheme, authority):
  1416. """Return a ProxyInfo instance (or None) based on the scheme
  1417. and authority.
  1418. """
  1419. hostname, port = urllib.splitport(authority)
  1420. proxy_info = self.proxy_info
  1421. if callable(proxy_info):
  1422. proxy_info = proxy_info(scheme)
  1423. if (hasattr(proxy_info, 'applies_to')
  1424. and not proxy_info.applies_to(hostname)):
  1425. proxy_info = None
  1426. return proxy_info
  1427. class Response(dict):
  1428. """An object more like email.Message than httplib.HTTPResponse."""
  1429. """Is this response from our local cache"""
  1430. fromcache = False
  1431. """HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """
  1432. version = 11
  1433. "Status code returned by server. "
  1434. status = 200
  1435. """Reason phrase returned by server."""
  1436. reason = "Ok"
  1437. previous = None
  1438. def __init__(self, info):
  1439. # info is either an email.Message or
  1440. # an httplib.HTTPResponse object.
  1441. if isinstance(info, httplib.HTTPResponse):
  1442. for key, value in info.getheaders():
  1443. self[key.lower()] = value
  1444. self.status = info.status
  1445. self['status'] = str(self.status)
  1446. self.reason = info.reason
  1447. self.version = info.version
  1448. elif isinstance(info, email.Message.Message):
  1449. for key, value in info.items():
  1450. self[key.lower()] = value
  1451. self.status = int(self['status'])
  1452. else:
  1453. for key, value in info.iteritems():
  1454. self[key.lower()] = value
  1455. self.status = int(self.get('status', self.status))
  1456. self.reason = self.get('reason', self.reason)
  1457. def __getattr__(self, name):
  1458. if name == 'dict':
  1459. return self
  1460. else:
  1461. raise AttributeError, name