buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
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...
def test_digest_next_nonce_nc(): password = tests.gen_password() grenew_nonce = [None] handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe", password),), out_renew_nonce=grenew_nonce, ) with tests.server_request(handler, request_count=5) as...
def test_digest_next_nonce_nc(): password = tests.gen_password() grenew_nonce = [None] handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe", password),), out_renew_nonce=grenew_nonce, ) with tests.server_request(handler, request_count=5) as uri: ht...
def test_digest_auth_stale(): http.add_credentials("joe", password) response, _ = http.request(uri, "GET") assert response.status == 200 info = httplib2._parse_www_authenticate( requests[0][1].headers, "www-authenticate" ) grenew_nonce[0]() response, _...
def test_digest_auth_stale(): http.add_credentials("joe", password) response, _ = http.request(uri, "GET") assert response.status == 200 info = httplib2.auth._parse_www_authenticate(requests[0][1].headers, "www-authenticate") grenew_nonce[0]() response, _ = http.request(u...
def test_digest_auth_stale(): ({}, {}), ({"www-authenticate": ""}, {}), ( { "www-authenticate": 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux' }, { "test": { "realm": "test realm", ...
def test_digest_auth_stale(): ({}, {}), ({"www-authenticate": ""}, {}), ( {"www-authenticate": 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux'}, {"test": {"realm": "test realm", "foo": "foo", "bar": "bar", "baz": "baz", "qux": "qux"}}, ), (...
def test_digest_auth_stale(): # 'wsse': {'realm': 'very', 'profile': 'UsernameToken'}}), # more quote combos ( { "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=3", algorithm=MD5, qop="auth", stale=true' }, { "digest"...
def test_digest_auth_stale(): # 'wsse': {'realm': 'very', 'profile': 'UsernameToken'}}), # more quote combos ( {"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=3", algorithm=MD5, qop="auth", stale=true'}, {"digest": {"realm": "myrealm", "nonce": "KBAA=3", "algo...
def test_parse_www_authenticate_correct(data, strict): # FIXME: move strict to parse argument httplib2.USE_WWW_AUTH_STRICT_PARSING = strict try: assert httplib2._parse_www_authenticate(headers) == info finally: httplib2.USE_WWW_AUTH_STRICT_PARSING = 0 def test_parse_www_authenticate_ma...
def test_parse_www_authenticate_correct(data, strict): # FIXME: move strict to parse argument httplib2.USE_WWW_AUTH_STRICT_PARSING = strict try: assert httplib2.auth._parse_www_authenticate(headers) == info finally: httplib2.USE_WWW_AUTH_STRICT_PARSING = 0 @pytest.mark.parametrize( ...
def test_digest_object(): host = None request_uri = "/test/digest/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"' } content = b"" d = httplib2.DigestAuthentication( credentials, host, request_uri, headers, ...
def test_digest_object(): host = None request_uri = "/test/digest/" headers = {} response = {"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"'} content = b"" d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None...
def test_digest_object_with_opaque(): request_uri = "/digest/opaque/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, ' 'qop="auth", opaque="atestopaque"' } content = "" d = httplib2.DigestAuthentication( credentials...
def test_digest_object_with_opaque(): request_uri = "/digest/opaque/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, ' 'qop="auth", opaque="atestopaque"' } content = "" d = httplib2.DigestAuthentication(credentials, host, request_u...
def test_digest_object_stale(): request_uri = "/digest/stale/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = ( 'Digest realm="myrealm", nonce="bd669f", ' 'algorithm=MD5, qop="auth", stale=true' ) response.status = 401 content = b"" d = httpl...
def test_digest_object_stale(): request_uri = "/digest/stale/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = 'Digest realm="myrealm", nonce="bd669f", ' 'algorithm=MD5, qop="auth", stale=true' response.status = 401 content = b"" d = httplib2.DigestAuthentication...
def test_digest_object_auth_info(): request_uri = "/digest/nextnonce/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = ( 'Digest realm="myrealm", nonce="barney", ' 'algorithm=MD5, qop="auth", stale=true' ) response["authentication-info"] = 'nextnonce=...
def test_digest_object_auth_info(): request_uri = "/digest/nextnonce/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = 'Digest realm="myrealm", nonce="barney", ' 'algorithm=MD5, qop="auth", stale=true' response["authentication-info"] = 'nextnonce="fred"' content = b"...
import re from io import BytesIO from waitress.compat import ( tostr, urlparse, unquote_bytes_to_wsgi, ) from waitress.buffers import OverflowableBuffer from waitress.receiver import ( FixedStreamReceiver, ChunkedReceiver, ) from waitress.utilities import ( find_double_newline, RequestEn...
import re from io import BytesIO from waitress.buffers import OverflowableBuffer from waitress.compat import tostr, unquote_bytes_to_wsgi, urlparse from waitress.receiver import ChunkedReceiver, FixedStreamReceiver from waitress.utilities import ( BadRequest, RequestEntityTooLarge, RequestHeaderFieldsTooLa...
def received(self, data): # Header finished. header_plus = s[:index] consumed = len(data) - (len(s) - index) # Remove preceeding blank lines. header_plus = header_plus.lstrip() if not header_plus: self.em...
def received(self, data): # Header finished. header_plus = s[:index] consumed = len(data) - (len(s) - index) # Remove preceeding blank lines. This is suggested by # https://tools.ietf.org/html/rfc7230#section-3.5 to support ...
def parse_header(self, header_plus): Parses the header_plus block of text (the headers plus the first line of the request). """ index = header_plus.find(b"\n") if index >= 0: first_line = header_plus[:index].rstrip() header = header_plus[index + 1 :] ...
def parse_header(self, header_plus): Parses the header_plus block of text (the headers plus the first line of the request). """ index = header_plus.find(b"\r\n") if index >= 0: first_line = header_plus[:index].rstrip() header = header_plus[index + 2 :] ...
def get_header_lines(header): Splits the header into lines, putting multi-line headers together. """ r = [] lines = header.split(b"\n") for line in lines: if line.startswith((b" ", b"\t")): if not r: # https://corte.si/posts/code/pathod/pythonservers/index.html
def get_header_lines(header): Splits the header into lines, putting multi-line headers together. """ r = [] lines = header.split(b"\r\n") for line in lines: if b"\r" in line or b"\n" in line: raise ParsingError('Bare CR or LF found in header line "%s"' % tostr(line)) if ...
"""Data Chunk Receiver """ from waitress.utilities import find_double_newline from waitress.utilities import BadRequest class FixedStreamReceiver(object):
"""Data Chunk Receiver """ from waitress.utilities import BadRequest, find_double_newline class FixedStreamReceiver(object):
def __len__(self): def received(self, data): "See IStreamConsumer" rm = self.remain if rm < 1: self.completed = True # Avoid any chance of spinning return 0 datalen = len(data) if rm <= datalen: self.buf.append(data[:rm]) self....
def __len__(self): def received(self, data): "See IStreamConsumer" rm = self.remain if rm < 1: self.completed = True # Avoid any chance of spinning return 0 datalen = len(data) if rm <= datalen: self.buf.append(data[:rm]) se...
def getbuf(self): class ChunkedReceiver(object): chunk_remainder = 0 control_line = b"" all_chunks_received = False trailer = b""
def getbuf(self): class ChunkedReceiver(object): chunk_remainder = 0 validate_chunk_end = False control_line = b"" all_chunks_received = False trailer = b""
def __len__(self): def received(self, s): # Returns the number of bytes consumed. if self.completed: return 0 orig_size = len(s) while s: rm = self.chunk_remainder if rm > 0: # Receive the remainder of a chunk. to_w...
def __len__(self): def received(self, s): # Returns the number of bytes consumed. if self.completed: return 0 orig_size = len(s) while s: rm = self.chunk_remainder if rm > 0: # Receive the remainder of a chunk. t...
def received(self, s): else: # Control line finished. line = s[:pos] s = s[pos + 1 :] self.control_line = b"" line = line.strip() if line: # Begin a new chunk. ...
def received(self, s): else: # Control line finished. line = s[:pos] s = s[pos + 2 :] self.control_line = b"" line = line.strip() if line: # Begin a new chunk....
def received(self, s): except ValueError: # garbage in input self.error = BadRequest("garbage in chunked encoding input") sz = 0 if sz > 0: # Start a new chunk. ...
def received(self, s): except ValueError: # garbage in input self.error = BadRequest("garbage in chunked encoding input") sz = 0 if sz > 0: # Start a new chunk. ...
def received(self, s): else: # Receive the trailer. trailer = self.trailer + s if trailer.startswith(b"\r\n"): # No trailer. self.completed = True return orig_size - (len(trailer) - 2) ...
def received(self, s): else: # Receive the trailer. trailer = self.trailer + s if trailer.startswith(b"\r\n"): # No trailer. self.completed = True return orig_size - (len(trailer) - 2) ...
def received(self, s): # Finished the trailer. self.completed = True self.trailer = trailer[:pos] return orig_size - (len(trailer) - pos) return orig_size def getfile(self):
def received(self, s): # Finished the trailer. self.completed = True self.trailer = trailer[:pos] return orig_size - (len(trailer) - pos) return orig_size def getfile(self):
def test_del_channel(self): def test_received(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.server.tasks, [inst]) self.assertTrue(inst.requests)
def test_del_channel(self): def test_received(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.server.tasks, [inst]) self.assertTrue(inst.requests)
def test_received_preq_not_completed(self): inst.request = preq preq.completed = False preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.requests, ()) self.assertEqual(inst.server.tasks, [])
def test_received_preq_not_completed(self): inst.request = preq preq.completed = False preq.empty = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.requests, ()) self.assertEqual(inst.server.tasks, [])
def test_received_preq_completed_empty(self): inst.request = preq preq.completed = True preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, [])
def test_received_preq_completed_empty(self): inst.request = preq preq.completed = True preq.empty = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, [])
def test_received_preq_error(self): inst.request = preq preq.completed = True preq.error = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(len(inst.server.tasks), 1) self.assertTrue(inst.requests)
def test_received_preq_error(self): inst.request = preq preq.completed = True preq.error = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, None) self.assertEqual(len(inst.server.tasks), 1) self.assertTrue(inst.requests)
def test_received_preq_completed_connection_close(self): preq.completed = True preq.empty = True preq.connection_close = True inst.received(b"GET / HTTP/1.1\n\n" + b"a" * 50000) self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, []) def test_rec...
def test_received_preq_completed_connection_close(self): preq.completed = True preq.empty = True preq.connection_close = True inst.received(b"GET / HTTP/1.1\r\n\r\n" + b"a" * 50000) self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, []) def test...
def test_received_headers_finished_expect_continue_false(self): preq.completed = False preq.empty = False preq.retval = 1 inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual(inst.outbuf...
def test_received_headers_finished_expect_continue_false(self): preq.completed = False preq.empty = False preq.retval = 1 inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual(inst.ou...
def test_received_headers_finished_expect_continue_true(self): preq.headers_finished = True preq.completed = False preq.empty = False inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual...
def test_received_headers_finished_expect_continue_true(self): preq.headers_finished = True preq.completed = False preq.empty = False inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertE...
def test_received_headers_finished_expect_continue_true_sent_true(self): preq.completed = False preq.empty = False inst.sent_continue = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.asse...
def test_received_headers_finished_expect_continue_true_sent_true(self): preq.completed = False preq.empty = False inst.sent_continue = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self....
def _read_echo(self, fp): return line, headers, echo.parse_response(body) def test_date_and_server(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def _read_echo(self, fp): return line, headers, echo.parse_response(body) def test_date_and_server(self): to_send = "GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_date_and_server(self): def test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = "GET / HTTP/1.0\n" " Host: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_date_and_server(self): def test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = "GET / HTTP/1.0\r\n Host: 0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_bad_host_header(self): self.assertTrue(headers.get("date")) def test_send_with_body(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n\n" to_send += "hello" to_send = tobytes(to_send) self.connect()
def test_bad_host_header(self): self.assertTrue(headers.get("date")) def test_send_with_body(self): to_send = "GET / HTTP/1.0\r\nContent-Length: 5\r\n\r\n" to_send += "hello" to_send = tobytes(to_send) self.connect()
def test_send_with_body(self): self.assertEqual(echo.body, b"hello") def test_send_empty_body(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_send_with_body(self): self.assertEqual(echo.body, b"hello") def test_send_empty_body(self): to_send = "GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_multiple_requests_without_body(self): self.sock = orig_sock def test_without_crlf(self): data = "Echo\nthis\r\nplease" s = tobytes( "GET / HTTP/1.0\n" "Connection: close\n" "Content-Length: %d\n" "\n" "%s" % (len(data), da...
def test_multiple_requests_without_body(self): self.sock = orig_sock def test_without_crlf(self): data = "Echo\r\nthis\r\nplease" s = tobytes( "GET / HTTP/1.0\r\n" "Connection: close\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len...
def test_large_body(self): # 1024 characters. body = "This string has 32 characters.\r\n" * 32 s = tobytes( "GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(body), body) ) self.connect() self.sock.send(s)
def test_large_body(self): # 1024 characters. body = "This string has 32 characters.\r\n" * 32 s = tobytes( "GET / HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(body), body) ) self.connect() self.sock.send(s)
def test_many_clients(self): h.close() def test_chunking_request_without_content(self): header = tobytes("GET / HTTP/1.1\n" "Transfer-Encoding: chunked\n\n") self.connect() self.sock.send(header) self.sock.send(b"0\r\n\r\n")
def test_many_clients(self): h.close() def test_chunking_request_without_content(self): header = tobytes("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n") self.connect() self.sock.send(header) self.sock.send(b"0\r\n\r\n")
def test_chunking_request_with_content(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" expected = s * 12 header = tobytes("GET / HTTP/1.1\n" "Transfer-Encoding: chunked\n\n") self.connect() self.sock.send(header) fp = ...
def test_chunking_request_with_content(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" expected = s * 12 header = tobytes("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n") self.connect() self.sock.send(header) fp...
def test_chunking_request_with_content(self): def test_broken_chunked_encoding(self): control_line = "20;\r\n" # 20 hex = 32 dec s = "This string has 32 characters.\r\n" to_send = "GET / HTTP/1.1\nTransfer-Encoding: chunked\n\n" to_send += control_line + s # garbage in input...
def test_chunking_request_with_content(self): def test_broken_chunked_encoding(self): control_line = "20;\r\n" # 20 hex = 32 dec s = "This string has 32 characters.\r\n" to_send = "GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" to_send += control_line + s + "\r\n" # g...
def test_broken_chunked_encoding(self): self.assertline(line, "400", "Bad Request", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "ser...
def test_broken_chunked_encoding(self): self.assertline(line, "400", "Bad Request", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(b"Chunk not properly terminated" in response_body) self.assertEqual( sorted(hea...
def test_keepalive_http_10(self): # Handling of Keep-Alive within HTTP 1.0 data = "Default: Don't keep me alive" s = tobytes( "GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s)
def test_keepalive_http_10(self): # Handling of Keep-Alive within HTTP 1.0 data = "Default: Don't keep me alive" s = tobytes( "GET / HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(data), data) ) self.connect() self.sock.send(s)
def test_keepalive_http10_explicit(self): # the corresponding header data = "Keep me alive" s = tobytes( "GET / HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect()
def test_keepalive_http10_explicit(self): # the corresponding header data = "Keep me alive" s = tobytes( "GET / HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(data), data) ) self.c...
def test_keepalive_http_11(self): # All connections are kept alive, unless stated otherwise data = "Default: Keep me alive" s = tobytes( "GET / HTTP/1.1\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s)
def test_keepalive_http_11(self): # All connections are kept alive, unless stated otherwise data = "Default: Keep me alive" s = tobytes( "GET / HTTP/1.1\r\nContent-Length: %d\r\n\r\n%s" % (len(data), data) ) self.connect() self.sock.send(s)
def test_keepalive_http11_explicit(self): # Explicitly set keep-alive data = "Default: Keep me alive" s = tobytes( "GET / HTTP/1.1\n" "Connection: keep-alive\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self...
def test_keepalive_http11_explicit(self): # Explicitly set keep-alive data = "Default: Keep me alive" s = tobytes( "GET / HTTP/1.1\r\n" "Connection: keep-alive\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(data), data) ) ...
def test_keepalive_http11_connclose(self): # specifying Connection: close explicitly data = "Don't keep me alive" s = tobytes( "GET / HTTP/1.1\n" "Connection: close\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) ...
def test_keepalive_http11_connclose(self): # specifying Connection: close explicitly data = "Don't keep me alive" s = tobytes( "GET / HTTP/1.1\r\n" "Connection: close\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(data), data) ...
def test_keepalive_http11_connclose(self): def test_proxy_headers(self): to_send = ( "GET / HTTP/1.0\n" "Content-Length: 0\n" "Host: www.google.com:8080\n" "X-Forwarded-For: 192.168.1.1\n" "X-Forwarded-Proto: https\n" "X-Forwarded-Port...
def test_keepalive_http11_connclose(self): def test_proxy_headers(self): to_send = ( "GET / HTTP/1.0\r\n" "Content-Length: 0\r\n" "Host: www.google.com:8080\r\n" "X-Forwarded-For: 192.168.1.1\r\n" "X-Forwarded-Proto: https\r\n" "X-Forw...
def test_expect_continue(self): # specifying Connection: close explicitly data = "I have expectations" to_send = tobytes( "GET / HTTP/1.1\n" "Connection: close\n" "Content-Length: %d\n" "Expect: 100-continue\n" "\n" "%s" % (...
def test_expect_continue(self): # specifying Connection: close explicitly data = "I have expectations" to_send = tobytes( "GET / HTTP/1.1\r\n" "Connection: close\r\n" "Content-Length: %d\r\n" "Expect: 100-continue\r\n" "\r\n" ...
def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = tobytes( "GET /short_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() ...
def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = tobytes( "GET /short_body HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: 0\r\n" "\r\n" ) self.connec...
def test_long_body(self): # check server doesnt close connection when body is too short # for cl header to_send = tobytes( "GET /long_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() se...
def test_long_body(self): # check server doesnt close connection when body is too short # for cl header to_send = tobytes( "GET /long_body HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: 0\r\n" "\r\n" ) self.connect() ...
def tearDown(self): def test_http10_generator(self): body = string.ascii_letters to_send = ( "GET / HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n\n" % len(body) ) to_send += body to_send = tobytes(to_send)
def tearDown(self): def test_http10_generator(self): body = string.ascii_letters to_send = ( "GET / HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: %d\r\n\r\n" % len(body) ) to_send += body to_send = tobytes(to_send)
def test_http10_generator(self): def test_http10_list(self): body = string.ascii_letters to_send = ( "GET /list HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n\n" % len(body) ) to_send += body to_send = tobytes(to_send)
def test_http10_generator(self): def test_http10_list(self): body = string.ascii_letters to_send = ( "GET /list HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: %d\r\n\r\n" % len(body) ) to_send += body to_send = tobytes(to_send)
def test_http10_list(self): def test_http10_listlentwo(self): body = string.ascii_letters to_send = ( "GET /list_lentwo HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n\n" % len(body) ) to_send += body to_send = tobytes(to_send)
def test_http10_list(self): def test_http10_listlentwo(self): body = string.ascii_letters to_send = ( "GET /list_lentwo HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: %d\r\n\r\n" % len(body) ) to_send += body to_send = tobytes(...
def test_http10_listlentwo(self): def test_http11_generator(self): body = string.ascii_letters to_send = "GET / HTTP/1.1\n" "Content-Length: %s\n\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect()
def test_http10_listlentwo(self): def test_http11_generator(self): body = string.ascii_letters to_send = "GET / HTTP/1.1\r\nContent-Length: %s\r\n\r\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect()
def test_http11_generator(self): def test_http11_list(self): body = string.ascii_letters to_send = "GET /list HTTP/1.1\n" "Content-Length: %d\n\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect()
def test_http11_generator(self): def test_http11_list(self): body = string.ascii_letters to_send = "GET /list HTTP/1.1\r\nContent-Length: %d\r\n\r\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect()
def test_http11_list(self): def test_http11_listlentwo(self): body = string.ascii_letters to_send = "GET /list_lentwo HTTP/1.1\n" "Content-Length: %s\n\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect()
def test_http11_list(self): def test_http11_listlentwo(self): body = string.ascii_letters to_send = "GET /list_lentwo HTTP/1.1\r\nContent-Length: %s\r\n\r\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect()