PageRenderTime 52ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/httplib2plus/__init__.py

https://github.com/fffonion/RoameBot
Python | 1685 lines | 1655 code | 7 blank | 23 comment | 17 complexity | 121995b36a4f425e7c3566e66997c677 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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(

Large files files are truncated, but you can click here to view the full file