-
Notifications
You must be signed in to change notification settings - Fork 40
/
dpinger.c
1528 lines (1306 loc) · 42.6 KB
/
dpinger.c
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 (c) 2015-2023, Denny Page
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Silly that this is required for accept4 on Linux
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <signal.h>
#include <netdb.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/icmp6.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <syslog.h>
// Who we are
static const char * progname;
// Process ID file
static const char * pidfile_name = NULL;
// Flags
static unsigned int foreground = 0;
static unsigned int flag_rewind = 0;
static unsigned int flag_syslog = 0;
static unsigned int flag_priority = 0;
// String representation of target
#define ADDR_STR_MAX (INET6_ADDRSTRLEN + IF_NAMESIZE + 1)
static char dest_str[ADDR_STR_MAX];
// Time period over which we are averaging results in ms
static unsigned long time_period_msec = 60000;
// Interval between sends in ms
static unsigned long send_interval_msec = 500;
// Interval before a sequence is initially treated as lost
// Input from command line in ms and used in us
static unsigned long loss_interval_msec = 0;
static unsigned long loss_interval_usec = 0;
// Interval between reports in ms
static unsigned long report_interval_msec = 1000;
// Interval between alert checks in ms
static unsigned long alert_interval_msec = 1000;
// Threshold for triggering alarms based on latency
// Input from command line in ms and used in us
static unsigned long latency_alarm_threshold_msec = 0;
static unsigned long latency_alarm_threshold_usec = 0;
// Threshold for triggering alarms based on loss percentage
static unsigned long loss_alarm_threshold_percent = 0;
// Command to invoke for alerts
static char * alert_cmd = NULL;
static size_t alert_cmd_offset;
// Interval before an alarm is cleared (hold time)
static unsigned long alarm_hold_msec = 0;
#define DEFAULT_HOLD_PERIODS 10
// Report file
static const char * report_name = NULL;
static int report_fd;
// Unix socket
static const char * usocket_name = NULL;
static int usocket_fd;
static char identifier[64] = "\0";
// Length of maximum output (dest_str alarm_flag average_latency_usec latency_deviation average_loss_percent)
#define OUTPUT_MAX (sizeof(identifier) + sizeof(dest_str) + sizeof(" 1 999999999999 999999999999 100\0"))
// Main ping status array
typedef struct
{
enum
{
PACKET_STATUS_EMPTY = 0,
PACKET_STATUS_SENT = 1,
PACKET_STATUS_RECEIVED = 2
} status;
struct timespec time_sent;
unsigned long latency_usec;
} ping_entry_t;
static ping_entry_t * array;
static unsigned int array_size;
static unsigned int next_slot = 0;
// Sockets used to send and receive
static int send_sock;
static int recv_sock;
// IPv4 / IPv6 parameters
static uint16_t af_family = AF_INET; // IPv6: AF_INET6
static uint8_t echo_request_type = ICMP_ECHO; // IPv6: ICMP6_ECHO_REQUEST
static uint8_t echo_reply_type = ICMP_ECHOREPLY; // IPv6: ICMP6_ECHO_REPLY
static int ip_proto = IPPROTO_ICMP; // IPv6: IPPROTO_ICMPV6
// Destination address
static struct sockaddr_storage dest_addr;
static socklen_t dest_addr_len;
// Source (bind) address
static struct sockaddr_storage bind_addr;
static socklen_t bind_addr_len = 0;
// ICMP echo request/reply header
//
// The physical layout of the ICMP is the same between IPv4 and IPv6 so we define our
// own type for convenience
typedef struct
{
uint8_t type;
uint8_t code;
uint16_t cksum;
uint16_t id;
uint16_t sequence;
} icmphdr_t;
// Echo request/reply packet buffers
#define IPV4_ICMP_DATA_MAX (IP_MAXPACKET - sizeof(struct ip) - sizeof(icmphdr_t))
#define IPV6_ICMP_DATA_MAX (IP_MAXPACKET - sizeof(icmphdr_t))
#define PACKET_BUFLEN (IP_MAXPACKET + 256)
static unsigned long echo_data_len = 0;
static unsigned int echo_request_len = sizeof(icmphdr_t);
static unsigned int echo_reply_len = IP_MAXPACKET;
static icmphdr_t * echo_request;
static void * echo_reply;
// Echo id and Sequence information
static uint16_t echo_id;
static uint16_t next_sequence = 0;
static uint16_t sequence_limit;
// Receive thread ready
static unsigned int recv_ready = 0;
//
// Log for abnormal events
//
__attribute__ ((format (printf, 1, 2)))
static void
logger(
const char * format,
...)
{
va_list args;
va_start(args, format);
if (flag_syslog)
{
vsyslog(LOG_WARNING, format, args);
}
else
{
vfprintf(stderr, format, args);
}
va_end(args);
}
//
// Termination handler
//
__attribute__ ((noreturn))
static void
term_handler(
int signum)
{
// NB: This function may be simultaneously invoked by multiple threads
if (usocket_name)
{
(void) unlink(usocket_name);
}
if (pidfile_name)
{
(void) unlink(pidfile_name);
}
logger("exiting on signal %d\n", signum);
exit(0);
}
//
// Compute checksum for ICMP
//
static uint16_t
cksum(
const uint16_t * p,
int len)
{
uint32_t sum = 0;
while (len > 1)
{
sum += *p++;
len -= sizeof(*p);
}
if (len == 1)
{
sum += (uint16_t) *((const uint8_t *) p);
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return (uint16_t) ~sum;
}
//
// sqrt function for standard deviation
//
static unsigned long
llsqrt(
unsigned long long x)
{
unsigned long long prev;
unsigned long long s;
s = x;
if (s)
{
prev = ~((unsigned long long) 1 << 63);
while (s < prev)
{
prev = s;
s = (s + (x / s)) / 2;
}
}
return (unsigned long) s;
}
//
// Compute delta between old time and new time in microseconds
//
static unsigned long
ts_elapsed_usec(
const struct timespec * old,
const struct timespec * new)
{
long r_usec;
// Note that we are using monotonic clock and time cannot run backwards
if (new->tv_nsec >= old->tv_nsec)
{
r_usec = (new->tv_sec - old->tv_sec) * 1000000 + (new->tv_nsec - old->tv_nsec) / 1000;
}
else
{
r_usec = (new->tv_sec - old->tv_sec - 1) * 1000000 + (1000000000 + new->tv_nsec - old->tv_nsec) / 1000;
}
return (unsigned long) r_usec;
}
//
// Send thread
//
__attribute__ ((noreturn))
static void *
send_thread(
__attribute__ ((unused))
void * arg)
{
struct timespec sleeptime;
ssize_t len;
int r;
// Set up our echo request packet
memset(echo_request, 0, echo_request_len);
echo_request->type = echo_request_type;
echo_request->code = 0;
echo_request->id = echo_id;
// Give the recv thread a moment to initialize
sleeptime.tv_sec = 0;
sleeptime.tv_nsec = 10000; // 10us
do {
r = nanosleep(&sleeptime, NULL);
if (r == -1)
{
logger("nanosleep error in send thread waiting for recv thread: %d\n", errno);
}
} while (recv_ready == 0);
// Set up the timespec for nanosleep
sleeptime.tv_sec = send_interval_msec / 1000;
sleeptime.tv_nsec = (send_interval_msec % 1000) * 1000000;
while (1)
{
// Set sequence number and checksum
echo_request->sequence = htons(next_sequence);
echo_request->cksum = 0;
echo_request->cksum = cksum((uint16_t *) echo_request, sizeof(icmphdr_t));
array[next_slot].status = PACKET_STATUS_EMPTY;
sched_yield();
clock_gettime(CLOCK_MONOTONIC, &array[next_slot].time_sent);
array[next_slot].status = PACKET_STATUS_SENT;
len = sendto(send_sock, echo_request, echo_request_len, 0, (struct sockaddr *) &dest_addr, dest_addr_len);
if (len == -1)
{
logger("%s%s: sendto error: %d\n", identifier, dest_str, errno);
}
next_slot = (next_slot + 1) % array_size;
next_sequence = (next_sequence + 1) % sequence_limit;
r = nanosleep(&sleeptime, NULL);
if (r == -1)
{
logger("nanosleep error in send thread: %d\n", errno);
}
}
}
//
// Receive thread
//
__attribute__ ((noreturn))
static void *
recv_thread(
__attribute__ ((unused))
void * arg)
{
struct sockaddr_storage src_addr;
socklen_t src_addr_len;
ssize_t len;
icmphdr_t * icmp;
struct timespec now;
unsigned int array_slot;
// Thread startup complete
recv_ready = 1;
while (1)
{
src_addr_len = sizeof(src_addr);
len = recvfrom(recv_sock, echo_reply, echo_reply_len, 0, (struct sockaddr *) &src_addr, &src_addr_len);
if (len == -1)
{
logger("%s%s: recvfrom error: %d\n", identifier, dest_str, errno);
continue;
}
clock_gettime(CLOCK_MONOTONIC, &now);
if (af_family == AF_INET)
{
struct ip * ip;
size_t ip_len;
// With IPv4, we get the entire IP packet
if (len < (ssize_t) sizeof(struct ip))
{
logger("%s%s: received packet too small for IP header\n", identifier, dest_str);
continue;
}
ip = echo_reply;
ip_len = (size_t) ip->ip_hl << 2;
icmp = (void *) ((char *) ip + ip_len);
len -= ip_len;
}
else
{
// With IPv6, we just get the ICMP payload
icmp = echo_reply;
}
// This should never happen
if (len < (ssize_t) sizeof(icmphdr_t))
{
logger("%s%s: received packet too small for ICMP header\n", identifier, dest_str);
continue;
}
// If it's not an echo reply for us, skip the packet
if (icmp->type != echo_reply_type || icmp->id != echo_id)
{
continue;
}
array_slot = ntohs(icmp->sequence) % array_size;
if (array[array_slot].status == PACKET_STATUS_RECEIVED)
{
logger("%s%s: duplicate echo reply received\n", identifier, dest_str);
continue;
}
array[array_slot].latency_usec = ts_elapsed_usec(&array[array_slot].time_sent, &now);
array[array_slot].status = PACKET_STATUS_RECEIVED;
}
}
//
// Generate a report
//
static void
report(
unsigned long *average_latency_usec,
unsigned long *latency_deviation,
unsigned long *average_loss_percent)
{
struct timespec now;
unsigned long packets_received = 0;
unsigned long packets_lost = 0;
unsigned long latency_usec = 0;
unsigned long total_latency_usec = 0;
unsigned long long total_latency_usec2 = 0;
unsigned int slot;
unsigned int i;
clock_gettime(CLOCK_MONOTONIC, &now);
slot = next_slot;
for (i = 0; i < array_size; i++)
{
if (array[slot].status == PACKET_STATUS_RECEIVED)
{
packets_received++;
latency_usec = array[slot].latency_usec;
total_latency_usec += latency_usec;
total_latency_usec2 += (unsigned long long) latency_usec * latency_usec;
}
else if (array[slot].status == PACKET_STATUS_SENT &&
ts_elapsed_usec(&array[slot].time_sent, &now) > loss_interval_usec)
{
packets_lost++;
}
slot = (slot + 1) % array_size;
}
if (packets_received)
{
unsigned long avg = total_latency_usec / packets_received;
unsigned long long avg2 = total_latency_usec2 / packets_received;
// stddev = sqrt((sum(rtt^2) / packets) - (sum(rtt) / packets)^2)
*average_latency_usec = avg;
*latency_deviation = llsqrt(avg2 - ((unsigned long long) avg * avg));
}
else
{
*average_latency_usec = 0;
*latency_deviation = 0;
}
if (packets_lost)
{
*average_loss_percent = packets_lost * 100 / (packets_received + packets_lost);
}
else
{
*average_loss_percent = 0;
}
}
//
// Report thread
//
__attribute__ ((noreturn))
static void *
report_thread(
__attribute__ ((unused))
void * arg)
{
char buf[OUTPUT_MAX];
struct timespec sleeptime;
unsigned long average_latency_usec;
unsigned long latency_deviation;
unsigned long average_loss_percent;
ssize_t len;
ssize_t rs;
int r;
// Set up the timespec for nanosleep
sleeptime.tv_sec = report_interval_msec / 1000;
sleeptime.tv_nsec = (report_interval_msec % 1000) * 1000000;
while (1)
{
r = nanosleep(&sleeptime, NULL);
if (r == -1)
{
logger("nanosleep error in report thread: %d\n", errno);
}
report(&average_latency_usec, &latency_deviation, &average_loss_percent);
len = snprintf(buf, sizeof(buf), "%s%lu %lu %lu\n", identifier, average_latency_usec, latency_deviation, average_loss_percent);
if (len < 0 || (size_t) len > sizeof(buf))
{
logger("error formatting output in report thread\n");
}
rs = write(report_fd, buf, (size_t) len);
if (rs == -1)
{
logger("write error in report thread: %d\n", errno);
}
else if (rs != len)
{
logger("short write in report thread: %zd/%zd\n", rs, len);
}
if (flag_rewind)
{
(void) ftruncate(report_fd, len);
(void) lseek(report_fd, SEEK_SET, 0);
}
}
}
//
// Alert thread
//
__attribute__ ((noreturn))
static void *
alert_thread(
__attribute__ ((unused))
void * arg)
{
struct timespec sleeptime;
unsigned long average_latency_usec;
unsigned long latency_deviation;
unsigned long average_loss_percent;
unsigned int alarm_hold_periods;
unsigned int latency_alarm_decay = 0;
unsigned int loss_alarm_decay = 0;
unsigned int alert = 0;
unsigned int alarm_on;
int r;
// Set up the timespec for nanosleep
sleeptime.tv_sec = alert_interval_msec / 1000;
sleeptime.tv_nsec = (alert_interval_msec % 1000) * 1000000;
// Set number of alarm hold periods
alarm_hold_periods = (unsigned int) ((alarm_hold_msec + alert_interval_msec - 1) / alert_interval_msec);
while (1)
{
r = nanosleep(&sleeptime, NULL);
if (r == -1)
{
logger("nanosleep error in alert thread: %d\n", errno);
}
report(&average_latency_usec, &latency_deviation, &average_loss_percent);
if (latency_alarm_threshold_usec)
{
if (average_latency_usec > latency_alarm_threshold_usec)
{
if (latency_alarm_decay == 0)
{
alert = 1;
}
latency_alarm_decay = alarm_hold_periods;
}
else if (latency_alarm_decay)
{
latency_alarm_decay--;
if (latency_alarm_decay == 0)
{
alert = 1;
}
}
}
if (loss_alarm_threshold_percent)
{
if (average_loss_percent > loss_alarm_threshold_percent)
{
if (loss_alarm_decay == 0)
{
alert = 1;
}
loss_alarm_decay = alarm_hold_periods;
}
else if (loss_alarm_decay)
{
loss_alarm_decay--;
if (loss_alarm_decay == 0)
{
alert = 1;
}
}
}
if (alert)
{
alert = 0;
alarm_on = latency_alarm_decay || loss_alarm_decay;
logger("%s%s: %s latency %luus stddev %luus loss %lu%%\n", identifier, dest_str, alarm_on ? "Alarm" : "Clear", average_latency_usec, latency_deviation, average_loss_percent);
if (alert_cmd)
{
r = snprintf(alert_cmd + alert_cmd_offset, OUTPUT_MAX, " %s%s %u %lu %lu %lu", identifier, dest_str, alarm_on, average_latency_usec, latency_deviation, average_loss_percent);
if (r < 0 || (size_t) r >= OUTPUT_MAX)
{
logger("error formatting command in alert thread\n");
continue;
}
// Note that system waits for the alert command to finish before returning
r = system(alert_cmd);
if (r == -1)
{
logger("error executing command in alert thread\n");
}
}
}
}
}
//
// Unix socket thread
//
__attribute__ ((noreturn))
static void *
usocket_thread(
__attribute__ ((unused))
void * arg)
{
char buf[OUTPUT_MAX];
unsigned long average_latency_usec;
unsigned long latency_deviation;
unsigned long average_loss_percent;
int sock_fd;
ssize_t len;
ssize_t rs;
int r;
while (1)
{
#if defined(DISABLE_ACCEPT4)
// Legacy
sock_fd = accept(usocket_fd, NULL, NULL);
(void) fcntl(sock_fd, F_SETFL, FD_CLOEXEC);
(void) fcntl(sock_fd, F_SETFL, fcntl(sock_fd, F_GETFL, 0) | O_NONBLOCK);
#else
sock_fd = accept4(usocket_fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
#endif
report(&average_latency_usec, &latency_deviation, &average_loss_percent);
len = snprintf(buf, sizeof(buf), "%s%lu %lu %lu\n", identifier, average_latency_usec, latency_deviation, average_loss_percent);
if (len < 0 || (size_t) len > sizeof(buf))
{
logger("error formatting output in usocket thread\n");
}
rs = write(sock_fd, buf, (size_t) len);
if (rs == -1)
{
logger("write error in usocket thread: %d\n", errno);
}
else if (rs != len)
{
logger("short write in usocket thread: %zd/%zd\n", rs, len);
}
r = close(sock_fd);
if (r == -1)
{
logger("close error in usocket thread: %d\n", errno);
}
}
}
//
// Decode a time argument
//
static int
get_time_arg_msec(
const char * arg,
unsigned long * value)
{
long t;
char * suffix;
t = strtol(arg, &suffix, 10);
if (*suffix == 'm')
{
// Milliseconds
suffix++;
}
else if (*suffix == 's')
{
// Seconds
t *= 1000;
suffix++;
}
// Invalid specification?
if (t < 0 || *suffix != 0)
{
return 1;
}
*value = (unsigned long) t;
return 0;
}
//
// Decode a percent argument
//
static int
get_percent_arg(
const char * arg,
unsigned long * value)
{
long t;
char * suffix;
t = strtol(arg, &suffix, 10);
if (*suffix == '%')
{
suffix++;
}
// Invalid specification?
if (t < 0 || t > 100 || *suffix != 0)
{
return 1;
}
*value = (unsigned long) t;
return 0;
}
//
// Decode a byte length argument
//
static int
get_length_arg(
const char * arg,
unsigned long * value)
{
long t;
char * suffix;
t = strtol(arg, &suffix, 10);
if (*suffix == 'b')
{
// Bytes
suffix++;
}
else if (*suffix == 'k')
{
// Kilobytes
t *= 1024;
suffix++;
}
// Invalid specification?
if (t < 0 || *suffix != 0)
{
return 1;
}
*value = (unsigned long) t;
return 0;
}
//
// Output usage
//
static void
usage(void)
{
fprintf(stderr, "Dpinger version 3.3\n\n");
fprintf(stderr, "Usage:\n");
fprintf(stderr, " %s [-f] [-R] [-S] [-P] [-h] [-B bind_addr] [-s send_interval] [-l loss_interval] [-t time_period] [-r report_interval] [-d data_length] [-o output_file] [-A alert_interval] [-D latency_alarm] [-L loss_alarm] [-H hold_interval] [-C alert_cmd] [-i identifier] [-u usocket] [-p pidfile] dest_addr\n\n", progname);
fprintf(stderr, " options:\n");
fprintf(stderr, " -f run in foreground\n");
fprintf(stderr, " -R rewind output file between reports\n");
fprintf(stderr, " -S log warnings via syslog\n");
fprintf(stderr, " -P priority scheduling for receive thread (requires root)\n");
fprintf(stderr, " -h display usage\n");
fprintf(stderr, " -B bind (source) address\n");
fprintf(stderr, " -s time interval between echo requests (default 500ms)\n");
fprintf(stderr, " -l time interval before packets are treated as lost (default 4x send interval)\n");
fprintf(stderr, " -t time period over which results are averaged (default 60s)\n");
fprintf(stderr, " -r time interval between reports (default 1s)\n");
fprintf(stderr, " -d data length (default 0)\n");
fprintf(stderr, " -o output file for reports (default stdout)\n");
fprintf(stderr, " -A time interval between alerts (default 1s)\n");
fprintf(stderr, " -D time threshold for latency alarm (default none)\n");
fprintf(stderr, " -L percent threshold for loss alarm (default none)\n");
fprintf(stderr, " -H time interval to hold an alarm before clearing it (default 10x alert interval)\n");
fprintf(stderr, " -C optional command to be invoked via system() for alerts\n");
fprintf(stderr, " -i identifier text to include in output\n");
fprintf(stderr, " -u unix socket name for polling\n");
fprintf(stderr, " -p process id file name\n\n");
fprintf(stderr, " notes:\n");
fprintf(stderr, " IP addresses can be in either IPv4 or IPv6 format\n\n");
fprintf(stderr, " time values can be expressed with a suffix of 'm' (milliseconds) or 's' (seconds)\n");
fprintf(stderr, " if no suffix is specified, milliseconds is the default\n\n");
fprintf(stderr, " the output format is \"latency_avg latency_stddev loss_pct\"\n");
fprintf(stderr, " latency values are output in microseconds\n");
fprintf(stderr, " loss percentage is reported in whole numbers of 0-100\n");
fprintf(stderr, " resolution of loss calculation is: 100 / ((time_period - loss_interval) / send_interval)\n\n");
fprintf(stderr, " the alert_cmd is invoked as \"alert_cmd dest_addr alarm_flag latency_avg latency_stddev loss_pct\"\n");
fprintf(stderr, " alarm_flag is set to 1 if either latency or loss is in alarm state\n");
fprintf(stderr, " alarm_flag will return to 0 when both have have cleared alarm state\n");
fprintf(stderr, " alarm hold time begins when the source of the alarm retruns to normal\n\n");
}
//
// Fatal error
//
__attribute__ ((noreturn, format (printf, 1, 2)))
static void
fatal(
const char * format,
...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
exit(EXIT_FAILURE);
}
//
// Parse command line arguments
//
static void
parse_args(
int argc,
char * const argv[])
{
struct addrinfo hint;
struct addrinfo * addr_info;
const char * dest_arg;
const char * bind_arg = NULL;
size_t len;
int opt;
int r;
progname = argv[0];
while((opt = getopt(argc, argv, "fhRSPB:s:l:t:r:d:o:A:D:L:H:C:i:u:p:")) != -1)
{
switch (opt)
{
case 'f':
foreground = 1;
break;
case 'R':
flag_rewind = 1;
break;
case 'S':
flag_syslog = 1;
break;
case 'P':
flag_priority = 1;
break;
case 'B':
bind_arg = optarg;
break;
case 's':
r = get_time_arg_msec(optarg, &send_interval_msec);
if (r || send_interval_msec == 0)
{
fatal("invalid send interval %s\n", optarg);
}
break;
case 'l':
r = get_time_arg_msec(optarg, &loss_interval_msec);
if (r || loss_interval_msec == 0)
{
fatal("invalid loss interval %s\n", optarg);
}
break;
case 't':
r = get_time_arg_msec(optarg, &time_period_msec);
if (r || time_period_msec == 0)
{
fatal("invalid averaging time period %s\n", optarg);
}
break;
case 'r':
r = get_time_arg_msec(optarg, &report_interval_msec);
if (r)
{
fatal("invalid report interval %s\n", optarg);
}
break;
case 'd':
r = get_length_arg(optarg, &echo_data_len);
if (r)
{
fatal("invalid data length %s\n", optarg);
}
break;
case 'o':
report_name = optarg;
break;
case 'A':
r = get_time_arg_msec(optarg, &alert_interval_msec);
if (r || alert_interval_msec == 0)
{
fatal("invalid alert interval %s\n", optarg);
}