-
Notifications
You must be signed in to change notification settings - Fork 37
/
trafgen.cpp
369 lines (316 loc) · 12.5 KB
/
trafgen.cpp
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright 2017 NSONE, Inc
#include <algorithm>
#include <iostream>
#include <memory>
#include <random>
#include <string>
#include "trafgen.h"
#include "tcptlssession.h"
TrafGen::TrafGen(std::shared_ptr<uvw::Loop> l,
std::shared_ptr<Metrics> s,
std::shared_ptr<Config> c,
std::shared_ptr<TrafGenConfig> tgc,
std::shared_ptr<QueryGenerator> q,
std::shared_ptr<TokenBucket> r)
: _loop(l)
, _metrics(s)
, _config(c)
, _traf_config(tgc)
, _qgen(q)
, _rate_limit(r)
, _stopping(false)
{
// build a list of random ids we will use for queries
for (uint16_t i = 0; i < std::numeric_limits<uint16_t>::max(); i++)
_free_id_list.push_back(i);
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(_free_id_list.begin(), _free_id_list.end(), g);
// allocate enough space for the amount of queries we expect to have in flight
// max here is based on uint16, the number of ids
_in_flight.reserve(std::numeric_limits<uint16_t>::max());
}
void TrafGen::process_wire(const char data[], size_t len)
{
if (len <= 12) {
_metrics->bad_receive(_in_flight.size());
return;
}
// The first 2 bytes are the query ID.
u_int16_t id = ntohs(*(u_int16_t *)data);
// The response code is in the low-order 4 bits of the flags header field.
uint8_t rcode = data[3] & 0xf;
if (_in_flight.find(id) == _in_flight.end()) {
std::cerr << "untracked " << id << std::endl;
_metrics->bad_receive(_in_flight.size());
return;
}
_metrics->receive(_in_flight[id].send_time, rcode, _in_flight.size());
_in_flight.erase(id);
_free_id_list.push_back(id);
}
void TrafGen::start_udp()
{
_udp_handle = _loop->resource<uvw::UDPHandle>(_traf_config->family);
_udp_handle->on<uvw::ErrorEvent>([this](const uvw::ErrorEvent &e, uvw::UDPHandle &) {
if (0 == strcmp(e.name(), "EADDRNOTAVAIL"))
throw std::runtime_error("unable to bind to ip address: " + _traf_config->bind_ip);
_metrics->net_error();
});
if (_traf_config->family == AF_INET) {
_udp_handle->bind<uvw::IPv4>(_traf_config->bind_ip, 0);
} else {
_udp_handle->bind<uvw::IPv6>(_traf_config->bind_ip, 0, uvw::UDPHandle::Bind::IPV6ONLY);
}
_metrics->trafgen_id(_udp_handle->sock().port);
_udp_handle->on<uvw::UDPDataEvent>([this](const uvw::UDPDataEvent &event, uvw::UDPHandle &h) {
process_wire(event.data.get(), event.length);
});
_udp_handle->recv();
}
void TrafGen::start_tcp_session()
{
assert(_tcp_handle.get() == 0);
assert(_tcp_session.get() == 0);
assert(_finish_session_timer.get() == 0);
_tcp_handle = _loop->resource<uvw::TcpHandle>(_traf_config->family);
if (_traf_config->family == AF_INET) {
_tcp_handle->bind<uvw::IPv4>(_traf_config->bind_ip, 0);
} else {
_tcp_handle->bind<uvw::IPv6>(_traf_config->bind_ip, 0, uvw::TcpHandle::Bind::IPV6ONLY);
}
_metrics->trafgen_id(_tcp_handle->sock().port);
auto malformed_data = [this]() {
_metrics->net_error();
handle_timeouts(true);
_tcp_handle->close();
};
auto got_dns_message = [this](std::unique_ptr<const char[]> data,
size_t size) {
process_wire(data.get(), size);
};
auto connection_ready = [this]() {
/** SEND DATA **/
uint16_t id{0};
std::vector<uint16_t> id_list;
for (int i = 0; i < _traf_config->batch_count; i++) {
if (_free_id_list.empty()) {
// out of ids, have to limit
break;
}
if (_rate_limit && !_rate_limit->consume(1, this->_loop->now()))
break;
id = _free_id_list.back();
_free_id_list.pop_back();
assert(_in_flight.find(id) == _in_flight.end());
id_list.push_back(id);
// might be better to do this after write (in WriteEvent) but it needs to be available
// by the time DataEvent fires, and we don't want a race there
_in_flight[id].send_time = std::chrono::high_resolution_clock::now();
}
if (id_list.size() == 0) {
// didn't send anything, probably due to rate limit. close.
_tcp_handle->close();
return;
}
auto qt = _qgen->next_tcp(id_list);
// async send the batch. fires WriteEvent when finished sending.
_tcp_session->write(std::move(std::get<0>(qt)), std::get<1>(qt));
_metrics->send(std::get<1>(qt), id_list.size(), _in_flight.size());
};
// For now, treat a TLS handshake failure as malformed data
_tcp_session = (_traf_config->protocol == Protocol::DOT)
? std::make_shared<TCPTLSSession>(_tcp_handle, malformed_data, got_dns_message, connection_ready, malformed_data)
: std::make_shared<TCPSession>(_tcp_handle, malformed_data, got_dns_message, connection_ready);
if (!_tcp_session->setup()) {
return;
}
/** SOCKET CALLBACKS **/
// SOCKET: local socket was closed, cleanup resources and possibly restart another connection
_tcp_handle->on<uvw::CloseEvent>([this](uvw::CloseEvent &event, uvw::TcpHandle &h) {
// if timer is still going (e.g. we got here through EndEvent), cancel it
if (_finish_session_timer.get()) {
_finish_session_timer->stop();
_finish_session_timer->close();
}
if (_tcp_handle.get()) {
_tcp_handle->stop();
}
_tcp_session.reset();
_tcp_handle.reset();
_finish_session_timer.reset();
handle_timeouts(true);
if (!_stopping) {
start_tcp_session();
}
});
// SOCKET: socket error
_tcp_handle->on<uvw::ErrorEvent>([this](uvw::ErrorEvent &event, uvw::TcpHandle &h) {
_metrics->net_error();
// XXX need to close?
});
// INCOMING: remote peer closed connection, EOF
_tcp_handle->on<uvw::EndEvent>([this](uvw::EndEvent &event, uvw::TcpHandle &h) {
_tcp_session->on_end_event();
});
// OUTGOING: we've finished writing all our data and are shutting down
_tcp_handle->on<uvw::ShutdownEvent>([this](uvw::ShutdownEvent &event, uvw::TcpHandle &h) {
_tcp_session->on_shutdown_event();
});
// INCOMING: remote peer sends data, pass to session
_tcp_handle->on<uvw::DataEvent>([this](uvw::DataEvent &event, uvw::TcpHandle &h) {
_tcp_session->receive_data(event.data.get(), event.length);
});
// OUTGOING: write operation has finished
_tcp_handle->on<uvw::WriteEvent>([this](uvw::WriteEvent &event, uvw::TcpHandle &h) {
if (!_finish_session_timer)
start_wait_timer_for_tcp_finish();
});
// SOCKET: on connect
_tcp_handle->on<uvw::ConnectEvent>([this](uvw::ConnectEvent &event, uvw::TcpHandle &h) {
_tcp_session->on_connect_event();
_metrics->tcp_connection();
// start reading from incoming stream, fires DataEvent when receiving
_tcp_handle->read();
});
// fires ConnectEvent when connected
if (_traf_config->family == AF_INET) {
_tcp_handle->connect<uvw::IPv4>(_traf_config->next_target_address(), _traf_config->port);
} else {
_tcp_handle->connect<uvw::IPv6>(_traf_config->next_target_address(), _traf_config->port);
}
}
void TrafGen::start_wait_timer_for_tcp_finish()
{
// wait for all responses, but no longer than query timeout
// once we have all responses, or timed out, delay for delay time, then start over
auto wait_time_start = std::chrono::high_resolution_clock::now();
assert(_finish_session_timer.get() == 0);
_finish_session_timer = _loop->resource<uvw::TimerHandle>();
_finish_session_timer->on<uvw::TimerEvent>([this, wait_time_start](const uvw::TimerEvent &event,
uvw::TimerHandle &h) {
auto now = std::chrono::high_resolution_clock::now();
auto cur_wait_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - wait_time_start).count();
if (_in_flight.size() && (cur_wait_ms < (_traf_config->r_timeout * 1000))) {
// queries in flight and timeout time not elapsed, still wait
return;
} else if (cur_wait_ms < (_traf_config->s_delay)) {
// either timed out or nothing in flight. ensure delay period has passed
// before restarting
return;
}
// shut down timer and connection. TCP CloseEvent will handle restarting sends.
_finish_session_timer->stop();
_finish_session_timer->close();
_tcp_handle->close();
});
_finish_session_timer->start(uvw::TimerHandle::Time{1}, uvw::TimerHandle::Time{50});
}
void TrafGen::udp_send()
{
if (_udp_handle.get() && !_udp_handle->active())
return;
if (_qgen->finished())
return;
if (_free_id_list.size() == 0) {
std::cerr << "max in flight reached" << std::endl;
return;
}
uint16_t id{0};
for (int i = 0; i < _traf_config->batch_count; i++) {
if (_rate_limit && !_rate_limit->consume(1, _loop->now()))
return;
if (_free_id_list.size() == 0) {
std::cerr << "max in flight reached" << std::endl;
return;
}
id = _free_id_list.back();
_free_id_list.pop_back();
assert(_in_flight.find(id) == _in_flight.end());
auto qt = _qgen->next_udp(id);
if (_traf_config->family == AF_INET) {
_udp_handle->send<uvw::IPv4>(_traf_config->next_target_address(), _traf_config->port,
std::move(std::get<0>(qt)),
std::get<1>(qt));
} else {
_udp_handle->send<uvw::IPv6>(_traf_config->next_target_address(), _traf_config->port,
std::move(std::get<0>(qt)),
std::get<1>(qt));
}
_metrics->send(std::get<1>(qt), 1, _in_flight.size());
_in_flight[id].send_time = std::chrono::high_resolution_clock::now();
}
}
void TrafGen::start()
{
if (_traf_config->protocol == Protocol::UDP) {
start_udp();
_sender_timer = _loop->resource<uvw::TimerHandle>();
_sender_timer->on<uvw::TimerEvent>([this](const uvw::TimerEvent &event, uvw::TimerHandle &h) {
if (_traf_config->protocol == Protocol::UDP) {
udp_send();
} else if (_traf_config->protocol == Protocol::TCP || _traf_config->protocol == Protocol::DOT) {
start_tcp_session();
}
});
_sender_timer->start(uvw::TimerHandle::Time{1}, uvw::TimerHandle::Time{_traf_config->s_delay});
} else {
start_tcp_session();
}
_timeout_timer = _loop->resource<uvw::TimerHandle>();
_timeout_timer->on<uvw::TimerEvent>([this](const uvw::TimerEvent &event, uvw::TimerHandle &h) {
handle_timeouts();
});
_timeout_timer->start(uvw::TimerHandle::Time{_traf_config->r_timeout * 1000}, uvw::TimerHandle::Time{1000});
_shutdown_timer = _loop->resource<uvw::TimerHandle>();
_shutdown_timer->on<uvw::TimerEvent>([this](auto &, auto &) {
if (_udp_handle.get()) {
_udp_handle->stop();
}
if (_tcp_handle.get()) {
_tcp_handle->stop();
}
_timeout_timer->stop();
if (_udp_handle.get()) {
_udp_handle->close();
}
if (_tcp_handle.get()) {
_tcp_handle->close();
}
if (_sender_timer.get()) {
_sender_timer->close();
}
_timeout_timer->close();
_shutdown_timer->close();
this->handle_timeouts();
});
}
/**
* GC the in-flight list, handling timeouts.
*
* @param force_reset when true, time out all queries. this happens when e.g. a TCP connection is dropped.
*/
void TrafGen::handle_timeouts(bool force_reset)
{
std::vector<uint16_t> timed_out;
auto now = std::chrono::high_resolution_clock::now();
for (auto i : _in_flight) {
if (force_reset || std::chrono::duration_cast<std::chrono::seconds>(now - i.second.send_time).count() >= _traf_config->r_timeout) {
timed_out.push_back(i.first);
}
}
for (auto i : timed_out) {
_in_flight.erase(i);
_metrics->timeout(_in_flight.size());
_free_id_list.push_back(i);
}
}
void TrafGen::stop()
{
_stopping = true;
if (_sender_timer.get()) {
_sender_timer->stop();
}
long shutdown_length = (_in_flight.size()) ? (_traf_config->r_timeout * 1000) : 1;
_shutdown_timer->start(uvw::TimerHandle::Time{shutdown_length}, uvw::TimerHandle::Time{0});
}