buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def request(self, method, request_uri, headers, content):
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"hmacdigest", {}
)
if challenge.get("reason") in ["integrity", "stale"]:
return True
... | def request(self, method, request_uri, headers, content):
)
def response(self, response, content):
challenge = auth._parse_www_authenticate(response, "www-authenticate").get("hmacdigest", {})
if challenge.get("reason") in ["integrity", "stale"]:
return True
return False |
class WsseAuthentication(Authentication):
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(... | class WsseAuthentication(Authentication):
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credenti... |
def request(self, method, request_uri, headers, content):
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = (
'UsernameToken Username="%s", PasswordD... | def request(self, method, request_uri, headers, content):
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = ('UsernameToken Username="%s", PasswordDigest="%s", '... |
def __init__(
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(
Email=credentials[0],
Passwd=credentials[1],
service=service,
source=headers["user-agent"],
)
resp, content = self.http.request(
... | def __init__(
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"],)
resp, content = self.http.request(
"https://www.google.com/accounts/ClientLogin",
... |
class FileCache(object):
be running on the same cache.
"""
def __init__(
self, cache, safe=safename
): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache): | class FileCache(object):
be running on the same cache.
"""
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache): |
def iter(self, domain):
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
| def iter(self, domain):
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
|
class ProxyInfo(object):
bypass_hosts = ()
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None,
):
"""Args:
| class ProxyInfo(object):
bypass_hosts = ()
def __init__(
self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
):
"""Args:
|
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
"Proxy support missing but proxy use was requested!"
)
if self.prox... | def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError("Proxy support missing but proxy use was requested!")
if self.proxy_info and self.proxy_info.isg... |
def connect(self):
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
... | def connect(self):
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,
)
else:
... |
def connect(self):
if use_proxy:
print(
"proxy: %s ************"
% str(
(
proxy_host,
proxy_port,
... | def connect(self):
if use_proxy:
print(
"proxy: %s ************"
% str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
)
if use_proxy:
... |
def connect(self):
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
... | def connect(self):
if use_proxy:
print(
"proxy: %s"
% str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
)
if self.sock:
self.soc... |
def connect(self):
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_... | def connect(self):
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
... |
def connect(self):
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
... | def connect(self):
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,
)
else:
sock = socket.socket(... |
def connect(self):
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
... | def connect(self):
if use_proxy:
print(
"proxy: %s"
% str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
)
if not self.disable_ssl_certificate_valida... |
def connect(self):
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
... | def connect(self):
if use_proxy:
print(
"proxy: %s"
% str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
)
if self.sock:
self.soc... |
def connect(self):
def _new_fixed_fetch(validate_certificate):
def fixed_fetch(
url,
payload=None,
method="GET",
headers={},
allow_truncated=False,
follow_redirects=True,
deadline=None,
):
return fetch(
url, | def connect(self):
def _new_fixed_fetch(validate_certificate):
def fixed_fetch(
url, payload=None, method="GET", headers={}, allow_truncated=False, follow_redirects=True, deadline=None,
):
return fetch(
url, |
def __init__(
disable_ssl_certificate_validation=False,
ssl_version=None,
):
httplib.HTTPConnection.__init__(
self, host, port=port, strict=strict, timeout=timeout
)
class AppEngineHttpsConnection(httplib.HTTPSConnection): | def __init__(
disable_ssl_certificate_validation=False,
ssl_version=None,
):
httplib.HTTPConnection.__init__(self, host, port=port, strict=strict, timeout=timeout)
class AppEngineHttpsConnection(httplib.HTTPSConnection): |
def __init__(
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
httplib.HTTPSConnection.__init__(
self,
host,
port=port,
key_file=key_file,
cert_file=cert_file,
strict=stric... | def __init__(
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
httplib.HTTPSConnection.__init__(
self, host, port=port, key_file=key_file, cert_file=cert_file, strict=strict, timeout=timeout,
)
self._fetch = _new_fix... |
def is_gae_instance():
raise NotRunningAppEngineEnvironment()
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub("urlfetch") is None:
raise ImportError
| def is_gae_instance():
raise NotRunningAppEngineEnvironment()
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub("urlfetch") is None:
raise ImportError
|
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
... | def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = auth._parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host)... |
def _conn_request(self, conn, request_uri, method, body, headers):
return (response, content)
def _request(
self,
conn,
host,
absolute_uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
):
"""Do the ac... | def _conn_request(self, conn, request_uri, method, body, headers):
return (response, content)
def _request(
self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey,
):
"""Do the actual request using the connection object
and also follow one lev... |
def _request(
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if (
"authorization" in headers
and not self.forward_authorization_header... | def _request(
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if "authorization" in headers and not self.forward_authorization_headers:
del headers["authorizat... |
def _request(
redirect_method = "GET"
body = None
(response, content) = self.request(
location,
method=redirect_method,
body=body,
... | def _request(
redirect_method = "GET"
body = None
(response, content) = self.request(
location, method=redirect_method, body=body, headers=headers, redirections=redirections - 1,
)
... |
def _normalize_headers(self, headers):
# including all socket.* and httplib.* exceptions.
def request(
self,
uri,
method="GET",
body=None,
headers=None,
redirections=DEFAULT_MAX_REDIRECTS,
connection_type=None,
):
""" Performs a single HTTP re... | def _normalize_headers(self, headers):
# including all socket.* and httplib.* exceptions.
def request(
self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
):
""" Performs a single HTTP request.
|
def request(
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ''
try:
if headers is None: | def request(
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ""
try:
if headers is None: |
def request(
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than rediection_limit allows.",
{}... | def request(
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than rediection_limit allows.", {}, "",
... |
def request(
return (response, content)
if entry_disposition == "STALE":
if (
"etag" in info
and not self.ignore_etag
and not "if-none-match" in headers
... | def request(
return (response, content)
if entry_disposition == "STALE":
if "etag" in info and not self.ignore_etag and not "if-none-match" in headers:
headers["if-none-match"] = info["etag"]
if "las... |
def request(
pass
(response, new_content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
... | def request(
pass
(response, new_content) = self._request(
conn, authority, uri, request_uri, method, body, headers, redirections, cachekey,
)
if response.status == 304 and method == "GET": |
def request(
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(
headers, merged_response, content, self.cache, cachekey
... | def request(
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(headers, merged_response, content, self.cache, cachekey)
respon... |
def request(
content = ""
else:
(response, content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
... | def request(
content = ""
else:
(response, content) = self._request(
conn, authority, uri, request_uri, method, body, headers, redirections, cachekey,
)
except Exception as e:
is_timeout = isinstance(... |
def request(
response.reason = str(e)
elif is_timeout:
content = "Request Timeout"
response = Response(
{
"content-type": "text/plain",
"status": "408",
... | def request(
response.reason = str(e)
elif is_timeout:
content = "Request Timeout"
response = Response({"content-type": "text/plain", "status": "408", "content-length": len(content),})
response.reason = "Request Timeout"
... |
# TODO: remove this fallback and copypasted socksipy module upon py2/3 merge,
# idea is to have soft-dependency on any compatible module called socks
from . import socks
from .iri2uri import iri2uri
| # TODO: remove this fallback and copypasted socksipy module upon py2/3 merge,
# idea is to have soft-dependency on any compatible module called socks
from . import socks
from . import auth
from .error import *
from .iri2uri import iri2uri
|
def has_timeout(timeout):
RETRIES = 2
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception):
pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
... | def has_timeout(timeout):
RETRIES = 2
# Open Items:
# -----------
|
class ProxiesUnavailableError(HttpLib2Error):
from httplib2 import certs
CA_CERTS = certs.where()
# PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated. | class ProxiesUnavailableError(HttpLib2Error):
from httplib2 import certs
CA_CERTS = certs.where()
# PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated. |
class ProxiesUnavailableError(HttpLib2Error):
# > Selects the highest protocol version that both the client and server support.
# > Despite the name, this option can select “TLS” protocols as well as “SSL”.
# source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS
DEFAULT_TLS_VERSION = getattr(ssl, "PROTO... | class ProxiesUnavailableError(HttpLib2Error):
# > Selects the highest protocol version that both the client and server support.
# > Despite the name, this option can select “TLS” protocols as well as “SSL”.
# source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS
DEFAULT_TLS_VERSION = getattr(ssl, "PROTO... |
def safename(filename):
def _normalize_headers(headers):
return dict(
[
(
_convert_byte_str(key).lower(),
NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),
)
for (key, value) in headers.items()
]
) | def safename(filename):
def _normalize_headers(headers):
return dict(
[
(_convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),)
for (key, value) in headers.items()
]
) |
def _parse_cache_control(headers):
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
parts_wo_args = [
... | def _parse_cache_control(headers):
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")
]
parts_wo_args = [(name.strip().lower(), 1) ... |
def _parse_cache_control(headers):
# Set to true to turn on, useful for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-str... | def _parse_cache_control(headers):
# Set to true to turn on, useful for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers. |
def _entry_disposition(response_headers, request_headers):
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if (
"pragma" in request_headers
and request_headers["pragma"].lower().find("no-cache") != -1
):
retval = "TRANSPARENT"
... | def _entry_disposition(response_headers, request_headers):
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1:
retval = "TRANSPARENT"
if "cache-control" n... |
def _decompressContent(response, new_content):
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
... | def _decompressContent(response, new_content):
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"),
response,
content,
) |
def _write_headers(self):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(
v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
... | def _write_headers(self):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h)
print(headers.... |
def _updateCache(request_headers, response_headers, content, cache, cachekey):
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = b"".join(
[status_header.encode("utf-8"), header_str.encode("utf-8"), content]
... | def _updateCache(request_headers, response_headers, content, cache, cachekey):
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = b"".join([status_header.encode("utf-8"), header_str.encode("utf-8"), content])
cache.set... |
def _wsse_username_token(cnonce, iso_now, password):
class Authentication(object):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host | def _wsse_username_token(cnonce, iso_now, password):
class Authentication(object):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host |
def __bool__(self):
class BasicAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, me... | def __bool__(self):
class BasicAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content)... |
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, ... | class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content,... |
def request(self, method, request_uri, headers, content, cnonce=None):
def response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == chal... | def request(self, method, request_uri, headers, content, cnonce=None):
def response(self, response, content):
if "authentication-info" not in response:
challenge = auth._parse_www_authenticate(response, "www-authenticate").get("digest", {})
if "true" == challenge.get("stale"):
... |
class HmacDigestAuthentication(Authentication):
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, ht... | class HmacDigestAuthentication(Authentication):
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = aut... |
def __init__(
self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_(
"Unsupported value for pw-algorithm: %s."
... | def __init__(
self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_("Unsupported value for pw-algorithm: %s." % self.challenge["pw-algorithm"])
... |
def __init__(
[
self.credentials[0],
":",
self.pwhashmod.new(
"".join([self.credentials[1], self.challenge["salt"]])
)
.hexdigest()
.lower(),
":",
self.challeng... | def __init__(
[
self.credentials[0],
":",
self.pwhashmod.new("".join([self.credentials[1], self.challenge["salt"]])).hexdigest().lower(),
":",
self.challenge["realm"],
] |
def request(self, method, request_uri, headers, content):
headers_val = "".join([headers[k] for k in keys])
created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (
method,
request_uri,
cnonc... | def request(self, method, request_uri, headers, content):
headers_val = "".join([headers[k] for k in keys])
created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge["snonce"], headers_... |
def request(self, method, request_uri, headers, content):
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"hmacdigest", {}
)
if challenge.get("reason") in ["integrity", "stale"]:
return True
... | def request(self, method, request_uri, headers, content):
)
def response(self, response, content):
challenge = auth._parse_www_authenticate(response, "www-authenticate").get("hmacdigest", {})
if challenge.get("reason") in ["integrity", "stale"]:
return True
return False |
class WsseAuthentication(Authentication):
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(... | class WsseAuthentication(Authentication):
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credenti... |
def request(self, method, request_uri, headers, content):
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = (
'UsernameToken Username="%s", PasswordD... | def request(self, method, request_uri, headers, content):
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = ('UsernameToken Username="%s", PasswordDigest="%s", '... |
def __init__(
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(
Email=credentials[0],
Passwd=credentials[1],
service=service,
source=headers["user-agent"],
)
resp, content = self.http.request(
... | def __init__(
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"],)
resp, content = self.http.request(
"https://www.google.com/accounts/ClientLogin",
... |
class FileCache(object):
be running on the same cache.
"""
def __init__(
self, cache, safe=safename
): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache): | class FileCache(object):
be running on the same cache.
"""
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache): |
def iter(self, domain):
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
| def iter(self, domain):
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
|
class ProxyInfo(object):
bypass_hosts = ()
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None,
):
"""Args:
| class ProxyInfo(object):
bypass_hosts = ()
def __init__(
self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
):
"""Args:
|
def __init__(
proxy_user = proxy_user.decode()
if isinstance(proxy_pass, bytes):
proxy_pass = proxy_pass.decode()
self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass, self.proxy_headers = (
proxy_type,
proxy... | def __init__(
proxy_user = proxy_user.decode()
if isinstance(proxy_pass, bytes):
proxy_pass = proxy_pass.decode()
(
self.proxy_type,
self.proxy_host,
self.proxy_port,
self.proxy_rdns,
self.proxy_user,
self.pr... |
def __init__(self, host, port=None, timeout=None, proxy_info=None):
def connect(self):
"""Connect to the host and port specified in __init__."""
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
"Proxy support missing but proxy use was requested!"
... | def __init__(self, host, port=None, timeout=None, proxy_info=None):
def connect(self):
"""Connect to the host and port specified in __init__."""
if self.proxy_info and socks is None:
raise ProxiesUnavailableError("Proxy support missing but proxy use was requested!")
if self.proxy... |
def connect(self):
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
... | def connect(self):
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass,
)
else:
s... |
def connect(self):
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
if self.debuglevel > 0:
print(
"connect: ({0}, {1}) ************".format(self.host, self.port)
)
if ... | def connect(self):
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
if self.debuglevel > 0:
print("connect: ({0}, {1}) ************".format(self.host, self.port))
if use_proxy:
print(
... |
def connect(self):
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
... | def connect(self):
if use_proxy:
print(
"proxy: {0}".format(
str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
)
)
i... |
def __init__(
self.proxy_info = proxy_info("https")
context = _build_ssl_context(
self.disable_ssl_certificate_validation, self.ca_certs, cert_file, key_file,
maximum_version=tls_maximum_version, minimum_version=tls_minimum_version,
key_password=key_password,
... | def __init__(
self.proxy_info = proxy_info("https")
context = _build_ssl_context(
self.disable_ssl_certificate_validation,
self.ca_certs,
cert_file,
key_file,
maximum_version=tls_maximum_version,
minimum_version=tls_minimum_ver... |
def connect(self):
"""Connect to a host on a given (SSL) port."""
if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
... | def connect(self):
"""Connect to a host on a given (SSL) port."""
if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
use_proxy = True
(
proxy_type,
proxy_host,
proxy_port,
prox... |
def connect(self):
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
... | def connect(self):
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass,
)
else:
sock = socket.socket(family, socktyp... |
def connect(self):
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
# Python 3.3 compatibility: emulate the check_hostname behavior
if (
not hasattr(self._context, "check_hostname")
and not self.disable_ssl_ce... | def connect(self):
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
# Python 3.3 compatibility: emulate the check_hostname behavior
if not hasattr(self._context, "check_hostname") and not self.disable_ssl_certificate_validation:
... |
def connect(self):
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
... | def connect(self):
if use_proxy:
print(
"proxy: {0}".format(
str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
)
)
excep... |
def connect(self):
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
... | def connect(self):
if use_proxy:
print(
"proxy: {0}".format(
str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
)
)
i... |
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
... | def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = auth._parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host)... |
def _conn_request(self, conn, request_uri, method, body, headers):
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except socket.error as e:
errno_ = (
e.args[0].errno if isinstance(e.args[0], socket.er... | def _conn_request(self, conn, request_uri, method, body, headers):
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except socket.error as e:
errno_ = e.args[0].errno if isinstance(e.args[0], socket.error) else e.errno
... |
def _conn_request(self, conn, request_uri, method, body, headers):
return (response, content)
def _request(
self,
conn,
host,
absolute_uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
):
"""Do the ac... | def _conn_request(self, conn, request_uri, method, body, headers):
return (response, content)
def _request(
self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey,
):
"""Do the actual request using the connection object
and also follow one lev... |
def _request(
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if (
"authorization" in headers
and not self.forward_authorization_header... | def _request(
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if "authorization" in headers and not self.forward_authorization_headers:
del headers["authorizat... |
def _request(
redirect_method = "GET"
body = None
(response, content) = self.request(
location,
method=redirect_method,
body=body,
... | def _request(
redirect_method = "GET"
body = None
(response, content) = self.request(
location, method=redirect_method, body=body, headers=headers, redirections=redirections - 1,
)
... |
def _normalize_headers(self, headers):
# including all socket.* and httplib.* exceptions.
def request(
self,
uri,
method="GET",
body=None,
headers=None,
redirections=DEFAULT_MAX_REDIRECTS,
connection_type=None,
):
""" Performs a single HTTP re... | def _normalize_headers(self, headers):
# including all socket.* and httplib.* exceptions.
def request(
self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource... |
def request(
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ''
try:
if headers is None: | def request(
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ""
try:
if headers is None: |
def request(
info = email.message_from_bytes(info)
for k, v in info.items():
if v.startswith("=?") and v.endswith("?="):
info.replace_header(
k, str(*email.header.decode_header... | def request(
info = email.message_from_bytes(info)
for k, v in info.items():
if v.startswith("=?") and v.endswith("?="):
info.replace_header(k, str(*email.header.decode_header(v)[0]))
except (... |
def request(
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than redirection_limit allows.",
{... | def request(
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than redirection_limit allows.", {}, "",
... |
def request(
return (response, content)
if entry_disposition == "STALE":
if (
"etag" in info
and not self.ignore_etag
and not "if-none-match" in headers
... | def request(
return (response, content)
if entry_disposition == "STALE":
if "etag" in info and not self.ignore_etag and not "if-none-match" in headers:
headers["if-none-match"] = info["etag"]
if "las... |
def request(
pass
(response, new_content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
... | def request(
pass
(response, new_content) = self._request(
conn, authority, uri, request_uri, method, body, headers, redirections, cachekey,
)
if response.status == 304 and method == "GET": |
def request(
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(
headers, merged_response, content, self.cache, cachekey
... | def request(
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(headers, merged_response, content, self.cache, cachekey)
respon... |
def request(
content = b""
else:
(response, content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
... | def request(
content = b""
else:
(response, content) = self._request(
conn, authority, uri, request_uri, method, body, headers, redirections, cachekey,
)
except Exception as e:
is_timeout = isinstance... |
def request(
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = b"Request Timeout"
response = Response(
{
"content-type": "text/plain",
"status"... | def request(
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = b"Request Timeout"
response = Response({"content-type": "text/plain", "status": "408", "content-length": len(content),})
response.reason = "... |
class TestCommand(setuptools.command.test.test):
def run_tests(self):
# pytest may be not installed yet
import pytest
args = ['--forked', '--fulltrace', '--no-cov', 'tests/']
if self.test_suite:
args += ['-k', self.test_suite]
sys.stderr.write('setup.py:test run p... | class TestCommand(setuptools.command.test.test):
def run_tests(self):
# pytest may be not installed yet
import pytest
args = ["--forked", "--fulltrace", "--no-cov", "tests/"]
if self.test_suite:
args += ["-k", self.test_suite]
sys.stderr.write("setup.py:test run ... |
def read_requirements(name):
package_dir=pkgdir,
packages=["httplib2"],
package_data={"httplib2": ["*.txt"]},
tests_require=read_requirements("requirements-test.txt"),
cmdclass={"test": TestCommand},
classifiers=[ | def read_requirements(name):
package_dir=pkgdir,
packages=["httplib2"],
package_data={"httplib2": ["*.txt"]},
install_requires=read_requirements("requirements.txt"),
tests_require=read_requirements("requirements-test.txt"),
cmdclass={"test": TestCommand},
classifiers=[ |
def parse_http_message(kind, buf):
msg = kind()
msg.raw = start_line
if kind is HttpRequest:
assert re.match(
br".+ HTTP/\d\.\d\r\n$", start_line
), "Start line does not look like HTTP request: " + repr(start_line)
msg.method, msg.uri, msg.proto = start_line.rstrip().deco... | def parse_http_message(kind, buf):
msg = kind()
msg.raw = start_line
if kind is HttpRequest:
assert re.match(br".+ HTTP/\d\.\d\r\n$", start_line), "Start line does not look like HTTP request: " + repr(
start_line
)
msg.method, msg.uri, msg.proto = start_line.rstrip().deco... |
class MockHTTPConnection(object):
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
):
self.host = host
self.port = port | class MockHTTPConnection(object):
"""
def __init__(
self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None,
):
self.host = host
self.port = port |
class MockHTTPBadStatusConnection(object):
num_calls = 0
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
):
self.host = host
self.port = port | class MockHTTPBadStatusConnection(object):
num_calls = 0
def __init__(
self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None,
):
self.host = host
self.port = port |
def server_socket_thread(srv):
# at least in other/connection_close test
# should not be a problem since socket would close upon garbage collection
if gcounter[0] > request_count:
gresult[0] = Exception(
"Request count expected={0} ... | def server_socket_thread(srv):
# at least in other/connection_close test
# should not be a problem since socket would close upon garbage collection
if gcounter[0] > request_count:
gresult[0] = Exception("Request count expected={0} actual={1}".format(re... |
def http_response_bytes(
if add_etag:
headers.setdefault("etag", '"{0}"'.format(hashlib.md5(body).hexdigest()))
header_string = "".join("{0}: {1}\r\n".format(k, v) for k, v in headers.items())
if (
not undefined_body_length
and proto != "HTTP/1.0"
and "content-length" not in ... | def http_response_bytes(
if add_etag:
headers.setdefault("etag", '"{0}"'.format(hashlib.md5(body).hexdigest()))
header_string = "".join("{0}: {1}\r\n".format(k, v) for k, v in headers.items())
if not undefined_body_length and proto != "HTTP/1.0" and "content-length" not in headers:
raise Exc... |
def server_reflect(**kwargs):
return server_request(http_handler, **kwargs)
def http_parse_auth(s):
"""https://tools.ietf.org/html/rfc7235#section-2.1
"""
scheme, rest = s.split(" ", 1)
result = {}
while True:
m = httplib2.WWW_AUTH_RELAXED.search(rest)
if not m:
bre... | def server_reflect(**kwargs):
return server_request(http_handler, **kwargs)
def store_request_response(out):
def wrapper(fun):
@functools.wraps(fun) |
def http_reflect_with_auth_handler(request):
auth_header = request.headers.get("authorization", "")
if not auth_header:
return deny()
if " " not in auth_header:
return http_response_bytes(status=400, body=b"authorization header syntax error")
scheme, data = auth_h... | def http_reflect_with_auth_handler(request):
auth_header = request.headers.get("authorization", "")
if not auth_header:
return deny()
try:
auth_parsed = httplib2.auth._parse_www_authenticate(request.headers, "authorization")
print("debug: auth_parsed", auth_pa... |
def http_reflect_with_auth_handler(request):
gserver_nonce[0] = nextnonce
gnextnonce[0] = None
server_nonce_current = gserver_nonce[0]
auth_info = http_parse_auth(data)
client_cnonce = auth_info.get("cnonce", "")
client_nc = auth_info.get("... | def http_reflect_with_auth_handler(request):
gserver_nonce[0] = nextnonce
gnextnonce[0] = None
server_nonce_current = gserver_nonce[0]
client_cnonce = auth_info.get("cnonce", "")
client_nc = auth_info.get("nc", "")
client_nonce = auth_info.... |
def http_reflect_with_auth_handler(request):
return deny(body=b"auth-info nc missing")
if client_opaque != server_opaque:
return deny(
body="auth-info opaque mismatch expected={} actual={}".format(
server_opaque, client_opaque
... | def http_reflect_with_auth_handler(request):
return deny(body=b"auth-info nc missing")
if client_opaque != server_opaque:
return deny(
body="auth-info opaque mismatch expected={} actual={}".format(server_opaque, client_opaque).encode()
)
... |
def http_reflect_with_auth_handler(request):
x_wsse = request.headers.get("x-wsse", "")
if x_wsse.count(",") != 3:
return http_response_bytes(status=400, body=b"x-wsse header syntax error")
auth_info = http_parse_auth(x_wsse)
client_username = auth_info.ge... | def http_reflect_with_auth_handler(request):
x_wsse = request.headers.get("x-wsse", "")
if x_wsse.count(",") != 3:
return http_response_bytes(status=400, body=b"x-wsse header syntax error")
wsse_params = httplib2.auth._parse_www_authenticate(request.headers, "x-wsse")... |
def http_reflect_with_auth_handler(request):
digest = hashlib.sha1("".join((client_nonce, client_created, allow_password)).encode("utf-8")).digest()
digest_b64 = base64.b64encode(digest).decode()
print("$$$ check client={} == real={}".format(client_digest, digest_b64))
i... | def http_reflect_with_auth_handler(request):
digest = hashlib.sha1("".join((client_nonce, client_created, allow_password)).encode("utf-8")).digest()
digest_b64 = base64.b64encode(digest).decode()
print("debug: check client={} == real={}".format(client_digest, digest_b64))
... |
import httplib2
import pytest
import tests | import time
import httplib2
import pytest
import tests |
def test_basic():
# Test Basic Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(
allow_scheme="basic", allow_credentials=(("joe", password),)
)
with tests.server_request(handler, request_count=3) as uri:
response, conten... | def test_basic():
# Test Basic Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(allow_scheme="basic", allow_credentials=(("joe", password),))
with tests.server_request(handler, request_count=3) as uri:
response, content = http.reque... |
def test_basic_for_domain():
# Test Basic Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(
allow_scheme="basic", allow_credentials=(("joe", password),)
)
with tests.server_request(handler, request_count=4) as uri:
respo... | def test_basic_for_domain():
# Test Basic Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(allow_scheme="basic", allow_credentials=(("joe", password),))
with tests.server_request(handler, request_count=4) as uri:
response, content =... |
def test_basic_two_credentials():
password1 = tests.gen_password()
password2 = tests.gen_password()
allowed = [("joe", password1)] # exploit shared mutable list
handler = tests.http_reflect_with_auth(
allow_scheme="basic", allow_credentials=allowed
)
with tests.server_request(handler, r... | def test_basic_two_credentials():
password1 = tests.gen_password()
password2 = tests.gen_password()
allowed = [("joe", password1)] # exploit shared mutable list
handler = tests.http_reflect_with_auth(allow_scheme="basic", allow_credentials=allowed)
with tests.server_request(handler, request_count=7... |
def test_digest():
# Test that we support Digest Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(
allow_scheme="digest", allow_credentials=(("joe", password),)
)
with tests.server_request(handler, request_count=3) as uri:
... | def test_digest():
# Test that we support Digest Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(allow_scheme="digest", allow_credentials=(("joe", password),))
with tests.server_request(handler, request_count=3) as uri:
response, c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.