-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
786 lines (687 loc) · 32.4 KB
/
Copy pathmain.cpp
File metadata and controls
786 lines (687 loc) · 32.4 KB
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
#include <iostream>
#include <map>
#include <iomanip>
#include <climits>
#include <chrono>
#include <ctime>
#include <cstdio>
#include <mutex>
#include <string>
#include <unistd.h>
#include <vector>
#include "SpeedTest.h"
#include "TestConfigTemplate.h"
#include "CmdOptions.h"
#include "ServerSelector.h"
#include "RunHistory.h"
#include "Internetometer.h"
#include <csignal>
#include <cstring>
// Terminal styling, degrading to plain text when piped or under NO_COLOR.
struct Style {
const char *reset, *bold, *dim, *cyan, *green, *green_bold, *cyan_bold;
Style() {
bool plain = ::isatty(STDOUT_FILENO) != 1 || ::getenv("NO_COLOR") != nullptr;
reset = plain ? "" : "\x1b[0m";
bold = plain ? "" : "\x1b[1m";
dim = plain ? "" : "\x1b[2m";
cyan = plain ? "" : "\x1b[36m";
green = plain ? "" : "\x1b[32m";
green_bold = plain ? "" : "\x1b[1;32m";
cyan_bold = plain ? "" : "\x1b[1;36m";
}
};
static const Style UI;
void banner(){
std::cout << UI.bold << UI.cyan << "SpeedTest++" << UI.reset
<< UI.dim << " v" << SpeedTest_VERSION_MAJOR << "." << SpeedTest_VERSION_MINOR << UI.reset
<< std::endl << std::endl;
}
// One aligned line of the result card: dim label, optionally accented value.
void row(const std::string& label, const std::string& value, const char* accent = nullptr){
char pad[16];
snprintf(pad, sizeof(pad), "%-9s", label.c_str());
std::cout << " " << UI.dim << pad << UI.reset << ' '
<< (accent ? accent : "") << value << (accent ? UI.reset : "") << std::endl;
}
std::string fmtMbit(double mbps){
if (mbps < 0)
return "-";
char buff[32];
snprintf(buff, sizeof(buff), "%.2f Mbit/s", mbps);
return std::string(buff);
}
std::string fmtKm(double km){
char buff[32];
snprintf(buff, sizeof(buff), "%.1f km", km);
return std::string(buff);
}
void usage(const char* name){
std::cerr << "Usage: " << name << " ";
std::cerr << " [--latency] [--quality] [--download] [--upload] [--share] [--help]\n"
" [--no-select] [--list[=N]] [--city NAME] [--last] [--history[=N]] [--yandex]\n"
" [--test-server host:port] [--output verbose|text|json]\n";
std::cerr << "optional arguments:" << std::endl;
std::cerr << " --help Show this message and exit\n";
std::cerr << " --latency Perform latency test only\n";
std::cerr << " --quality Perform quality test only. It includes latency test\n";
std::cerr << " --download Perform download test only. It includes latency test\n";
std::cerr << " --upload Perform upload test only. It includes latency test\n";
std::cerr << " --share Generate and provide a URL to the speedtest.net share results image\n";
std::cerr << " --insecure Skip SSL certificate verify (Useful for Embedded devices)\n";
std::cerr << " --select Pick the server interactively. Default when run in a terminal\n";
std::cerr << " --no-select Skip the picker and take the lowest-ping server automatically\n";
std::cerr << " --list[=N] List the N nearest servers with their ping and exit. Default: 25\n";
std::cerr << " --last Show the most recent saved result and exit. No test is run\n";
std::cerr << " --history[=N] Show the last N saved results and exit. Default: 10\n";
std::cerr << " --yandex Test against Yandex Internetometer instead of speedtest.net\n";
std::cerr << " --city NAME Only consider servers whose city/sponsor/host matches NAME\n";
std::cerr << " --test-server host:port Run speed test against a specific server\n";
std::cerr << " --quality-server host:port Run line quality test against a specific server\n";
std::cerr << " --output verbose|text|json Set output type. Default: verbose\n";
}
// Reports the server the test is about to run against.
void printServer(const ProgramOptions& options, const ServerInfo& server, long latency){
if (options.output_type == OutputType::verbose){
row("Server", server.name + " \xC2\xB7 " + server.sponsor + " \xC2\xB7 " + fmtKm(server.distance), UI.bold);
row("Host", server.host, UI.dim);
} else if (options.output_type == OutputType::text) {
std::cout << "TEST_SERVER_HOST=" << server.host << std::endl;
std::cout << "TEST_SERVER_CITY=" << server.name << std::endl;
std::cout << "TEST_SERVER_DISTANCE=" << server.distance << std::endl;
} else if (options.output_type == OutputType::json) {
std::cout << "\"server\":{";
std::cout << "\"name\":\"" << server.name << "\",";
std::cout << "\"sponsor\":\"" << server.sponsor << "\",";
std::cout << "\"distance\":\"" << server.distance << "\",";
std::cout << "\"latency\":\"" << latency << "\",";
std::cout << "\"host\":\"" << server.host << "\"";
std::cout << "},";
}
}
// Formats a probe result without touching the stream's own formatting state.
std::string latencyField(const ProbeResult& probe, const char* unreachable){
if (probe.state != ProbeResult::Ok)
return unreachable;
char buff[32];
snprintf(buff, sizeof(buff), "%.1f", probe.latency_ms);
return std::string(buff);
}
// npm-style progress line: a spinner of moving dots plus the live aggregate
// speed, redrawn in place. Falls back to the classic dot-per-chunk stream when
// stdout is not a terminal, and stays silent for text/json output.
class SpeedMeter {
public:
SpeedMeter(const std::string& label, OutputType output):
mLabel(label),
mSilent(output != OutputType::verbose),
mAnimate(!mSilent && ::isatty(STDOUT_FILENO) == 1),
mErrors(0),
mFrame(0),
mLast(std::chrono::steady_clock::now()) {
if (!mSilent && !mAnimate)
std::cout << mLabel << " " << std::flush;
}
// Called concurrently by every worker thread.
void tick(bool success, double mbps){
std::lock_guard<std::mutex> lock(mMutex);
if (!success)
mErrors++;
if (mSilent)
return;
auto now = std::chrono::steady_clock::now();
auto since_last = std::chrono::duration_cast<std::chrono::milliseconds>(now - mLast).count();
if (!mAnimate){
// Errors always show; successful ticks are rate-limited so callers
// reporting per-chunk (e.g. every 16KB) don't flood the line.
if (!success || since_last >= 200){
mLast = now;
std::cout << (success ? '.' : '*') << std::flush;
}
return;
}
if (since_last < 100)
return;
mLast = now;
static const char* frames[] = {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"};
mFrame = (mFrame + 1) % 10;
char speed[32];
snprintf(speed, sizeof(speed), "%7.2f Mbit/s", mbps);
std::cout << "\r\x1b[K" << frames[mFrame] << ' ' << mLabel << ' ' << speed;
if (mErrors)
std::cout << " (" << mErrors << " errors)";
std::cout << std::flush;
}
// Clears the progress line (or finishes the dot stream) before the result.
void done(){
if (mSilent)
return;
if (mAnimate)
std::cout << "\r\x1b[K" << std::flush;
else
std::cout << std::endl;
}
private:
std::string mLabel;
bool mSilent;
bool mAnimate;
int mErrors;
int mFrame;
std::chrono::steady_clock::time_point mLast;
std::mutex mMutex;
};
// Handles --list: prints the nearest servers with a measured ping, then exits.
int listServers(const ProgramOptions& options, const std::vector<ServerInfo>& serverList, const IPInfo& client){
auto candidates = filterServers(serverList, options.city);
if (candidates.empty()){
std::cerr << "No server matches \"" << options.city << "\"" << std::endl;
if (options.output_type == OutputType::json)
std::cout << "\"error\":\"no server matches the given city\"}" << std::endl;
return EXIT_FAILURE;
}
if (candidates.size() > options.list_count)
candidates.resize(options.list_count);
auto probes = probeServers(candidates, SPEED_TEST_MIN_SERVER_VERSION_STR);
if (options.output_type == OutputType::verbose) {
printServerTable(candidates, probes, client);
} else if (options.output_type == OutputType::text) {
for (size_t i = 0; i < candidates.size(); i++) {
std::cout << "SERVER=" << candidates[i].host
<< "|" << candidates[i].name
<< "|" << candidates[i].sponsor
<< "|" << candidates[i].distance << "km"
<< "|" << latencyField(probes[i], "unreachable")
<< std::endl;
}
} else if (options.output_type == OutputType::json) {
std::cout << "\"servers\":[";
for (size_t i = 0; i < candidates.size(); i++) {
std::cout << (i ? "," : "") << "{"
<< "\"host\":\"" << candidates[i].host << "\","
<< "\"name\":\"" << candidates[i].name << "\","
<< "\"sponsor\":\"" << candidates[i].sponsor << "\","
<< "\"distance\":\"" << candidates[i].distance << "\","
<< "\"latency\":\"" << latencyField(probes[i], "-1") << "\"}";
}
std::cout << "],";
std::cout << "\"_\":\"server list requested\"}" << std::endl;
}
return EXIT_SUCCESS;
}
// --last: replay the most recent saved result without touching the network.
int showLast(const ProgramOptions& options){
auto records = readHistory(1);
if (records.empty()){
std::cerr << "No saved results yet. Run a test first." << std::endl;
if (options.output_type == OutputType::json)
std::cout << "{\"error\":\"no saved results\"}" << std::endl;
return EXIT_FAILURE;
}
const RunRecord& r = records.back();
if (options.output_type == OutputType::json){
std::cout << historyJsonLine(r) << std::endl;
return EXIT_SUCCESS;
}
if (options.output_type == OutputType::text){
std::cout << "WHEN=" << formatTimestamp(r.ts) << std::endl;
std::cout << "IP=" << r.ip << std::endl;
std::cout << "PROVIDER=" << r.isp << std::endl;
std::cout << "TEST_SERVER_HOST=" << r.server_host << std::endl;
std::cout << "TEST_SERVER_CITY=" << r.server_name << std::endl;
std::cout << "LATENCY=" << r.ping << std::endl;
std::cout << "JITTER=" << r.jitter << std::endl;
std::cout << "DOWNLOAD_SPEED=" << fmtMbit(r.download) << std::endl;
std::cout << "UPLOAD_SPEED=" << fmtMbit(r.upload) << std::endl;
return EXIT_SUCCESS;
}
row("Last", formatTimestamp(r.ts) + " \xC2\xB7 " + formatAgo(r.ts));
std::string who = r.ip + " \xC2\xB7 " + r.isp;
if (!r.city.empty())
who += " \xC2\xB7 " + r.city;
row("IP", who);
std::string server_line = r.server_name + " \xC2\xB7 " + r.server_sponsor;
if (r.distance >= 0)
server_line += " \xC2\xB7 " + fmtKm(r.distance);
row("Server", server_line, UI.bold);
row("Host", r.server_host, UI.dim);
row("Ping", std::to_string(r.ping) + " ms");
row("Jitter", std::to_string(r.jitter) + " ms");
row("Download", fmtMbit(r.download), UI.green_bold);
row("Upload", fmtMbit(r.upload), UI.cyan_bold);
return EXIT_SUCCESS;
}
// Byte-safe truncation that never cuts a UTF-8 sequence in half.
std::string clip(const std::string& in, size_t max_bytes){
if (in.size() <= max_bytes)
return in;
size_t cut = max_bytes;
while (cut > 0 && (static_cast<unsigned char>(in[cut]) & 0xC0) == 0x80)
cut--;
return in.substr(0, cut);
}
// --history: table of the last N saved results, oldest first.
int showHistory(const ProgramOptions& options){
auto records = readHistory(options.history_count);
if (records.empty()){
std::cerr << "No saved results yet. Run a test first." << std::endl;
if (options.output_type == OutputType::json)
std::cout << "{\"error\":\"no saved results\"}" << std::endl;
return EXIT_FAILURE;
}
if (options.output_type == OutputType::json){
std::cout << "[";
for (size_t i = 0; i < records.size(); i++)
std::cout << (i ? "," : "") << historyJsonLine(records[i]);
std::cout << "]" << std::endl;
return EXIT_SUCCESS;
}
if (options.output_type == OutputType::text){
for (auto &r : records)
std::cout << "RESULT=" << formatTimestamp(r.ts)
<< "|" << r.server_name
<< "|" << r.ping << "ms"
<< "|" << fmtMbit(r.download)
<< "|" << fmtMbit(r.upload) << std::endl;
return EXIT_SUCCESS;
}
char header[128];
snprintf(header, sizeof(header), " %-16s %-24s %6s %13s %13s", "WHEN", "SERVER", "PING", "DOWN", "UP");
std::cout << UI.bold << header << UI.reset << std::endl;
for (auto &r : records){
char line[192];
snprintf(line, sizeof(line), " %-16s %-24s %4ld ms %13s %13s",
formatTimestamp(r.ts).c_str(),
clip(r.server_name, 24).c_str(),
r.ping,
fmtMbit(r.download).c_str(),
fmtMbit(r.upload).c_str());
std::cout << line << std::endl;
}
return EXIT_SUCCESS;
}
int main(const int argc, const char **argv) {
ProgramOptions programOptions;
if (!ParseOptions(argc, argv, programOptions)){
usage(argv[0]);
return EXIT_FAILURE;
}
if (programOptions.output_type == OutputType::verbose)
banner();
if (programOptions.help) {
usage(argv[0]);
return EXIT_SUCCESS;
}
if (programOptions.last)
return showLast(programOptions);
if (programOptions.history)
return showHistory(programOptions);
signal(SIGPIPE, SIG_IGN);
auto sp = SpeedTest(SPEED_TEST_MIN_SERVER_VERSION_STR);
IPInfo info;
ServerInfo serverInfo;
ServerInfo serverQualityInfo;
if (programOptions.insecure) {
sp.setInsecure(programOptions.insecure);
}
if (programOptions.output_type == OutputType::json)
std::cout << "{";
if (!sp.ipInfo(info)){
std::cerr << "Unable to retrieve your IP info. Try again later" << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"unable to retrieve your ip info\"}" << std::endl;
return EXIT_FAILURE;
}
RunRecord record;
record.ip = info.ip_address;
record.isp = info.isp;
record.city = info.city;
if (programOptions.output_type == OutputType::verbose){
std::string who = info.ip_address + " \xC2\xB7 " + info.isp;
if (!info.city.empty())
who += " \xC2\xB7 " + info.city;
row("IP", who);
if (info.country_code == "RU" && !programOptions.yandex)
row("Hint", "\xD0\xB4\xD0\xBB\xD1\x8F \xD0\xA0\xD0\xA4 \xD0\xB5\xD1\x81\xD1\x82\xD1\x8C \xD0\xAF\xD0\xBD\xD0\xB4\xD0\xB5\xD0\xBA\xD1\x81 \xD0\x98\xD0\xBD\xD1\x82\xD0\xB5\xD1\x80\xD0\xBD\xD0\xB5\xD1\x82\xD0\xBE\xD0\xBC\xD0\xB5\xD1\x82\xD1\x80: SpeedTest --yandex", UI.dim);
} else if (programOptions.output_type == OutputType::text) {
std::cout << "IP=" << info.ip_address << std::endl;
std::cout << "IP_LAT=" << info.lat << std::endl;
std::cout << "IP_LON=" << info.lon << std::endl;
std::cout << "PROVIDER=" << info.isp << std::endl;
} else if (programOptions.output_type == OutputType::json) {
std::cout << "\"client\":{";
std::cout << "\"ip\":\"" << info.ip_address << "\",";
std::cout << "\"lat\":\"" << info.lat << "\",";
std::cout << "\"lon\":\"" << info.lon << "\",";
std::cout << "\"isp\":\"" << info.isp << "\"";
std::cout << "},";
}
if (programOptions.yandex){
YandexProbes probes;
if (!yandexGetProbes(probes, programOptions.insecure)){
std::cerr << "Unable to reach Yandex Internetometer. Try again later" << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"unable to reach yandex internetometer\"}" << std::endl;
return EXIT_FAILURE;
}
record.server_name = "Yandex Internetometer";
record.server_sponsor = "Yandex";
record.server_host = "yandex.ru/internet";
if (programOptions.output_type == OutputType::verbose){
row("Server", "Yandex Internetometer", UI.bold);
row("Host", record.server_host, UI.dim);
} else if (programOptions.output_type == OutputType::text) {
std::cout << "TEST_SERVER_HOST=" << record.server_host << std::endl;
} else if (programOptions.output_type == OutputType::json) {
std::cout << "\"server\":{\"host\":\"" << record.server_host << "\"},";
}
long ping = -1, jitterMs = -1;
if (yandexLatency(probes, ping, jitterMs, programOptions.insecure)){
record.ping = ping;
record.jitter = jitterMs;
if (programOptions.output_type == OutputType::verbose){
row("Ping", std::to_string(ping) + " ms " + UI.dim + "(HTTP)" + UI.reset);
row("Jitter", std::to_string(jitterMs) + " ms");
} else if (programOptions.output_type == OutputType::text) {
std::cout << "LATENCY=" << ping << std::endl;
std::cout << "JITTER=" << jitterMs << std::endl;
} else if (programOptions.output_type == OutputType::json) {
std::cout << "\"ping\":\"" << ping << "\",";
std::cout << "\"jitter\":\"" << jitterMs << "\",";
}
}
if (programOptions.latency) {
if (programOptions.output_type == OutputType::json)
std::cout << "\"_\":\"only latency requested\"}" << std::endl;
return record.ping >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
if (!programOptions.upload){
SpeedMeter downMeter("Testing download speed (" + std::to_string(4) + ")", programOptions.output_type);
double down = -1;
bool ok = yandexDownload(probes, down, programOptions.insecure,
[&downMeter](bool success, double mbps){ downMeter.tick(success, mbps); });
downMeter.done();
if (!ok){
std::cerr << "Download test failed." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"download test failed\"}" << std::endl;
return EXIT_FAILURE;
}
record.download = down;
if (programOptions.output_type == OutputType::verbose)
row("Download", fmtMbit(down), UI.green_bold);
else if (programOptions.output_type == OutputType::text)
std::cout << "DOWNLOAD_SPEED=" << fmtMbit(down) << std::endl;
else if (programOptions.output_type == OutputType::json)
std::cout << "\"download\":\"" << std::fixed << (down * 1000 * 1000) << "\",";
}
if (!programOptions.download){
SpeedMeter upMeter("Testing upload speed (" + std::to_string(4) + ")", programOptions.output_type);
double up = -1;
bool ok = yandexUpload(probes, up, programOptions.insecure,
[&upMeter](bool success, double mbps){ upMeter.tick(success, mbps); });
upMeter.done();
if (!ok){
std::cerr << "Upload test failed." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"upload test failed\"}" << std::endl;
return EXIT_FAILURE;
}
record.upload = up;
if (programOptions.output_type == OutputType::verbose)
row("Upload", fmtMbit(up), UI.cyan_bold);
else if (programOptions.output_type == OutputType::text)
std::cout << "UPLOAD_SPEED=" << fmtMbit(up) << std::endl;
else if (programOptions.output_type == OutputType::json)
std::cout << "\"upload\":\"" << std::fixed << (up * 1000 * 1000) << "\",";
}
record.ts = ::time(nullptr);
if (appendHistory(record) && programOptions.output_type == OutputType::verbose)
row("Saved", "view again with SpeedTest --last", UI.dim);
if (programOptions.output_type == OutputType::json)
std::cout << "\"_\":\"all ok\"}" << std::endl;
return EXIT_SUCCESS;
}
auto serverList = sp.serverList();
if (serverList.empty() && programOptions.selected_server.empty()){
std::cerr << "Unable to download server list. Try again later" << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"unable to download server list\"}" << std::endl;
return EXIT_FAILURE;
}
if (programOptions.list)
return listServers(programOptions, serverList, info);
if (programOptions.select && programOptions.no_select){
std::cerr << "--select and --no-select contradict each other" << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"--select and --no-select contradict each other\"}" << std::endl;
return EXIT_FAILURE;
}
// The picker is the default, but it needs someone to drive it: without a
// terminal (a pipe, cron, a script) fall back to picking by ping instead.
bool pickInteractively = !programOptions.no_select && programOptions.selected_server.empty();
if (pickInteractively && !stdinIsInteractive()){
if (programOptions.select){
std::cerr << "--select needs a terminal. Use --list to see the servers "
<< "and --test-server host:port to pick one." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"--select requires a terminal\"}" << std::endl;
return EXIT_FAILURE;
}
pickInteractively = false;
}
if (!programOptions.selected_server.empty()){
serverInfo.host.append(programOptions.selected_server);
for (auto &s : serverList) {
if (s.host == serverInfo.host) {
serverInfo = s;
break;
}
}
if (!sp.setServer(serverInfo)){
std::cerr << "Unable to reach " << serverInfo.host << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"unable to reach the selected server\"}" << std::endl;
return EXIT_FAILURE;
}
if (programOptions.output_type == OutputType::verbose)
row("Server", serverInfo.host, UI.bold);
else if (programOptions.output_type == OutputType::text) {
std::cout << "TEST_SERVER_HOST=" << serverInfo.host << std::endl;
}
else if (programOptions.output_type == OutputType::json) {
std::cout << "\"server\":{";
std::cout << "\"host\":\"" << serverInfo.host << "\"";
std::cout << "},";
}
} else if (pickInteractively){
if (!selectServerInteractive(serverList, info, programOptions.city,
SPEED_TEST_MIN_SERVER_VERSION_STR, serverInfo)){
std::cerr << "No server selected." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"no server selected\"}" << std::endl;
return EXIT_FAILURE;
}
if (!sp.setServer(serverInfo)){
std::cerr << "Unable to reach " << serverInfo.host << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"unable to reach the selected server\"}" << std::endl;
return EXIT_FAILURE;
}
printServer(programOptions, serverInfo, sp.latency());
} else {
auto candidates = filterServers(serverList, programOptions.city);
if (candidates.empty()){
std::cerr << "No server matches \"" << programOptions.city << "\". "
<< "Try --list to see what is available." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"no server matches the given city\"}" << std::endl;
return EXIT_FAILURE;
}
if (programOptions.output_type == OutputType::verbose){
std::cout << " " << UI.dim << "Finding fastest of " << candidates.size();
if (programOptions.city.empty())
std::cout << " nearby servers ";
else
std::cout << " servers matching \"" << programOptions.city << "\" ";
std::cout << std::flush;
} else if (programOptions.output_type == OutputType::json) {
std::cout << "\"servers_online\":\"" << serverList.size() << "\",";
}
// Without a city filter, only the nearest handful is worth probing.
int sample_size = programOptions.city.empty() ? 10 : static_cast<int>(candidates.size());
serverInfo = sp.bestServerWithin(candidates, sample_size, [&programOptions](bool success) {
if (programOptions.output_type == OutputType::verbose)
std::cout << (success ? '.' : '*') << std::flush;
});
if (programOptions.output_type == OutputType::verbose)
std::cout << UI.reset << std::endl;
if (serverInfo.host.empty() || sp.latency() >= INT_MAX){
std::cerr << "None of the candidate servers answered." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"no candidate server answered\"}" << std::endl;
return EXIT_FAILURE;
}
printServer(programOptions, serverInfo, sp.latency());
}
record.server_name = serverInfo.name;
record.server_sponsor = serverInfo.sponsor;
record.server_host = serverInfo.host;
record.distance = serverInfo.distance;
record.ping = sp.latency();
if (programOptions.output_type == OutputType::verbose)
row("Ping", std::to_string(sp.latency()) + " ms");
else if (programOptions.output_type == OutputType::text)
std::cout << "LATENCY=" << sp.latency() << std::endl;
else if (programOptions.output_type == OutputType::json) {
std::cout << "\"ping\":\"";
std::cout << std::fixed;
std::cout << sp.latency() << "\",";
}
long jitter = 0;
if (sp.jitter(serverInfo, jitter)){
record.jitter = jitter;
if (programOptions.output_type == OutputType::verbose)
row("Jitter", std::to_string(jitter) + " ms");
else if (programOptions.output_type == OutputType::text)
std::cout << "JITTER=" << jitter << std::endl;
else if (programOptions.output_type == OutputType::json) {
std::cout << "\"jitter\":\"";
std::cout << std::fixed;
std::cout << jitter << "\",";
}
} else {
std::cerr << "Jitter measurement is unavailable at this time." << std::endl;
}
if (programOptions.latency) {
if (programOptions.output_type == OutputType::json)
std::cout << "\"_\":\"only latency requested\"}" << std::endl;
return EXIT_SUCCESS;
}
SpeedMeter preMeter("Determine line type (" + std::to_string(preflightConfigDownload.concurrency) + ")",
programOptions.output_type);
double preSpeed = 0;
bool preOk = sp.downloadSpeed(serverInfo, preflightConfigDownload, preSpeed,
[&preMeter](bool success, double mbps){
preMeter.tick(success, mbps);
});
preMeter.done();
if (!preOk){
std::cerr << "Pre-flight check failed." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"pre-flight check failed\"}" << std::endl;
return EXIT_FAILURE;
}
TestConfig uploadConfig;
TestConfig downloadConfig;
testConfigSelector(preSpeed, uploadConfig, downloadConfig);
if (programOptions.output_type == OutputType::verbose){
std::string profile = downloadConfig.label;
size_t pos = profile.find("profile selected ");
if (pos != std::string::npos)
profile = profile.substr(pos + strlen("profile selected "));
row("Line", profile);
}
if (!programOptions.upload){
SpeedMeter downMeter("Testing download speed (" + std::to_string(downloadConfig.concurrency) + ")",
programOptions.output_type);
double downloadSpeed = 0;
bool downOk = sp.downloadSpeed(serverInfo, downloadConfig, downloadSpeed,
[&downMeter](bool success, double mbps){
downMeter.tick(success, mbps);
});
downMeter.done();
if (downOk){
record.download = downloadSpeed;
if (programOptions.output_type == OutputType::verbose){
row("Download", fmtMbit(downloadSpeed), UI.green_bold);
} else if (programOptions.output_type == OutputType::text) {
std::cout << "DOWNLOAD_SPEED=";
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << downloadSpeed << std::endl;
} else if (programOptions.output_type == OutputType::json) {
std::cout << "\"download\":\"";
std::cout << std::fixed;
std::cout << (downloadSpeed*1000*1000) << "\",";
}
} else {
std::cerr << "Download test failed." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"download test failed\"}" << std::endl;
return EXIT_FAILURE;
}
}
if (programOptions.download) {
record.ts = ::time(nullptr);
appendHistory(record);
if (programOptions.output_type == OutputType::json)
std::cout << "\"_\":\"only download requested\"}" << std::endl;
return EXIT_SUCCESS;
}
SpeedMeter upMeter("Testing upload speed (" + std::to_string(uploadConfig.concurrency) + ")",
programOptions.output_type);
double uploadSpeed = 0;
bool upOk = sp.uploadSpeed(serverInfo, uploadConfig, uploadSpeed,
[&upMeter](bool success, double mbps){
upMeter.tick(success, mbps);
});
upMeter.done();
if (upOk){
record.upload = uploadSpeed;
if (programOptions.output_type == OutputType::verbose){
row("Upload", fmtMbit(uploadSpeed), UI.cyan_bold);
} else if (programOptions.output_type == OutputType::text) {
std::cout << "UPLOAD_SPEED=";
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << uploadSpeed << std::endl;
} else if (programOptions.output_type == OutputType::json) {
std::cout << "\"upload\":\"";
std::cout << std::fixed;
std::cout << (uploadSpeed*1000*1000) << "\",";
}
} else {
std::cerr << "Upload test failed." << std::endl;
if (programOptions.output_type == OutputType::json)
std::cout << "\"error\":\"upload test failed\"}" << std::endl;
return EXIT_FAILURE;
}
if (programOptions.share){
std::string share_it;
if (sp.share(serverInfo, share_it)) {
if (programOptions.output_type == OutputType::verbose) {
row("Share", share_it);
} else if (programOptions.output_type == OutputType::text) {
std::cout << "IMAGE_URL=" << share_it << std::endl;
} else if (programOptions.output_type == OutputType::json) {
std::cout << "\"share\":\"" << share_it << "\",";
}
}
}
record.ts = ::time(nullptr);
if (appendHistory(record) && programOptions.output_type == OutputType::verbose)
row("Saved", "view again with SpeedTest --last", UI.dim);
if (programOptions.output_type == OutputType::json)
std::cout << "\"_\":\"all ok\"}" << std::endl;
return EXIT_SUCCESS;
}