1 /**
2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2016 Florian octo Forster <ff at octo.it>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; only version 2 of the License is
8 * applicable.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 #if STDC_HEADERS
25 # include <stdlib.h>
26 # include <stdio.h>
27 # include <string.h>
28 # include <stdint.h>
29 # include <inttypes.h>
30 # include <errno.h>
31 # include <assert.h>
32 #else
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
40 #if HAVE_MATH_H
41 # include <math.h>
42 #endif
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
46 # include <time.h>
47 #else
48 # if HAVE_SYS_TIME_H
49 # include <sys/time.h>
50 # else
51 # include <time.h>
52 # endif
53 #endif
55 #if HAVE_SYS_SOCKET_H
56 # include <sys/socket.h>
57 #endif
58 #if HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #if HAVE_NETINET_IP_H
62 # include <netinet/ip.h>
63 #endif
65 #if HAVE_NETDB_H
66 # include <netdb.h> /* NI_MAXHOST */
67 #endif
69 #if HAVE_SIGNAL_H
70 # include <signal.h>
71 #endif
73 #if HAVE_SYS_TYPES_H
74 #include <sys/types.h>
75 #endif
77 #include <locale.h>
78 #include <langinfo.h>
80 #if USE_NCURSES
81 # define NCURSES_OPAQUE 1
82 /* http://newsgroups.derkeiler.com/Archive/Rec/rec.games.roguelike.development/2010-09/msg00050.html */
83 # define _X_OPEN_SOURCE_EXTENDED
85 # if HAVE_NCURSESW_NCURSES_H
86 # include <ncursesw/ncurses.h>
87 # elif HAVE_NCURSES_H
88 # include <ncurses.h>
89 # endif
91 # define OPING_GREEN 1
92 # define OPING_YELLOW 2
93 # define OPING_RED 3
94 # define OPING_GREEN_HIST 4
95 # define OPING_YELLOW_HIST 5
96 # define OPING_RED_HIST 6
98 double const threshold_green = 0.8;
99 double const threshold_yellow = 0.95;
101 static char const * const hist_symbols_utf8[] = {
102 "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
103 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
104 / sizeof (hist_symbols_utf8[0]);
106 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
107 /* those are not the usual constants because those are not constant */
108 static int const hist_symbols_acs[] = {
109 115, /* ACS_S9 "⎽" */
110 114, /* ACS_S7 "⎼" */
111 113, /* ACS_S5 "─" */
112 112, /* ACS_S3 "⎻" */
113 111 /* ACS_S1 "⎺" */
114 };
115 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
116 / sizeof (hist_symbols_acs[0]);
118 /* use different colors without a background for scancodes */
119 static int const hist_colors_utf8[] = {
120 OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
121 static int const hist_colors_acs[] = {
122 OPING_GREEN, OPING_YELLOW, OPING_RED };
123 /* assuming that both arrays are the same size */
124 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
125 / sizeof (hist_colors_utf8[0]);
126 #endif
128 /* "─" */
129 #define BOXPLOT_WHISKER_BAR (113 | A_ALTCHARSET)
130 /* "├" */
131 #define BOXPLOT_WHISKER_LEFT_END (116 | A_ALTCHARSET)
132 /* "┤" */
133 #define BOXPLOT_WHISKER_RIGHT_END (117 | A_ALTCHARSET)
134 /* Inverted */
135 #define BOXPLOT_BOX ' '
136 /* "│", inverted */
137 #define BOXPLOT_MEDIAN (120 | A_ALTCHARSET)
139 #include "oping.h"
141 #ifndef _POSIX_SAVED_IDS
142 # define _POSIX_SAVED_IDS 0
143 #endif
145 #ifndef IPTOS_MINCOST
146 # define IPTOS_MINCOST 0x02
147 #endif
149 /* Remove GNU specific __attribute__ settings when using another compiler */
150 #if !__GNUC__
151 # define __attribute__(x) /**/
152 #endif
154 typedef struct ping_context
155 {
156 char host[NI_MAXHOST];
157 char addr[NI_MAXHOST];
159 int index;
160 int req_sent;
161 int req_rcvd;
163 double latency_total;
165 #ifndef HISTORY_SIZE_MAX
166 # define HISTORY_SIZE_MAX 900
167 #endif
168 /* The last n RTTs in the order they were sent. */
169 double history_by_time[HISTORY_SIZE_MAX];
171 /* Current number of entries in the history. This is a value between 0
172 * and HISTORY_SIZE_MAX. */
173 size_t history_size;
175 /* Number "received" entries in the history, i.e. non-NAN entries. */
176 size_t history_received;
178 /* Index of the next RTT to be written to history_by_time. This wraps
179 * around to 0 once the histroty has grown to HISTORY_SIZE_MAX. */
180 size_t history_index;
182 /* The last history_size RTTs sorted by value. timed out packets (NAN
183 * entries) are sorted to the back. */
184 double history_by_value[HISTORY_SIZE_MAX];
186 /* If set to true, history_by_value has to be re-calculated. */
187 _Bool history_dirty;
189 #if USE_NCURSES
190 WINDOW *window;
191 #endif
192 } ping_context_t;
194 static double opt_interval = 1.0;
195 static double opt_timeout = PING_DEF_TIMEOUT;
196 static int opt_addrfamily = PING_DEF_AF;
197 static char *opt_srcaddr = NULL;
198 static char *opt_device = NULL;
199 static char *opt_mark = NULL;
200 static char *opt_filename = NULL;
201 static int opt_count = -1;
202 static int opt_send_ttl = 64;
203 static uint8_t opt_send_qos = 0;
204 #define OPING_DEFAULT_PERCENTILE 95.0
205 static double opt_percentile = -1.0;
206 static double opt_exit_status_threshold = 1.0;
207 #if USE_NCURSES
208 static int opt_show_graph = 1;
209 static int opt_utf8 = 0;
210 #endif
211 static char *opt_outfile = NULL;
212 static int opt_bell = 0;
214 static int host_num = 0;
215 static FILE *outfile = NULL;
217 #if USE_NCURSES
218 static WINDOW *main_win = NULL;
219 #endif
221 static void sigint_handler (int signal) /* {{{ */
222 {
223 /* Make compiler happy */
224 signal = 0;
225 /* Exit the loop */
226 opt_count = 0;
227 } /* }}} void sigint_handler */
229 static ping_context_t *context_create (void) /* {{{ */
230 {
231 ping_context_t *ret;
233 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
234 return (NULL);
236 memset (ret, '\0', sizeof (ping_context_t));
238 ret->latency_total = 0.0;
240 #if USE_NCURSES
241 ret->window = NULL;
242 #endif
244 return (ret);
245 } /* }}} ping_context_t *context_create */
247 static void context_destroy (ping_context_t *context) /* {{{ */
248 {
249 if (context == NULL)
250 return;
252 #if USE_NCURSES
253 if (context->window != NULL)
254 {
255 delwin (context->window);
256 context->window = NULL;
257 }
258 #endif
260 free (context);
261 } /* }}} void context_destroy */
263 static int compare_double (void const *arg0, void const *arg1) /* {{{ */
264 {
265 double dbl0 = *((double *) arg0);
266 double dbl1 = *((double *) arg1);
268 if (isnan (dbl0))
269 {
270 if (isnan (dbl1))
271 return 0;
272 else
273 return 1;
274 }
275 else if (isnan (dbl1))
276 return -1;
277 else if (dbl0 < dbl1)
278 return -1;
279 else if (dbl0 > dbl1)
280 return 1;
281 else
282 return 0;
283 } /* }}} int compare_double */
285 static void clean_history (ping_context_t *ctx) /* {{{ */
286 {
287 size_t i;
289 if (!ctx->history_dirty)
290 return;
292 /* Copy all values from by_time to by_value. */
293 memcpy (ctx->history_by_value, ctx->history_by_time,
294 sizeof (ctx->history_by_time));
296 /* Remove impossible values caused by adding a new host */
297 for (i = 0; i < ctx->history_size; i++)
298 if (ctx->history_by_value[i]<0)
299 ctx->history_by_value[i]=NAN;
301 /* Sort all RTTs. */
302 qsort (ctx->history_by_value, ctx->history_size, sizeof
303 (ctx->history_by_value[0]), compare_double);
305 /* Update the number of received RTTs. */
306 ctx->history_received = 0;
307 for (i = 0; i < ctx->history_size; i++)
308 if (!isnan (ctx->history_by_value[i]))
309 ctx->history_received++;
311 /* Mark as clean. */
312 ctx->history_dirty = 0;
313 } /* }}} void clean_history */
315 static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
316 double percentile)
317 {
318 size_t index;
320 clean_history (ctx);
322 /* Not a single packet was received successfully. */
323 if (ctx->history_received == 0)
324 return NAN;
326 if (percentile <= 0.0)
327 index = 0;
328 else if (percentile >= 100.0)
329 index = ctx->history_received - 1;
330 else
331 {
332 index = (size_t) ceil ((percentile / 100.0) * ((double) ctx->history_received));
333 assert (index > 0);
334 index--;
335 }
337 return (ctx->history_by_value[index]);
338 } /* }}} double percentile_to_latency */
340 #if USE_NCURSES
341 static double latency_to_ratio (ping_context_t *ctx, /* {{{ */
342 double latency)
343 {
344 size_t low;
345 size_t high;
346 size_t index;
348 clean_history (ctx);
350 /* Not a single packet was received successfully. */
351 if (ctx->history_received == 0)
352 return NAN;
354 low = 0;
355 high = ctx->history_received - 1;
357 if (latency < ctx->history_by_value[low])
358 return 0.0;
359 else if (latency >= ctx->history_by_value[high])
360 return 100.0;
362 /* Do a binary search for the latency. This will work even when the
363 * exact latency is not in the array. If the latency is in the array
364 * multiple times, "low" will be set to the index of the last
365 * occurrence. The value at index "high" will be larger than the
366 * searched for latency (assured by the above "if" block. */
367 while ((high - low) > 1)
368 {
369 index = (high + low) / 2;
371 if (ctx->history_by_value[index] > latency)
372 high = index;
373 else
374 low = index;
375 }
377 assert (ctx->history_by_value[high] > latency);
378 assert (ctx->history_by_value[low] <= latency);
380 if (ctx->history_by_value[low] == latency)
381 index = low;
382 else
383 index = high;
385 return (((double) (index + 1)) / ((double) ctx->history_received));
386 } /* }}} double latency_to_ratio */
387 #endif
389 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
390 {
391 if (ctx == NULL)
392 return (-1.0);
394 if (ctx->req_sent < 1)
395 return (0.0);
397 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
398 / ((double) ctx->req_sent));
399 } /* }}} double context_get_packet_loss */
401 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
402 {
403 pingobj_iter_t *iter;
404 int index;
405 size_t history_size = 0;
407 if (ping == NULL)
408 return (EINVAL);
410 index = 0;
411 for (iter = ping_iterator_get (ping);
412 iter != NULL;
413 iter = ping_iterator_next (iter))
414 {
415 ping_context_t *context;
416 size_t buffer_size;
418 context = ping_iterator_get_context(iter);
420 /* if this is a previously existing host, do not recreate it */
421 if (context != NULL) {
422 history_size = context->history_size;
423 context->index = index++;
424 continue;
425 }
427 context = context_create ();
428 context->index = index;
430 /* start new hosts at the same graph point as old hosts */
431 context->history_size = history_size;
432 context->history_index = history_size;
433 for (int i = 0; i<history_size; i++) {
434 context->history_by_time[i] = -1;
435 }
437 buffer_size = sizeof (context->host);
438 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
440 buffer_size = sizeof (context->addr);
441 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
443 ping_iterator_set_context (iter, (void *) context);
445 index++;
446 }
448 return (0);
449 } /* }}} int ping_initialize_contexts */
451 static void usage_exit (const char *name, int status) /* {{{ */
452 {
453 fprintf (stderr, "Usage: %s [OPTIONS] "
454 "-f filename | host [host [host ...]]\n"
456 "\nAvailable options:\n"
457 " -4|-6 force the use of IPv4 or IPv6\n"
458 " -c count number of ICMP packets to send\n"
459 " -i interval interval with which to send ICMP packets\n"
460 " -w timeout time to wait for replies, in seconds\n"
461 " -t ttl time to live for each ICMP packet\n"
462 " -Q qos Quality of Service (QoS) of outgoing packets\n"
463 " Use \"-Q help\" for a list of valid options.\n"
464 " -I srcaddr source address\n"
465 " -D device outgoing interface name\n"
466 " -m mark mark to set on outgoing packets\n"
467 " -f filename read hosts from <filename>\n"
468 " -O filename write RTT measurements to <filename>\n"
469 #if USE_NCURSES
470 " -u / -U force / disable UTF-8 output\n"
471 " -g graph graph type to draw\n"
472 #endif
473 " -P percent Report the n'th percentile of latency\n"
474 " -Z percent Exit with non-zero exit status if more than this percentage of\n"
475 " probes timed out. (default: never)\n"
477 "\noping "PACKAGE_VERSION", http://noping.cc/\n"
478 "by Florian octo Forster <ff@octo.it>\n"
479 "for contributions see `AUTHORS'\n",
480 name);
481 exit (status);
482 } /* }}} void usage_exit */
484 __attribute__((noreturn))
485 static void usage_qos_exit (const char *arg, int status) /* {{{ */
486 {
487 if (arg != 0)
488 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
490 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
491 "\n"
492 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
493 "\n"
494 " be Best Effort (BE, default PHB).\n"
495 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
496 " (low delay, low loss, low jitter)\n"
497 " va Voice Admit (VA) DSCP (RFC 5865).\n"
498 " (capacity-admitted traffic)\n"
499 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
500 " For example: \"af12\" (class 1, precedence 2)\n"
501 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
502 " For example: \"cs1\" (priority traffic)\n"
503 "\n"
504 " Type of Service (IPv4, RFC 1349, obsolete)\n"
505 "\n"
506 " lowdelay (%#04x) minimize delay\n"
507 " throughput (%#04x) maximize throughput\n"
508 " reliability (%#04x) maximize reliability\n"
509 " mincost (%#04x) minimize monetary cost\n"
510 "\n"
511 " Specify manually\n"
512 "\n"
513 " 0x00 - 0xff Hexadecimal numeric specification.\n"
514 " 0 - 255 Decimal numeric specification.\n"
515 "\n",
516 (unsigned int) IPTOS_LOWDELAY,
517 (unsigned int) IPTOS_THROUGHPUT,
518 (unsigned int) IPTOS_RELIABILITY,
519 (unsigned int) IPTOS_MINCOST);
521 exit (status);
522 } /* }}} void usage_qos_exit */
524 static int set_opt_send_qos (const char *opt) /* {{{ */
525 {
526 if (opt == NULL)
527 return (EINVAL);
529 if (strcasecmp ("help", opt) == 0)
530 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
531 /* DiffServ (RFC 2474): */
532 /* - Best effort (BE) */
533 else if (strcasecmp ("be", opt) == 0)
534 opt_send_qos = 0;
535 /* - Expedited Forwarding (EF, RFC 3246) */
536 else if (strcasecmp ("ef", opt) == 0)
537 opt_send_qos = 0xB8; /* == 0x2E << 2 */
538 /* - Voice Admit (VA, RFC 5865) */
539 else if (strcasecmp ("va", opt) == 0)
540 opt_send_qos = 0xB0; /* == 0x2D << 2 */
541 /* - Assured Forwarding (AF, RFC 2597) */
542 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
543 && (strlen (opt) == 4))
544 {
545 uint8_t dscp;
546 uint8_t class = 0;
547 uint8_t prec = 0;
549 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
550 if (opt[2] == '1')
551 class = 1;
552 else if (opt[2] == '2')
553 class = 2;
554 else if (opt[2] == '3')
555 class = 3;
556 else if (opt[2] == '4')
557 class = 4;
558 else
559 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
561 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
562 if (opt[3] == '1')
563 prec = 1;
564 else if (opt[3] == '2')
565 prec = 2;
566 else if (opt[3] == '3')
567 prec = 3;
568 else
569 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
571 dscp = (8 * class) + (2 * prec);
572 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
573 opt_send_qos = dscp << 2;
574 }
575 /* - Class Selector (CS) */
576 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
577 && (strlen (opt) == 3))
578 {
579 uint8_t class;
581 if ((opt[2] < '0') || (opt[2] > '7'))
582 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
584 /* Not exactly legal by the C standard, but I don't know of any
585 * system not supporting this hack. */
586 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
587 opt_send_qos = class << 5;
588 }
589 /* Type of Service (RFC 1349) */
590 else if (strcasecmp ("lowdelay", opt) == 0)
591 opt_send_qos = IPTOS_LOWDELAY;
592 else if (strcasecmp ("throughput", opt) == 0)
593 opt_send_qos = IPTOS_THROUGHPUT;
594 else if (strcasecmp ("reliability", opt) == 0)
595 opt_send_qos = IPTOS_RELIABILITY;
596 else if (strcasecmp ("mincost", opt) == 0)
597 opt_send_qos = IPTOS_MINCOST;
598 /* Numeric value */
599 else
600 {
601 unsigned long value;
602 char *endptr;
604 errno = 0;
605 endptr = NULL;
606 value = strtoul (opt, &endptr, /* base = */ 0);
607 if ((errno != 0) || (endptr == opt)
608 || (endptr == NULL) || (*endptr != 0)
609 || (value > 0xff))
610 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
612 opt_send_qos = (uint8_t) value;
613 }
615 return (0);
616 } /* }}} int set_opt_send_qos */
618 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
619 {
620 uint8_t dscp;
621 uint8_t ecn;
622 char *dscp_str;
623 char *ecn_str;
625 dscp = qos >> 2;
626 ecn = qos & 0x03;
628 switch (dscp)
629 {
630 case 0x00: dscp_str = "be"; break;
631 case 0x2e: dscp_str = "ef"; break;
632 case 0x2d: dscp_str = "va"; break;
633 case 0x0a: dscp_str = "af11"; break;
634 case 0x0c: dscp_str = "af12"; break;
635 case 0x0e: dscp_str = "af13"; break;
636 case 0x12: dscp_str = "af21"; break;
637 case 0x14: dscp_str = "af22"; break;
638 case 0x16: dscp_str = "af23"; break;
639 case 0x1a: dscp_str = "af31"; break;
640 case 0x1c: dscp_str = "af32"; break;
641 case 0x1e: dscp_str = "af33"; break;
642 case 0x22: dscp_str = "af41"; break;
643 case 0x24: dscp_str = "af42"; break;
644 case 0x26: dscp_str = "af43"; break;
645 case 0x08: dscp_str = "cs1"; break;
646 case 0x10: dscp_str = "cs2"; break;
647 case 0x18: dscp_str = "cs3"; break;
648 case 0x20: dscp_str = "cs4"; break;
649 case 0x28: dscp_str = "cs5"; break;
650 case 0x30: dscp_str = "cs6"; break;
651 case 0x38: dscp_str = "cs7"; break;
652 default: dscp_str = NULL;
653 }
655 switch (ecn)
656 {
657 case 0x01: ecn_str = ",ecn(1)"; break;
658 case 0x02: ecn_str = ",ecn(0)"; break;
659 case 0x03: ecn_str = ",ce"; break;
660 default: ecn_str = "";
661 }
663 if (dscp_str == NULL)
664 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
665 else
666 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
667 buffer[buffer_size - 1] = 0;
669 return (buffer);
670 } /* }}} char *format_qos */
672 static int read_options (int argc, char **argv) /* {{{ */
673 {
674 int optchar;
676 while (1)
677 {
678 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:O:P:m:w:b"
679 #if USE_NCURSES
680 "uUg:"
681 #endif
682 );
684 if (optchar == -1)
685 break;
687 switch (optchar)
688 {
689 case '4':
690 case '6':
691 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
692 break;
694 case 'c':
695 {
696 int new_count;
697 new_count = atoi (optarg);
698 if (new_count > 0)
699 {
700 opt_count = new_count;
702 if ((opt_percentile < 0.0) && (opt_count < 20))
703 opt_percentile = 100.0 * (opt_count - 1) / opt_count;
704 }
705 else
706 fprintf(stderr, "Ignoring invalid count: %s\n",
707 optarg);
708 }
709 break;
711 case 'f':
712 {
713 if (opt_filename != NULL)
714 free (opt_filename);
715 opt_filename = strdup (optarg);
716 }
717 break;
719 case 'i':
720 {
721 double new_interval;
722 new_interval = atof (optarg);
723 if (new_interval < 0.001)
724 fprintf (stderr, "Ignoring invalid interval: %s\n",
725 optarg);
726 else
727 opt_interval = new_interval;
728 }
729 break;
731 case 'w':
732 {
733 char *endp = NULL;
734 double t = strtod (optarg, &endp);
735 if ((optarg[0] != 0) && (endp != NULL) && (*endp == 0))
736 opt_timeout = t;
737 else
738 fprintf (stderr, "Ignoring invalid timeout: %s\n",
739 optarg);
740 }
741 break;
743 case 'I':
744 {
745 if (opt_srcaddr != NULL)
746 free (opt_srcaddr);
747 opt_srcaddr = strdup (optarg);
748 }
749 break;
751 case 'D':
752 opt_device = optarg;
753 break;
755 case 'm':
756 opt_mark = optarg;
757 break;
759 case 't':
760 {
761 int new_send_ttl;
762 new_send_ttl = atoi (optarg);
763 if ((new_send_ttl > 0) && (new_send_ttl < 256))
764 opt_send_ttl = new_send_ttl;
765 else
766 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
767 optarg);
768 break;
769 }
771 case 'Q':
772 set_opt_send_qos (optarg);
773 break;
775 case 'O':
776 {
777 free (opt_outfile);
778 opt_outfile = strdup (optarg);
779 }
780 break;
782 case 'P':
783 {
784 double new_percentile;
785 new_percentile = atof (optarg);
786 if (isnan (new_percentile)
787 || (new_percentile < 0.1)
788 || (new_percentile > 100.0))
789 fprintf (stderr, "Ignoring invalid percentile: %s\n",
790 optarg);
791 else
792 opt_percentile = new_percentile;
793 }
794 break;
796 #if USE_NCURSES
797 case 'g':
798 if (strcasecmp ("none", optarg) == 0)
799 opt_show_graph = 0;
800 else if (strcasecmp ("prettyping", optarg) == 0)
801 opt_show_graph = 1;
802 else if (strcasecmp ("histogram", optarg) == 0)
803 opt_show_graph = 2;
804 else if (strcasecmp ("boxplot", optarg) == 0)
805 opt_show_graph = 3;
806 else
807 fprintf (stderr, "Unknown graph option: %s\n", optarg);
808 break;
810 case 'u':
811 opt_utf8 = 2;
812 break;
813 case 'U':
814 opt_utf8 = 1;
815 break;
816 #endif
817 case 'b':
818 opt_bell = 1;
819 break;
821 case 'Z':
822 {
823 char *endptr = NULL;
824 double tmp;
826 errno = 0;
827 tmp = strtod (optarg, &endptr);
828 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
829 {
830 fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
831 fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
832 }
833 else
834 opt_exit_status_threshold = tmp / 100.0;
836 break;
837 }
839 case 'h':
840 usage_exit (argv[0], 0);
841 break;
843 default:
844 usage_exit (argv[0], 1);
845 }
846 }
848 if (opt_percentile <= 0.0)
849 opt_percentile = OPING_DEFAULT_PERCENTILE;
851 return (optind);
852 } /* }}} read_options */
854 static void time_normalize (struct timespec *ts) /* {{{ */
855 {
856 while (ts->tv_nsec < 0)
857 {
858 if (ts->tv_sec == 0)
859 {
860 ts->tv_nsec = 0;
861 return;
862 }
864 ts->tv_sec -= 1;
865 ts->tv_nsec += 1000000000;
866 }
868 while (ts->tv_nsec >= 1000000000)
869 {
870 ts->tv_sec += 1;
871 ts->tv_nsec -= 1000000000;
872 }
873 } /* }}} void time_normalize */
875 static void time_calc (struct timespec *ts_dest, /* {{{ */
876 const struct timespec *ts_int,
877 const struct timeval *tv_begin,
878 const struct timeval *tv_end)
879 {
880 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
881 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
882 time_normalize (ts_dest);
884 /* Assure that `(begin + interval) > end'.
885 * This may seem overly complicated, but `tv_sec' is of type `time_t'
886 * which may be `unsigned. *sigh* */
887 if ((tv_end->tv_sec > ts_dest->tv_sec)
888 || ((tv_end->tv_sec == ts_dest->tv_sec)
889 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
890 {
891 ts_dest->tv_sec = 0;
892 ts_dest->tv_nsec = 0;
893 return;
894 }
896 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
897 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
898 time_normalize (ts_dest);
899 } /* }}} void time_calc */
901 #if USE_NCURSES
902 static _Bool has_utf8() /* {{{ */
903 {
904 # if HAVE_NCURSESW_NCURSES_H
905 if (!opt_utf8)
906 {
907 /* Automatically determine */
908 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
909 opt_utf8 = 2;
910 else
911 opt_utf8 = 1;
912 }
913 return ((_Bool) (opt_utf8 - 1));
914 # else
915 return (0);
916 # endif
917 } /* }}} _Bool has_utf8 */
919 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
920 {
921 uint32_t *counters;
922 double *ratios;
923 size_t i;
924 size_t x_max;
925 size_t x;
927 clean_history (ctx);
929 if (ctx->history_received == 0)
930 return (ENOENT);
932 x_max = (size_t) getmaxx (ctx->window);
933 if (x_max <= 8)
934 return (EINVAL);
935 x_max -= 4;
937 counters = calloc (x_max, sizeof (*counters));
938 ratios = calloc (x_max, sizeof (*ratios));
940 /* Bucketize */
941 for (i = 0; i < ctx->history_received; i++)
942 {
943 double latency = ctx->history_by_value[i] / 1000.0;
944 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
946 if (index >= x_max)
947 index = x_max - 1;
949 counters[index]++;
950 }
952 /* Sum and calc ratios */
953 ratios[0] = ((double) counters[0]) / ((double) ctx->history_received);
954 for (x = 1; x < x_max; x++)
955 {
956 counters[x] += counters[x - 1];
957 ratios[x] = ((double) counters[x]) / ((double) ctx->history_received);
958 }
960 for (x = 0; x < x_max; x++)
961 {
962 int symbol = ' ';
963 _Bool reverse = 0;
965 if (x == 0)
966 {
967 if (ratios[x] >= 0.5)
968 {
969 symbol = BOXPLOT_MEDIAN;
970 reverse = 1;
971 }
972 else if (ratios[x] > 0.25)
973 {
974 symbol = BOXPLOT_BOX;
975 reverse = 1;
976 }
977 else if (ratios[x] > 0.025)
978 symbol = BOXPLOT_WHISKER_BAR;
979 else
980 symbol = ' '; /* NOP */
981 }
982 else /* (x != 0) */
983 {
984 if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
985 {
986 symbol = BOXPLOT_MEDIAN;
987 reverse = 1;
988 }
989 else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
990 || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
991 {
992 symbol = BOXPLOT_BOX;
993 reverse = 1;
994 }
995 else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
996 {
997 if (ratios[x - 1] < 0.025)
998 symbol = BOXPLOT_WHISKER_LEFT_END;
999 else
1000 symbol = BOXPLOT_WHISKER_BAR;
1001 }
1002 else if ((ratios[x] > .5) && (ratios[x] < 0.975))
1003 {
1004 symbol = BOXPLOT_WHISKER_BAR;
1005 }
1006 else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
1007 symbol = BOXPLOT_WHISKER_RIGHT_END;
1008 }
1010 if (reverse)
1011 wattron (ctx->window, A_REVERSE);
1012 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
1013 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
1014 if (reverse)
1015 wattroff (ctx->window, A_REVERSE);
1016 }
1018 free (counters);
1019 free (ratios);
1020 return (0);
1021 } /* }}} int update_graph_boxplot */
1023 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
1024 double latency)
1025 {
1026 size_t x;
1027 size_t x_max;
1028 size_t history_offset;
1030 x_max = (size_t) getmaxx (ctx->window);
1031 if (x_max <= 4)
1032 return (EINVAL);
1033 x_max -= 4;
1035 /* Determine the first index in the history we need to draw
1036 * the graph. */
1037 history_offset = 0;
1038 if (((size_t) x_max) < ctx->history_size) /* window is smaller than history */
1039 {
1040 if (ctx->history_index > x_max)
1041 history_offset = ctx->history_index - x_max;
1042 else /* wrap around */
1043 history_offset = ctx->history_index + ctx->history_size - x_max;
1044 }
1045 else /* window is larger than history */
1046 {
1047 if (ctx->history_index != ctx->history_size) /* no longer growing. */
1048 history_offset = ctx->history_index;
1049 else /* start-up */
1050 history_offset = 0;
1051 }
1053 for (x = 0; x < x_max; x++)
1054 {
1055 size_t index;
1056 double latency;
1058 int color = OPING_RED;
1059 char const *symbol = "!";
1060 int symbolc = '!';
1062 if (x >= ctx->history_size)
1063 {
1064 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1065 continue;
1066 }
1068 index = (history_offset + x) % ctx->history_size;
1069 latency = ctx->history_by_time[index];
1071 if (latency < 0) {
1072 continue;
1073 }
1075 if (latency >= 0.0)
1076 {
1077 double ratio;
1079 size_t symbols_num = hist_symbols_acs_num;
1080 size_t colors_num = 1;
1082 size_t index_symbols;
1083 size_t index_colors;
1084 size_t intensity;
1086 /* latency is in milliseconds, opt_interval is in seconds. */
1087 ratio = (latency * 0.001) / opt_interval;
1088 if (ratio > 1) {
1089 ratio = 1.0;
1090 }
1092 if (has_utf8 ())
1093 symbols_num = hist_symbols_utf8_num;
1095 if (has_colors () == TRUE)
1096 colors_num = hist_colors_num;
1098 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
1099 if (intensity >= (symbols_num * colors_num))
1100 intensity = (symbols_num * colors_num) - 1;
1102 index_symbols = intensity % symbols_num;
1103 assert (index_symbols < symbols_num);
1105 index_colors = intensity / symbols_num;
1106 assert (index_colors < colors_num);
1108 if (has_utf8())
1109 {
1110 color = hist_colors_utf8[index_colors];
1111 symbol = hist_symbols_utf8[index_symbols];
1112 }
1113 else
1114 {
1115 color = hist_colors_acs[index_colors];
1116 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
1117 }
1118 }
1119 else /* if (!(latency >= 0.0)) */
1120 wattron (ctx->window, A_BOLD);
1122 if (has_colors () == TRUE)
1123 wattron (ctx->window, COLOR_PAIR(color));
1125 if (has_utf8())
1126 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2, symbol);
1127 else
1128 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, symbolc);
1130 if (has_colors () == TRUE)
1131 wattroff (ctx->window, COLOR_PAIR(color));
1133 /* Use negation here to handle NaN correctly. */
1134 if (!(latency >= 0.0))
1135 wattroff (ctx->window, A_BOLD);
1136 } /* for (x) */
1138 return (0);
1139 } /* }}} int update_graph_prettyping */
1141 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
1142 {
1143 uint32_t *counters;
1144 uint32_t *accumulated;
1145 uint32_t max;
1146 size_t i;
1147 size_t x_max;
1148 size_t x;
1150 size_t symbols_num = hist_symbols_acs_num;
1152 clean_history (ctx);
1154 if (ctx->history_received == 0)
1155 return (ENOENT);
1157 if (has_utf8 ())
1158 symbols_num = hist_symbols_utf8_num;
1160 x_max = (size_t) getmaxx (ctx->window);
1161 if (x_max <= 4)
1162 return (EINVAL);
1163 x_max -= 4;
1165 counters = calloc (x_max, sizeof (*counters));
1166 accumulated = calloc (x_max, sizeof (*accumulated));
1168 /* Bucketize */
1169 max = 0;
1170 for (i = 0; i < ctx->history_received; i++)
1171 {
1172 double latency = ctx->history_by_value[i] / 1000.0;
1173 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
1175 if (index >= x_max)
1176 index = x_max - 1;
1178 counters[index]++;
1179 if (max < counters[index])
1180 max = counters[index];
1181 }
1183 /* Sum */
1184 accumulated[0] = counters[0];
1185 for (x = 1; x < x_max; x++)
1186 accumulated[x] = counters[x] + accumulated[x - 1];
1188 /* Calculate ratios */
1189 for (x = 0; x < x_max; x++)
1190 {
1191 double height = ((double) counters[x]) / ((double) max);
1192 double ratio_this = ((double) accumulated[x]) / ((double) ctx->history_received);
1193 double ratio_prev = 0.0;
1194 size_t index;
1195 int color = 0;
1197 index = (size_t) (height * ((double) symbols_num));
1198 if (index >= symbols_num)
1199 index = symbols_num - 1;
1201 if (x > 0)
1202 ratio_prev = ((double) accumulated[x - 1]) / ((double) ctx->history_received);
1204 if (has_colors () == TRUE)
1205 {
1206 if ((ratio_this <= threshold_green)
1207 || ((ratio_prev < threshold_green)
1208 && (ratio_this > threshold_green)))
1209 color = OPING_GREEN;
1210 else if ((ratio_this <= threshold_yellow)
1211 || ((ratio_prev < threshold_yellow)
1212 && (ratio_this > threshold_yellow)))
1213 color = OPING_YELLOW;
1214 else
1215 color = OPING_RED;
1217 wattron (ctx->window, COLOR_PAIR(color));
1218 }
1220 if (counters[x] == 0)
1221 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1222 else if (has_utf8 ())
1223 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1224 hist_symbols_utf8[index]);
1225 else
1226 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1227 hist_symbols_acs[index] | A_ALTCHARSET);
1229 if (has_colors () == TRUE)
1230 wattroff (ctx->window, COLOR_PAIR(color));
1232 }
1234 free (accumulated);
1235 return (0);
1236 } /* }}} int update_graph_histogram */
1238 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1239 {
1240 double latency = -1.0;
1241 size_t buffer_len = sizeof (latency);
1243 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1244 &latency, &buffer_len);
1246 if ((ctx == NULL) || (ctx->window == NULL))
1247 return (EINVAL);
1249 /* werase (ctx->window); */
1251 box (ctx->window, 0, 0);
1252 wattron (ctx->window, A_BOLD);
1253 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1254 " %s ", ctx->host);
1255 wattroff (ctx->window, A_BOLD);
1256 wprintw (ctx->window, "ping statistics ");
1257 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1258 "%i packets transmitted, %i received, %.2f%% packet "
1259 "loss, time %.1fms",
1260 ctx->req_sent, ctx->req_rcvd,
1261 context_get_packet_loss (ctx),
1262 ctx->latency_total);
1263 if (ctx->req_rcvd != 0)
1264 {
1265 double min;
1266 double median;
1267 double max;
1268 double percentile;
1270 min = percentile_to_latency (ctx, 0.0);
1271 median = percentile_to_latency (ctx, 50.0);
1272 max = percentile_to_latency (ctx, 100.0);
1273 percentile = percentile_to_latency (ctx, opt_percentile);
1275 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1276 "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f ",
1277 min, median, opt_percentile, percentile, max);
1278 }
1280 if (opt_show_graph == 1)
1281 update_graph_prettyping (ctx, latency);
1282 else if (opt_show_graph == 2)
1283 update_graph_histogram (ctx);
1284 else if (opt_show_graph == 3)
1285 update_graph_boxplot (ctx);
1287 wrefresh (ctx->window);
1289 return (0);
1290 } /* }}} int update_stats_from_context */
1292 static int on_resize (pingobj_t *ping) /* {{{ */
1293 {
1294 pingobj_iter_t *iter;
1295 int width = 0;
1296 int height = 0;
1297 int main_win_height;
1298 int box_height = (opt_show_graph == 0) ? 4 : 5;
1300 getmaxyx (stdscr, height, width);
1301 if ((height < 1) || (width < 1))
1302 return (EINVAL);
1304 main_win_height = height - (box_height * host_num);
1305 wresize (main_win, main_win_height, /* width = */ width);
1306 /* Allow scrolling */
1307 scrollok (main_win, TRUE);
1308 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1309 /* Allow hardware accelerated scrolling. */
1310 idlok (main_win, TRUE);
1311 wrefresh (main_win);
1313 for (iter = ping_iterator_get (ping);
1314 iter != NULL;
1315 iter = ping_iterator_next (iter))
1316 {
1317 ping_context_t *context;
1319 context = ping_iterator_get_context (iter);
1320 if (context == NULL)
1321 continue;
1323 if (context->window != NULL)
1324 {
1325 delwin (context->window);
1326 context->window = NULL;
1327 }
1328 context->window = newwin (/* height = */ box_height,
1329 /* width = */ width,
1330 /* y = */ main_win_height + (box_height * context->index),
1331 /* x = */ 0);
1332 }
1334 return (0);
1335 } /* }}} */
1337 static int check_resize (pingobj_t *ping) /* {{{ */
1338 {
1339 int need_resize = 0;
1341 while (42)
1342 {
1343 int key = wgetch (stdscr);
1344 if (key == ERR)
1345 break;
1346 else if (key == KEY_RESIZE)
1347 need_resize = 1;
1348 else if (key == 'g')
1349 {
1350 if (opt_show_graph == 3)
1351 opt_show_graph = 1;
1352 else if (opt_show_graph > 0)
1353 opt_show_graph++;
1354 }
1355 else if (key == 'a')
1356 {
1357 char host[80];
1359 wprintw(main_win, "New Host: ");
1360 echo();
1361 wgetnstr(main_win, host, sizeof(host));
1362 noecho();
1364 if (ping_host_add(ping, host) < 0)
1365 {
1366 const char *errmsg = ping_get_error (ping);
1368 wprintw (main_win, "Adding host `%s' failed: %s\n", host, errmsg);
1369 }
1370 else
1371 {
1372 int box_height = (opt_show_graph == 0) ? 4 : 5;
1374 /* make sure old data is still visible */
1375 for (int i = 0; i<box_height; i++)
1376 wprintw (main_win, "\n");
1378 need_resize = 1;
1379 host_num++;
1380 ping_initialize_contexts(ping);
1381 }
1382 }
1383 }
1385 if (need_resize)
1386 return (on_resize (ping));
1387 else
1388 return (0);
1389 } /* }}} int check_resize */
1391 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1392 {
1393 pingobj_iter_t *iter;
1394 int width = 0;
1395 int height = 0;
1396 int main_win_height;
1397 int box_height = (opt_show_graph == 0) ? 4 : 5;
1399 initscr ();
1400 cbreak ();
1401 noecho ();
1402 nodelay (stdscr, TRUE);
1404 getmaxyx (stdscr, height, width);
1405 if ((height < 1) || (width < 1))
1406 return (EINVAL);
1408 if (has_colors () == TRUE)
1409 {
1410 start_color ();
1411 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
1412 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1413 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
1414 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
1415 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1416 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
1417 }
1419 main_win_height = height - (box_height * host_num);
1420 main_win = newwin (/* height = */ main_win_height,
1421 /* width = */ width,
1422 /* y = */ 0, /* x = */ 0);
1423 /* Allow scrolling */
1424 scrollok (main_win, TRUE);
1425 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1426 /* Allow hardware accelerated scrolling. */
1427 idlok (main_win, TRUE);
1428 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1429 wrefresh (main_win);
1431 for (iter = ping_iterator_get (ping);
1432 iter != NULL;
1433 iter = ping_iterator_next (iter))
1434 {
1435 ping_context_t *context;
1437 context = ping_iterator_get_context (iter);
1438 if (context == NULL)
1439 continue;
1441 if (context->window != NULL)
1442 {
1443 delwin (context->window);
1444 context->window = NULL;
1445 }
1446 context->window = newwin (/* height = */ box_height,
1447 /* width = */ width,
1448 /* y = */ main_win_height + (box_height * context->index),
1449 /* x = */ 0);
1450 }
1453 /* Don't know what good this does exactly, but without this code
1454 * "check_resize" will be called right after startup and *somehow*
1455 * this leads to display errors. If we purge all initial characters
1456 * here, the problem goes away. "wgetch" is non-blocking due to
1457 * "nodelay" (see above). */
1458 while (wgetch (stdscr) != ERR)
1459 {
1460 /* eat up characters */;
1461 }
1463 return (0);
1464 } /* }}} int pre_loop_hook */
1466 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1467 {
1468 return (check_resize (ping));
1469 } /* }}} int pre_sleep_hook */
1471 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1472 {
1473 return (check_resize (ping));
1474 } /* }}} int pre_sleep_hook */
1475 #else /* if !USE_NCURSES */
1476 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1477 {
1478 pingobj_iter_t *iter;
1480 for (iter = ping_iterator_get (ping);
1481 iter != NULL;
1482 iter = ping_iterator_next (iter))
1483 {
1484 ping_context_t *ctx;
1485 size_t buffer_size;
1487 ctx = ping_iterator_get_context (iter);
1488 if (ctx == NULL)
1489 continue;
1491 buffer_size = 0;
1492 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1494 printf ("PING %s (%s) %zu bytes of data.\n",
1495 ctx->host, ctx->addr, buffer_size);
1496 }
1498 return (0);
1499 } /* }}} int pre_loop_hook */
1501 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1502 {
1503 fflush (stdout);
1505 return (0);
1506 } /* }}} int pre_sleep_hook */
1508 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1509 {
1510 return (0);
1511 } /* }}} int post_sleep_hook */
1512 #endif
1514 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1515 {
1516 ctx->req_sent++;
1518 if (latency > 0.0)
1519 {
1520 ctx->req_rcvd++;
1521 ctx->latency_total += latency;
1522 }
1523 else
1524 {
1525 latency = NAN;
1526 }
1528 ctx->history_by_time[ctx->history_index] = latency;
1530 ctx->history_dirty = 1;
1532 /* Update index and size. */
1533 ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1534 if (ctx->history_size < HISTORY_SIZE_MAX)
1535 ctx->history_size++;
1536 } /* }}} void update_context */
1538 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1539 __attribute__((unused)) int index)
1540 {
1541 double latency;
1542 unsigned int sequence;
1543 int recv_ttl;
1544 uint8_t recv_qos;
1545 char recv_qos_str[16];
1546 size_t buffer_len;
1547 size_t data_len;
1548 ping_context_t *context;
1550 latency = -1.0;
1551 buffer_len = sizeof (latency);
1552 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1553 &latency, &buffer_len);
1555 sequence = 0;
1556 buffer_len = sizeof (sequence);
1557 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1558 &sequence, &buffer_len);
1560 recv_ttl = -1;
1561 buffer_len = sizeof (recv_ttl);
1562 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1563 &recv_ttl, &buffer_len);
1565 recv_qos = 0;
1566 buffer_len = sizeof (recv_qos);
1567 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1568 &recv_qos, &buffer_len);
1570 data_len = 0;
1571 ping_iterator_get_info (iter, PING_INFO_DATA,
1572 NULL, &data_len);
1574 context = (ping_context_t *) ping_iterator_get_context (iter);
1576 #if USE_NCURSES
1577 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1578 #else
1579 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1580 #endif
1582 update_context (context, latency);
1584 if (latency > 0.0)
1585 {
1586 #if USE_NCURSES
1587 if (has_colors () == TRUE)
1588 {
1589 double ratio;
1590 int color = OPING_GREEN;
1592 ratio = latency_to_ratio (context, latency);
1593 if (ratio < threshold_green)
1594 color = OPING_GREEN;
1595 else if (ratio < threshold_yellow)
1596 color = OPING_YELLOW;
1597 else
1598 color = OPING_RED;
1600 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1601 data_len, context->host, context->addr,
1602 sequence, recv_ttl,
1603 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1604 if ((recv_qos != 0) || (opt_send_qos != 0))
1605 {
1606 HOST_PRINTF ("qos=%s ",
1607 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1608 }
1609 HOST_PRINTF ("time=");
1610 wattron (main_win, COLOR_PAIR(color));
1611 HOST_PRINTF ("%.2f", latency);
1612 wattroff (main_win, COLOR_PAIR(color));
1613 HOST_PRINTF (" ms\n");
1614 }
1615 else
1616 {
1617 #endif
1618 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1619 data_len,
1620 context->host, context->addr,
1621 sequence, recv_ttl);
1622 if ((recv_qos != 0) || (opt_send_qos != 0))
1623 {
1624 HOST_PRINTF ("qos=%s ",
1625 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1626 }
1627 HOST_PRINTF ("time=%.2f ms\n", latency);
1628 #if USE_NCURSES
1629 }
1630 #endif
1631 if (opt_bell) {
1632 #if USE_NCURSES
1633 beep();
1634 #else
1635 HOST_PRINTF ("\a");
1636 #endif
1637 }
1638 }
1639 else /* if (!(latency > 0.0)) */
1640 {
1641 #if USE_NCURSES
1642 if (has_colors () == TRUE)
1643 {
1644 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1645 context->host, context->addr,
1646 sequence);
1647 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1648 HOST_PRINTF ("timeout");
1649 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1650 HOST_PRINTF ("\n");
1651 }
1652 else
1653 {
1654 #endif
1655 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1656 context->host, context->addr,
1657 sequence);
1658 #if USE_NCURSES
1659 }
1660 #endif
1661 }
1663 if (outfile != NULL)
1664 {
1665 struct timespec ts = { 0, 0 };
1667 if (clock_gettime (CLOCK_REALTIME, &ts) == 0)
1668 {
1669 double t = ((double) ts.tv_sec) + (((double) ts.tv_nsec) / 1000000000.0);
1671 if ((sequence % 32) == 0)
1672 fprintf (outfile, "#time,host,latency[ms]\n");
1674 fprintf (outfile, "%.3f,\"%s\",%.2f\n", t, context->host, latency);
1675 }
1676 }
1678 #if USE_NCURSES
1679 update_stats_from_context (context, iter);
1680 wrefresh (main_win);
1681 #endif
1682 } /* }}} void update_host_hook */
1684 /* Prints statistics for each host, cleans up the contexts and returns the
1685 * number of hosts which failed to return more than the fraction
1686 * opt_exit_status_threshold of pings. */
1687 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1688 {
1689 pingobj_iter_t *iter;
1690 int failure_count = 0;
1692 #if USE_NCURSES
1693 endwin ();
1694 #endif
1696 for (iter = ping_iterator_get (ping);
1697 iter != NULL;
1698 iter = ping_iterator_next (iter))
1699 {
1700 ping_context_t *context;
1702 context = ping_iterator_get_context (iter);
1704 printf ("\n--- %s ping statistics ---\n"
1705 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1706 context->host, context->req_sent, context->req_rcvd,
1707 context_get_packet_loss (context),
1708 context->latency_total);
1710 {
1711 double pct_failed = 1.0 - (((double) context->req_rcvd)
1712 / ((double) context->req_sent));
1713 if (pct_failed > opt_exit_status_threshold)
1714 failure_count++;
1715 }
1717 if (context->req_rcvd != 0)
1718 {
1719 double min;
1720 double median;
1721 double max;
1722 double percentile;
1724 min = percentile_to_latency (context, 0.0);
1725 median = percentile_to_latency (context, 50.0);
1726 max = percentile_to_latency (context, 100.0);
1727 percentile = percentile_to_latency (context, opt_percentile);
1729 printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1730 min, median, opt_percentile, percentile, max);
1731 }
1733 ping_iterator_set_context (iter, NULL);
1734 context_destroy (context);
1735 }
1737 return (failure_count);
1738 } /* }}} int post_loop_hook */
1740 int main (int argc, char **argv) /* {{{ */
1741 {
1742 pingobj_t *ping;
1743 pingobj_iter_t *iter;
1745 struct sigaction sigint_action;
1747 struct timeval tv_begin;
1748 struct timeval tv_end;
1749 struct timespec ts_wait;
1750 struct timespec ts_int;
1752 int optind;
1753 int i;
1754 int status;
1755 #if _POSIX_SAVED_IDS
1756 uid_t saved_set_uid;
1758 /* Save the old effective user id */
1759 saved_set_uid = geteuid ();
1760 /* Set the effective user ID to the real user ID without changing the
1761 * saved set-user ID */
1762 status = seteuid (getuid ());
1763 if (status != 0)
1764 {
1765 fprintf (stderr, "Temporarily dropping privileges "
1766 "failed: %s\n", strerror (errno));
1767 exit (EXIT_FAILURE);
1768 }
1769 #endif
1771 setlocale(LC_ALL, "");
1772 optind = read_options (argc, argv);
1774 #if !_POSIX_SAVED_IDS
1775 /* Cannot temporarily drop privileges -> reject every file but "-". */
1776 if ((opt_filename != NULL)
1777 && (strcmp ("-", opt_filename) != 0)
1778 && (getuid () != geteuid ()))
1779 {
1780 fprintf (stderr, "Your real and effective user IDs don't "
1781 "match. Reading from a file (option '-f')\n"
1782 "is therefore too risky. You can still read "
1783 "from STDIN using '-f -' if you like.\n"
1784 "Sorry.\n");
1785 exit (EXIT_FAILURE);
1786 }
1787 #endif
1789 if ((optind >= argc) && (opt_filename == NULL)) {
1790 usage_exit (argv[0], 1);
1791 }
1793 if ((ping = ping_construct ()) == NULL)
1794 {
1795 fprintf (stderr, "ping_construct failed\n");
1796 return (1);
1797 }
1799 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1800 {
1801 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1802 opt_send_ttl, ping_get_error (ping));
1803 }
1805 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1806 {
1807 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1808 opt_send_qos, ping_get_error (ping));
1809 }
1811 {
1812 double temp_sec;
1813 double temp_nsec;
1815 temp_nsec = modf (opt_interval, &temp_sec);
1816 ts_int.tv_sec = (time_t) temp_sec;
1817 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1819 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1820 }
1822 if (ping_setopt (ping, PING_OPT_TIMEOUT, (void*)(&opt_timeout)) != 0)
1823 {
1824 fprintf (stderr, "Setting timeout failed: %s\n",
1825 ping_get_error (ping));
1826 }
1828 if (opt_addrfamily != PING_DEF_AF)
1829 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1831 if (opt_srcaddr != NULL)
1832 {
1833 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1834 {
1835 fprintf (stderr, "Setting source address failed: %s\n",
1836 ping_get_error (ping));
1837 }
1838 }
1840 if (opt_device != NULL)
1841 {
1842 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1843 {
1844 fprintf (stderr, "Setting device failed: %s\n",
1845 ping_get_error (ping));
1846 }
1847 }
1849 if (opt_mark != NULL)
1850 {
1851 char *endp = NULL;
1852 int mark = (int) strtol (opt_mark, &endp, /* base = */ 0);
1853 if ((opt_mark[0] != 0) && (endp != NULL) && (*endp == 0))
1854 {
1855 if (ping_setopt(ping, PING_OPT_MARK, (void*)(&mark)) != 0)
1856 {
1857 fprintf (stderr, "Setting mark failed: %s\n",
1858 ping_get_error (ping));
1859 }
1860 }
1861 else
1862 {
1863 fprintf(stderr, "Ignoring invalid mark: %s\n", optarg);
1864 }
1865 }
1867 if (opt_filename != NULL)
1868 {
1869 FILE *infile;
1870 char line[256];
1871 char host[256];
1873 if (strcmp (opt_filename, "-") == 0)
1874 /* Open STDIN */
1875 infile = fdopen(0, "r");
1876 else
1877 infile = fopen(opt_filename, "r");
1879 if (infile == NULL)
1880 {
1881 fprintf (stderr, "Opening %s failed: %s\n",
1882 (strcmp (opt_filename, "-") == 0)
1883 ? "STDIN" : opt_filename,
1884 strerror(errno));
1885 return (1);
1886 }
1888 #if _POSIX_SAVED_IDS
1889 /* Regain privileges */
1890 status = seteuid (saved_set_uid);
1891 if (status != 0)
1892 {
1893 fprintf (stderr, "Temporarily re-gaining privileges "
1894 "failed: %s\n", strerror (errno));
1895 exit (EXIT_FAILURE);
1896 }
1897 #endif
1899 while (fgets(line, sizeof(line), infile))
1900 {
1901 /* Strip whitespace */
1902 if (sscanf(line, "%s", host) != 1)
1903 continue;
1905 if ((host[0] == 0) || (host[0] == '#'))
1906 continue;
1908 if (ping_host_add(ping, host) < 0)
1909 {
1910 const char *errmsg = ping_get_error (ping);
1912 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1913 continue;
1914 }
1915 else
1916 {
1917 host_num++;
1918 }
1919 }
1921 #if _POSIX_SAVED_IDS
1922 /* Drop privileges */
1923 status = seteuid (getuid ());
1924 if (status != 0)
1925 {
1926 fprintf (stderr, "Temporarily dropping privileges "
1927 "failed: %s\n", strerror (errno));
1928 exit (EXIT_FAILURE);
1929 }
1930 #endif
1932 fclose(infile);
1933 }
1935 #if _POSIX_SAVED_IDS
1936 /* Regain privileges */
1937 status = seteuid (saved_set_uid);
1938 if (status != 0)
1939 {
1940 fprintf (stderr, "Temporarily re-gaining privileges "
1941 "failed: %s\n", strerror (errno));
1942 exit (EXIT_FAILURE);
1943 }
1944 #endif
1946 for (i = optind; i < argc; i++)
1947 {
1948 if (ping_host_add (ping, argv[i]) < 0)
1949 {
1950 const char *errmsg = ping_get_error (ping);
1952 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1953 continue;
1954 }
1955 else
1956 {
1957 host_num++;
1958 }
1959 }
1961 /* Permanently drop root privileges if we're setuid-root. */
1962 status = setuid (getuid ());
1963 if (status != 0)
1964 {
1965 fprintf (stderr, "Dropping privileges failed: %s\n",
1966 strerror (errno));
1967 exit (EXIT_FAILURE);
1968 }
1970 if (host_num == 0)
1971 exit (EXIT_FAILURE);
1973 #if _POSIX_SAVED_IDS
1974 saved_set_uid = (uid_t) -1;
1975 #endif
1977 if (opt_outfile != NULL)
1978 {
1979 outfile = fopen (opt_outfile, "a");
1980 if (outfile == NULL)
1981 {
1982 fprintf (stderr, "opening \"%s\" failed: %s\n",
1983 opt_outfile, strerror (errno));
1984 exit (EXIT_FAILURE);
1985 }
1986 }
1988 ping_initialize_contexts (ping);
1990 if (i == 0)
1991 return (1);
1993 memset (&sigint_action, '\0', sizeof (sigint_action));
1994 sigint_action.sa_handler = sigint_handler;
1995 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1996 {
1997 perror ("sigaction");
1998 return (1);
1999 }
2001 pre_loop_hook (ping);
2003 while (opt_count != 0)
2004 {
2005 int index;
2006 int status;
2008 if (gettimeofday (&tv_begin, NULL) < 0)
2009 {
2010 perror ("gettimeofday");
2011 return (1);
2012 }
2014 status = ping_send (ping);
2015 if (status == -EINTR)
2016 {
2017 continue;
2018 }
2019 else if (status < 0)
2020 {
2021 fprintf (stderr, "ping_send failed: %s\n",
2022 ping_get_error (ping));
2023 return (1);
2024 }
2026 index = 0;
2027 for (iter = ping_iterator_get (ping);
2028 iter != NULL;
2029 iter = ping_iterator_next (iter))
2030 {
2031 update_host_hook (iter, index);
2032 index++;
2033 }
2035 pre_sleep_hook (ping);
2037 /* Don't sleep in the last iteration */
2038 if (opt_count == 1)
2039 break;
2041 if (gettimeofday (&tv_end, NULL) < 0)
2042 {
2043 perror ("gettimeofday");
2044 return (1);
2045 }
2047 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
2049 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
2050 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
2051 {
2052 if (errno == EINTR)
2053 {
2054 continue;
2055 }
2056 else
2057 {
2058 perror ("nanosleep");
2059 break;
2060 }
2061 }
2063 post_sleep_hook (ping);
2065 if (opt_count > 0)
2066 opt_count--;
2067 } /* while (opt_count != 0) */
2069 /* Returns the number of failed hosts according to -Z. */
2070 status = post_loop_hook (ping);
2072 ping_destroy (ping);
2074 if (outfile != NULL)
2075 {
2076 fclose (outfile);
2077 outfile = NULL;
2078 }
2080 if (status == 0)
2081 exit (EXIT_SUCCESS);
2082 else
2083 {
2084 if (status > 255)
2085 status = 255;
2086 exit (status);
2087 }
2088 } /* }}} int main */
2090 /* vim: set fdm=marker : */