def open(self): if self.request == 'hyper': if self.http2: self.__http = hyper.HTTP20Connection( self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers) else: self.__http = hyper.HTTPConnection( self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers) elif self.request == 'httpx': self.__http = httpx.AsyncClient(base_url='%s://%s' % (self.scheme, self.host), http2=self.http2) else: if self.http2: self.__http = httplib2.Http() elif self.scheme == 'http': self.__http = http_client.HTTPConnection(self.host, self.port) elif self.scheme == 'https': self.__http = http_client.HTTPSConnection(self.host, self.port) if self.using_proxy(): self.__http.set_tunnel(self.realhost, self.realport, self.proxy_headers)
def __init__(self, **kwargs): self.auth_key = kwargs["auth_key"] self.bundle_id = kwargs["bundle_id"] self.key_id = kwargs["key_id"] self.team_id = kwargs["team_id"] self.appname = kwargs["appname"] self.instanceid = kwargs["instanceid"] self.last_token_refresh = 0 self.token = None self.http2 = hyper.HTTPConnection(BASE_URL)
def __init__(self, **kwargs): self.auth_key = kwargs["auth_key"] self.bundle_id = kwargs["bundle_id"] self.key_id = kwargs["key_id"] self.team_id = kwargs["team_id"] self.appname = kwargs["appname"] self.instanceid = kwargs["instanceid"] self.last_token_refresh = 0 self.token = None url = IOS_PROD_URL if ios_production else IOS_DEV_URL self.http2 = hyper.HTTPConnection(url)
def test_http2_request_hyper(self): ''' Test HTTP/2 w/ hyper (Normal Scenario) ''' try: conn = hyper.HTTPConnection('127.0.0.1', self.http2_port, secure=True) stream_id = conn.request('GET', '/') ret = conn.get_response() self.assertNotEqual(stream_id, None) self.assertEqual(ret.status, 200) except Exception as e: log.error(e) self.__traffic_out() self.__diags_log()
def test_hyper_connection_timeout(self): self.set_up(timeout=0.5) def socket_handler(listener): time.sleep(1) self._start_server(socket_handler) conn = hyper.HTTPConnection(self.host, self.port, self.secure, timeout=self.timeout) with pytest.raises((SocketTimeout, ssl.SSLError)): # Py2 raises this as a BaseSSLError, # Py3 raises it as socket timeout. conn.request('GET', '/') self.tear_down()
def main(): parser = argparse.ArgumentParser(description='Spams a Google Form.') parser.add_argument('url', help='the url of the form to spam') parser.add_argument('--window-size', type=int, default=10, help='number of requests to send at once') args = parser.parse_args() try: r = requests.get(args.url) r.raise_for_status() except RequestException as e: sys.exit(e) match = pattern.search(r.text) try: form = json.loads(match.group(1)) except (AttributeError, JSONDecodeError): sys.exit('Could not parse form data.') action = '/forms/d/%s/formResponse' % form[14] success = fail = 0 c = hyper.HTTPConnection('docs.google.com:443') while True: status = 'Successful: %i, Failed: %i' % (success, fail) print(status, flush=True, end='\r') r = [send_request(c, action, form) for _ in range(args.window_size)] for request in r: try: resp = c.get_response(request) if resp.status is not 200: raise ValueError('invalid response from server') text = resp.read().decode('utf-8') if pattern.search(text): raise ValueError('form response rejected') success += 1 except (ValueError, ConnectionError, socket.timeout): fail += 1
def get_alexa_tokens(self): date_format = "%a %b %d %H:%M:%S %Y" alexa_tokens = json.loads(open(self._tokens_filename, 'r').read()) if 'access_token' in alexa_tokens: if 'expiry' in alexa_tokens: expiry = datetime.datetime.strptime(alexa_tokens['expiry'], date_format) # refresh 60 seconds early to avoid chance of using expired access_token if (datetime.datetime.utcnow() - expiry) > datetime.timedelta(seconds=60): self._log.info("Refreshing access_token") else: self._log.info("access_token should be OK, expires %s", expiry) return alexa_tokens payload = { 'client_id': alexa_tokens['client_id'], 'client_secret': alexa_tokens['client_secret'], 'grant_type': 'refresh_token', 'refresh_token': alexa_tokens['refresh_token'] } conn = hyper.HTTPConnection('api.amazon.com:443', secure=True, force_proto="h2") conn.request("POST", "/auth/o2/token", headers={'Content-Type': "application/json"}, body=json.dumps(payload).encode('utf-8')) r = conn.get_response() self._log.info(r.status) tokens = json.loads(r.read().decode('utf-8')) self._log.info(tokens) expiry_time = datetime.datetime.utcnow() + datetime.timedelta( seconds=tokens['expires_in']) tokens['expiry'] = expiry_time.strftime(date_format) payload.update(tokens) open(self._tokens_filename, 'w').write(json.dumps(payload)) return payload
def Push(self, device_token, title, message): path = '/3/device/%s' % device_token token = jwt.encode({ 'iss': self.team_id, 'iat': int(time.time()) }, self.key, algorithm=IOS_JWT_ALGORITHM, headers={ 'alg': IOS_JWT_ALGORITHM, 'kid': self.key_id }) headers = { 'authorization': 'bearer %s' % token.decode('ascii'), 'apns-topic': self.app_id } payload = { 'aps': { 'alert': { 'title': title, 'body': message }, 'sound': IOS_SOUND } } http_connection = hyper.HTTPConnection(self.server_url) http_connection.request(IOS_HTTP_METHOD, path, body=json.dumps(payload).encode('utf-8'), headers=headers) http_response = http_connection.get_response() if http_response.status == 410: raise DeleteSessionException() if http_response.status != 200: raise PushNotificationException(http_response.read())
def create_connection(): hyper.tls.cert_loc = "./cert.pem" return hyper.HTTPConnection(cfg["INTERNAL"]["HOST"], secure=True)
def __init__(self, uri_or_host, port=None, path=None, customThrift=False, request='httplib', http2=False, proxy_host=None, proxy_port=None, proxy_auth=None): '''THttpClient supports two different types constructor parameters. THttpClient(host, port, path) - deprecated THttpClient(uri) Only the second supports https. ''' if port is not None: warnings.warn( 'Please use the THttpClient("http://host:port/path") syntax', DeprecationWarning, stacklevel=2) self.host = uri_or_host self.port = port assert path self.path = path self.scheme = 'http' else: parsed = urllib.parse.urlparse(uri_or_host) self.scheme = parsed.scheme assert self.scheme in ('http', 'https') if self.scheme == 'http': self.port = parsed.port or http_client.HTTP_PORT elif self.scheme == 'https': self.port = parsed.port or http_client.HTTPS_PORT self.host = parsed.hostname self.path = parsed.path if parsed.query: self.path += '?%s' % parsed.query proxy = None self.request = request self.http2 = http2 self.realhost = proxy_host self.realport = proxy_port self.proxy_auth = proxy_auth self.__wbuf = BytesIO() if self.scheme == 'https' and self.using_proxy() and self.proxy_auth: self.proxy_headers = {'Proxy-Authorization': self.proxy_auth} else: self.proxy_headers = None self.url = '%s://%s:%s%s' % (self.scheme, self.host, self.port, self.path) if customThrift: if self.request == 'hyper': if self.http2: self.__http = hyper.HTTP20Connection( self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers) else: self.__http = hyper.HTTPConnection( self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers) elif self.request == 'httpx': self.__http = httpx.AsyncClient(base_url='%s://%s' % (self.scheme, self.host), http2=self.http2) else: if self.http2: self.__http = httplib2.Http() elif self.scheme == 'http': self.__http = http_client.HTTPConnection( self.host, self.port) elif self.scheme == 'https': self.__http = http_client.HTTPSConnection( self.host, self.port) if self.using_proxy(): self.__http.set_tunnel(self.realhost, self.realport, self.proxy_headers) else: self.__http = None self.__async_loop = asyncio.get_event_loop( ) if self.request == 'httpx' else None self.__http_response = None self.__response_data = None self.__last_read = 0 self.__timeout = None self.__custom_headers = None self.__time = time.time() self.__custom_thrift = customThrift self.__loop = 0
def test_upgrade(self): self.set_up(secure=False) recv_event = threading.Event() wait_event = threading.Event() def socket_handler(listener): sock = listener.accept()[0] # First read the HTTP/1.1 request data = b'' while not data.endswith(b'\r\n\r\n'): data += sock.recv(65535) # Check it's an upgrade. assert b'upgrade: h2c\r\n' in data # Send back an upgrade message. data = (b'HTTP/1.1 101 Switching Protocols\r\n' b'Server: some-server\r\n' b'Connection: upgrade\r\n' b'Upgrade: h2c\r\n' b'\r\n') sock.sendall(data) # We get a message for connection open, specifically the preamble. receive_preamble(sock) # Now, send the headers for the response. This response has a body. f = build_headers_frame([(':status', '200')]) f.stream_id = 1 sock.sendall(f.serialize()) # Send the first two chunks. f = DataFrame(1) f.data = b'hello' sock.sendall(f.serialize()) f = DataFrame(1) f.data = b'there' sock.sendall(f.serialize()) # Now, delay a bit. We want to wait a half a second before we send # the next frame. wait_event.wait(5) time.sleep(0.5) f = DataFrame(1) f.data = b'world' f.flags.add('END_STREAM') sock.sendall(f.serialize()) # Wait for the message from the main thread. recv_event.set() sock.close() self._start_server(socket_handler) conn = hyper.HTTPConnection(self.host, self.port, self.secure) conn.request('GET', '/') resp = conn.get_response() # Confirm the status code. assert resp.status == 200 first_chunk = resp.read(10) wait_event.set() second_chunk = resp.read(5) assert first_chunk == b'hellothere' assert second_chunk == b'world' # Awesome, we're done now. recv_event.wait(5) self.tear_down()