1 /**
2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2014 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
212 static int host_num = 0;
214 #if USE_NCURSES
215 static WINDOW *main_win = NULL;
216 #endif
218 static void sigint_handler (int signal) /* {{{ */
219 {
220 /* Make compiler happy */
221 signal = 0;
222 /* Exit the loop */
223 opt_count = 0;
224 } /* }}} void sigint_handler */
226 static ping_context_t *context_create (void) /* {{{ */
227 {
228 ping_context_t *ret;
230 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
231 return (NULL);
233 memset (ret, '\0', sizeof (ping_context_t));
235 ret->latency_total = 0.0;
237 #if USE_NCURSES
238 ret->window = NULL;
239 #endif
241 return (ret);
242 } /* }}} ping_context_t *context_create */
244 static void context_destroy (ping_context_t *context) /* {{{ */
245 {
246 if (context == NULL)
247 return;
249 #if USE_NCURSES
250 if (context->window != NULL)
251 {
252 delwin (context->window);
253 context->window = NULL;
254 }
255 #endif
257 free (context);
258 } /* }}} void context_destroy */
260 static int compare_double (void const *arg0, void const *arg1) /* {{{ */
261 {
262 double dbl0 = *((double *) arg0);
263 double dbl1 = *((double *) arg1);
265 if (isnan (dbl0))
266 {
267 if (isnan (dbl1))
268 return 0;
269 else
270 return 1;
271 }
272 else if (isnan (dbl1))
273 return -1;
274 else if (dbl0 < dbl1)
275 return -1;
276 else if (dbl0 > dbl1)
277 return 1;
278 else
279 return 0;
280 } /* }}} int compare_double */
282 static void clean_history (ping_context_t *ctx) /* {{{ */
283 {
284 size_t i;
286 if (!ctx->history_dirty)
287 return;
289 /* Copy all values from by_time to by_value. */
290 memcpy (ctx->history_by_value, ctx->history_by_time,
291 sizeof (ctx->history_by_time));
293 /* Sort all RTTs. */
294 qsort (ctx->history_by_value, ctx->history_size, sizeof
295 (ctx->history_by_value[0]), compare_double);
297 /* Update the number of received RTTs. */
298 ctx->history_received = 0;
299 for (i = 0; i < ctx->history_size; i++)
300 if (!isnan (ctx->history_by_value[i]))
301 ctx->history_received++;
303 /* Mark as clean. */
304 ctx->history_dirty = 0;
305 } /* }}} void clean_history */
307 static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
308 double percentile)
309 {
310 size_t index;
312 clean_history (ctx);
314 /* Not a single packet was received successfully. */
315 if (ctx->history_received == 0)
316 return NAN;
318 if (percentile <= 0.0)
319 index = 0;
320 else if (percentile >= 100.0)
321 index = ctx->history_received - 1;
322 else
323 {
324 index = (size_t) ceil ((percentile / 100.0) * ((double) ctx->history_received));
325 assert (index > 0);
326 index--;
327 }
329 return (ctx->history_by_value[index]);
330 } /* }}} double percentile_to_latency */
332 #if USE_NCURSES
333 static double latency_to_ratio (ping_context_t *ctx, /* {{{ */
334 double latency)
335 {
336 size_t low;
337 size_t high;
338 size_t index;
340 clean_history (ctx);
342 /* Not a single packet was received successfully. */
343 if (ctx->history_received == 0)
344 return NAN;
346 low = 0;
347 high = ctx->history_received - 1;
349 if (latency < ctx->history_by_value[low])
350 return 0.0;
351 else if (latency >= ctx->history_by_value[high])
352 return 100.0;
354 /* Do a binary search for the latency. This will work even when the
355 * exact latency is not in the array. If the latency is in the array
356 * multiple times, "low" will be set to the index of the last
357 * occurrence. The value at index "high" will be larger than the
358 * searched for latency (assured by the above "if" block. */
359 while ((high - low) > 1)
360 {
361 index = (high + low) / 2;
363 if (ctx->history_by_value[index] > latency)
364 high = index;
365 else
366 low = index;
367 }
369 assert (ctx->history_by_value[high] > latency);
370 assert (ctx->history_by_value[low] <= latency);
372 if (ctx->history_by_value[low] == latency)
373 index = low;
374 else
375 index = high;
377 return (((double) (index + 1)) / ((double) ctx->history_received));
378 } /* }}} double latency_to_ratio */
379 #endif
381 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
382 {
383 if (ctx == NULL)
384 return (-1.0);
386 if (ctx->req_sent < 1)
387 return (0.0);
389 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
390 / ((double) ctx->req_sent));
391 } /* }}} double context_get_packet_loss */
393 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
394 {
395 pingobj_iter_t *iter;
396 int index;
398 if (ping == NULL)
399 return (EINVAL);
401 index = 0;
402 for (iter = ping_iterator_get (ping);
403 iter != NULL;
404 iter = ping_iterator_next (iter))
405 {
406 ping_context_t *context;
407 size_t buffer_size;
409 context = context_create ();
410 context->index = index;
412 buffer_size = sizeof (context->host);
413 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
415 buffer_size = sizeof (context->addr);
416 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
418 ping_iterator_set_context (iter, (void *) context);
420 index++;
421 }
423 return (0);
424 } /* }}} int ping_initialize_contexts */
426 static void usage_exit (const char *name, int status) /* {{{ */
427 {
428 fprintf (stderr, "Usage: %s [OPTIONS] "
429 "-f filename | host [host [host ...]]\n"
431 "\nAvailable options:\n"
432 " -4|-6 force the use of IPv4 or IPv6\n"
433 " -c count number of ICMP packets to send\n"
434 " -i interval interval with which to send ICMP packets\n"
435 " -w timeout time to wait for replies, in seconds\n"
436 " -t ttl time to live for each ICMP packet\n"
437 " -Q qos Quality of Service (QoS) of outgoing packets\n"
438 " Use \"-Q help\" for a list of valid options.\n"
439 " -I srcaddr source address\n"
440 " -D device outgoing interface name\n"
441 " -m mark mark to set on outgoing packets\n"
442 " -f filename filename to read hosts from\n"
443 #if USE_NCURSES
444 " -u / -U force / disable UTF-8 output\n"
445 " -g graph graph type to draw\n"
446 #endif
447 " -P percent Report the n'th percentile of latency\n"
448 " -Z percent Exit with non-zero exit status if more than this percentage of\n"
449 " probes timed out. (default: never)\n"
451 "\noping "PACKAGE_VERSION", http://noping.cc/\n"
452 "by Florian octo Forster <ff@octo.it>\n"
453 "for contributions see `AUTHORS'\n",
454 name);
455 exit (status);
456 } /* }}} void usage_exit */
458 __attribute__((noreturn))
459 static void usage_qos_exit (const char *arg, int status) /* {{{ */
460 {
461 if (arg != 0)
462 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
464 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
465 "\n"
466 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
467 "\n"
468 " be Best Effort (BE, default PHB).\n"
469 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
470 " (low delay, low loss, low jitter)\n"
471 " va Voice Admit (VA) DSCP (RFC 5865).\n"
472 " (capacity-admitted traffic)\n"
473 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
474 " For example: \"af12\" (class 1, precedence 2)\n"
475 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
476 " For example: \"cs1\" (priority traffic)\n"
477 "\n"
478 " Type of Service (IPv4, RFC 1349, obsolete)\n"
479 "\n"
480 " lowdelay (%#04x) minimize delay\n"
481 " throughput (%#04x) maximize throughput\n"
482 " reliability (%#04x) maximize reliability\n"
483 " mincost (%#04x) minimize monetary cost\n"
484 "\n"
485 " Specify manually\n"
486 "\n"
487 " 0x00 - 0xff Hexadecimal numeric specification.\n"
488 " 0 - 255 Decimal numeric specification.\n"
489 "\n",
490 (unsigned int) IPTOS_LOWDELAY,
491 (unsigned int) IPTOS_THROUGHPUT,
492 (unsigned int) IPTOS_RELIABILITY,
493 (unsigned int) IPTOS_MINCOST);
495 exit (status);
496 } /* }}} void usage_qos_exit */
498 static int set_opt_send_qos (const char *opt) /* {{{ */
499 {
500 if (opt == NULL)
501 return (EINVAL);
503 if (strcasecmp ("help", opt) == 0)
504 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
505 /* DiffServ (RFC 2474): */
506 /* - Best effort (BE) */
507 else if (strcasecmp ("be", opt) == 0)
508 opt_send_qos = 0;
509 /* - Expedited Forwarding (EF, RFC 3246) */
510 else if (strcasecmp ("ef", opt) == 0)
511 opt_send_qos = 0xB8; /* == 0x2E << 2 */
512 /* - Voice Admit (VA, RFC 5865) */
513 else if (strcasecmp ("va", opt) == 0)
514 opt_send_qos = 0xB0; /* == 0x2D << 2 */
515 /* - Assured Forwarding (AF, RFC 2597) */
516 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
517 && (strlen (opt) == 4))
518 {
519 uint8_t dscp;
520 uint8_t class = 0;
521 uint8_t prec = 0;
523 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
524 if (opt[2] == '1')
525 class = 1;
526 else if (opt[2] == '2')
527 class = 2;
528 else if (opt[2] == '3')
529 class = 3;
530 else if (opt[2] == '4')
531 class = 4;
532 else
533 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
535 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
536 if (opt[3] == '1')
537 prec = 1;
538 else if (opt[3] == '2')
539 prec = 2;
540 else if (opt[3] == '3')
541 prec = 3;
542 else
543 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
545 dscp = (8 * class) + (2 * prec);
546 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
547 opt_send_qos = dscp << 2;
548 }
549 /* - Class Selector (CS) */
550 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
551 && (strlen (opt) == 3))
552 {
553 uint8_t class;
555 if ((opt[2] < '0') || (opt[2] > '7'))
556 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
558 /* Not exactly legal by the C standard, but I don't know of any
559 * system not supporting this hack. */
560 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
561 opt_send_qos = class << 5;
562 }
563 /* Type of Service (RFC 1349) */
564 else if (strcasecmp ("lowdelay", opt) == 0)
565 opt_send_qos = IPTOS_LOWDELAY;
566 else if (strcasecmp ("throughput", opt) == 0)
567 opt_send_qos = IPTOS_THROUGHPUT;
568 else if (strcasecmp ("reliability", opt) == 0)
569 opt_send_qos = IPTOS_RELIABILITY;
570 else if (strcasecmp ("mincost", opt) == 0)
571 opt_send_qos = IPTOS_MINCOST;
572 /* Numeric value */
573 else
574 {
575 unsigned long value;
576 char *endptr;
578 errno = 0;
579 endptr = NULL;
580 value = strtoul (opt, &endptr, /* base = */ 0);
581 if ((errno != 0) || (endptr == opt)
582 || (endptr == NULL) || (*endptr != 0)
583 || (value > 0xff))
584 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
586 opt_send_qos = (uint8_t) value;
587 }
589 return (0);
590 } /* }}} int set_opt_send_qos */
592 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
593 {
594 uint8_t dscp;
595 uint8_t ecn;
596 char *dscp_str;
597 char *ecn_str;
599 dscp = qos >> 2;
600 ecn = qos & 0x03;
602 switch (dscp)
603 {
604 case 0x00: dscp_str = "be"; break;
605 case 0x2e: dscp_str = "ef"; break;
606 case 0x2d: dscp_str = "va"; break;
607 case 0x0a: dscp_str = "af11"; break;
608 case 0x0c: dscp_str = "af12"; break;
609 case 0x0e: dscp_str = "af13"; break;
610 case 0x12: dscp_str = "af21"; break;
611 case 0x14: dscp_str = "af22"; break;
612 case 0x16: dscp_str = "af23"; break;
613 case 0x1a: dscp_str = "af31"; break;
614 case 0x1c: dscp_str = "af32"; break;
615 case 0x1e: dscp_str = "af33"; break;
616 case 0x22: dscp_str = "af41"; break;
617 case 0x24: dscp_str = "af42"; break;
618 case 0x26: dscp_str = "af43"; break;
619 case 0x08: dscp_str = "cs1"; break;
620 case 0x10: dscp_str = "cs2"; break;
621 case 0x18: dscp_str = "cs3"; break;
622 case 0x20: dscp_str = "cs4"; break;
623 case 0x28: dscp_str = "cs5"; break;
624 case 0x30: dscp_str = "cs6"; break;
625 case 0x38: dscp_str = "cs7"; break;
626 default: dscp_str = NULL;
627 }
629 switch (ecn)
630 {
631 case 0x01: ecn_str = ",ecn(1)"; break;
632 case 0x02: ecn_str = ",ecn(0)"; break;
633 case 0x03: ecn_str = ",ce"; break;
634 default: ecn_str = "";
635 }
637 if (dscp_str == NULL)
638 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
639 else
640 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
641 buffer[buffer_size - 1] = 0;
643 return (buffer);
644 } /* }}} char *format_qos */
646 static int read_options (int argc, char **argv) /* {{{ */
647 {
648 int optchar;
650 while (1)
651 {
652 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:P:m:w:"
653 #if USE_NCURSES
654 "uUg:"
655 #endif
656 );
658 if (optchar == -1)
659 break;
661 switch (optchar)
662 {
663 case '4':
664 case '6':
665 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
666 break;
668 case 'c':
669 {
670 int new_count;
671 new_count = atoi (optarg);
672 if (new_count > 0)
673 {
674 opt_count = new_count;
676 if ((opt_percentile < 0.0) && (opt_count < 20))
677 opt_percentile = 100.0 * (opt_count - 1) / opt_count;
678 }
679 else
680 fprintf(stderr, "Ignoring invalid count: %s\n",
681 optarg);
682 }
683 break;
685 case 'f':
686 {
687 if (opt_filename != NULL)
688 free (opt_filename);
689 opt_filename = strdup (optarg);
690 }
691 break;
693 case 'i':
694 {
695 double new_interval;
696 new_interval = atof (optarg);
697 if (new_interval < 0.001)
698 fprintf (stderr, "Ignoring invalid interval: %s\n",
699 optarg);
700 else
701 opt_interval = new_interval;
702 }
703 break;
705 case 'w':
706 {
707 char *endp = NULL;
708 double t = strtod (optarg, &endp);
709 if ((optarg[0] != 0) && (endp != NULL) && (*endp == 0))
710 opt_timeout = t;
711 else
712 fprintf (stderr, "Ignoring invalid timeout: %s\n",
713 optarg);
714 }
715 break;
717 case 'I':
718 {
719 if (opt_srcaddr != NULL)
720 free (opt_srcaddr);
721 opt_srcaddr = strdup (optarg);
722 }
723 break;
725 case 'D':
726 opt_device = optarg;
727 break;
729 case 'm':
730 opt_mark = optarg;
731 break;
733 case 't':
734 {
735 int new_send_ttl;
736 new_send_ttl = atoi (optarg);
737 if ((new_send_ttl > 0) && (new_send_ttl < 256))
738 opt_send_ttl = new_send_ttl;
739 else
740 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
741 optarg);
742 break;
743 }
745 case 'Q':
746 set_opt_send_qos (optarg);
747 break;
749 case 'P':
750 {
751 double new_percentile;
752 new_percentile = atof (optarg);
753 if (isnan (new_percentile)
754 || (new_percentile < 0.1)
755 || (new_percentile > 100.0))
756 fprintf (stderr, "Ignoring invalid percentile: %s\n",
757 optarg);
758 else
759 opt_percentile = new_percentile;
760 }
761 break;
763 #if USE_NCURSES
764 case 'g':
765 if (strcasecmp ("none", optarg) == 0)
766 opt_show_graph = 0;
767 else if (strcasecmp ("prettyping", optarg) == 0)
768 opt_show_graph = 1;
769 else if (strcasecmp ("histogram", optarg) == 0)
770 opt_show_graph = 2;
771 else if (strcasecmp ("boxplot", optarg) == 0)
772 opt_show_graph = 3;
773 else
774 fprintf (stderr, "Unknown graph option: %s\n", optarg);
775 break;
777 case 'u':
778 opt_utf8 = 2;
779 break;
780 case 'U':
781 opt_utf8 = 1;
782 break;
783 #endif
785 case 'Z':
786 {
787 char *endptr = NULL;
788 double tmp;
790 errno = 0;
791 tmp = strtod (optarg, &endptr);
792 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
793 {
794 fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
795 fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
796 }
797 else
798 opt_exit_status_threshold = tmp / 100.0;
800 break;
801 }
803 case 'h':
804 usage_exit (argv[0], 0);
805 break;
807 default:
808 usage_exit (argv[0], 1);
809 }
810 }
812 if (opt_percentile <= 0.0)
813 opt_percentile = OPING_DEFAULT_PERCENTILE;
815 return (optind);
816 } /* }}} read_options */
818 static void time_normalize (struct timespec *ts) /* {{{ */
819 {
820 while (ts->tv_nsec < 0)
821 {
822 if (ts->tv_sec == 0)
823 {
824 ts->tv_nsec = 0;
825 return;
826 }
828 ts->tv_sec -= 1;
829 ts->tv_nsec += 1000000000;
830 }
832 while (ts->tv_nsec >= 1000000000)
833 {
834 ts->tv_sec += 1;
835 ts->tv_nsec -= 1000000000;
836 }
837 } /* }}} void time_normalize */
839 static void time_calc (struct timespec *ts_dest, /* {{{ */
840 const struct timespec *ts_int,
841 const struct timeval *tv_begin,
842 const struct timeval *tv_end)
843 {
844 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
845 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
846 time_normalize (ts_dest);
848 /* Assure that `(begin + interval) > end'.
849 * This may seem overly complicated, but `tv_sec' is of type `time_t'
850 * which may be `unsigned. *sigh* */
851 if ((tv_end->tv_sec > ts_dest->tv_sec)
852 || ((tv_end->tv_sec == ts_dest->tv_sec)
853 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
854 {
855 ts_dest->tv_sec = 0;
856 ts_dest->tv_nsec = 0;
857 return;
858 }
860 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
861 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
862 time_normalize (ts_dest);
863 } /* }}} void time_calc */
865 #if USE_NCURSES
866 static _Bool has_utf8() /* {{{ */
867 {
868 # if HAVE_NCURSESW_NCURSES_H
869 if (!opt_utf8)
870 {
871 /* Automatically determine */
872 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
873 opt_utf8 = 2;
874 else
875 opt_utf8 = 1;
876 }
877 return ((_Bool) (opt_utf8 - 1));
878 # else
879 return (0);
880 # endif
881 } /* }}} _Bool has_utf8 */
883 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
884 {
885 uint32_t *counters;
886 double *ratios;
887 size_t i;
888 size_t x_max;
889 size_t x;
891 clean_history (ctx);
893 if (ctx->history_received == 0)
894 return (ENOENT);
896 x_max = (size_t) getmaxx (ctx->window);
897 if (x_max <= 8)
898 return (EINVAL);
899 x_max -= 4;
901 counters = calloc (x_max, sizeof (*counters));
902 ratios = calloc (x_max, sizeof (*ratios));
904 /* Bucketize */
905 for (i = 0; i < ctx->history_received; i++)
906 {
907 double latency = ctx->history_by_value[i] / 1000.0;
908 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
910 if (index >= x_max)
911 index = x_max - 1;
913 counters[index]++;
914 }
916 /* Sum and calc ratios */
917 ratios[0] = ((double) counters[0]) / ((double) ctx->history_received);
918 for (x = 1; x < x_max; x++)
919 {
920 counters[x] += counters[x - 1];
921 ratios[x] = ((double) counters[x]) / ((double) ctx->history_received);
922 }
924 for (x = 0; x < x_max; x++)
925 {
926 int symbol = ' ';
927 _Bool reverse = 0;
929 if (x == 0)
930 {
931 if (ratios[x] >= 0.5)
932 {
933 symbol = BOXPLOT_MEDIAN;
934 reverse = 1;
935 }
936 else if (ratios[x] > 0.25)
937 {
938 symbol = BOXPLOT_BOX;
939 reverse = 1;
940 }
941 else if (ratios[x] > 0.025)
942 symbol = BOXPLOT_WHISKER_BAR;
943 else
944 symbol = ' '; /* NOP */
945 }
946 else /* (x != 0) */
947 {
948 if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
949 {
950 symbol = BOXPLOT_MEDIAN;
951 reverse = 1;
952 }
953 else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
954 || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
955 {
956 symbol = BOXPLOT_BOX;
957 reverse = 1;
958 }
959 else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
960 {
961 if (ratios[x - 1] < 0.025)
962 symbol = BOXPLOT_WHISKER_LEFT_END;
963 else
964 symbol = BOXPLOT_WHISKER_BAR;
965 }
966 else if ((ratios[x] > .5) && (ratios[x] < 0.975))
967 {
968 symbol = BOXPLOT_WHISKER_BAR;
969 }
970 else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
971 symbol = BOXPLOT_WHISKER_RIGHT_END;
972 }
974 if (reverse)
975 wattron (ctx->window, A_REVERSE);
976 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
977 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
978 if (reverse)
979 wattroff (ctx->window, A_REVERSE);
980 }
982 free (counters);
983 free (ratios);
984 return (0);
985 } /* }}} int update_graph_boxplot */
987 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
988 double latency, unsigned int sequence)
989 {
990 size_t x;
991 size_t x_max;
992 size_t history_offset;
994 x_max = (size_t) getmaxx (ctx->window);
995 if (x_max <= 4)
996 return (EINVAL);
997 x_max -= 4;
999 /* Determine the first index in the history we need to draw
1000 * the graph. */
1001 history_offset = 0;
1002 if (((size_t) x_max) < ctx->history_size) /* window is smaller than history */
1003 {
1004 if (ctx->history_index > x_max)
1005 history_offset = ctx->history_index - x_max;
1006 else /* wrap around */
1007 history_offset = ctx->history_index + ctx->history_size - x_max;
1008 }
1009 else /* window is larger than history */
1010 {
1011 if (ctx->history_index != ctx->history_size) /* no longer growing. */
1012 history_offset = ctx->history_index;
1013 else /* start-up */
1014 history_offset = 0;
1015 }
1017 for (x = 0; x < x_max; x++)
1018 {
1019 size_t index;
1020 double latency;
1022 int color = OPING_RED;
1023 char const *symbol = "!";
1024 int symbolc = '!';
1026 if (x >= ctx->history_size)
1027 {
1028 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1029 continue;
1030 }
1032 index = (history_offset + x) % ctx->history_size;
1033 latency = ctx->history_by_time[index];
1035 if (latency >= 0.0)
1036 {
1037 double ratio;
1039 size_t symbols_num = hist_symbols_acs_num;
1040 size_t colors_num = 1;
1042 size_t index_symbols;
1043 size_t index_colors;
1044 size_t intensity;
1046 /* latency is in milliseconds, opt_interval is in seconds. */
1047 ratio = (latency * 0.001) / opt_interval;
1048 if (ratio > 1) {
1049 ratio = 1.0;
1050 }
1052 if (has_utf8 ())
1053 symbols_num = hist_symbols_utf8_num;
1055 if (has_colors () == TRUE)
1056 colors_num = hist_colors_num;
1058 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
1059 if (intensity >= (symbols_num * colors_num))
1060 intensity = (symbols_num * colors_num) - 1;
1062 index_symbols = intensity % symbols_num;
1063 assert (index_symbols < symbols_num);
1065 index_colors = intensity / symbols_num;
1066 assert (index_colors < colors_num);
1068 if (has_utf8())
1069 {
1070 color = hist_colors_utf8[index_colors];
1071 symbol = hist_symbols_utf8[index_symbols];
1072 }
1073 else
1074 {
1075 color = hist_colors_acs[index_colors];
1076 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
1077 }
1078 }
1079 else /* if (!(latency >= 0.0)) */
1080 wattron (ctx->window, A_BOLD);
1082 if (has_colors () == TRUE)
1083 wattron (ctx->window, COLOR_PAIR(color));
1085 if (has_utf8())
1086 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2, symbol);
1087 else
1088 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, symbolc);
1090 if (has_colors () == TRUE)
1091 wattroff (ctx->window, COLOR_PAIR(color));
1093 /* Use negation here to handle NaN correctly. */
1094 if (!(latency >= 0.0))
1095 wattroff (ctx->window, A_BOLD);
1096 } /* for (x) */
1098 return (0);
1099 } /* }}} int update_graph_prettyping */
1101 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
1102 {
1103 uint32_t *counters;
1104 uint32_t *accumulated;
1105 uint32_t max;
1106 size_t i;
1107 size_t x_max;
1108 size_t x;
1110 size_t symbols_num = hist_symbols_acs_num;
1112 clean_history (ctx);
1114 if (ctx->history_received == 0)
1115 return (ENOENT);
1117 if (has_utf8 ())
1118 symbols_num = hist_symbols_utf8_num;
1120 x_max = (size_t) getmaxx (ctx->window);
1121 if (x_max <= 4)
1122 return (EINVAL);
1123 x_max -= 4;
1125 counters = calloc (x_max, sizeof (*counters));
1126 accumulated = calloc (x_max, sizeof (*accumulated));
1128 /* Bucketize */
1129 max = 0;
1130 for (i = 0; i < ctx->history_received; i++)
1131 {
1132 double latency = ctx->history_by_value[i] / 1000.0;
1133 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
1135 if (index >= x_max)
1136 index = x_max - 1;
1138 counters[index]++;
1139 if (max < counters[index])
1140 max = counters[index];
1141 }
1143 /* Sum */
1144 accumulated[0] = counters[0];
1145 for (x = 1; x < x_max; x++)
1146 accumulated[x] = counters[x] + accumulated[x - 1];
1148 /* Calculate ratios */
1149 for (x = 0; x < x_max; x++)
1150 {
1151 double height = ((double) counters[x]) / ((double) max);
1152 double ratio_this = ((double) accumulated[x]) / ((double) ctx->history_received);
1153 double ratio_prev = 0.0;
1154 size_t index;
1155 int color = 0;
1157 index = (size_t) (height * ((double) symbols_num));
1158 if (index >= symbols_num)
1159 index = symbols_num - 1;
1161 if (x > 0)
1162 ratio_prev = ((double) accumulated[x - 1]) / ((double) ctx->history_received);
1164 if (has_colors () == TRUE)
1165 {
1166 if ((ratio_this <= threshold_green)
1167 || ((ratio_prev < threshold_green)
1168 && (ratio_this > threshold_green)))
1169 color = OPING_GREEN;
1170 else if ((ratio_this <= threshold_yellow)
1171 || ((ratio_prev < threshold_yellow)
1172 && (ratio_this > threshold_yellow)))
1173 color = OPING_YELLOW;
1174 else
1175 color = OPING_RED;
1177 wattron (ctx->window, COLOR_PAIR(color));
1178 }
1180 if (counters[x] == 0)
1181 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1182 else if (has_utf8 ())
1183 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1184 hist_symbols_utf8[index]);
1185 else
1186 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1187 hist_symbols_acs[index] | A_ALTCHARSET);
1189 if (has_colors () == TRUE)
1190 wattroff (ctx->window, COLOR_PAIR(color));
1192 }
1194 free (accumulated);
1195 return (0);
1196 } /* }}} int update_graph_histogram */
1198 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1199 {
1200 double latency = -1.0;
1201 size_t buffer_len = sizeof (latency);
1203 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1204 &latency, &buffer_len);
1206 unsigned int sequence = 0;
1207 buffer_len = sizeof (sequence);
1208 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1209 &sequence, &buffer_len);
1212 if ((ctx == NULL) || (ctx->window == NULL))
1213 return (EINVAL);
1215 /* werase (ctx->window); */
1217 box (ctx->window, 0, 0);
1218 wattron (ctx->window, A_BOLD);
1219 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1220 " %s ", ctx->host);
1221 wattroff (ctx->window, A_BOLD);
1222 wprintw (ctx->window, "ping statistics ");
1223 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1224 "%i packets transmitted, %i received, %.2f%% packet "
1225 "loss, time %.1fms",
1226 ctx->req_sent, ctx->req_rcvd,
1227 context_get_packet_loss (ctx),
1228 ctx->latency_total);
1229 if (ctx->req_rcvd != 0)
1230 {
1231 double min;
1232 double median;
1233 double max;
1234 double percentile;
1236 min = percentile_to_latency (ctx, 0.0);
1237 median = percentile_to_latency (ctx, 50.0);
1238 max = percentile_to_latency (ctx, 100.0);
1239 percentile = percentile_to_latency (ctx, opt_percentile);
1241 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1242 "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f ",
1243 min, median, opt_percentile, percentile, max);
1244 }
1246 if (opt_show_graph == 1)
1247 update_graph_prettyping (ctx, latency, sequence);
1248 else if (opt_show_graph == 2)
1249 update_graph_histogram (ctx);
1250 else if (opt_show_graph == 3)
1251 update_graph_boxplot (ctx);
1253 wrefresh (ctx->window);
1255 return (0);
1256 } /* }}} int update_stats_from_context */
1258 static int on_resize (pingobj_t *ping) /* {{{ */
1259 {
1260 pingobj_iter_t *iter;
1261 int width = 0;
1262 int height = 0;
1263 int main_win_height;
1264 int box_height = (opt_show_graph == 0) ? 4 : 5;
1266 getmaxyx (stdscr, height, width);
1267 if ((height < 1) || (width < 1))
1268 return (EINVAL);
1270 main_win_height = height - (box_height * host_num);
1271 wresize (main_win, main_win_height, /* width = */ width);
1272 /* Allow scrolling */
1273 scrollok (main_win, TRUE);
1274 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1275 /* Allow hardware accelerated scrolling. */
1276 idlok (main_win, TRUE);
1277 wrefresh (main_win);
1279 for (iter = ping_iterator_get (ping);
1280 iter != NULL;
1281 iter = ping_iterator_next (iter))
1282 {
1283 ping_context_t *context;
1285 context = ping_iterator_get_context (iter);
1286 if (context == NULL)
1287 continue;
1289 if (context->window != NULL)
1290 {
1291 delwin (context->window);
1292 context->window = NULL;
1293 }
1294 context->window = newwin (/* height = */ box_height,
1295 /* width = */ width,
1296 /* y = */ main_win_height + (box_height * context->index),
1297 /* x = */ 0);
1298 }
1300 return (0);
1301 } /* }}} */
1303 static int check_resize (pingobj_t *ping) /* {{{ */
1304 {
1305 int need_resize = 0;
1307 while (42)
1308 {
1309 int key = wgetch (stdscr);
1310 if (key == ERR)
1311 break;
1312 else if (key == KEY_RESIZE)
1313 need_resize = 1;
1314 else if (key == 'g')
1315 {
1316 if (opt_show_graph == 3)
1317 opt_show_graph = 1;
1318 else if (opt_show_graph > 0)
1319 opt_show_graph++;
1320 }
1321 }
1323 if (need_resize)
1324 return (on_resize (ping));
1325 else
1326 return (0);
1327 } /* }}} int check_resize */
1329 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1330 {
1331 pingobj_iter_t *iter;
1332 int width = 0;
1333 int height = 0;
1334 int main_win_height;
1335 int box_height = (opt_show_graph == 0) ? 4 : 5;
1337 initscr ();
1338 cbreak ();
1339 noecho ();
1340 nodelay (stdscr, TRUE);
1342 getmaxyx (stdscr, height, width);
1343 if ((height < 1) || (width < 1))
1344 return (EINVAL);
1346 if (has_colors () == TRUE)
1347 {
1348 start_color ();
1349 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
1350 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1351 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
1352 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
1353 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1354 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
1355 }
1357 main_win_height = height - (box_height * host_num);
1358 main_win = newwin (/* height = */ main_win_height,
1359 /* width = */ width,
1360 /* y = */ 0, /* x = */ 0);
1361 /* Allow scrolling */
1362 scrollok (main_win, TRUE);
1363 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1364 /* Allow hardware accelerated scrolling. */
1365 idlok (main_win, TRUE);
1366 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1367 wrefresh (main_win);
1369 for (iter = ping_iterator_get (ping);
1370 iter != NULL;
1371 iter = ping_iterator_next (iter))
1372 {
1373 ping_context_t *context;
1375 context = ping_iterator_get_context (iter);
1376 if (context == NULL)
1377 continue;
1379 if (context->window != NULL)
1380 {
1381 delwin (context->window);
1382 context->window = NULL;
1383 }
1384 context->window = newwin (/* height = */ box_height,
1385 /* width = */ width,
1386 /* y = */ main_win_height + (box_height * context->index),
1387 /* x = */ 0);
1388 }
1391 /* Don't know what good this does exactly, but without this code
1392 * "check_resize" will be called right after startup and *somehow*
1393 * this leads to display errors. If we purge all initial characters
1394 * here, the problem goes away. "wgetch" is non-blocking due to
1395 * "nodelay" (see above). */
1396 while (wgetch (stdscr) != ERR)
1397 {
1398 /* eat up characters */;
1399 }
1401 return (0);
1402 } /* }}} int pre_loop_hook */
1404 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1405 {
1406 return (check_resize (ping));
1407 } /* }}} int pre_sleep_hook */
1409 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1410 {
1411 return (check_resize (ping));
1412 } /* }}} int pre_sleep_hook */
1413 #else /* if !USE_NCURSES */
1414 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1415 {
1416 pingobj_iter_t *iter;
1418 for (iter = ping_iterator_get (ping);
1419 iter != NULL;
1420 iter = ping_iterator_next (iter))
1421 {
1422 ping_context_t *ctx;
1423 size_t buffer_size;
1425 ctx = ping_iterator_get_context (iter);
1426 if (ctx == NULL)
1427 continue;
1429 buffer_size = 0;
1430 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1432 printf ("PING %s (%s) %zu bytes of data.\n",
1433 ctx->host, ctx->addr, buffer_size);
1434 }
1436 return (0);
1437 } /* }}} int pre_loop_hook */
1439 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1440 {
1441 fflush (stdout);
1443 return (0);
1444 } /* }}} int pre_sleep_hook */
1446 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1447 {
1448 return (0);
1449 } /* }}} int post_sleep_hook */
1450 #endif
1452 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1453 {
1454 ctx->req_sent++;
1456 if (latency > 0.0)
1457 {
1458 ctx->req_rcvd++;
1459 ctx->latency_total += latency;
1460 }
1461 else
1462 {
1463 latency = NAN;
1464 }
1466 ctx->history_by_time[ctx->history_index] = latency;
1468 ctx->history_dirty = 1;
1470 /* Update index and size. */
1471 ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1472 if (ctx->history_size < HISTORY_SIZE_MAX)
1473 ctx->history_size++;
1474 } /* }}} void update_context */
1476 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1477 __attribute__((unused)) int index)
1478 {
1479 double latency;
1480 unsigned int sequence;
1481 int recv_ttl;
1482 uint8_t recv_qos;
1483 char recv_qos_str[16];
1484 size_t buffer_len;
1485 size_t data_len;
1486 ping_context_t *context;
1488 latency = -1.0;
1489 buffer_len = sizeof (latency);
1490 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1491 &latency, &buffer_len);
1493 sequence = 0;
1494 buffer_len = sizeof (sequence);
1495 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1496 &sequence, &buffer_len);
1498 recv_ttl = -1;
1499 buffer_len = sizeof (recv_ttl);
1500 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1501 &recv_ttl, &buffer_len);
1503 recv_qos = 0;
1504 buffer_len = sizeof (recv_qos);
1505 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1506 &recv_qos, &buffer_len);
1508 data_len = 0;
1509 ping_iterator_get_info (iter, PING_INFO_DATA,
1510 NULL, &data_len);
1512 context = (ping_context_t *) ping_iterator_get_context (iter);
1514 #if USE_NCURSES
1515 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1516 #else
1517 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1518 #endif
1520 update_context (context, latency);
1522 if (latency > 0.0)
1523 {
1524 #if USE_NCURSES
1525 if (has_colors () == TRUE)
1526 {
1527 double ratio;
1528 int color = OPING_GREEN;
1530 ratio = latency_to_ratio (context, latency);
1531 if (ratio < threshold_green)
1532 color = OPING_GREEN;
1533 else if (ratio < threshold_yellow)
1534 color = OPING_YELLOW;
1535 else
1536 color = OPING_RED;
1538 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1539 data_len, context->host, context->addr,
1540 sequence, recv_ttl,
1541 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1542 if ((recv_qos != 0) || (opt_send_qos != 0))
1543 {
1544 HOST_PRINTF ("qos=%s ",
1545 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1546 }
1547 HOST_PRINTF ("time=");
1548 wattron (main_win, COLOR_PAIR(color));
1549 HOST_PRINTF ("%.2f", latency);
1550 wattroff (main_win, COLOR_PAIR(color));
1551 HOST_PRINTF (" ms\n");
1552 }
1553 else
1554 {
1555 #endif
1556 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1557 data_len,
1558 context->host, context->addr,
1559 sequence, recv_ttl);
1560 if ((recv_qos != 0) || (opt_send_qos != 0))
1561 {
1562 HOST_PRINTF ("qos=%s ",
1563 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1564 }
1565 HOST_PRINTF ("time=%.2f ms\n", latency);
1566 #if USE_NCURSES
1567 }
1568 #endif
1569 }
1570 else /* if (!(latency > 0.0)) */
1571 {
1572 #if USE_NCURSES
1573 if (has_colors () == TRUE)
1574 {
1575 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1576 context->host, context->addr,
1577 sequence);
1578 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1579 HOST_PRINTF ("timeout");
1580 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1581 HOST_PRINTF ("\n");
1582 }
1583 else
1584 {
1585 #endif
1586 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1587 context->host, context->addr,
1588 sequence);
1589 #if USE_NCURSES
1590 }
1591 #endif
1592 }
1594 #if USE_NCURSES
1595 update_stats_from_context (context, iter);
1596 wrefresh (main_win);
1597 #endif
1598 } /* }}} void update_host_hook */
1600 /* Prints statistics for each host, cleans up the contexts and returns the
1601 * number of hosts which failed to return more than the fraction
1602 * opt_exit_status_threshold of pings. */
1603 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1604 {
1605 pingobj_iter_t *iter;
1606 int failure_count = 0;
1608 #if USE_NCURSES
1609 endwin ();
1610 #endif
1612 for (iter = ping_iterator_get (ping);
1613 iter != NULL;
1614 iter = ping_iterator_next (iter))
1615 {
1616 ping_context_t *context;
1618 context = ping_iterator_get_context (iter);
1620 printf ("\n--- %s ping statistics ---\n"
1621 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1622 context->host, context->req_sent, context->req_rcvd,
1623 context_get_packet_loss (context),
1624 context->latency_total);
1626 {
1627 double pct_failed = 1.0 - (((double) context->req_rcvd)
1628 / ((double) context->req_sent));
1629 if (pct_failed > opt_exit_status_threshold)
1630 failure_count++;
1631 }
1633 if (context->req_rcvd != 0)
1634 {
1635 double min;
1636 double median;
1637 double max;
1638 double percentile;
1640 min = percentile_to_latency (context, 0.0);
1641 median = percentile_to_latency (context, 50.0);
1642 max = percentile_to_latency (context, 100.0);
1643 percentile = percentile_to_latency (context, opt_percentile);
1645 printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1646 min, median, opt_percentile, percentile, max);
1647 }
1649 ping_iterator_set_context (iter, NULL);
1650 context_destroy (context);
1651 }
1653 return (failure_count);
1654 } /* }}} int post_loop_hook */
1656 int main (int argc, char **argv) /* {{{ */
1657 {
1658 pingobj_t *ping;
1659 pingobj_iter_t *iter;
1661 struct sigaction sigint_action;
1663 struct timeval tv_begin;
1664 struct timeval tv_end;
1665 struct timespec ts_wait;
1666 struct timespec ts_int;
1668 int optind;
1669 int i;
1670 int status;
1671 #if _POSIX_SAVED_IDS
1672 uid_t saved_set_uid;
1674 /* Save the old effective user id */
1675 saved_set_uid = geteuid ();
1676 /* Set the effective user ID to the real user ID without changing the
1677 * saved set-user ID */
1678 status = seteuid (getuid ());
1679 if (status != 0)
1680 {
1681 fprintf (stderr, "Temporarily dropping privileges "
1682 "failed: %s\n", strerror (errno));
1683 exit (EXIT_FAILURE);
1684 }
1685 #endif
1687 setlocale(LC_ALL, "");
1688 optind = read_options (argc, argv);
1690 #if !_POSIX_SAVED_IDS
1691 /* Cannot temporarily drop privileges -> reject every file but "-". */
1692 if ((opt_filename != NULL)
1693 && (strcmp ("-", opt_filename) != 0)
1694 && (getuid () != geteuid ()))
1695 {
1696 fprintf (stderr, "Your real and effective user IDs don't "
1697 "match. Reading from a file (option '-f')\n"
1698 "is therefore too risky. You can still read "
1699 "from STDIN using '-f -' if you like.\n"
1700 "Sorry.\n");
1701 exit (EXIT_FAILURE);
1702 }
1703 #endif
1705 if ((optind >= argc) && (opt_filename == NULL)) {
1706 usage_exit (argv[0], 1);
1707 }
1709 if ((ping = ping_construct ()) == NULL)
1710 {
1711 fprintf (stderr, "ping_construct failed\n");
1712 return (1);
1713 }
1715 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1716 {
1717 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1718 opt_send_ttl, ping_get_error (ping));
1719 }
1721 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1722 {
1723 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1724 opt_send_qos, ping_get_error (ping));
1725 }
1727 {
1728 double temp_sec;
1729 double temp_nsec;
1731 temp_nsec = modf (opt_interval, &temp_sec);
1732 ts_int.tv_sec = (time_t) temp_sec;
1733 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1735 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1736 }
1738 if (ping_setopt (ping, PING_OPT_TIMEOUT, (void*)(&opt_timeout)) != 0)
1739 {
1740 fprintf (stderr, "Setting timeout failed: %s\n",
1741 ping_get_error (ping));
1742 }
1744 if (opt_addrfamily != PING_DEF_AF)
1745 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1747 if (opt_srcaddr != NULL)
1748 {
1749 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1750 {
1751 fprintf (stderr, "Setting source address failed: %s\n",
1752 ping_get_error (ping));
1753 }
1754 }
1756 if (opt_device != NULL)
1757 {
1758 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1759 {
1760 fprintf (stderr, "Setting device failed: %s\n",
1761 ping_get_error (ping));
1762 }
1763 }
1765 if (opt_mark != NULL)
1766 {
1767 char *endp = NULL;
1768 int mark = (int) strtol (opt_mark, &endp, /* base = */ 0);
1769 if ((opt_mark[0] != 0) && (endp != NULL) && (*endp == 0))
1770 {
1771 if (ping_setopt(ping, PING_OPT_MARK, (void*)(&mark)) != 0)
1772 {
1773 fprintf (stderr, "Setting mark failed: %s\n",
1774 ping_get_error (ping));
1775 }
1776 }
1777 else
1778 {
1779 fprintf(stderr, "Ignoring invalid mark: %s\n", optarg);
1780 }
1781 }
1783 if (opt_filename != NULL)
1784 {
1785 FILE *infile;
1786 char line[256];
1787 char host[256];
1789 if (strcmp (opt_filename, "-") == 0)
1790 /* Open STDIN */
1791 infile = fdopen(0, "r");
1792 else
1793 infile = fopen(opt_filename, "r");
1795 if (infile == NULL)
1796 {
1797 fprintf (stderr, "Opening %s failed: %s\n",
1798 (strcmp (opt_filename, "-") == 0)
1799 ? "STDIN" : opt_filename,
1800 strerror(errno));
1801 return (1);
1802 }
1804 #if _POSIX_SAVED_IDS
1805 /* Regain privileges */
1806 status = seteuid (saved_set_uid);
1807 if (status != 0)
1808 {
1809 fprintf (stderr, "Temporarily re-gaining privileges "
1810 "failed: %s\n", strerror (errno));
1811 exit (EXIT_FAILURE);
1812 }
1813 #endif
1815 while (fgets(line, sizeof(line), infile))
1816 {
1817 /* Strip whitespace */
1818 if (sscanf(line, "%s", host) != 1)
1819 continue;
1821 if ((host[0] == 0) || (host[0] == '#'))
1822 continue;
1824 if (ping_host_add(ping, host) < 0)
1825 {
1826 const char *errmsg = ping_get_error (ping);
1828 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1829 continue;
1830 }
1831 else
1832 {
1833 host_num++;
1834 }
1835 }
1837 #if _POSIX_SAVED_IDS
1838 /* Drop privileges */
1839 status = seteuid (getuid ());
1840 if (status != 0)
1841 {
1842 fprintf (stderr, "Temporarily dropping privileges "
1843 "failed: %s\n", strerror (errno));
1844 exit (EXIT_FAILURE);
1845 }
1846 #endif
1848 fclose(infile);
1849 }
1851 #if _POSIX_SAVED_IDS
1852 /* Regain privileges */
1853 status = seteuid (saved_set_uid);
1854 if (status != 0)
1855 {
1856 fprintf (stderr, "Temporarily re-gaining privileges "
1857 "failed: %s\n", strerror (errno));
1858 exit (EXIT_FAILURE);
1859 }
1860 #endif
1862 for (i = optind; i < argc; i++)
1863 {
1864 if (ping_host_add (ping, argv[i]) < 0)
1865 {
1866 const char *errmsg = ping_get_error (ping);
1868 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1869 continue;
1870 }
1871 else
1872 {
1873 host_num++;
1874 }
1875 }
1877 /* Permanently drop root privileges if we're setuid-root. */
1878 status = setuid (getuid ());
1879 if (status != 0)
1880 {
1881 fprintf (stderr, "Dropping privileges failed: %s\n",
1882 strerror (errno));
1883 exit (EXIT_FAILURE);
1884 }
1886 if (host_num == 0)
1887 exit (EXIT_FAILURE);
1889 #if _POSIX_SAVED_IDS
1890 saved_set_uid = (uid_t) -1;
1891 #endif
1893 ping_initialize_contexts (ping);
1895 if (i == 0)
1896 return (1);
1898 memset (&sigint_action, '\0', sizeof (sigint_action));
1899 sigint_action.sa_handler = sigint_handler;
1900 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1901 {
1902 perror ("sigaction");
1903 return (1);
1904 }
1906 pre_loop_hook (ping);
1908 while (opt_count != 0)
1909 {
1910 int index;
1911 int status;
1913 if (gettimeofday (&tv_begin, NULL) < 0)
1914 {
1915 perror ("gettimeofday");
1916 return (1);
1917 }
1919 status = ping_send (ping);
1920 if (status == -EINTR)
1921 {
1922 continue;
1923 }
1924 else if (status < 0)
1925 {
1926 fprintf (stderr, "ping_send failed: %s\n",
1927 ping_get_error (ping));
1928 return (1);
1929 }
1931 index = 0;
1932 for (iter = ping_iterator_get (ping);
1933 iter != NULL;
1934 iter = ping_iterator_next (iter))
1935 {
1936 update_host_hook (iter, index);
1937 index++;
1938 }
1940 pre_sleep_hook (ping);
1942 /* Don't sleep in the last iteration */
1943 if (opt_count == 1)
1944 break;
1946 if (gettimeofday (&tv_end, NULL) < 0)
1947 {
1948 perror ("gettimeofday");
1949 return (1);
1950 }
1952 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1954 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1955 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1956 {
1957 if (errno == EINTR)
1958 {
1959 continue;
1960 }
1961 else
1962 {
1963 perror ("nanosleep");
1964 break;
1965 }
1966 }
1968 post_sleep_hook (ping);
1970 if (opt_count > 0)
1971 opt_count--;
1972 } /* while (opt_count != 0) */
1974 /* Returns the number of failed hosts according to -Z. */
1975 status = post_loop_hook (ping);
1977 ping_destroy (ping);
1979 if (status == 0)
1980 exit (EXIT_SUCCESS);
1981 else
1982 {
1983 if (status > 255)
1984 status = 255;
1985 exit (status);
1986 }
1987 } /* }}} int main */
1989 /* vim: set fdm=marker : */