forked from hugosantos/dbeacon
/
dbeacon.cpp
1665 lines (1352 loc) · 39.9 KB
/
dbeacon.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
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
/*
* Copyright 2005-2010, Hugo Santos <hugo@fivebits.net>
* Distributed under the terms of the MIT License.
*/
#include "dbeacon.h"
#include "address.h"
#include "msocket.h"
#include "protocol.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <math.h>
#include <errno.h>
#include <signal.h>
#include <libgen.h>
#include <ctype.h>
#include <syslog.h>
#include <assert.h>
#include <map>
#include <string>
#include <iostream>
#include <list>
#include <vector>
#include <set>
using namespace std;
const char * const versionInfo = "0.3.9.2p1 ($Rev$)";
const char * const defaultIPv6SSMChannel = "ff3e::beac";
const char * const defaultIPv4SSMChannel = "232.2.3.2";
const char * const defaultPort = "10000";
#ifndef SOLARIS
const int defaultTTL = 127;
#else
const int defaultTTL = 64;
#endif
const char * const defaultDumpFile = "dump.xml";
/* time related constants */
static const int timeOutI = 6;
static const int reportI = 2;
static const int ssmReportI = 4;
static const int mapReportI = 6;
static const int websiteReportI = 24;
/* other constants */
static const int probeBurstLength = 10;
// Timer Events
enum {
GARBAGE_COLLECT_EVENT,
DUMP_EVENT,
DUMP_BW_EVENT,
DUMP_BIG_BW_EVENT,
SENDING_EVENT,
WILLSEND_EVENT,
SSM_SENDING_EVENT,
WILLSEND_SSM_EVENT,
// Report types
REPORT_EVENT = 'R',
SSM_REPORT_EVENT,
MAP_REPORT_EVENT,
WEBSITE_REPORT_EVENT
};
// Timer event names
const char *TimerEventName[] = {
"Garbage Collect",
"Dump Stats",
"Bandwidth stats",
"Bandwidth stats [2]",
"Send Probe",
"New send probe process",
"SSM Send Probe",
"New SSM send probe process",
"Send Report",
"Send SSM Report",
"Send Map-Report",
"Send Website-Report"
};
const char *EventName(int type) {
if (type < REPORT_EVENT)
return TimerEventName[type];
return TimerEventName[type - REPORT_EVENT + 8];
}
static const char *Flags[] = {
"SSM",
"SSMPing"
};
static const uint32_t KnownFlags = 2;
static uint32_t timeFact(int val, bool random = false);
string beaconName, adminContact, twoLetterCC;
Sources sources;
WebSites webSites;
address beaconUnicastAddr;
int verbose = 0;
uint32_t flags = 0;
int mcastInterface = 0;
static char sessionName[256];
static address probeAddr;
static string probeAddrLiteral;
static string probeSSMAddrLiteral;
static bool useSSM = false;
static bool listenForSSM = false;
static bool useSSMPing = false;
static address ssmProbeAddr;
static int mcastSock, ssmMcastSock = 0;
static bool dumpBwReport = false;
static string launchSomething;
static double beacInt = 5.;
static uint64_t startTime = 0;
static string dumpFile;
typedef pair<address, bool> ContentDesc;
typedef vector<ContentDesc> McastListen;
static McastListen mcastListen;
typedef pair<int, SocketHandler> SocketDesc;
typedef set<SocketDesc> McastSocks;
static McastSocks mcastSocks;
static vector<address> redist;
static vector<address> ssmBootstrap;
static uint32_t bytesReceived = 0;
static uint32_t bytesSent = 0;
static uint64_t bigBytesReceived = 0;
static uint64_t bigBytesSent = 0;
static uint64_t lastDumpBwTS = 0;
static uint64_t dumpBytesReceived = 0;
static uint64_t dumpBytesSent = 0;
static uint64_t lastDumpDumpBwTS = 0;
static int dumpInterval = 5;
int forceFamily = AF_UNSPEC;
bool daemonize = false;
bool use_syslog = false;
bool past_init = false;
const char *pidfile = NULL;
static void next_event(timeval *);
static void insert_event(uint32_t, uint32_t);
static void handle_event();
static void handle_gc();
static int send_probe();
static int send_ssm_probe();
static int send_report(int);
static void do_dump();
static void do_bw_dump(bool);
extern "C" void dumpBigBwStats(int);
extern "C" void sendLeaveReport(int);
static inline double Rand() {
double f = rand();
/* Prevent 0.0 and 1.0, thanks to Alexander Gall */
if (f == 0)
f = 1;
else if (f == RAND_MAX)
f = RAND_MAX-1;
return f / (double)RAND_MAX;
}
static inline double Exprnd(double mean) {
return -mean * log(1 - Rand());
}
static const int bufferLen = 8192;
static uint8_t buffer[bufferLen];
void usage() {
fprintf(stdout, "Usage: dbeacon [OPTIONS...]\n\n");
fprintf(stdout, " -n NAME, -name NAME Specifies the beacon name\n");
fprintf(stdout, " -a MAIL Supply administration contact\n");
fprintf(stdout, " -i IN, -interface IN Use IN instead of the default interface for multicast\n");
fprintf(stdout, " -b BEACON_ADDR[/PORT] Multicast group address to send probes to\n");
fprintf(stdout, " -S [GROUP_ADDR[/PORT]] Enables SSM reception/sending on optional GROUP_ADDR/PORT\n");
fprintf(stdout, " -O Disables the joining of SSM groups but still sends via SSM.\n");
fprintf(stdout, " Use this option if your operating system has problems with SSM\n");
fprintf(stdout, " -B ADDR Bootstraps by joining the specified address\n");
fprintf(stdout, " -P, -ssmping Enable the SSMPing server capability\n");
fprintf(stdout, " -s ADDR Bind to local address\n");
fprintf(stdout, " -d [FILE] Dump periodic reports to dump.xml or specified file\n");
fprintf(stdout, " -I N, -interval N Interval between dumps. Defaults to 5 secs\n");
fprintf(stdout, " -W URL, -website URL Specify a website to announce.\n");
fprintf(stdout, " -Wm URL, -matrix URL Specify your matrix URL\n");
fprintf(stdout, " -Wl URL, -lg URL Specify your LG URL\n");
fprintf(stdout, " will announce an URL for that type instead\n");
fprintf(stdout, " -C CC Specify your two letter Country Code\n");
fprintf(stdout, " -L program Launch program after each dump.\n");
fprintf(stdout, " The first argument will be the dump filename\n");
fprintf(stdout, " -F flag Set a dbeacon flag to be announced.\n");
fprintf(stdout, " Available flags are: ssmping\n");
fprintf(stdout, " -4, -ipv4 Force IPv4 usage\n");
fprintf(stdout, " -6, -ipv6 Force IPv6 usage\n");
fprintf(stdout, " -v be verbose (use several for more verbosity)\n");
fprintf(stdout, " -U Dump periodic bandwidth usage reports to stdout\n");
fprintf(stdout, " -D, -daemon fork to the background (daemonize)\n");
fprintf(stdout, " -pidfile FILE Specifies the PID filename to use\n");
fprintf(stdout, " -syslog Outputs using syslog facility.\n");
fprintf(stdout, " -c FILE Specifies the configuration file\n");
fprintf(stdout, " -V, -version Outputs version information and leaves\n");
fprintf(stdout, "\n");
exit(1);
}
static void d_logv(int level, const char *format, va_list vl)
{
char buffer[256];
vsnprintf(buffer, sizeof(buffer), format, vl);
if (use_syslog && past_init) {
syslog(level, buffer);
} else {
char tbuf[64];
timeval tv;
gettimeofday(&tv, 0);
/* Some FreeBSDs' tv.tv_sec isn't time_t */
time_t tv_sec = tv.tv_sec;
strftime(tbuf, sizeof(tbuf), "%b %d %H:%M:%S", localtime(&tv_sec));
fprintf(stderr, "%s.%06u %s\n", tbuf, (uint32_t)tv.tv_usec, buffer);
}
}
void d_log(int level, const char *format, ...)
{
va_list vl;
va_start(vl, format);
d_logv(level, format, vl);
va_end(vl);
}
void info(const char *format, ...)
{
va_list vl;
va_start(vl, format);
d_logv(LOG_INFO, format, vl);
va_end(vl);
}
void fatal(const char *format, ...)
{
va_list vl;
va_start(vl, format);
d_logv(LOG_CRIT, format, vl);
va_end(vl);
exit(-1);
}
extern "C" void waitForMe(int) {
int whocares;
wait(&whocares);
}
static void parse_arguments(int, char **);
static inline bool IsSSMEnabled() {
return ssmMcastSock != 0;
}
static void handle_asm(int sock, const Message &msg)
{
bytesReceived += msg.len;
handle_nmsg(msg.from, msg.timestamp, msg.ttl, msg.buffer, msg.len, false);
}
static void handle_ssm(int sock, const Message &msg)
{
bytesReceived += msg.len;
handle_nmsg(msg.from, msg.timestamp, msg.ttl, msg.buffer, msg.len, true);
}
static void handle_mcast(const SocketDesc &desc)
{
Message msg;
int len = RecvMsg(desc.first, msg.from, msg.to, buffer, bufferLen, msg.ttl,
msg.timestamp);
if (len < 0)
return;
if (msg.from.is_equal(beaconUnicastAddr))
return;
msg.buffer = buffer;
msg.len = len;
if (verbose > 3) {
char tmp[64];
info("RecvMsg(%s): len = %u", msg.from.to_string(tmp, sizeof(tmp)), len);
}
desc.second(desc.first, msg);
}
int main(int argc, char **argv) {
int res;
srand(time(NULL));
char tmp[256];
if (gethostname(tmp, sizeof(tmp)) != 0) {
perror("Failed to get hostname");
return -1;
}
beaconName = tmp;
parse_arguments(argc, argv);
MulticastStartup();
if (beaconName.empty())
fatal("No name supplied, check `dbeacon -h`.");
if (!probeAddrLiteral.empty()) {
if (!probeAddr.parse(probeAddrLiteral.c_str(), true))
return -1;
probeAddr.to_string(sessionName, sizeof(sessionName));
if (!probeAddr.is_multicast())
fatal("Specified probe addr (%s) is not of a multicast group.",
sessionName);
if (adminContact.empty())
fatal("No administration contact supplied, check `dbeacon -h`.");
mcastListen.push_back(ContentDesc(probeAddr, false));
insert_event(SENDING_EVENT, 100);
insert_event(REPORT_EVENT, 10000);
insert_event(MAP_REPORT_EVENT, 30000);
insert_event(WEBSITE_REPORT_EVENT, 120000);
redist.push_back(probeAddr);
if (useSSM) {
if (probeSSMAddrLiteral.empty()) {
int family = forceFamily;
if (family == AF_UNSPEC) {
family = probeAddr.family();
}
if (family == AF_INET) {
probeSSMAddrLiteral = defaultIPv4SSMChannel;
} else {
probeSSMAddrLiteral = defaultIPv6SSMChannel;
}
}
if (!ssmProbeAddr.parse(probeSSMAddrLiteral.c_str(), true)) {
fatal("Bad address format for SSM channel.");
} else if (!ssmProbeAddr.is_unspecified()) {
insert_event(SSM_SENDING_EVENT, 100);
insert_event(SSM_REPORT_EVENT, 15000);
if (listenForSSM) {
mcastListen.push_back(ContentDesc(ssmProbeAddr, true));
}
}
}
} else {
if (mcastListen.empty())
fatal("Nothing to do, check `dbeacon -h`.");
else
strcpy(sessionName, beaconName.c_str());
}
address local;
local.set_family(probeAddr.family());
mcastSock = SetupSocket(local, false, false);
if (mcastSock < 0)
return -1;
if (beaconUnicastAddr.is_unspecified())
beaconUnicastAddr = get_local_address_for(probeAddr);
if (bind(mcastSock, beaconUnicastAddr.saddr(), beaconUnicastAddr.addrlen()) != 0) {
perror("Failed to bind local socket");
return -1;
}
if (beaconUnicastAddr.fromsocket(mcastSock) < 0) {
perror("getsockname");
return -1;
}
for (McastListen::const_iterator i = mcastListen.begin();
i != mcastListen.end(); ++i) {
int sock = SetupSocket(i->first, true, i->second);
if (sock < 0)
return -1;
if (i->second) {
ListenTo(sock, handle_ssm);
ssmMcastSock = sock;
} else {
ListenTo(sock, handle_asm);
}
}
if (useSSMPing) {
if (SetupSSMPing() < 0)
d_log(LOG_ERR, "Failed to setup SSM Ping.");
else
flags |= SSMPING_CAPABLE;
}
if (IsSSMEnabled()) {
flags |= SSM_CAPABLE;
uint64_t now = get_timestamp();
for (vector<address>::const_iterator i = ssmBootstrap.begin();
i != ssmBootstrap.end(); ++i)
getSource(*i, 0, now, 0, false);
} else if (!ssmBootstrap.empty())
d_log(LOG_WARNING, "Tried to bootstrap using SSM when SSM is not enabled.");
if (daemonize || use_syslog) {
use_syslog = true;
openlog("dbeacon", LOG_NDELAY | LOG_PID, LOG_DAEMON);
}
past_init = true;
if (daemonize) {
if (dbeacon_daemonize(pidfile)) {
perror("Failed to daemon()ize.");
return -1;
}
}
// Init timer events
insert_event(GARBAGE_COLLECT_EVENT, 30000);
if (!dumpFile.empty())
insert_event(DUMP_EVENT, dumpInterval * 1000);
insert_event(DUMP_BW_EVENT, 10000);
if (dumpBwReport)
insert_event(DUMP_BIG_BW_EVENT, 600000);
info("Local name is `%s` [Beacon group: %s, Local address: %s]",
beaconName.c_str(), sessionName, beaconUnicastAddr.to_string(tmp, sizeof(tmp), false));
send_report(WEBSITE_REPORT_EVENT);
signal(SIGUSR1, dumpBigBwStats);
signal(SIGINT, sendLeaveReport);
signal(SIGTERM, sendLeaveReport);
signal(SIGCHLD, waitForMe); // bloody fork, we dont want to wait for thee
startTime = lastDumpBwTS = lastDumpDumpBwTS = get_timestamp();
while (1) {
fd_set readset;
timeval eventm;
FD_ZERO(&readset);
for (McastSocks::const_iterator i = mcastSocks.begin();
i != mcastSocks.end(); ++i)
FD_SET(i->first, &readset);
next_event(&eventm);
res = select(mcastSocks.rbegin()->first + 1, &readset, 0, 0, &eventm);
if (res < 0) {
if (errno == EINTR)
continue;
fatal("Select failed: %s", strerror(errno));
} else {
for (McastSocks::const_iterator i = mcastSocks.begin();
res > 0 && i != mcastSocks.end(); ++i) {
if (FD_ISSET(i->first, &readset)) {
handle_mcast(*i);
res--;
}
}
handle_event();
}
}
return 0;
}
void ListenTo(int sock, SocketHandler handler)
{
mcastSocks.insert(SocketDesc(sock, handler));
}
void show_version() {
fprintf(stderr, "\n");
fprintf(stderr, "dbeacon - a Multicast Beacon %s\n", versionInfo);
fprintf(stderr, "\n");
fprintf(stderr, " Copyright (c) 2005-7, Hugo Santos <hugo@fivebits.net>\n");
fprintf(stderr, "\n");
fprintf(stderr, " http://fivebits.net/proj/dbeacon\n");
fprintf(stderr, "\n");
fprintf(stderr, " o Ideas, IPv4 port, SSM pushing by Hoerdt Mickael;\n");
fprintf(stderr, " o Ideas and testing by Sebastien Chaumontet;\n");
fprintf(stderr, " o SSM Ping originaly by Stig Venaas\n");
fprintf(stderr, " - first proposed by Pavan Namburi, Kamil Sarac and Kevin C. Almeroth;\n");
fprintf(stderr, " o Bernhard Schmidt provided valuable resources and helped during testing.\n");
fprintf(stderr, "\n");
exit(1);
}
enum {
NAME = 1,
CONTACT,
INTERFACE,
BEACONADDR,
SSMADDR,
SSMSENDONLY,
BOOTSTRAP,
ENABLESSMPING,
SOURCEADDR,
DUMP,
DUMPINTERVAL,
DUMPEXEC,
SPECWEBSITE,
SPECMATRIX,
SPECLG,
COUNTRY,
SPECFLAG,
VERBOSE,
DUMPBW,
HELP,
FORCEv4,
FORCEv6,
SHOWVERSION,
DAEMON,
PIDFILE,
USE_SYSLOG,
CONFFILE
};
enum {
NO_ARG = 0,
REQ_ARG,
OPT_ARG
};
static const struct param_tok {
int name;
const char *sf, *lf;
int param;
} param_format[] = {
{ NAME, "n", "name", REQ_ARG },
{ CONTACT, "a", "contact", REQ_ARG },
{ INTERFACE, "i", "interface", REQ_ARG },
{ BEACONADDR, "b", "addr", REQ_ARG },
{ SSMADDR, "S", "ssm_addr", OPT_ARG },
{ SSMSENDONLY, "O", "ssm_send_only", OPT_ARG },
{ BOOTSTRAP, "B", "bootstrap", REQ_ARG },
{ ENABLESSMPING,"P", "ssmping", OPT_ARG },
{ SOURCEADDR, "s", "source", REQ_ARG },
{ DUMP, "d", "dump", OPT_ARG },
{ DUMPINTERVAL, "I", "interval", REQ_ARG },
{ DUMPEXEC, "L", "exec", REQ_ARG },
{ SPECWEBSITE, "W", "website", REQ_ARG },
{ SPECMATRIX, "Wm", "matrix", REQ_ARG },
{ SPECLG, "Wl", "lg", REQ_ARG },
{ COUNTRY, "C", "CC", REQ_ARG },
{ SPECFLAG, "F", "flag", REQ_ARG },
{ VERBOSE, "v", "verbose", OPT_ARG },
{ DUMPBW, "U", "dump-bw", OPT_ARG },
{ HELP, "h", "help", NO_ARG },
{ FORCEv4, "4", "ipv4", NO_ARG },
{ FORCEv6, "6", "ipv6", NO_ARG },
{ DAEMON, "D", "daemon", NO_ARG },
{ PIDFILE, "p", "pidfile", REQ_ARG },
{ USE_SYSLOG, "Y", "syslog", NO_ARG },
{ CONFFILE, "c", NULL, REQ_ARG },
{ SHOWVERSION, "V", "version", NO_ARG },
{ 0, NULL, NULL, 0 }
};
static const char *check_good_string(const char *what, const char *value) {
int l = strlen(value);
for (int i = 0; i < l; i++) {
if (!isprint(value[i])) {
fprintf(stderr, "Invalid `%s` string.\n", what);
exit(1);
}
}
return value;
}
static void parse_or_fail(address *addr, const char *arg, bool mc, bool addport) {
if (!addr->parse(arg, mc, addport))
fatal("Bad address format.");
}
static void add_bootstrap_address(const char *arg) {
address addr;
parse_or_fail(&addr, arg, false, true);
ssmBootstrap.push_back(addr);
}
static uint32_t parse_u32(const char *name, const char *arg) {
uint32_t result;
char *end;
result = strtoul(arg, &end, 10);
if (end[0] != 0)
fatal("%s: Expected unsigned integer.", name);
return result;
}
static bool parse_bool(const char *name, const char *arg, bool def) {
if (arg == NULL)
return def;
if (!strcasecmp(arg, "yes"))
return true;
else if (!strcasecmp(arg, "true"))
return true;
else if (!strcasecmp(arg, "1"))
return true;
else if (!strcasecmp(arg, "no"))
return false;
else if (!strcasecmp(arg, "false"))
return false;
else if (!strcasecmp(arg, "0"))
return false;
fatal("%s: Expected one of \'yes\', \'true\', \'no\' or \'false\'.");
return false;
}
static void parse_config_file(const char *);
static void process_param(const param_tok *tok, const char *arg) {
switch (tok->name) {
case NAME:
beaconName = check_good_string("name", arg);
break;
case CONTACT:
if (!strchr(arg, '@'))
fatal("Not a valid email address.");
adminContact = check_good_string("admin contact", arg);
break;
case INTERFACE:
mcastInterface = if_nametoindex(arg);
if (mcastInterface <= 0)
fatal("Invalid interface name.");
break;
case BEACONADDR:
probeAddrLiteral = arg;
break;
case SSMADDR:
if (arg)
probeSSMAddrLiteral = arg;
useSSM = true;
listenForSSM = true;
break;
case SSMSENDONLY:
useSSM = true;
listenForSSM = parse_bool("SSMSendOnly", arg, false);
break;
case BOOTSTRAP:
add_bootstrap_address(arg);
break;
case ENABLESSMPING:
useSSMPing = parse_bool("SSMPing", arg, true);
break;
case SOURCEADDR:
parse_or_fail(&beaconUnicastAddr, arg, false, false);
break;
case DUMP:
dumpFile = arg ? arg : defaultDumpFile;
break;
case DUMPINTERVAL:
dumpInterval = parse_u32("Dump interval", arg);
if (dumpInterval < 5)
dumpInterval = 5;
break;
case DUMPEXEC:
launchSomething = arg;
break;
case SPECWEBSITE:
if (strncmp(arg, "lg$", 3) == 0) {
webSites[T_WEBSITE_LG] =
check_good_string("LG website", arg + 3);
} else if (strncmp(arg, "matrix$", 7) == 0) {
webSites[T_WEBSITE_MATRIX] =
check_good_string("matrix url", arg + 7);
} else {
webSites[T_WEBSITE_GENERIC] =
check_good_string("website", arg);
}
break;
case SPECMATRIX:
webSites[T_WEBSITE_MATRIX] =
check_good_string("matrix url", arg);
break;
case SPECLG:
webSites[T_WEBSITE_LG] =
check_good_string("lg url", arg);
break;
case COUNTRY:
if (strlen(arg) != 2)
fatal("Bad country code.");
twoLetterCC = check_good_string("country", arg);
break;
case SPECFLAG:
if (!strcmp(arg, "ssmping")) {
flags |= SSMPING_CAPABLE;
} else {
fprintf(stderr, "Unknown flag \"%s\"\n", arg);
}
break;
case VERBOSE:
if (arg)
verbose = parse_u32("Verbose", arg);
else
verbose ++;
break;
case DUMPBW:
dumpBwReport = parse_bool("DumpBandwidth", arg, true);
break;
case HELP:
usage();
break;
case FORCEv4:
forceFamily = AF_INET;
break;
case FORCEv6:
forceFamily = AF_INET6;
break;
case SHOWVERSION:
show_version();
break;
case DAEMON:
daemonize = true;
break;
case PIDFILE:
pidfile = check_good_string("pidfile", arg);
break;
case USE_SYSLOG:
use_syslog = true;
break;
case CONFFILE:
parse_config_file(arg);
break;
}
}
static char *skip_spaces(char *in) {
while (isspace(in[0]))
in++;
return in;
}
static char *terminate_str(char *left, char *right) {
for (; left < right && isspace(*right); right--);
right[1] = 0;
return left;
}
static const param_tok *resolve_tok(const char *arg, bool longonly) {
for (int j = 0; param_format[j].sf != NULL; j++) {
if (param_format[j].lf && !strcmp(arg, param_format[j].lf))
return ¶m_format[j];
if (longonly)
continue;
if (!strcmp(arg, param_format[j].sf))
return ¶m_format[j];
}
return NULL;
}
static void resolve_string(const char *name, char **ptr) {
char *p, *str = (*ptr);
if (str[0] != '\"')
return;
for (p = str + 1; (*p) != '\"'; p++);
if (p[0] == 0 || p[1] != 0)
fatal("%s: Bad string format.", name);
p[0] = 0;
(*ptr) = str + 1;
}
static void check_option_value(const param_tok *tok, const char *lp,
const char *value)
{
if (tok == NULL)
fatal("Unknown option `%s`", lp);
else if (tok->param == REQ_ARG && value == NULL)
fatal("Parameter `%s` requires an argument.", lp);
else if (tok->param == NO_ARG && value != NULL)
fatal("Parameter `%s` doesn't accept an argument.", lp);
}
static void parse_config_file(const char *filename) {
FILE *f = fopen(filename, "r");
if (f == NULL)
fatal("Failed to open configuration file.");
char linebuf[256];
int lc = 0;
while (fgets(linebuf, sizeof(linebuf), f)) {
char *lp = skip_spaces(linebuf);
char *val, *end = lp + strlen(lp);
lc++;
if (lp[0] == 0 || lp[0] == '#' || strncmp(lp, "//", 2) == 0)
continue;
val = strchr(lp, ':');
if (val) {
terminate_str(lp, val - 1);
val = terminate_str(skip_spaces(val + 1), end - 1);
} else {
terminate_str(lp, lp + strlen(lp) - 1);
}
const param_tok *tok = resolve_tok(lp, true);
check_option_value(tok, lp, val);
if (val)
resolve_string(lp, &val);
process_param(tok, val);
}
fclose(f);
}
typedef pair<const char *, const char *> string_pair;
void parse_arguments(int argc, char **argv) {
vector<string_pair> args;
vector<const char *> stray;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
const char *mast = argv[i];
const char *arg = 0;
if ((i + 1) < argc && argv[i+1][0] != '-') {
arg = argv[i+1];
i++;
}
args.push_back(make_pair(mast + 1, arg));
} else {
stray.push_back(argv[i]);
}
}
for (vector<string_pair>::const_iterator i = args.begin();
i != args.end(); ++i) {
const param_tok *tok = resolve_tok(i->first, false);
check_option_value(tok, i->first, i->second);
process_param(tok, i->second);
}
}
struct timer {
uint32_t type, interval;
uint32_t target;
};
typedef std::list<timer> tq_def;
static tq_def timers;
/* accumulated time waiting to be spent by events */
static uint32_t taccum = 0;
static uint64_t lastclk = 0;
static void update_taccum() {
uint64_t now = get_timestamp();
int32_t diff = now - (int64_t)lastclk;
assert(now >= lastclk);
lastclk = now;
taccum += diff;
}
void next_event(timeval *eventm) {
update_taccum();
timer &h = *timers.begin();
/* we assume we always have a timer in the list */
if (taccum > h.target) {
taccum -= h.target;
h.target = 0;
} else {
h.target -= taccum;
taccum = 0;
}
eventm->tv_sec = h.target / 1000;
eventm->tv_usec = (h.target % 1000) * 1000;
}
void insert_sorted_event(timer &t) {
uint32_t accum = 0;
tq_def::iterator i = timers.begin();
while (1) {
if (i == timers.end() || (accum + i->target) >= t.interval)
break;
accum += i->target;
++i;
}
t.target = t.interval - accum;
if (i != timers.end())
i->target -= t.target;
if (timers.empty()) {
lastclk = get_timestamp();
taccum = 0;
}
timers.insert(i, t);
}
void insert_event(uint32_t type, uint32_t interval) {
timer t;
t.type = type;
t.interval = interval;
insert_sorted_event(t);
}
static int send_count = 0;
static int send_ssm_count = 0;
uint32_t timeFact(int val, bool random) {
return (uint32_t) ((random ? ceil(Exprnd(beacInt * val)) : (beacInt * val)) * 1000);
}