You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2040 lines
72KB

  1. # -*- coding: utf-8 -*-
  2. """Small, fast HTTP client library for Python."""
  3. __author__ = "Joe Gregorio (joe@bitworking.org)"
  4. __copyright__ = "Copyright 2006, Joe Gregorio"
  5. __contributors__ = [
  6. "Thomas Broyer (t.broyer@ltgt.net)",
  7. "James Antill",
  8. "Xavier Verges Farrero",
  9. "Jonathan Feinberg",
  10. "Blair Zajac",
  11. "Sam Ruby",
  12. "Louis Nyffenegger",
  13. "Mark Pilgrim",
  14. "Alex Yu",
  15. ]
  16. __license__ = "MIT"
  17. __version__ = '0.13.1'
  18. import base64
  19. import calendar
  20. import copy
  21. import email
  22. import email.feedparser
  23. from email import header
  24. import email.message
  25. import email.utils
  26. import errno
  27. from gettext import gettext as _
  28. import gzip
  29. from hashlib import md5 as _md5
  30. from hashlib import sha1 as _sha
  31. import hmac
  32. import http.client
  33. import io
  34. import os
  35. import random
  36. import re
  37. import socket
  38. import ssl
  39. import sys
  40. import time
  41. import urllib.parse
  42. import zlib
  43. try:
  44. import socks
  45. except ImportError:
  46. # TODO: remove this fallback and copypasted socksipy module upon py2/3 merge,
  47. # idea is to have soft-dependency on any compatible module called socks
  48. from . import socks
  49. from .iri2uri import iri2uri
  50. def has_timeout(timeout):
  51. if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"):
  52. return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT
  53. return timeout is not None
  54. __all__ = [
  55. "debuglevel",
  56. "FailedToDecompressContent",
  57. "Http",
  58. "HttpLib2Error",
  59. "ProxyInfo",
  60. "RedirectLimit",
  61. "RedirectMissingLocation",
  62. "Response",
  63. "RETRIES",
  64. "UnimplementedDigestAuthOptionError",
  65. "UnimplementedHmacDigestAuthOptionError",
  66. ]
  67. # The httplib debug level, set to a non-zero value to get debug output
  68. debuglevel = 0
  69. # A request will be tried 'RETRIES' times if it fails at the socket/connection level.
  70. RETRIES = 2
  71. # All exceptions raised here derive from HttpLib2Error
  72. class HttpLib2Error(Exception):
  73. pass
  74. # Some exceptions can be caught and optionally
  75. # be turned back into responses.
  76. class HttpLib2ErrorWithResponse(HttpLib2Error):
  77. def __init__(self, desc, response, content):
  78. self.response = response
  79. self.content = content
  80. HttpLib2Error.__init__(self, desc)
  81. class RedirectMissingLocation(HttpLib2ErrorWithResponse):
  82. pass
  83. class RedirectLimit(HttpLib2ErrorWithResponse):
  84. pass
  85. class FailedToDecompressContent(HttpLib2ErrorWithResponse):
  86. pass
  87. class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse):
  88. pass
  89. class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse):
  90. pass
  91. class MalformedHeader(HttpLib2Error):
  92. pass
  93. class RelativeURIError(HttpLib2Error):
  94. pass
  95. class ServerNotFoundError(HttpLib2Error):
  96. pass
  97. class ProxiesUnavailableError(HttpLib2Error):
  98. pass
  99. # Open Items:
  100. # -----------
  101. # Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
  102. # Pluggable cache storage (supports storing the cache in
  103. # flat files by default. We need a plug-in architecture
  104. # that can support Berkeley DB and Squid)
  105. # == Known Issues ==
  106. # Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
  107. # Does not handle Cache-Control: max-stale
  108. # Does not use Age: headers when calculating cache freshness.
  109. # The number of redirections to follow before giving up.
  110. # Note that only GET redirects are automatically followed.
  111. # Will also honor 301 requests by saving that info and never
  112. # requesting that URI again.
  113. DEFAULT_MAX_REDIRECTS = 5
  114. # Which headers are hop-by-hop headers by default
  115. HOP_BY_HOP = [
  116. "connection",
  117. "keep-alive",
  118. "proxy-authenticate",
  119. "proxy-authorization",
  120. "te",
  121. "trailers",
  122. "transfer-encoding",
  123. "upgrade",
  124. ]
  125. from httplib2 import certs
  126. CA_CERTS = certs.where()
  127. # PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated.
  128. # Both PROTOCOL_TLS and PROTOCOL_SSLv23 are equivalent and means:
  129. # > Selects the highest protocol version that both the client and server support.
  130. # > Despite the name, this option can select “TLS” protocols as well as “SSL”.
  131. # source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS
  132. DEFAULT_TLS_VERSION = getattr(ssl, "PROTOCOL_TLS", None) or getattr(
  133. ssl, "PROTOCOL_SSLv23"
  134. )
  135. def _build_ssl_context(
  136. disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None,
  137. maximum_version=None, minimum_version=None,
  138. ):
  139. if not hasattr(ssl, "SSLContext"):
  140. raise RuntimeError("httplib2 requires Python 3.2+ for ssl.SSLContext")
  141. context = ssl.SSLContext(DEFAULT_TLS_VERSION)
  142. context.verify_mode = (
  143. ssl.CERT_NONE if disable_ssl_certificate_validation else ssl.CERT_REQUIRED
  144. )
  145. # SSLContext.maximum_version and SSLContext.minimum_version are python 3.7+.
  146. # source: https://docs.python.org/3/library/ssl.html#ssl.SSLContext.maximum_version
  147. if maximum_version is not None:
  148. if hasattr(context, "maximum_version"):
  149. context.maximum_version = getattr(ssl.TLSVersion, maximum_version)
  150. else:
  151. raise RuntimeError("setting tls_maximum_version requires Python 3.7 and OpenSSL 1.1 or newer")
  152. if minimum_version is not None:
  153. if hasattr(context, "minimum_version"):
  154. context.minimum_version = getattr(ssl.TLSVersion, minimum_version)
  155. else:
  156. raise RuntimeError("setting tls_minimum_version requires Python 3.7 and OpenSSL 1.1 or newer")
  157. # check_hostname requires python 3.4+
  158. # we will perform the equivalent in HTTPSConnectionWithTimeout.connect() by calling ssl.match_hostname
  159. # if check_hostname is not supported.
  160. if hasattr(context, "check_hostname"):
  161. context.check_hostname = not disable_ssl_certificate_validation
  162. context.load_verify_locations(ca_certs)
  163. if cert_file:
  164. context.load_cert_chain(cert_file, key_file)
  165. return context
  166. def _get_end2end_headers(response):
  167. hopbyhop = list(HOP_BY_HOP)
  168. hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")])
  169. return [header for header in list(response.keys()) if header not in hopbyhop]
  170. URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
  171. def parse_uri(uri):
  172. """Parses a URI using the regex given in Appendix B of RFC 3986.
  173. (scheme, authority, path, query, fragment) = parse_uri(uri)
  174. """
  175. groups = URI.match(uri).groups()
  176. return (groups[1], groups[3], groups[4], groups[6], groups[8])
  177. def urlnorm(uri):
  178. (scheme, authority, path, query, fragment) = parse_uri(uri)
  179. if not scheme or not authority:
  180. raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
  181. authority = authority.lower()
  182. scheme = scheme.lower()
  183. if not path:
  184. path = "/"
  185. # Could do syntax based normalization of the URI before
  186. # computing the digest. See Section 6.2.2 of Std 66.
  187. request_uri = query and "?".join([path, query]) or path
  188. scheme = scheme.lower()
  189. defrag_uri = scheme + "://" + authority + request_uri
  190. return scheme, authority, request_uri, defrag_uri
  191. # Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
  192. re_url_scheme = re.compile(r"^\w+://")
  193. re_unsafe = re.compile(r"[^\w\-_.()=!]+", re.ASCII)
  194. def safename(filename):
  195. """Return a filename suitable for the cache.
  196. Strips dangerous and common characters to create a filename we
  197. can use to store the cache in.
  198. """
  199. if isinstance(filename, bytes):
  200. filename_bytes = filename
  201. filename = filename.decode("utf-8")
  202. else:
  203. filename_bytes = filename.encode("utf-8")
  204. filemd5 = _md5(filename_bytes).hexdigest()
  205. filename = re_url_scheme.sub("", filename)
  206. filename = re_unsafe.sub("", filename)
  207. # limit length of filename (vital for Windows)
  208. # https://github.com/httplib2/httplib2/pull/74
  209. # C:\Users\ <username> \AppData\Local\Temp\ <safe_filename> , <md5>
  210. # 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars
  211. # Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:
  212. filename = filename[:90]
  213. return ",".join((filename, filemd5))
  214. NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+")
  215. def _normalize_headers(headers):
  216. return dict(
  217. [
  218. (
  219. _convert_byte_str(key).lower(),
  220. NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),
  221. )
  222. for (key, value) in headers.items()
  223. ]
  224. )
  225. def _convert_byte_str(s):
  226. if not isinstance(s, str):
  227. return str(s, "utf-8")
  228. return s
  229. def _parse_cache_control(headers):
  230. retval = {}
  231. if "cache-control" in headers:
  232. parts = headers["cache-control"].split(",")
  233. parts_with_args = [
  234. tuple([x.strip().lower() for x in part.split("=", 1)])
  235. for part in parts
  236. if -1 != part.find("=")
  237. ]
  238. parts_wo_args = [
  239. (name.strip().lower(), 1) for name in parts if -1 == name.find("=")
  240. ]
  241. retval = dict(parts_with_args + parts_wo_args)
  242. return retval
  243. # Whether to use a strict mode to parse WWW-Authenticate headers
  244. # Might lead to bad results in case of ill-formed header value,
  245. # so disabled by default, falling back to relaxed parsing.
  246. # Set to true to turn on, usefull for testing servers.
  247. USE_WWW_AUTH_STRICT_PARSING = 0
  248. # In regex below:
  249. # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
  250. # "(?:[^\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
  251. # 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:
  252. # \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
  253. WWW_AUTH_STRICT = re.compile(
  254. r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$"
  255. )
  256. WWW_AUTH_RELAXED = re.compile(
  257. r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$"
  258. )
  259. UNQUOTE_PAIRS = re.compile(r"\\(.)")
  260. def _parse_www_authenticate(headers, headername="www-authenticate"):
  261. """Returns a dictionary of dictionaries, one dict
  262. per auth_scheme."""
  263. retval = {}
  264. if headername in headers:
  265. try:
  266. authenticate = headers[headername].strip()
  267. www_auth = (
  268. USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
  269. )
  270. while authenticate:
  271. # Break off the scheme at the beginning of the line
  272. if headername == "authentication-info":
  273. (auth_scheme, the_rest) = ("digest", authenticate)
  274. else:
  275. (auth_scheme, the_rest) = authenticate.split(" ", 1)
  276. # Now loop over all the key value pairs that come after the scheme,
  277. # being careful not to roll into the next scheme
  278. match = www_auth.search(the_rest)
  279. auth_params = {}
  280. while match:
  281. if match and len(match.groups()) == 3:
  282. (key, value, the_rest) = match.groups()
  283. auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
  284. r"\1", value
  285. ) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
  286. match = www_auth.search(the_rest)
  287. retval[auth_scheme.lower()] = auth_params
  288. authenticate = the_rest.strip()
  289. except ValueError:
  290. raise MalformedHeader("WWW-Authenticate")
  291. return retval
  292. def _entry_disposition(response_headers, request_headers):
  293. """Determine freshness from the Date, Expires and Cache-Control headers.
  294. We don't handle the following:
  295. 1. Cache-Control: max-stale
  296. 2. Age: headers are not used in the calculations.
  297. Not that this algorithm is simpler than you might think
  298. because we are operating as a private (non-shared) cache.
  299. This lets us ignore 's-maxage'. We can also ignore
  300. 'proxy-invalidate' since we aren't a proxy.
  301. We will never return a stale document as
  302. fresh as a design decision, and thus the non-implementation
  303. of 'max-stale'. This also lets us safely ignore 'must-revalidate'
  304. since we operate as if every server has sent 'must-revalidate'.
  305. Since we are private we get to ignore both 'public' and
  306. 'private' parameters. We also ignore 'no-transform' since
  307. we don't do any transformations.
  308. The 'no-store' parameter is handled at a higher level.
  309. So the only Cache-Control parameters we look at are:
  310. no-cache
  311. only-if-cached
  312. max-age
  313. min-fresh
  314. """
  315. retval = "STALE"
  316. cc = _parse_cache_control(request_headers)
  317. cc_response = _parse_cache_control(response_headers)
  318. if (
  319. "pragma" in request_headers
  320. and request_headers["pragma"].lower().find("no-cache") != -1
  321. ):
  322. retval = "TRANSPARENT"
  323. if "cache-control" not in request_headers:
  324. request_headers["cache-control"] = "no-cache"
  325. elif "no-cache" in cc:
  326. retval = "TRANSPARENT"
  327. elif "no-cache" in cc_response:
  328. retval = "STALE"
  329. elif "only-if-cached" in cc:
  330. retval = "FRESH"
  331. elif "date" in response_headers:
  332. date = calendar.timegm(email.utils.parsedate_tz(response_headers["date"]))
  333. now = time.time()
  334. current_age = max(0, now - date)
  335. if "max-age" in cc_response:
  336. try:
  337. freshness_lifetime = int(cc_response["max-age"])
  338. except ValueError:
  339. freshness_lifetime = 0
  340. elif "expires" in response_headers:
  341. expires = email.utils.parsedate_tz(response_headers["expires"])
  342. if None == expires:
  343. freshness_lifetime = 0
  344. else:
  345. freshness_lifetime = max(0, calendar.timegm(expires) - date)
  346. else:
  347. freshness_lifetime = 0
  348. if "max-age" in cc:
  349. try:
  350. freshness_lifetime = int(cc["max-age"])
  351. except ValueError:
  352. freshness_lifetime = 0
  353. if "min-fresh" in cc:
  354. try:
  355. min_fresh = int(cc["min-fresh"])
  356. except ValueError:
  357. min_fresh = 0
  358. current_age += min_fresh
  359. if freshness_lifetime > current_age:
  360. retval = "FRESH"
  361. return retval
  362. def _decompressContent(response, new_content):
  363. content = new_content
  364. try:
  365. encoding = response.get("content-encoding", None)
  366. if encoding in ["gzip", "deflate"]:
  367. if encoding == "gzip":
  368. content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
  369. if encoding == "deflate":
  370. content = zlib.decompress(content, -zlib.MAX_WBITS)
  371. response["content-length"] = str(len(content))
  372. # Record the historical presence of the encoding in a way the won't interfere.
  373. response["-content-encoding"] = response["content-encoding"]
  374. del response["content-encoding"]
  375. except (IOError, zlib.error):
  376. content = ""
  377. raise FailedToDecompressContent(
  378. _("Content purported to be compressed with %s but failed to decompress.")
  379. % response.get("content-encoding"),
  380. response,
  381. content,
  382. )
  383. return content
  384. def _bind_write_headers(msg):
  385. def _write_headers(self):
  386. # Self refers to the Generator object.
  387. for h, v in msg.items():
  388. print("%s:" % h, end=" ", file=self._fp)
  389. if isinstance(v, header.Header):
  390. print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
  391. else:
  392. # email.Header got lots of smarts, so use it.
  393. headers = header.Header(
  394. v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
  395. )
  396. print(headers.encode(), file=self._fp)
  397. # A blank line always separates headers from body.
  398. print(file=self._fp)
  399. return _write_headers
  400. def _updateCache(request_headers, response_headers, content, cache, cachekey):
  401. if cachekey:
  402. cc = _parse_cache_control(request_headers)
  403. cc_response = _parse_cache_control(response_headers)
  404. if "no-store" in cc or "no-store" in cc_response:
  405. cache.delete(cachekey)
  406. else:
  407. info = email.message.Message()
  408. for key, value in response_headers.items():
  409. if key not in ["status", "content-encoding", "transfer-encoding"]:
  410. info[key] = value
  411. # Add annotations to the cache to indicate what headers
  412. # are variant for this request.
  413. vary = response_headers.get("vary", None)
  414. if vary:
  415. vary_headers = vary.lower().replace(" ", "").split(",")
  416. for header in vary_headers:
  417. key = "-varied-%s" % header
  418. try:
  419. info[key] = request_headers[header]
  420. except KeyError:
  421. pass
  422. status = response_headers.status
  423. if status == 304:
  424. status = 200
  425. status_header = "status: %d\r\n" % status
  426. try:
  427. header_str = info.as_string()
  428. except UnicodeEncodeError:
  429. setattr(info, "_write_headers", _bind_write_headers(info))
  430. header_str = info.as_string()
  431. header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
  432. text = b"".join(
  433. [status_header.encode("utf-8"), header_str.encode("utf-8"), content]
  434. )
  435. cache.set(cachekey, text)
  436. def _cnonce():
  437. dig = _md5(
  438. (
  439. "%s:%s"
  440. % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])
  441. ).encode("utf-8")
  442. ).hexdigest()
  443. return dig[:16]
  444. def _wsse_username_token(cnonce, iso_now, password):
  445. return base64.b64encode(
  446. _sha(("%s%s%s" % (cnonce, iso_now, password)).encode("utf-8")).digest()
  447. ).strip()
  448. # For credentials we need two things, first
  449. # a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
  450. # Then we also need a list of URIs that have already demanded authentication
  451. # That list is tricky since sub-URIs can take the same auth, or the
  452. # auth scheme may change as you descend the tree.
  453. # So we also need each Auth instance to be able to tell us
  454. # how close to the 'top' it is.
  455. class Authentication(object):
  456. def __init__(
  457. self, credentials, host, request_uri, headers, response, content, http
  458. ):
  459. (scheme, authority, path, query, fragment) = parse_uri(request_uri)
  460. self.path = path
  461. self.host = host
  462. self.credentials = credentials
  463. self.http = http
  464. def depth(self, request_uri):
  465. (scheme, authority, path, query, fragment) = parse_uri(request_uri)
  466. return request_uri[len(self.path) :].count("/")
  467. def inscope(self, host, request_uri):
  468. # XXX Should we normalize the request_uri?
  469. (scheme, authority, path, query, fragment) = parse_uri(request_uri)
  470. return (host == self.host) and path.startswith(self.path)
  471. def request(self, method, request_uri, headers, content):
  472. """Modify the request headers to add the appropriate
  473. Authorization header. Over-rise this in sub-classes."""
  474. pass
  475. def response(self, response, content):
  476. """Gives us a chance to update with new nonces
  477. or such returned from the last authorized response.
  478. Over-rise this in sub-classes if necessary.
  479. Return TRUE is the request is to be retried, for
  480. example Digest may return stale=true.
  481. """
  482. return False
  483. def __eq__(self, auth):
  484. return False
  485. def __ne__(self, auth):
  486. return True
  487. def __lt__(self, auth):
  488. return True
  489. def __gt__(self, auth):
  490. return False
  491. def __le__(self, auth):
  492. return True
  493. def __ge__(self, auth):
  494. return False
  495. def __bool__(self):
  496. return True
  497. class BasicAuthentication(Authentication):
  498. def __init__(
  499. self, credentials, host, request_uri, headers, response, content, http
  500. ):
  501. Authentication.__init__(
  502. self, credentials, host, request_uri, headers, response, content, http
  503. )
  504. def request(self, method, request_uri, headers, content):
  505. """Modify the request headers to add the appropriate
  506. Authorization header."""
  507. headers["authorization"] = "Basic " + base64.b64encode(
  508. ("%s:%s" % self.credentials).encode("utf-8")
  509. ).strip().decode("utf-8")
  510. class DigestAuthentication(Authentication):
  511. """Only do qop='auth' and MD5, since that
  512. is all Apache currently implements"""
  513. def __init__(
  514. self, credentials, host, request_uri, headers, response, content, http
  515. ):
  516. Authentication.__init__(
  517. self, credentials, host, request_uri, headers, response, content, http
  518. )
  519. challenge = _parse_www_authenticate(response, "www-authenticate")
  520. self.challenge = challenge["digest"]
  521. qop = self.challenge.get("qop", "auth")
  522. self.challenge["qop"] = (
  523. ("auth" in [x.strip() for x in qop.split()]) and "auth" or None
  524. )
  525. if self.challenge["qop"] is None:
  526. raise UnimplementedDigestAuthOptionError(
  527. _("Unsupported value for qop: %s." % qop)
  528. )
  529. self.challenge["algorithm"] = self.challenge.get("algorithm", "MD5").upper()
  530. if self.challenge["algorithm"] != "MD5":
  531. raise UnimplementedDigestAuthOptionError(
  532. _("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
  533. )
  534. self.A1 = "".join(
  535. [
  536. self.credentials[0],
  537. ":",
  538. self.challenge["realm"],
  539. ":",
  540. self.credentials[1],
  541. ]
  542. )
  543. self.challenge["nc"] = 1
  544. def request(self, method, request_uri, headers, content, cnonce=None):
  545. """Modify the request headers"""
  546. H = lambda x: _md5(x.encode("utf-8")).hexdigest()
  547. KD = lambda s, d: H("%s:%s" % (s, d))
  548. A2 = "".join([method, ":", request_uri])
  549. self.challenge["cnonce"] = cnonce or _cnonce()
  550. request_digest = '"%s"' % KD(
  551. H(self.A1),
  552. "%s:%s:%s:%s:%s"
  553. % (
  554. self.challenge["nonce"],
  555. "%08x" % self.challenge["nc"],
  556. self.challenge["cnonce"],
  557. self.challenge["qop"],
  558. H(A2),
  559. ),
  560. )
  561. headers["authorization"] = (
  562. 'Digest username="%s", realm="%s", nonce="%s", '
  563. 'uri="%s", algorithm=%s, response=%s, qop=%s, '
  564. 'nc=%08x, cnonce="%s"'
  565. ) % (
  566. self.credentials[0],
  567. self.challenge["realm"],
  568. self.challenge["nonce"],
  569. request_uri,
  570. self.challenge["algorithm"],
  571. request_digest,
  572. self.challenge["qop"],
  573. self.challenge["nc"],
  574. self.challenge["cnonce"],
  575. )
  576. if self.challenge.get("opaque"):
  577. headers["authorization"] += ', opaque="%s"' % self.challenge["opaque"]
  578. self.challenge["nc"] += 1
  579. def response(self, response, content):
  580. if "authentication-info" not in response:
  581. challenge = _parse_www_authenticate(response, "www-authenticate").get(
  582. "digest", {}
  583. )
  584. if "true" == challenge.get("stale"):
  585. self.challenge["nonce"] = challenge["nonce"]
  586. self.challenge["nc"] = 1
  587. return True
  588. else:
  589. updated_challenge = _parse_www_authenticate(
  590. response, "authentication-info"
  591. ).get("digest", {})
  592. if "nextnonce" in updated_challenge:
  593. self.challenge["nonce"] = updated_challenge["nextnonce"]
  594. self.challenge["nc"] = 1
  595. return False
  596. class HmacDigestAuthentication(Authentication):
  597. """Adapted from Robert Sayre's code and DigestAuthentication above."""
  598. __author__ = "Thomas Broyer (t.broyer@ltgt.net)"
  599. def __init__(
  600. self, credentials, host, request_uri, headers, response, content, http
  601. ):
  602. Authentication.__init__(
  603. self, credentials, host, request_uri, headers, response, content, http
  604. )
  605. challenge = _parse_www_authenticate(response, "www-authenticate")
  606. self.challenge = challenge["hmacdigest"]
  607. # TODO: self.challenge['domain']
  608. self.challenge["reason"] = self.challenge.get("reason", "unauthorized")
  609. if self.challenge["reason"] not in ["unauthorized", "integrity"]:
  610. self.challenge["reason"] = "unauthorized"
  611. self.challenge["salt"] = self.challenge.get("salt", "")
  612. if not self.challenge.get("snonce"):
  613. raise UnimplementedHmacDigestAuthOptionError(
  614. _("The challenge doesn't contain a server nonce, or this one is empty.")
  615. )
  616. self.challenge["algorithm"] = self.challenge.get("algorithm", "HMAC-SHA-1")
  617. if self.challenge["algorithm"] not in ["HMAC-SHA-1", "HMAC-MD5"]:
  618. raise UnimplementedHmacDigestAuthOptionError(
  619. _("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
  620. )
  621. self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
  622. if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
  623. raise UnimplementedHmacDigestAuthOptionError(
  624. _(
  625. "Unsupported value for pw-algorithm: %s."
  626. % self.challenge["pw-algorithm"]
  627. )
  628. )
  629. if self.challenge["algorithm"] == "HMAC-MD5":
  630. self.hashmod = _md5
  631. else:
  632. self.hashmod = _sha
  633. if self.challenge["pw-algorithm"] == "MD5":
  634. self.pwhashmod = _md5
  635. else:
  636. self.pwhashmod = _sha
  637. self.key = "".join(
  638. [
  639. self.credentials[0],
  640. ":",
  641. self.pwhashmod.new(
  642. "".join([self.credentials[1], self.challenge["salt"]])
  643. )
  644. .hexdigest()
  645. .lower(),
  646. ":",
  647. self.challenge["realm"],
  648. ]
  649. )
  650. self.key = self.pwhashmod.new(self.key).hexdigest().lower()
  651. def request(self, method, request_uri, headers, content):
  652. """Modify the request headers"""
  653. keys = _get_end2end_headers(headers)
  654. keylist = "".join(["%s " % k for k in keys])
  655. headers_val = "".join([headers[k] for k in keys])
  656. created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
  657. cnonce = _cnonce()
  658. request_digest = "%s:%s:%s:%s:%s" % (
  659. method,
  660. request_uri,
  661. cnonce,
  662. self.challenge["snonce"],
  663. headers_val,
  664. )
  665. request_digest = (
  666. hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
  667. )
  668. headers["authorization"] = (
  669. 'HMACDigest username="%s", realm="%s", snonce="%s",'
  670. ' cnonce="%s", uri="%s", created="%s", '
  671. 'response="%s", headers="%s"'
  672. ) % (
  673. self.credentials[0],
  674. self.challenge["realm"],
  675. self.challenge["snonce"],
  676. cnonce,
  677. request_uri,
  678. created,
  679. request_digest,
  680. keylist,
  681. )
  682. def response(self, response, content):
  683. challenge = _parse_www_authenticate(response, "www-authenticate").get(
  684. "hmacdigest", {}
  685. )
  686. if challenge.get("reason") in ["integrity", "stale"]:
  687. return True
  688. return False
  689. class WsseAuthentication(Authentication):
  690. """This is thinly tested and should not be relied upon.
  691. At this time there isn't any third party server to test against.
  692. Blogger and TypePad implemented this algorithm at one point
  693. but Blogger has since switched to Basic over HTTPS and
  694. TypePad has implemented it wrong, by never issuing a 401
  695. challenge but instead requiring your client to telepathically know that
  696. their endpoint is expecting WSSE profile="UsernameToken"."""
  697. def __init__(
  698. self, credentials, host, request_uri, headers, response, content, http
  699. ):
  700. Authentication.__init__(
  701. self, credentials, host, request_uri, headers, response, content, http
  702. )
  703. def request(self, method, request_uri, headers, content):
  704. """Modify the request headers to add the appropriate
  705. Authorization header."""
  706. headers["authorization"] = 'WSSE profile="UsernameToken"'
  707. iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
  708. cnonce = _cnonce()
  709. password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
  710. headers["X-WSSE"] = (
  711. 'UsernameToken Username="%s", PasswordDigest="%s", '
  712. 'Nonce="%s", Created="%s"'
  713. ) % (self.credentials[0], password_digest, cnonce, iso_now)
  714. class GoogleLoginAuthentication(Authentication):
  715. def __init__(
  716. self, credentials, host, request_uri, headers, response, content, http
  717. ):
  718. from urllib.parse import urlencode
  719. Authentication.__init__(
  720. self, credentials, host, request_uri, headers, response, content, http
  721. )
  722. challenge = _parse_www_authenticate(response, "www-authenticate")
  723. service = challenge["googlelogin"].get("service", "xapi")
  724. # Bloggger actually returns the service in the challenge
  725. # For the rest we guess based on the URI
  726. if service == "xapi" and request_uri.find("calendar") > 0:
  727. service = "cl"
  728. # No point in guessing Base or Spreadsheet
  729. # elif request_uri.find("spreadsheets") > 0:
  730. # service = "wise"
  731. auth = dict(
  732. Email=credentials[0],
  733. Passwd=credentials[1],
  734. service=service,
  735. source=headers["user-agent"],
  736. )
  737. resp, content = self.http.request(
  738. "https://www.google.com/accounts/ClientLogin",
  739. method="POST",
  740. body=urlencode(auth),
  741. headers={"Content-Type": "application/x-www-form-urlencoded"},
  742. )
  743. lines = content.split("\n")
  744. d = dict([tuple(line.split("=", 1)) for line in lines if line])
  745. if resp.status == 403:
  746. self.Auth = ""
  747. else:
  748. self.Auth = d["Auth"]
  749. def request(self, method, request_uri, headers, content):
  750. """Modify the request headers to add the appropriate
  751. Authorization header."""
  752. headers["authorization"] = "GoogleLogin Auth=" + self.Auth
  753. AUTH_SCHEME_CLASSES = {
  754. "basic": BasicAuthentication,
  755. "wsse": WsseAuthentication,
  756. "digest": DigestAuthentication,
  757. "hmacdigest": HmacDigestAuthentication,
  758. "googlelogin": GoogleLoginAuthentication,
  759. }
  760. AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
  761. class FileCache(object):
  762. """Uses a local directory as a store for cached files.
  763. Not really safe to use if multiple threads or processes are going to
  764. be running on the same cache.
  765. """
  766. def __init__(
  767. self, cache, safe=safename
  768. ): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
  769. self.cache = cache
  770. self.safe = safe
  771. if not os.path.exists(cache):
  772. os.makedirs(self.cache)
  773. def get(self, key):
  774. retval = None
  775. cacheFullPath = os.path.join(self.cache, self.safe(key))
  776. try:
  777. f = open(cacheFullPath, "rb")
  778. retval = f.read()
  779. f.close()
  780. except IOError:
  781. pass
  782. return retval
  783. def set(self, key, value):
  784. cacheFullPath = os.path.join(self.cache, self.safe(key))
  785. f = open(cacheFullPath, "wb")
  786. f.write(value)
  787. f.close()
  788. def delete(self, key):
  789. cacheFullPath = os.path.join(self.cache, self.safe(key))
  790. if os.path.exists(cacheFullPath):
  791. os.remove(cacheFullPath)
  792. class Credentials(object):
  793. def __init__(self):
  794. self.credentials = []
  795. def add(self, name, password, domain=""):
  796. self.credentials.append((domain.lower(), name, password))
  797. def clear(self):
  798. self.credentials = []
  799. def iter(self, domain):
  800. for (cdomain, name, password) in self.credentials:
  801. if cdomain == "" or domain == cdomain:
  802. yield (name, password)
  803. class KeyCerts(Credentials):
  804. """Identical to Credentials except that
  805. name/password are mapped to key/cert."""
  806. pass
  807. class AllHosts(object):
  808. pass
  809. class ProxyInfo(object):
  810. """Collect information required to use a proxy."""
  811. bypass_hosts = ()
  812. def __init__(
  813. self,
  814. proxy_type,
  815. proxy_host,
  816. proxy_port,
  817. proxy_rdns=True,
  818. proxy_user=None,
  819. proxy_pass=None,
  820. proxy_headers=None,
  821. ):
  822. """Args:
  823. proxy_type: The type of proxy server. This must be set to one of
  824. socks.PROXY_TYPE_XXX constants. For example: p =
  825. ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost',
  826. proxy_port=8000)
  827. proxy_host: The hostname or IP address of the proxy server.
  828. proxy_port: The port that the proxy server is running on.
  829. proxy_rdns: If True (default), DNS queries will not be performed
  830. locally, and instead, handed to the proxy to resolve. This is useful
  831. if the network does not allow resolution of non-local names. In
  832. httplib2 0.9 and earlier, this defaulted to False.
  833. proxy_user: The username used to authenticate with the proxy server.
  834. proxy_pass: The password used to authenticate with the proxy server.
  835. proxy_headers: Additional or modified headers for the proxy connect
  836. request.
  837. """
  838. self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass, self.proxy_headers = (
  839. proxy_type,
  840. proxy_host,
  841. proxy_port,
  842. proxy_rdns,
  843. proxy_user,
  844. proxy_pass,
  845. proxy_headers,
  846. )
  847. def astuple(self):
  848. return (
  849. self.proxy_type,
  850. self.proxy_host,
  851. self.proxy_port,
  852. self.proxy_rdns,
  853. self.proxy_user,
  854. self.proxy_pass,
  855. self.proxy_headers,
  856. )
  857. def isgood(self):
  858. return socks and (self.proxy_host != None) and (self.proxy_port != None)
  859. def applies_to(self, hostname):
  860. return not self.bypass_host(hostname)
  861. def bypass_host(self, hostname):
  862. """Has this host been excluded from the proxy config"""
  863. if self.bypass_hosts is AllHosts:
  864. return True
  865. hostname = "." + hostname.lstrip(".")
  866. for skip_name in self.bypass_hosts:
  867. # *.suffix
  868. if skip_name.startswith(".") and hostname.endswith(skip_name):
  869. return True
  870. # exact match
  871. if hostname == "." + skip_name:
  872. return True
  873. return False
  874. def __repr__(self):
  875. return (
  876. "<ProxyInfo type={p.proxy_type} "
  877. "host:port={p.proxy_host}:{p.proxy_port} rdns={p.proxy_rdns}"
  878. + " user={p.proxy_user} headers={p.proxy_headers}>"
  879. ).format(p=self)
  880. def proxy_info_from_environment(method="http"):
  881. """Read proxy info from the environment variables.
  882. """
  883. if method not in ("http", "https"):
  884. return
  885. env_var = method + "_proxy"
  886. url = os.environ.get(env_var, os.environ.get(env_var.upper()))
  887. if not url:
  888. return
  889. return proxy_info_from_url(url, method, noproxy=None)
  890. def proxy_info_from_url(url, method="http", noproxy=None):
  891. """Construct a ProxyInfo from a URL (such as http_proxy env var)
  892. """
  893. url = urllib.parse.urlparse(url)
  894. username = None
  895. password = None
  896. port = None
  897. if "@" in url[1]:
  898. ident, host_port = url[1].split("@", 1)
  899. if ":" in ident:
  900. username, password = ident.split(":", 1)
  901. else:
  902. password = ident
  903. else:
  904. host_port = url[1]
  905. if ":" in host_port:
  906. host, port = host_port.split(":", 1)
  907. else:
  908. host = host_port
  909. if port:
  910. port = int(port)
  911. else:
  912. port = dict(https=443, http=80)[method]
  913. proxy_type = 3 # socks.PROXY_TYPE_HTTP
  914. pi = ProxyInfo(
  915. proxy_type=proxy_type,
  916. proxy_host=host,
  917. proxy_port=port,
  918. proxy_user=username or None,
  919. proxy_pass=password or None,
  920. proxy_headers=None,
  921. )
  922. bypass_hosts = []
  923. # If not given an explicit noproxy value, respect values in env vars.
  924. if noproxy is None:
  925. noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", ""))
  926. # Special case: A single '*' character means all hosts should be bypassed.
  927. if noproxy == "*":
  928. bypass_hosts = AllHosts
  929. elif noproxy.strip():
  930. bypass_hosts = noproxy.split(",")
  931. bypass_hosts = tuple(filter(bool, bypass_hosts)) # To exclude empty string.
  932. pi.bypass_hosts = bypass_hosts
  933. return pi
  934. class HTTPConnectionWithTimeout(http.client.HTTPConnection):
  935. """HTTPConnection subclass that supports timeouts
  936. HTTPConnection subclass that supports timeouts
  937. All timeouts are in seconds. If None is passed for timeout then
  938. Python's default timeout for sockets will be used. See for example
  939. the docs of socket.setdefaulttimeout():
  940. http://docs.python.org/library/socket.html#socket.setdefaulttimeout
  941. """
  942. def __init__(self, host, port=None, timeout=None, proxy_info=None):
  943. http.client.HTTPConnection.__init__(self, host, port=port, timeout=timeout)
  944. self.proxy_info = proxy_info
  945. if proxy_info and not isinstance(proxy_info, ProxyInfo):
  946. self.proxy_info = proxy_info("http")
  947. def connect(self):
  948. """Connect to the host and port specified in __init__."""
  949. if self.proxy_info and socks is None:
  950. raise ProxiesUnavailableError(
  951. "Proxy support missing but proxy use was requested!"
  952. )
  953. if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
  954. use_proxy = True
  955. proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
  956. self.proxy_info.astuple()
  957. )
  958. host = proxy_host
  959. port = proxy_port
  960. else:
  961. use_proxy = False
  962. host = self.host
  963. port = self.port
  964. proxy_type = None
  965. socket_err = None
  966. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  967. af, socktype, proto, canonname, sa = res
  968. try:
  969. if use_proxy:
  970. self.sock = socks.socksocket(af, socktype, proto)
  971. self.sock.setproxy(
  972. proxy_type,
  973. proxy_host,
  974. proxy_port,
  975. proxy_rdns,
  976. proxy_user,
  977. proxy_pass,
  978. )
  979. else:
  980. self.sock = socket.socket(af, socktype, proto)
  981. self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  982. if has_timeout(self.timeout):
  983. self.sock.settimeout(self.timeout)
  984. if self.debuglevel > 0:
  985. print(
  986. "connect: ({0}, {1}) ************".format(self.host, self.port)
  987. )
  988. if use_proxy:
  989. print(
  990. "proxy: {0} ************".format(
  991. str(
  992. (
  993. proxy_host,
  994. proxy_port,
  995. proxy_rdns,
  996. proxy_user,
  997. proxy_pass,
  998. proxy_headers,
  999. )
  1000. )
  1001. )
  1002. )
  1003. self.sock.connect((self.host, self.port) + sa[2:])
  1004. except socket.error as e:
  1005. socket_err = e
  1006. if self.debuglevel > 0:
  1007. print("connect fail: ({0}, {1})".format(self.host, self.port))
  1008. if use_proxy:
  1009. print(
  1010. "proxy: {0}".format(
  1011. str(
  1012. (
  1013. proxy_host,
  1014. proxy_port,
  1015. proxy_rdns,
  1016. proxy_user,
  1017. proxy_pass,
  1018. proxy_headers,
  1019. )
  1020. )
  1021. )
  1022. )
  1023. if self.sock:
  1024. self.sock.close()
  1025. self.sock = None
  1026. continue
  1027. break
  1028. if not self.sock:
  1029. raise socket_err
  1030. class HTTPSConnectionWithTimeout(http.client.HTTPSConnection):
  1031. """This class allows communication via SSL.
  1032. All timeouts are in seconds. If None is passed for timeout then
  1033. Python's default timeout for sockets will be used. See for example
  1034. the docs of socket.setdefaulttimeout():
  1035. http://docs.python.org/library/socket.html#socket.setdefaulttimeout
  1036. """
  1037. def __init__(
  1038. self,
  1039. host,
  1040. port=None,
  1041. key_file=None,
  1042. cert_file=None,
  1043. timeout=None,
  1044. proxy_info=None,
  1045. ca_certs=None,
  1046. disable_ssl_certificate_validation=False,
  1047. tls_maximum_version=None,
  1048. tls_minimum_version=None,
  1049. ):
  1050. self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
  1051. self.ca_certs = ca_certs if ca_certs else CA_CERTS
  1052. self.proxy_info = proxy_info
  1053. if proxy_info and not isinstance(proxy_info, ProxyInfo):
  1054. self.proxy_info = proxy_info("https")
  1055. context = _build_ssl_context(
  1056. self.disable_ssl_certificate_validation, self.ca_certs, cert_file, key_file,
  1057. maximum_version=tls_maximum_version, minimum_version=tls_minimum_version,
  1058. )
  1059. super(HTTPSConnectionWithTimeout, self).__init__(
  1060. host,
  1061. port=port,
  1062. key_file=key_file,
  1063. cert_file=cert_file,
  1064. timeout=timeout,
  1065. context=context,
  1066. )
  1067. def connect(self):
  1068. """Connect to a host on a given (SSL) port."""
  1069. if self.proxy_info and self.proxy_info.isgood():
  1070. use_proxy = True
  1071. proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
  1072. self.proxy_info.astuple()
  1073. )
  1074. host = proxy_host
  1075. port = proxy_port
  1076. else:
  1077. use_proxy = False
  1078. host = self.host
  1079. port = self.port
  1080. proxy_type = None
  1081. proxy_headers = None
  1082. socket_err = None
  1083. address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  1084. for family, socktype, proto, canonname, sockaddr in address_info:
  1085. try:
  1086. if use_proxy:
  1087. sock = socks.socksocket(family, socktype, proto)
  1088. sock.setproxy(
  1089. proxy_type,
  1090. proxy_host,
  1091. proxy_port,
  1092. proxy_rdns,
  1093. proxy_user,
  1094. proxy_pass,
  1095. )
  1096. else:
  1097. sock = socket.socket(family, socktype, proto)
  1098. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1099. if has_timeout(self.timeout):
  1100. sock.settimeout(self.timeout)
  1101. sock.connect((self.host, self.port))
  1102. self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
  1103. # Python 3.3 compatibility: emulate the check_hostname behavior
  1104. if (
  1105. not hasattr(self._context, "check_hostname")
  1106. and not self.disable_ssl_certificate_validation
  1107. ):
  1108. try:
  1109. ssl.match_hostname(self.sock.getpeercert(), self.host)
  1110. except Exception:
  1111. self.sock.shutdown(socket.SHUT_RDWR)
  1112. self.sock.close()
  1113. raise
  1114. if self.debuglevel > 0:
  1115. print("connect: ({0}, {1})".format(self.host, self.port))
  1116. if use_proxy:
  1117. print(
  1118. "proxy: {0}".format(
  1119. str(
  1120. (
  1121. proxy_host,
  1122. proxy_port,
  1123. proxy_rdns,
  1124. proxy_user,
  1125. proxy_pass,
  1126. proxy_headers,
  1127. )
  1128. )
  1129. )
  1130. )
  1131. except (ssl.SSLError, ssl.CertificateError) as e:
  1132. if sock:
  1133. sock.close()
  1134. if self.sock:
  1135. self.sock.close()
  1136. self.sock = None
  1137. raise
  1138. except (socket.timeout, socket.gaierror):
  1139. raise
  1140. except socket.error as e:
  1141. socket_err = e
  1142. if self.debuglevel > 0:
  1143. print("connect fail: ({0}, {1})".format((self.host, self.port)))
  1144. if use_proxy:
  1145. print(
  1146. "proxy: {0}".format(
  1147. str(
  1148. (
  1149. proxy_host,
  1150. proxy_port,
  1151. proxy_rdns,
  1152. proxy_user,
  1153. proxy_pass,
  1154. proxy_headers,
  1155. )
  1156. )
  1157. )
  1158. )
  1159. if self.sock:
  1160. self.sock.close()
  1161. self.sock = None
  1162. continue
  1163. break
  1164. if not self.sock:
  1165. raise socket_err
  1166. SCHEME_TO_CONNECTION = {
  1167. "http": HTTPConnectionWithTimeout,
  1168. "https": HTTPSConnectionWithTimeout,
  1169. }
  1170. class Http(object):
  1171. """An HTTP client that handles:
  1172. - all methods
  1173. - caching
  1174. - ETags
  1175. - compression,
  1176. - HTTPS
  1177. - Basic
  1178. - Digest
  1179. - WSSE
  1180. and more.
  1181. """
  1182. def __init__(
  1183. self,
  1184. cache=None,
  1185. timeout=None,
  1186. proxy_info=proxy_info_from_environment,
  1187. ca_certs=None,
  1188. disable_ssl_certificate_validation=False,
  1189. tls_maximum_version=None,
  1190. tls_minimum_version=None,
  1191. ):
  1192. """If 'cache' is a string then it is used as a directory name for
  1193. a disk cache. Otherwise it must be an object that supports the
  1194. same interface as FileCache.
  1195. All timeouts are in seconds. If None is passed for timeout
  1196. then Python's default timeout for sockets will be used. See
  1197. for example the docs of socket.setdefaulttimeout():
  1198. http://docs.python.org/library/socket.html#socket.setdefaulttimeout
  1199. `proxy_info` may be:
  1200. - a callable that takes the http scheme ('http' or 'https') and
  1201. returns a ProxyInfo instance per request. By default, uses
  1202. proxy_info_from_environment.
  1203. - a ProxyInfo instance (static proxy config).
  1204. - None (proxy disabled).
  1205. ca_certs is the path of a file containing root CA certificates for SSL
  1206. server certificate validation. By default, a CA cert file bundled with
  1207. httplib2 is used.
  1208. If disable_ssl_certificate_validation is true, SSL cert validation will
  1209. not be performed.
  1210. tls_maximum_version / tls_minimum_version require Python 3.7+ /
  1211. OpenSSL 1.1.0g+. A value of "TLSv1_3" requires OpenSSL 1.1.1+.
  1212. """
  1213. self.proxy_info = proxy_info
  1214. self.ca_certs = ca_certs
  1215. self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
  1216. self.tls_maximum_version = tls_maximum_version
  1217. self.tls_minimum_version = tls_minimum_version
  1218. # Map domain name to an httplib connection
  1219. self.connections = {}
  1220. # The location of the cache, for now a directory
  1221. # where cached responses are held.
  1222. if cache and isinstance(cache, str):
  1223. self.cache = FileCache(cache)
  1224. else:
  1225. self.cache = cache
  1226. # Name/password
  1227. self.credentials = Credentials()
  1228. # Key/cert
  1229. self.certificates = KeyCerts()
  1230. # authorization objects
  1231. self.authorizations = []
  1232. # If set to False then no redirects are followed, even safe ones.
  1233. self.follow_redirects = True
  1234. # Which HTTP methods do we apply optimistic concurrency to, i.e.
  1235. # which methods get an "if-match:" etag header added to them.
  1236. self.optimistic_concurrency_methods = ["PUT", "PATCH"]
  1237. # If 'follow_redirects' is True, and this is set to True then
  1238. # all redirecs are followed, including unsafe ones.
  1239. self.follow_all_redirects = False
  1240. self.ignore_etag = False
  1241. self.force_exception_to_status_code = False
  1242. self.timeout = timeout
  1243. # Keep Authorization: headers on a redirect.
  1244. self.forward_authorization_headers = False
  1245. def __getstate__(self):
  1246. state_dict = copy.copy(self.__dict__)
  1247. # In case request is augmented by some foreign object such as
  1248. # credentials which handle auth
  1249. if "request" in state_dict:
  1250. del state_dict["request"]
  1251. if "connections" in state_dict:
  1252. del state_dict["connections"]
  1253. return state_dict
  1254. def __setstate__(self, state):
  1255. self.__dict__.update(state)
  1256. self.connections = {}
  1257. def _auth_from_challenge(self, host, request_uri, headers, response, content):
  1258. """A generator that creates Authorization objects
  1259. that can be applied to requests.
  1260. """
  1261. challenges = _parse_www_authenticate(response, "www-authenticate")
  1262. for cred in self.credentials.iter(host):
  1263. for scheme in AUTH_SCHEME_ORDER:
  1264. if scheme in challenges:
  1265. yield AUTH_SCHEME_CLASSES[scheme](
  1266. cred, host, request_uri, headers, response, content, self
  1267. )
  1268. def add_credentials(self, name, password, domain=""):
  1269. """Add a name and password that will be used
  1270. any time a request requires authentication."""
  1271. self.credentials.add(name, password, domain)
  1272. def add_certificate(self, key, cert, domain):
  1273. """Add a key and cert that will be used
  1274. any time a request requires authentication."""
  1275. self.certificates.add(key, cert, domain)
  1276. def clear_credentials(self):
  1277. """Remove all the names and passwords
  1278. that are used for authentication"""
  1279. self.credentials.clear()
  1280. self.authorizations = []
  1281. def _conn_request(self, conn, request_uri, method, body, headers):
  1282. i = 0
  1283. seen_bad_status_line = False
  1284. while i < RETRIES:
  1285. i += 1
  1286. try:
  1287. if conn.sock is None:
  1288. conn.connect()
  1289. conn.request(method, request_uri, body, headers)
  1290. except socket.timeout:
  1291. conn.close()
  1292. raise
  1293. except socket.gaierror:
  1294. conn.close()
  1295. raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
  1296. except socket.error as e:
  1297. errno_ = (
  1298. e.args[0].errno if isinstance(e.args[0], socket.error) else e.errno
  1299. )
  1300. if errno_ in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
  1301. continue # retry on potentially transient errors
  1302. raise
  1303. except http.client.HTTPException:
  1304. if conn.sock is None:
  1305. if i < RETRIES - 1:
  1306. conn.close()
  1307. conn.connect()
  1308. continue
  1309. else:
  1310. conn.close()
  1311. raise
  1312. if i < RETRIES - 1:
  1313. conn.close()
  1314. conn.connect()
  1315. continue
  1316. # Just because the server closed the connection doesn't apparently mean
  1317. # that the server didn't send a response.
  1318. pass
  1319. try:
  1320. response = conn.getresponse()
  1321. except (http.client.BadStatusLine, http.client.ResponseNotReady):
  1322. # If we get a BadStatusLine on the first try then that means
  1323. # the connection just went stale, so retry regardless of the
  1324. # number of RETRIES set.
  1325. if not seen_bad_status_line and i == 1:
  1326. i = 0
  1327. seen_bad_status_line = True
  1328. conn.close()
  1329. conn.connect()
  1330. continue
  1331. else:
  1332. conn.close()
  1333. raise
  1334. except socket.timeout:
  1335. raise
  1336. except (socket.error, http.client.HTTPException):
  1337. conn.close()
  1338. if i == 0:
  1339. conn.close()
  1340. conn.connect()
  1341. continue
  1342. else:
  1343. raise
  1344. else:
  1345. content = b""
  1346. if method == "HEAD":
  1347. conn.close()
  1348. else:
  1349. content = response.read()
  1350. response = Response(response)
  1351. if method != "HEAD":
  1352. content = _decompressContent(response, content)
  1353. break
  1354. return (response, content)
  1355. def _request(
  1356. self,
  1357. conn,
  1358. host,
  1359. absolute_uri,
  1360. request_uri,
  1361. method,
  1362. body,
  1363. headers,
  1364. redirections,
  1365. cachekey,
  1366. ):
  1367. """Do the actual request using the connection object
  1368. and also follow one level of redirects if necessary"""
  1369. auths = [
  1370. (auth.depth(request_uri), auth)
  1371. for auth in self.authorizations
  1372. if auth.inscope(host, request_uri)
  1373. ]
  1374. auth = auths and sorted(auths)[0][1] or None
  1375. if auth:
  1376. auth.request(method, request_uri, headers, body)
  1377. (response, content) = self._conn_request(
  1378. conn, request_uri, method, body, headers
  1379. )
  1380. if auth:
  1381. if auth.response(response, body):
  1382. auth.request(method, request_uri, headers, body)
  1383. (response, content) = self._conn_request(
  1384. conn, request_uri, method, body, headers
  1385. )
  1386. response._stale_digest = 1
  1387. if response.status == 401:
  1388. for authorization in self._auth_from_challenge(
  1389. host, request_uri, headers, response, content
  1390. ):
  1391. authorization.request(method, request_uri, headers, body)
  1392. (response, content) = self._conn_request(
  1393. conn, request_uri, method, body, headers
  1394. )
  1395. if response.status != 401:
  1396. self.authorizations.append(authorization)
  1397. authorization.response(response, body)
  1398. break
  1399. if (
  1400. self.follow_all_redirects
  1401. or (method in ["GET", "HEAD"])
  1402. or response.status == 303
  1403. ):
  1404. if self.follow_redirects and response.status in [300, 301, 302, 303, 307]:
  1405. # Pick out the location header and basically start from the beginning
  1406. # remembering first to strip the ETag header and decrement our 'depth'
  1407. if redirections:
  1408. if "location" not in response and response.status != 300:
  1409. raise RedirectMissingLocation(
  1410. _(
  1411. "Redirected but the response is missing a Location: header."
  1412. ),
  1413. response,
  1414. content,
  1415. )
  1416. # Fix-up relative redirects (which violate an RFC 2616 MUST)
  1417. if "location" in response:
  1418. location = response["location"]
  1419. (scheme, authority, path, query, fragment) = parse_uri(location)
  1420. if authority == None:
  1421. response["location"] = urllib.parse.urljoin(
  1422. absolute_uri, location
  1423. )
  1424. if response.status == 301 and method in ["GET", "HEAD"]:
  1425. response["-x-permanent-redirect-url"] = response["location"]
  1426. if "content-location" not in response:
  1427. response["content-location"] = absolute_uri
  1428. _updateCache(headers, response, content, self.cache, cachekey)
  1429. if "if-none-match" in headers:
  1430. del headers["if-none-match"]
  1431. if "if-modified-since" in headers:
  1432. del headers["if-modified-since"]
  1433. if (
  1434. "authorization" in headers
  1435. and not self.forward_authorization_headers
  1436. ):
  1437. del headers["authorization"]
  1438. if "location" in response:
  1439. location = response["location"]
  1440. old_response = copy.deepcopy(response)
  1441. if "content-location" not in old_response:
  1442. old_response["content-location"] = absolute_uri
  1443. redirect_method = method
  1444. if response.status in [302, 303]:
  1445. redirect_method = "GET"
  1446. body = None
  1447. (response, content) = self.request(
  1448. location,
  1449. method=redirect_method,
  1450. body=body,
  1451. headers=headers,
  1452. redirections=redirections - 1,
  1453. )
  1454. response.previous = old_response
  1455. else:
  1456. raise RedirectLimit(
  1457. "Redirected more times than redirection_limit allows.",
  1458. response,
  1459. content,
  1460. )
  1461. elif response.status in [200, 203] and method in ["GET", "HEAD"]:
  1462. # Don't cache 206's since we aren't going to handle byte range requests
  1463. if "content-location" not in response:
  1464. response["content-location"] = absolute_uri
  1465. _updateCache(headers, response, content, self.cache, cachekey)
  1466. return (response, content)
  1467. def _normalize_headers(self, headers):
  1468. return _normalize_headers(headers)
  1469. # Need to catch and rebrand some exceptions
  1470. # Then need to optionally turn all exceptions into status codes
  1471. # including all socket.* and httplib.* exceptions.
  1472. def request(
  1473. self,
  1474. uri,
  1475. method="GET",
  1476. body=None,
  1477. headers=None,
  1478. redirections=DEFAULT_MAX_REDIRECTS,
  1479. connection_type=None,
  1480. ):
  1481. """ Performs a single HTTP request.
  1482. The 'uri' is the URI of the HTTP resource and can begin
  1483. with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
  1484. The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
  1485. There is no restriction on the methods allowed.
  1486. The 'body' is the entity body to be sent with the request. It is a string
  1487. object.
  1488. Any extra headers that are to be sent with the request should be provided in the
  1489. 'headers' dictionary.
  1490. The maximum number of redirect to follow before raising an
  1491. exception is 'redirections. The default is 5.
  1492. The return value is a tuple of (response, content), the first
  1493. being and instance of the 'Response' class, the second being
  1494. a string that contains the response entity body.
  1495. """
  1496. conn_key = ''
  1497. try:
  1498. if headers is None:
  1499. headers = {}
  1500. else:
  1501. headers = self._normalize_headers(headers)
  1502. if "user-agent" not in headers:
  1503. headers["user-agent"] = "Python-httplib2/%s (gzip)" % __version__
  1504. uri = iri2uri(uri)
  1505. (scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
  1506. conn_key = scheme + ":" + authority
  1507. conn = self.connections.get(conn_key)
  1508. if conn is None:
  1509. if not connection_type:
  1510. connection_type = SCHEME_TO_CONNECTION[scheme]
  1511. certs = list(self.certificates.iter(authority))
  1512. if issubclass(connection_type, HTTPSConnectionWithTimeout):
  1513. if certs:
  1514. conn = self.connections[conn_key] = connection_type(
  1515. authority,
  1516. key_file=certs[0][0],
  1517. cert_file=certs[0][1],
  1518. timeout=self.timeout,
  1519. proxy_info=self.proxy_info,
  1520. ca_certs=self.ca_certs,
  1521. disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
  1522. tls_maximum_version=self.tls_maximum_version,
  1523. tls_minimum_version=self.tls_minimum_version,
  1524. )
  1525. else:
  1526. conn = self.connections[conn_key] = connection_type(
  1527. authority,
  1528. timeout=self.timeout,
  1529. proxy_info=self.proxy_info,
  1530. ca_certs=self.ca_certs,
  1531. disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
  1532. tls_maximum_version=self.tls_maximum_version,
  1533. tls_minimum_version=self.tls_minimum_version,
  1534. )
  1535. else:
  1536. conn = self.connections[conn_key] = connection_type(
  1537. authority, timeout=self.timeout, proxy_info=self.proxy_info
  1538. )
  1539. conn.set_debuglevel(debuglevel)
  1540. if "range" not in headers and "accept-encoding" not in headers:
  1541. headers["accept-encoding"] = "gzip, deflate"
  1542. info = email.message.Message()
  1543. cached_value = None
  1544. if self.cache:
  1545. cachekey = defrag_uri
  1546. cached_value = self.cache.get(cachekey)
  1547. if cached_value:
  1548. try:
  1549. info, content = cached_value.split(b"\r\n\r\n", 1)
  1550. info = email.message_from_bytes(info)
  1551. for k, v in info.items():
  1552. if v.startswith("=?") and v.endswith("?="):
  1553. info.replace_header(
  1554. k, str(*email.header.decode_header(v)[0])
  1555. )
  1556. except (IndexError, ValueError):
  1557. self.cache.delete(cachekey)
  1558. cachekey = None
  1559. cached_value = None
  1560. else:
  1561. cachekey = None
  1562. if (
  1563. method in self.optimistic_concurrency_methods
  1564. and self.cache
  1565. and "etag" in info
  1566. and not self.ignore_etag
  1567. and "if-match" not in headers
  1568. ):
  1569. # http://www.w3.org/1999/04/Editing/
  1570. headers["if-match"] = info["etag"]
  1571. if method not in ["GET", "HEAD"] and self.cache and cachekey:
  1572. # RFC 2616 Section 13.10
  1573. self.cache.delete(cachekey)
  1574. # Check the vary header in the cache to see if this request
  1575. # matches what varies in the cache.
  1576. if method in ["GET", "HEAD"] and "vary" in info:
  1577. vary = info["vary"]
  1578. vary_headers = vary.lower().replace(" ", "").split(",")
  1579. for header in vary_headers:
  1580. key = "-varied-%s" % header
  1581. value = info[key]
  1582. if headers.get(header, None) != value:
  1583. cached_value = None
  1584. break
  1585. if (
  1586. cached_value
  1587. and method in ["GET", "HEAD"]
  1588. and self.cache
  1589. and "range" not in headers
  1590. ):
  1591. if "-x-permanent-redirect-url" in info:
  1592. # Should cached permanent redirects be counted in our redirection count? For now, yes.
  1593. if redirections <= 0:
  1594. raise RedirectLimit(
  1595. "Redirected more times than redirection_limit allows.",
  1596. {},
  1597. "",
  1598. )
  1599. (response, new_content) = self.request(
  1600. info["-x-permanent-redirect-url"],
  1601. method="GET",
  1602. headers=headers,
  1603. redirections=redirections - 1,
  1604. )
  1605. response.previous = Response(info)
  1606. response.previous.fromcache = True
  1607. else:
  1608. # Determine our course of action:
  1609. # Is the cached entry fresh or stale?
  1610. # Has the client requested a non-cached response?
  1611. #
  1612. # There seems to be three possible answers:
  1613. # 1. [FRESH] Return the cache entry w/o doing a GET
  1614. # 2. [STALE] Do the GET (but add in cache validators if available)
  1615. # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
  1616. entry_disposition = _entry_disposition(info, headers)
  1617. if entry_disposition == "FRESH":
  1618. if not cached_value:
  1619. info["status"] = "504"
  1620. content = b""
  1621. response = Response(info)
  1622. if cached_value:
  1623. response.fromcache = True
  1624. return (response, content)
  1625. if entry_disposition == "STALE":
  1626. if (
  1627. "etag" in info
  1628. and not self.ignore_etag
  1629. and not "if-none-match" in headers
  1630. ):
  1631. headers["if-none-match"] = info["etag"]
  1632. if "last-modified" in info and not "last-modified" in headers:
  1633. headers["if-modified-since"] = info["last-modified"]
  1634. elif entry_disposition == "TRANSPARENT":
  1635. pass
  1636. (response, new_content) = self._request(
  1637. conn,
  1638. authority,
  1639. uri,
  1640. request_uri,
  1641. method,
  1642. body,
  1643. headers,
  1644. redirections,
  1645. cachekey,
  1646. )
  1647. if response.status == 304 and method == "GET":
  1648. # Rewrite the cache entry with the new end-to-end headers
  1649. # Take all headers that are in response
  1650. # and overwrite their values in info.
  1651. # unless they are hop-by-hop, or are listed in the connection header.
  1652. for key in _get_end2end_headers(response):
  1653. info[key] = response[key]
  1654. merged_response = Response(info)
  1655. if hasattr(response, "_stale_digest"):
  1656. merged_response._stale_digest = response._stale_digest
  1657. _updateCache(
  1658. headers, merged_response, content, self.cache, cachekey
  1659. )
  1660. response = merged_response
  1661. response.status = 200
  1662. response.fromcache = True
  1663. elif response.status == 200:
  1664. content = new_content
  1665. else:
  1666. self.cache.delete(cachekey)
  1667. content = new_content
  1668. else:
  1669. cc = _parse_cache_control(headers)
  1670. if "only-if-cached" in cc:
  1671. info["status"] = "504"
  1672. response = Response(info)
  1673. content = b""
  1674. else:
  1675. (response, content) = self._request(
  1676. conn,
  1677. authority,
  1678. uri,
  1679. request_uri,
  1680. method,
  1681. body,
  1682. headers,
  1683. redirections,
  1684. cachekey,
  1685. )
  1686. except Exception as e:
  1687. is_timeout = isinstance(e, socket.timeout)
  1688. if is_timeout:
  1689. conn = self.connections.pop(conn_key, None)
  1690. if conn:
  1691. conn.close()
  1692. if self.force_exception_to_status_code:
  1693. if isinstance(e, HttpLib2ErrorWithResponse):
  1694. response = e.response
  1695. content = e.content
  1696. response.status = 500
  1697. response.reason = str(e)
  1698. elif isinstance(e, socket.timeout):
  1699. content = b"Request Timeout"
  1700. response = Response(
  1701. {
  1702. "content-type": "text/plain",
  1703. "status": "408",
  1704. "content-length": len(content),
  1705. }
  1706. )
  1707. response.reason = "Request Timeout"
  1708. else:
  1709. content = str(e).encode("utf-8")
  1710. response = Response(
  1711. {
  1712. "content-type": "text/plain",
  1713. "status": "400",
  1714. "content-length": len(content),
  1715. }
  1716. )
  1717. response.reason = "Bad Request"
  1718. else:
  1719. raise
  1720. return (response, content)
  1721. class Response(dict):
  1722. """An object more like email.message than httplib.HTTPResponse."""
  1723. """Is this response from our local cache"""
  1724. fromcache = False
  1725. """HTTP protocol version used by server.
  1726. 10 for HTTP/1.0, 11 for HTTP/1.1.
  1727. """
  1728. version = 11
  1729. "Status code returned by server. "
  1730. status = 200
  1731. """Reason phrase returned by server."""
  1732. reason = "Ok"
  1733. previous = None
  1734. def __init__(self, info):
  1735. # info is either an email.message or
  1736. # an httplib.HTTPResponse object.
  1737. if isinstance(info, http.client.HTTPResponse):
  1738. for key, value in info.getheaders():
  1739. key = key.lower()
  1740. prev = self.get(key)
  1741. if prev is not None:
  1742. value = ", ".join((prev, value))
  1743. self[key] = value
  1744. self.status = info.status
  1745. self["status"] = str(self.status)
  1746. self.reason = info.reason
  1747. self.version = info.version
  1748. elif isinstance(info, email.message.Message):
  1749. for key, value in list(info.items()):
  1750. self[key.lower()] = value
  1751. self.status = int(self["status"])
  1752. else:
  1753. for key, value in info.items():
  1754. self[key.lower()] = value
  1755. self.status = int(self.get("status", self.status))
  1756. def __getattr__(self, name):
  1757. if name == "dict":
  1758. return self
  1759. else:
  1760. raise AttributeError(name)