This repository has been archived by the owner on Dec 21, 2023. It is now read-only.
/
impl.hpp
3310 lines (3141 loc) · 114 KB
/
impl.hpp
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef MEASUREMENT_KIT_LIBNDT_IMPL_HPP
#define MEASUREMENT_KIT_LIBNDT_IMPL_HPP
#ifndef LIBNDT_STANDALONE
#include "sys.hpp"
#include "api.hpp"
#endif // !LIBNDT_STANDALONE
// Implementation section
// ``````````````````````
// This is a single header library. In some use cases you may want to split
// the interface and implementation using LIBNDT_NO_INLINE_IMPL.
#ifndef LIBNDT_NO_INLINE_IMPL
#ifdef __linux__
#include <linux/tcp.h>
#define NDT7_ENUM_TCP_INFO \
XX(tcpi_state, TcpiState) \
XX(tcpi_ca_state, TcpiCaState) \
XX(tcpi_retransmits, TcpiRetransmits) \
XX(tcpi_probes, TcpiProbes) \
XX(tcpi_backoff, TcpiBackoff) \
XX(tcpi_options, TcpiOptions) \
XX(tcpi_snd_wscale, TcpiSndWscale) \
XX(tcpi_rcv_wscale, TcpiRcvWscale) \
XX(tcpi_delivery_rate_app_limited, TcpiDeliveryRateAppLimited) \
XX(tcpi_rto, TcpiRto) \
XX(tcpi_ato, TcpiAto) \
XX(tcpi_snd_mss, TcpiSndMss) \
XX(tcpi_rcv_mss, TcpiRcvMss) \
XX(tcpi_unacked, TcpiUnacked) \
XX(tcpi_sacked, TcpiSacked) \
XX(tcpi_lost, TcpiLost) \
XX(tcpi_retrans, TcpiRetrans) \
XX(tcpi_fackets, TcpiFackets) \
XX(tcpi_last_data_sent, TcpiLastDataSent) \
XX(tcpi_last_ack_sent, TcpiLastAckSent) \
XX(tcpi_last_data_recv, TcpiLastDataRecv) \
XX(tcpi_last_ack_recv, TcpiLastAckRecv) \
XX(tcpi_pmtu, TcpiPmtu) \
XX(tcpi_rcv_ssthresh, TcpiRcvSsthresh) \
XX(tcpi_rtt, TcpiRtt) \
XX(tcpi_rttvar, TcpiRttvar) \
XX(tcpi_snd_ssthresh, TcpiSndSsthresh) \
XX(tcpi_snd_cwnd, TcpiSndCwnd) \
XX(tcpi_advmss, TcpiAdvmss) \
XX(tcpi_reordering, TcpiReordering) \
XX(tcpi_rcv_rtt, TcpiRcvRtt) \
XX(tcpi_rcv_space, TcpiRcvSpace) \
XX(tcpi_total_retrans, TcpiTotalRetrans) \
XX(tcpi_pacing_rate, TcpiPacingRate) \
XX(tcpi_max_pacing_rate, TcpiMaxPacingRate) \
XX(tcpi_bytes_acked, TcpiBytesAcked) \
XX(tcpi_bytes_received, TcpiBytesReceived) \
XX(tcpi_segs_out, TcpiSegsOut) \
XX(tcpi_segs_in, TcpiSegsIn) \
XX(tcpi_notsent_bytes, TcpiNotsentBytes) \
XX(tcpi_min_rtt, TcpiMinRtt) \
XX(tcpi_data_segs_in, TcpiDataSegsIn) \
XX(tcpi_data_segs_out, TcpiDataSegsOut) \
XX(tcpi_delivery_rate, TcpiDeliveryRate) \
XX(tcpi_busy_time, TcpiBusyTime) \
XX(tcpi_rwnd_limited, TcpiRwndLimited) \
XX(tcpi_sndbuf_limited, TcpiSndbufLimited) \
XX(tcpi_delivered, TcpiDelivered) \
XX(tcpi_delivered_ce, TcpiDeliveredCe) \
XX(tcpi_bytes_sent, TcpiBytesSent) \
XX(tcpi_bytes_retrans, TcpiBytesRetrans) \
XX(tcpi_dsack_dups, TcpiDsackDups) \
XX(tcpi_reord_seen, TcpiReordSeen)
#endif // __linux__
// WebSocket constants
// ```````````````````
namespace measurement_kit {
namespace libndt {
// Opcodes. See <https://tools.ietf.org/html/rfc6455#section-11.8>.
constexpr uint8_t ws_opcode_continue = 0;
constexpr uint8_t ws_opcode_text = 1;
constexpr uint8_t ws_opcode_binary = 2;
constexpr uint8_t ws_opcode_close = 8;
constexpr uint8_t ws_opcode_ping = 9;
constexpr uint8_t ws_opcode_pong = 10;
// Constants useful to process the first octet of a websocket frame. For more
// info see <https://tools.ietf.org/html/rfc6455#section-5.2>.
constexpr uint8_t ws_fin_flag = 0x80;
constexpr uint8_t ws_reserved_mask = 0x70;
constexpr uint8_t ws_opcode_mask = 0x0f;
// Constants useful to process the second octet of a websocket frame. For more
// info see <https://tools.ietf.org/html/rfc6455#section-5.2>.
constexpr uint8_t ws_mask_flag = 0x80;
constexpr uint8_t ws_len_mask = 0x7f;
// Flags used to specify what HTTP headers are required and present into the
// websocket handshake where we upgrade from HTTP/1.1 to websocket.
constexpr uint64_t ws_f_connection = 1 << 0;
constexpr uint64_t ws_f_sec_ws_accept = 1 << 1;
constexpr uint64_t ws_f_sec_ws_protocol = 1 << 2;
constexpr uint64_t ws_f_upgrade = 1 << 3;
// Values of Sec-WebSocket-Protocol used by ndt-project/ndt.
constexpr const char *ws_proto_control = "ndt";
constexpr const char *ws_proto_c2s = "c2s";
constexpr const char *ws_proto_s2c = "s2c";
constexpr const char *ws_proto_ndt7 = "net.measurementlab.ndt.v7";
// Private constants
// `````````````````
constexpr auto max_loops = 256;
constexpr char msg_kickoff[] = "123456 654321";
constexpr size_t msg_kickoff_size = sizeof(msg_kickoff) - 1;
// SIGPIPE correctness
// ```````````````````
#if !defined _WIN32 && !defined LIBNDT_HAVE_MSG_NOSIGNAL && !defined LIBNDT_HAVE_SO_NOSIGPIPE
#error "No way to avoid SIGPIPE in the current thread when doing socket I/O."
#endif
// Private utils
// `````````````
// Format OpenSSL error as a C++ string.
static std::string ssl_format_error() noexcept {
std::stringstream ss;
for (unsigned short i = 0; i < USHRT_MAX; ++i) {
unsigned long err = ERR_get_error();
if (err == 0) {
break;
}
ss << ((i > 0) ? ": " : "") << ERR_reason_error_string(err);
}
return ss.str();
}
// Map an error code to the corresponding string value.
static std::string libndt_perror(Err err) noexcept {
std::string rv;
//
#define LIBNDT_PERROR(value) \
case Err::value: \
rv = #value; \
break
//
switch (err) {
LIBNDT_PERROR(none);
LIBNDT_PERROR(broken_pipe);
LIBNDT_PERROR(connection_aborted);
LIBNDT_PERROR(connection_refused);
LIBNDT_PERROR(connection_reset);
LIBNDT_PERROR(function_not_supported);
LIBNDT_PERROR(host_unreachable);
LIBNDT_PERROR(interrupted);
LIBNDT_PERROR(invalid_argument);
LIBNDT_PERROR(io_error);
LIBNDT_PERROR(message_size);
LIBNDT_PERROR(network_down);
LIBNDT_PERROR(network_reset);
LIBNDT_PERROR(network_unreachable);
LIBNDT_PERROR(operation_in_progress);
LIBNDT_PERROR(operation_would_block);
LIBNDT_PERROR(timed_out);
LIBNDT_PERROR(value_too_large);
LIBNDT_PERROR(eof);
LIBNDT_PERROR(ai_generic);
LIBNDT_PERROR(ai_again);
LIBNDT_PERROR(ai_fail);
LIBNDT_PERROR(ai_noname);
LIBNDT_PERROR(socks5h);
LIBNDT_PERROR(ssl_generic);
LIBNDT_PERROR(ssl_want_read);
LIBNDT_PERROR(ssl_want_write);
LIBNDT_PERROR(ssl_syscall);
LIBNDT_PERROR(ws_proto);
}
#undef LIBNDT_PERROR // Tidy
//
if (err == Err::ssl_generic) {
rv += ": ";
rv += ssl_format_error();
}
//
return rv;
}
// Generic macro for emitting logs.
#define LIBNDT_EMIT_LOG_EX(client, level, statements) \
do { \
if (client->get_verbosity() >= verbosity_##level) { \
std::stringstream ss_log_lines; \
ss_log_lines << statements; \
std::string log_line; \
while (std::getline(ss_log_lines, log_line, '\n')) { \
if (!log_line.empty()) { \
client->on_##level(std::move(log_line)); \
} \
} \
} \
} while (0)
#define LIBNDT_EMIT_WARNING_EX(clnt, stmnts) LIBNDT_EMIT_LOG_EX(clnt, warning, stmnts)
#define LIBNDT_EMIT_INFO_EX(clnt, stmnts) LIBNDT_EMIT_LOG_EX(clnt, info, stmnts)
#define LIBNDT_EMIT_DEBUG_EX(clnt, stmnts) LIBNDT_EMIT_LOG_EX(clnt, debug, stmnts)
#define LIBNDT_EMIT_WARNING(statements) LIBNDT_EMIT_WARNING_EX(this, statements)
#define LIBNDT_EMIT_INFO(statements) LIBNDT_EMIT_INFO_EX(this, statements)
#define LIBNDT_EMIT_DEBUG(statements) LIBNDT_EMIT_DEBUG_EX(this, statements)
#ifdef _WIN32
#define LIBNDT_OS_SHUT_RDWR SD_BOTH
#else
#define LIBNDT_OS_SHUT_RDWR SHUT_RDWR
#endif
static void random_printable_fill(char *buffer, size_t length) noexcept {
static const std::string ascii =
" !\"#$%&\'()*+,-./" // before numbers
"0123456789" // numbers
":;<=>?@" // after numbers
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" // uppercase
"[\\]^_`" // between upper and lower
"abcdefghijklmnopqrstuvwxyz" // lowercase
"{|}~" // final
;
// TODO(bassosimone): the random device is not actually random in a
// mingw environment. Here we should perhaps take advantage of the
// OpenSSL dependency, when available, and use OpenSSL.
std::random_device rd;
std::mt19937 g(rd());
for (size_t i = 0; i < length; ++i) {
buffer[i] = ascii[g() % ascii.size()];
}
}
static double compute_speed_kbits(double data, double elapsed) noexcept {
return (elapsed > 0.0) ? ((data * 8.0) / 1000.0 / elapsed) : 0.0;
}
// format_speed_from_kbits format the input speed, which must be in kbit/s, to
// a string describing the speed with a measurement unit.
static std::string format_speed_from_kbits(double speed) noexcept {
std::string unit = "kbit/s";
if (speed > 1000) {
unit = "Mbit/s";
speed /= 1000;
if (speed > 1000) {
unit = "Gbit/s";
speed /= 1000;
}
}
std::stringstream ss;
ss << std::setprecision(3) << std::setw(6) << std::right
<< speed << " " << unit;
return ss.str();
}
static std::string format_speed_from_kbits(double data, double elapsed) noexcept {
return format_speed_from_kbits(compute_speed_kbits(data, elapsed));
}
static std::string represent(std::string message) noexcept {
bool printable = true;
for (auto &c : message) {
if (c < ' ' || c > '~') {
printable = false;
break;
}
}
if (printable) {
return message;
}
std::stringstream ss;
ss << "binary([";
for (auto &c : message) {
if (c <= ' ' || c > '~') {
ss << "<0x" << std::fixed << std::setw(2) << std::setfill('0') << std::hex
<< (unsigned)(uint8_t)c << ">";
} else {
ss << (char)c;
}
}
ss << "])";
return ss.str();
}
static std::string trim(std::string s) noexcept {
auto pos = s.find_first_not_of(" \t");
if (pos != std::string::npos) {
s = s.substr(pos);
}
pos = s.find_last_not_of(" \t");
if (pos != std::string::npos) {
s = s.substr(0, pos + 1);
}
return s;
}
static bool jsonify_web100(Client *client, nlohmann::json &json,
std::string message) noexcept {
std::stringstream ss_line{message};
std::string line;
while ((std::getline(ss_line, line, '\n'))) {
std::vector<std::string> keyval;
// Split for ":" and use the first part as key and the rest of the string
// as value.
size_t pos = 0;
std::string token;
pos = line.find(":");
// Fail if there isn't any ":" or the delimiter is at the end of the str.
if (pos == std::string::npos || pos == line.length() - 1) {
LIBNDT_EMIT_WARNING_EX(client, "incorrectly formatted message: " << message);
continue;
}
keyval.push_back(line.substr(0, pos));
keyval.push_back(line.substr(pos + 1));
json[trim(keyval[0])] = trim(keyval[1]);
}
return true;
}
// Private classes
// ```````````````
#ifdef _WIN32
// "There must be a call to WSACleanup for each successful call
// to WSAStartup. Only the final WSACleanup function call performs
// the actual cleanup. The preceding calls simply decrement
// an internal reference count in the WS2_32.DLL."
Client::Winsock::Winsock() noexcept {
WORD requested = MAKEWORD(2, 2);
WSADATA data;
if (::WSAStartup(requested, &data) != 0) {
abort();
}
}
Client::Winsock::~Winsock() noexcept {
if (::WSACleanup() != 0) {
abort();
}
}
#endif // _WIN32
class SocketVector {
public:
SocketVector(Client *c) noexcept;
~SocketVector() noexcept;
Client *owner = nullptr;
std::vector<Socket> sockets;
};
SocketVector::SocketVector(Client *c) noexcept : owner{c} {}
SocketVector::~SocketVector() noexcept {
if (owner != nullptr) {
for (auto &fd : sockets) {
owner->netx_closesocket(fd);
}
}
}
// Client constructor and destructor
// `````````````````````````````````
Client::Client() noexcept {}
Client::Client(Settings settings) noexcept : Client::Client() {
std::swap(settings_, settings);
}
Client::~Client() noexcept {
if (sock_ != -1) {
netx_closesocket(sock_);
}
}
// Top-level API
// `````````````
bool Client::run() noexcept {
std::vector<std::string> fqdns;
if (!query_mlabns(&fqdns)) {
return false;
}
for (auto &fqdn : fqdns) {
LIBNDT_EMIT_DEBUG("trying to connect to " << fqdn);
settings_.hostname = fqdn;
// TODO(bassosimone): we will eventually want to refactor the code to
// make ndt7 the default and ndt5 the optional case.
if ((settings_.protocol_flags & protocol_flag_ndt7) != 0) {
LIBNDT_EMIT_INFO("using the ndt7 protocol");
if ((settings_.nettest_flags & nettest_flag_download) != 0) {
// TODO(bassosimone): for now we do not try with more than one host
// when using ndt7 and there's a failure. We may want to do that.
if (!ndt7_download()) {
LIBNDT_EMIT_WARNING("ndt7: download failed");
// FALLTHROUGH
}
}
if ((settings_.nettest_flags & nettest_flag_upload) != 0) {
// TODO(bassosimone): same as above.
if (!ndt7_upload()) {
LIBNDT_EMIT_WARNING("ndt7: upload failed");
// FALLTHROUGH
}
}
LIBNDT_EMIT_INFO("ndt7: test complete");
// TODO(bassosimone): here we may want to warn if the user selects
// subtests that we actually do not implement.
return true;
}
if (!connect()) {
LIBNDT_EMIT_WARNING("cannot connect to remote host; trying another one");
continue;
}
LIBNDT_EMIT_DEBUG("connected to remote host");
if (!send_login()) {
LIBNDT_EMIT_WARNING("cannot send login; trying another host");
continue;
}
LIBNDT_EMIT_DEBUG("sent login message");
if (!recv_kickoff()) {
LIBNDT_EMIT_WARNING("failed to receive kickoff; trying another host");
continue;
}
if (!wait_in_queue()) {
LIBNDT_EMIT_WARNING("failed to wait in queue; trying another host");
continue;
}
LIBNDT_EMIT_DEBUG("authorized to run test");
// From this point on we fail the test in case of error rather than
// trying with another host. The rationale of trying with another host
// above is that sometimes NDT servers are busy and we would like to
// use another one rather than creating queue at the busy one.
if (!recv_version()) {
return false;
}
LIBNDT_EMIT_DEBUG("received server version");
if (!recv_tests_ids()) {
return false;
}
LIBNDT_EMIT_DEBUG("received tests ids");
if (!run_tests()) {
return false;
}
LIBNDT_EMIT_DEBUG("finished running tests; now reading summary data:");
if (!recv_results_and_logout()) {
return false;
}
LIBNDT_EMIT_DEBUG("received logout message");
if (!wait_close()) {
return false;
}
LIBNDT_EMIT_DEBUG("connection closed");
return true;
}
LIBNDT_EMIT_WARNING("no more hosts to try; failing the test");
return false;
}
void Client::on_warning(const std::string &msg) const {
std::clog << "[!] " << msg << std::endl;
}
void Client::on_info(const std::string &msg) const {
std::clog << msg << std::endl;
}
void Client::on_debug(const std::string &msg) const {
std::clog << "[D] " << msg << std::endl;
}
void Client::on_performance(NettestFlags tid, uint8_t nflows,
double measured_bytes,
double elapsed_time, double max_runtime) {
auto percent = 0.0;
if (max_runtime > 0.0) {
percent = (elapsed_time * 100.0 / max_runtime);
}
LIBNDT_EMIT_INFO(" [" << std::fixed << std::setprecision(0) << std::setw(2)
<< std::right << percent << "%] speed: "
<< format_speed_from_kbits(measured_bytes, elapsed_time));
LIBNDT_EMIT_DEBUG(" [" << std::fixed << std::setprecision(0) << std::setw(2)
<< std::right << percent << "%]"
<< " elapsed: " << std::fixed << std::setprecision(3)
<< std::setw(6) << elapsed_time << " s;"
<< " test_id: " << (int)tid << "; num_flows: " << (int)nflows
<< "; measured_bytes: " << measured_bytes);
}
void Client::on_result(std::string scope, std::string name, std::string value) {
LIBNDT_EMIT_INFO(" - [" << scope << "] " << name << ": " << value);
}
void Client::on_server_busy(std::string msg) {
LIBNDT_EMIT_WARNING("server is busy: " << msg);
}
// High-level API
// ``````````````
bool Client::query_mlabns(std::vector<std::string> *fqdns) noexcept {
assert(fqdns != nullptr);
if (!settings_.hostname.empty()) {
LIBNDT_EMIT_DEBUG("no need to query mlab-ns; we have hostname");
// When we already know the hostname that we want to use just fake out the
// result of a mlabns query as like mlabns returned that hostname.
fqdns->push_back(std::move(settings_.hostname));
return true;
}
std::string mlabns_url = settings_.mlabns_base_url;
if ((settings_.nettest_flags & nettest_flag_download_ext) != 0) {
LIBNDT_EMIT_WARNING("tweaking mlabns settings to allow for multi stream download");
LIBNDT_EMIT_WARNING("we need to use the neubot sliver and to force json since");
LIBNDT_EMIT_WARNING("this is the only configuration supported by neubot's sliver");
settings_.protocol_flags &= ~protocol_flag_tls;
settings_.protocol_flags &= ~protocol_flag_websocket;
settings_.protocol_flags |= protocol_flag_json;
mlabns_url += "/neubot"; // only botticelli implements multi stream dload
} else {
if ((settings_.protocol_flags & protocol_flag_ndt7) != 0) {
mlabns_url += "/ndt7";
} else if ((settings_.protocol_flags & protocol_flag_tls) != 0) {
mlabns_url += "/ndt_ssl";
} else {
mlabns_url += "/ndt";
}
}
if (settings_.mlabns_policy == mlabns_policy_random) {
mlabns_url += "?policy=random";
} else if (settings_.mlabns_policy == mlabns_policy_geo_options) {
mlabns_url += "?policy=geo_options";
}
std::string body;
if (!query_mlabns_curl(mlabns_url, settings_.timeout, &body)) {
return false;
}
LIBNDT_EMIT_DEBUG("mlabns reply: " << body);
nlohmann::json json;
try {
json = nlohmann::json::parse(body);
} catch (const nlohmann::json::exception &exc) {
LIBNDT_EMIT_WARNING("cannot parse JSON: " << exc.what());
return false;
}
// In some cases mlab-ns returns a single object but in other cases (e.g.
// with the `geo_options` policy) it returns an array. Always make an
// array so that we can write uniform code for processing mlab-ns response.
if (json.is_object()) {
auto array = nlohmann::json::array();
array.push_back(json);
std::swap(json, array);
}
for (auto &entry : json) {
std::string fqdn;
try {
fqdn = entry.at("fqdn").get<std::string>();
} catch (const nlohmann::json::exception &exc) {
LIBNDT_EMIT_WARNING("cannot access FQDN field: " << exc.what());
return false;
}
LIBNDT_EMIT_DEBUG("discovered host: " << fqdn);
fqdns->push_back(std::move(fqdn));
}
return true;
}
bool Client::connect() noexcept {
std::string port;
if (!settings_.port.empty()) {
port = settings_.port;
} else if ((settings_.protocol_flags & protocol_flag_tls) != 0) {
port = "3010";
} else {
port = "3001";
}
// We may be called more than once when looping over the list returned by
// geo_options. Therefore, the socket may already be open. In such case we
// want to close it such that we don't leak resources.
if (is_socket_valid(sock_)) {
LIBNDT_EMIT_DEBUG("closing socket openned in previous attempt");
(void)netx_closesocket(sock_);
sock_ = (Socket)-1;
}
return netx_maybews_dial( //
settings_.hostname, port,
ws_f_connection | ws_f_upgrade | ws_f_sec_ws_accept |
ws_f_sec_ws_protocol,
ws_proto_control, "/ndt_protocol", &sock_) == Err::none;
}
bool Client::send_login() noexcept {
return msg_write_login(ndt_version_compat);
}
bool Client::recv_kickoff() noexcept {
if ((settings_.protocol_flags & protocol_flag_websocket) != 0) {
LIBNDT_EMIT_INFO("no kickoff when using websocket");
return true;
}
char buf[msg_kickoff_size];
auto err = netx_recvn(sock_, buf, sizeof(buf));
if (err != Err::none) {
LIBNDT_EMIT_WARNING("recv_kickoff: netx_recvn() failed");
return false;
}
if (memcmp(buf, msg_kickoff, sizeof(buf)) != 0) {
LIBNDT_EMIT_WARNING("recv_kickoff: invalid kickoff message");
return false;
}
LIBNDT_EMIT_DEBUG("received kickoff message");
return true;
}
bool Client::wait_in_queue() noexcept {
std::string message;
if (!msg_expect(msg_srv_queue, &message)) {
return false;
}
// There is consensus among NDT developers that modern NDT should not
// wait in queue rather it should fail immediately.
if (message != "0") {
on_server_busy(std::move(message));
return false;
}
return true;
}
bool Client::recv_version() noexcept {
std::string message;
if (!msg_expect(msg_login, &message)) {
return false;
}
// TODO(bassosimone): validate version number?
LIBNDT_EMIT_DEBUG("server version: " << message);
return true;
}
bool Client::recv_tests_ids() noexcept {
std::string message;
if (!msg_expect(msg_login, &message)) {
return false;
}
std::istringstream ss{message};
std::string cur;
while ((std::getline(ss, cur, ' '))) {
const char *errstr = nullptr;
static_assert(sizeof(NettestFlags) == sizeof(uint8_t),
"Invalid NettestFlags size");
auto tid = (uint8_t)sys->Strtonum(cur.data(), 1, 256, &errstr);
if (errstr != nullptr) {
LIBNDT_EMIT_WARNING("recv_tests_ids: found invalid test-id: "
<< cur.data() << " (error: " << errstr << ")");
return false;
}
granted_suite_.push_back(NettestFlags{tid});
}
return true;
}
bool Client::run_tests() noexcept {
for (auto &tid : granted_suite_) {
if (tid == nettest_flag_upload) {
LIBNDT_EMIT_INFO("running upload test");
if (!run_upload()) {
return false;
}
} else if (tid == nettest_flag_meta) {
LIBNDT_EMIT_DEBUG("running meta test"); // don't annoy the user with this
if (!run_meta()) {
return false;
}
} else if (tid == nettest_flag_download ||
tid == nettest_flag_download_ext) {
LIBNDT_EMIT_INFO("running download test");
if (!run_download()) {
return false;
}
} else {
LIBNDT_EMIT_WARNING("run_tests(): unexpected test id");
return false;
}
}
return true;
}
bool Client::recv_results_and_logout() noexcept {
// Read summary from the server and put it into a JSON object.
nlohmann::json summary;
for (auto i = 0; i < max_loops; ++i) { // don't loop forever
std::string message;
MsgType code = MsgType{0};
if (!msg_read(&code, &message)) {
return false;
}
if (code != msg_results && code != msg_logout) {
LIBNDT_EMIT_WARNING("recv_results_and_logout: unexpected message type");
return false;
}
if (code == msg_logout) {
return true;
}
LIBNDT_EMIT_INFO("[summary] " + message);
}
LIBNDT_EMIT_WARNING("recv_results_and_logout: too many msg_results messages");
return false; // Too many loops
}
bool Client::wait_close() noexcept {
// So, the NDT protocol specification just says: "At the end the Server MUST
// close the whole test session by sending an empty MSG_LOGOUT message and
// closing connection with the Client." The following code gives the server
// one second to close the connection, using netx_wait_readable(). Once that
// function returns, we unconditionally close the socket. This is simpler
// than a previous implementation in that we do not care much about the state
// of the socket after netx_wait_readable() returns. I don't think here
// we've any "dirty shutdown" concerns, because the NDT protocol includes a
// MSG_LOGOUT sent from the server, hence we know we reached the final state.
//
// Note: after reading RFC6455, I realized why the server SHOULD close the
// connection rather than the client: so that the TIME_WAIT state is entered
// by the server, such that there is little server side impact.
constexpr Timeout wait_for_close = 3;
(void)netx_wait_readable(sock_, wait_for_close);
(void)netx_closesocket(sock_);
return true;
}
// Mid-level API
// `````````````
bool Client::run_download() noexcept {
SocketVector dload_socks{this};
std::string port;
uint8_t nflows = 1;
if (!msg_expect_test_prepare(&port, &nflows)) {
return false;
}
for (uint8_t i = 0; i < nflows; ++i) {
Socket sock = (Socket)-1;
// Implementation note: here connection attempts are serialized. This is
// consistent with <https://tools.ietf.org/html/rfc6455#section-4.1>, and
// namely with requirement 2: "If multiple connections to the same IP
// address are attempted simultaneously, the client MUST serialize them".
Err err = netx_maybews_dial( //
settings_.hostname, port,
ws_f_connection | ws_f_upgrade | ws_f_sec_ws_accept
| ws_f_sec_ws_protocol, ws_proto_s2c, "/ndt_protocol",
&sock);
if (err != Err::none) {
break;
}
dload_socks.sockets.push_back(sock);
}
if (dload_socks.sockets.size() != nflows) {
LIBNDT_EMIT_WARNING("run_download: not all connect succeeded");
return false;
}
if (!msg_expect_empty(msg_test_start)) {
return false;
}
LIBNDT_EMIT_DEBUG("run_download: got the test_start message");
double client_side_speed = 0.0;
{
std::atomic<uint8_t> active{0};
auto begin = std::chrono::steady_clock::now();
std::atomic<uint64_t> total_data{0};
auto max_runtime = settings_.max_runtime;
auto ws = (settings_.protocol_flags & protocol_flag_websocket) != 0;
const Client *const_this = this;
for (Socket fd : dload_socks.sockets) {
// TODO(bassosimone): increment active inside the thread main function
// as this is more consistent with the fact that thread decrements it
active += 1; // atomic
auto main = [
&active, // reference to atomic
begin, // copy for safety
fd, // copy for safety
max_runtime, // copy for safety
const_this, // const pointer
&total_data, // reference to atomic
ws // copy for safety
]() noexcept {
constexpr size_t ndt_bufsize = 131072;
std::unique_ptr<char[]> buf(new char[ndt_bufsize]);
for (;;) {
auto err = Err::none;
Size n = 0;
if (ws) {
uint8_t op = 0;
err = const_this->ws_recvmsg(
fd, &op, (uint8_t *)buf.get(), ndt_bufsize, &n);
if (err == Err::none && op != ws_opcode_binary) {
LIBNDT_EMIT_WARNING_EX(const_this,
"run_download: unexpected opcode: " << (unsigned int)op);
break;
}
} else {
err = const_this->netx_recv(fd, buf.get(), ndt_bufsize, &n);
}
if (err != Err::none) {
if (err != Err::eof) {
LIBNDT_EMIT_WARNING_EX(const_this,
"run_download: receiving: " << libndt_perror(err));
}
break;
}
total_data += (uint64_t)n; // atomic
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - begin;
if (elapsed.count() > max_runtime) {
break;
}
}
active -= 1; // atomic
};
std::thread thread{std::move(main)};
thread.detach();
}
auto prev = begin;
for (;;) {
constexpr int timeout_msec = 250;
std::this_thread::sleep_for(std::chrono::milliseconds(timeout_msec));
if (active <= 0) {
break;
}
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - begin;
on_performance(nettest_flag_download, //
active, // atomic
static_cast<double>(total_data), // atomic
elapsed.count(), //
settings_.max_runtime);
prev = now;
}
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - begin;
client_side_speed = compute_speed_kbits( //
static_cast<double>(total_data), elapsed.count());
}
{
// TODO(bassosimone): emit this information.
MsgType code = MsgType{0};
std::string message;
if (!msg_read_legacy(&code, &message)) { // legacy on purpose!
return false;
}
if (code != msg_test_msg) {
LIBNDT_EMIT_WARNING("run_download: unexpected message type");
return false;
}
LIBNDT_EMIT_DEBUG("run_download: server computed speed: " << message);
}
if (!msg_write(msg_test_msg, std::to_string(client_side_speed))) {
return false;
}
LIBNDT_EMIT_DEBUG("reading summary web100 variables");
nlohmann::json web100;
for (auto i = 0; i < max_loops; ++i) { // don't loop forever
std::string message;
MsgType code = MsgType{0};
if (!msg_read(&code, &message)) {
return false;
}
if (code != msg_test_msg && code != msg_test_finalize) {
LIBNDT_EMIT_WARNING("run_download: unexpected message type");
return false;
}
if (code == msg_test_finalize) {
if (this->get_verbosity() == verbosity_debug) {
this->on_result("web100", "web100", web100.dump());
}
return true;
}
if (!jsonify_web100(this, web100, std::move(message))) {
// NOTHING: warning already printed by emit_result() and failing the whole
// test - rather than warning - because of an incorrect data format is
// probably being too strict in this context. So just keep going.
}
}
LIBNDT_EMIT_WARNING("run_download: too many msg_test_msg messages");
return false; // Too many loops
}
bool Client::run_meta() noexcept {
if (!msg_expect_empty(msg_test_prepare)) {
return false;
}
if (!msg_expect_empty(msg_test_start)) {
return false;
}
for (auto &kv : settings_.metadata) {
std::stringstream ss;
ss << kv.first << ":" << kv.second;
if (!msg_write(msg_test_msg, ss.str())) {
return false;
}
}
if (!msg_write(msg_test_msg, "")) {
return false;
}
if (!msg_expect_empty(msg_test_finalize)) {
return false;
}
return true;
}
bool Client::run_upload() noexcept {
SocketVector upload_socks{this};
std::string port;
uint8_t nflows = 1;
if (!msg_expect_test_prepare(&port, &nflows)) {
return false;
}
// TODO(bassosimone): implement C2S_EXT
if (nflows != 1) {
LIBNDT_EMIT_WARNING("run_upload: unexpected number of flows");
return false;
}
{
Socket sock = (Socket)-1;
// Remark: in case we'll ever implement multi-stream here, remember that
// WebSocket requires connections to be serialized. See above.
Err err = netx_maybews_dial( //
settings_.hostname, port,
ws_f_connection | ws_f_upgrade | ws_f_sec_ws_accept
| ws_f_sec_ws_protocol, ws_proto_c2s, "/ndt_protocol",
&sock);
if (err != Err::none) {
return false;
}
upload_socks.sockets.push_back(sock);
}
if (!msg_expect_empty(msg_test_start)) {
return false;
}
double client_side_speed = 0.0;
{
std::atomic<uint8_t> active{0};
auto begin = std::chrono::steady_clock::now();
std::atomic<uint64_t> total_data{0};
auto max_runtime = settings_.max_runtime;
auto ws = (settings_.protocol_flags & protocol_flag_websocket) != 0;
const Client *const_this = this;
for (Socket fd : upload_socks.sockets) {
// TODO(bassosimone): increment active inside the thread main function
// as this is more consistent with the fact that thread decrements it
active += 1; // atomic
auto main = [
&active, // reference to atomic
begin, // copy for safety
fd, // copy for safety
max_runtime, // copy for safety
const_this, // const pointer
&total_data, // reference to atomic
ws // copy for safety
]() noexcept {
constexpr size_t ndt_bufsize = 131072;
std::unique_ptr<char[]> buf(new char[ndt_bufsize]);
{
auto start = std::chrono::steady_clock::now();
random_printable_fill(buf.get(), ndt_bufsize);
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - start;
LIBNDT_EMIT_DEBUG_EX(const_this,
"run_upload: time to fill random buffer: " << elapsed.count());
}
std::string frame = const_this->ws_prepare_frame(
ws_opcode_binary | ws_fin_flag, (uint8_t *)buf.get(), ndt_bufsize);
for (;;) {
Size n = 0;
auto err = Err::none;