2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2014 Florian octo Forster <ff at octo.it>
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
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.
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
29 # include <inttypes.h>
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
49 # include <sys/time.h>
56 # include <sys/socket.h>
59 # include <netinet/in.h>
62 # include <netinet/ip.h>
66 # include <netdb.h> /* NI_MAXHOST */
74 #include <sys/types.h>
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>
91 # define OPING_GREEN 1
92 # define OPING_YELLOW 2
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 "⎻" */
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]);
129 #define BOXPLOT_WHISKER_BAR (113 | A_ALTCHARSET)
131 #define BOXPLOT_WHISKER_LEFT_END (116 | A_ALTCHARSET)
133 #define BOXPLOT_WHISKER_RIGHT_END (117 | A_ALTCHARSET)
135 #define BOXPLOT_BOX ' '
137 #define BOXPLOT_MEDIAN (120 | A_ALTCHARSET)
141 #ifndef _POSIX_SAVED_IDS
142 # define _POSIX_SAVED_IDS 0
145 #ifndef IPTOS_MINCOST
146 # define IPTOS_MINCOST 0x02
149 /* Remove GNU specific __attribute__ settings when using another compiler */
151 # define __attribute__(x) /**/
154 typedef struct ping_context
156 char host[NI_MAXHOST];
157 char addr[NI_MAXHOST];
163 double latency_total;
165 #ifndef HISTORY_SIZE_MAX
166 # define HISTORY_SIZE_MAX 900
168 /* The last n RTTs in the order they were sent. */
169 double history_by_time[HISTORY_SIZE_MAX];
170 /* Current size of the history. This is a value between 0 and
171 * HISTORY_SIZE_MAX. */
173 /* Index of the next RTT to be written to history_by_time. This wraps
174 * around to 0 once the histroty has grown to HISTORY_SIZE_MAX. */
175 size_t history_index;
176 /* Number received replies, i.e. non-NAN entries. */
177 size_t history_received;
178 /* The last n RTTs sorted by value. timed out packets are sorted to the
180 double history_by_value[HISTORY_SIZE_MAX];
181 /* If set to true, history_by_value has to be re-calculated. */
189 static double opt_interval = 1.0;
190 static int opt_addrfamily = PING_DEF_AF;
191 static char *opt_srcaddr = NULL;
192 static char *opt_device = NULL;
193 static char *opt_filename = NULL;
194 static int opt_count = -1;
195 static int opt_send_ttl = 64;
196 static uint8_t opt_send_qos = 0;
197 #define OPING_DEFAULT_PERCENTILE 95.0
198 static double opt_percentile = -1.0;
199 static double opt_exit_status_threshold = 1.0;
201 static int opt_show_graph = 1;
202 static int opt_utf8 = 0;
205 static int host_num = 0;
208 static WINDOW *main_win = NULL;
211 static void sigint_handler (int signal) /* {{{ */
213 /* Make compiler happy */
217 } /* }}} void sigint_handler */
219 static ping_context_t *context_create (void) /* {{{ */
223 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
226 memset (ret, '\0', sizeof (ping_context_t));
228 ret->latency_total = 0.0;
235 } /* }}} ping_context_t *context_create */
237 static void context_destroy (ping_context_t *context) /* {{{ */
243 if (context->window != NULL)
245 delwin (context->window);
246 context->window = NULL;
251 } /* }}} void context_destroy */
253 static int compare_double (void const *arg0, void const *arg1) /* {{{ */
255 double dbl0 = *((double *) arg0);
256 double dbl1 = *((double *) arg1);
265 else if (isnan (dbl1))
267 else if (dbl0 < dbl1)
269 else if (dbl0 > dbl1)
273 } /* }}} int compare_double */
275 static void clean_history (ping_context_t *ctx) /* {{{ */
279 if (!ctx->history_dirty)
282 /* Copy all values from by_time to by_value. */
283 memcpy (ctx->history_by_value, ctx->history_by_time,
284 sizeof (ctx->history_by_time));
286 qsort (ctx->history_by_value, ctx->history_size, sizeof
287 (ctx->history_by_value[0]), compare_double);
289 ctx->history_received = 0;
290 for (i = 0; i < ctx->history_size; i++)
291 if (!isnan (ctx->history_by_value[i]))
292 ctx->history_received++;
295 ctx->history_dirty = 0;
296 } /* }}} void clean_history */
298 static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
305 if (ctx->history_received == 0)
308 if (percentile <= 0.0)
310 else if (percentile >= 100.0)
311 index = ctx->history_received - 1;
314 index = (size_t) ceil ((percentile / 100.0) * ((double) ctx->history_received));
319 return (ctx->history_by_value[index]);
320 } /* }}} double percentile_to_latency */
323 static double latency_to_percentile (ping_context_t *ctx, /* {{{ */
332 if (ctx->history_received == 0)
336 high = ctx->history_received - 1;
338 if (latency < ctx->history_by_value[low])
340 else if (latency >= ctx->history_by_value[high])
343 while ((high - low) > 1)
345 index = (high + low) / 2;
347 if (ctx->history_by_value[index] > latency)
353 assert (ctx->history_by_value[high] > latency);
354 assert (ctx->history_by_value[low] <= latency);
356 if (ctx->history_by_value[low] == latency)
361 return (100.0 * ((double) (index + 1)) / ((double) ctx->history_received));
362 } /* }}} double latency_to_percentile */
365 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
370 if (ctx->req_sent < 1)
373 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
374 / ((double) ctx->req_sent));
375 } /* }}} double context_get_packet_loss */
377 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
379 pingobj_iter_t *iter;
386 for (iter = ping_iterator_get (ping);
388 iter = ping_iterator_next (iter))
390 ping_context_t *context;
393 context = context_create ();
394 context->index = index;
396 buffer_size = sizeof (context->host);
397 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
399 buffer_size = sizeof (context->addr);
400 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
402 ping_iterator_set_context (iter, (void *) context);
408 } /* }}} int ping_initialize_contexts */
410 static void usage_exit (const char *name, int status) /* {{{ */
412 fprintf (stderr, "Usage: %s [OPTIONS] "
413 "-f filename | host [host [host ...]]\n"
415 "\nAvailable options:\n"
416 " -4|-6 force the use of IPv4 or IPv6\n"
417 " -c count number of ICMP packets to send\n"
418 " -i interval interval with which to send ICMP packets\n"
419 " -t ttl time to live for each ICMP packet\n"
420 " -Q qos Quality of Service (QoS) of outgoing packets\n"
421 " Use \"-Q help\" for a list of valid options.\n"
422 " -I srcaddr source address\n"
423 " -D device outgoing interface name\n"
424 " -f filename filename to read hosts from\n"
426 " -u / -U force / disable UTF-8 output\n"
427 " -g graph graph type to draw\n"
429 " -P percent Report the n'th percentile of latency\n"
430 " -Z percent Exit with non-zero exit status if more than this percentage of\n"
431 " probes timed out. (default: never)\n"
433 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
434 "by Florian octo Forster <octo@verplant.org>\n"
435 "for contributions see `AUTHORS'\n",
438 } /* }}} void usage_exit */
440 __attribute__((noreturn))
441 static void usage_qos_exit (const char *arg, int status) /* {{{ */
444 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
446 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
448 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
450 " be Best Effort (BE, default PHB).\n"
451 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
452 " (low delay, low loss, low jitter)\n"
453 " va Voice Admit (VA) DSCP (RFC 5865).\n"
454 " (capacity-admitted traffic)\n"
455 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
456 " For example: \"af12\" (class 1, precedence 2)\n"
457 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
458 " For example: \"cs1\" (priority traffic)\n"
460 " Type of Service (IPv4, RFC 1349, obsolete)\n"
462 " lowdelay (%#04x) minimize delay\n"
463 " throughput (%#04x) maximize throughput\n"
464 " reliability (%#04x) maximize reliability\n"
465 " mincost (%#04x) minimize monetary cost\n"
467 " Specify manually\n"
469 " 0x00 - 0xff Hexadecimal numeric specification.\n"
470 " 0 - 255 Decimal numeric specification.\n"
472 (unsigned int) IPTOS_LOWDELAY,
473 (unsigned int) IPTOS_THROUGHPUT,
474 (unsigned int) IPTOS_RELIABILITY,
475 (unsigned int) IPTOS_MINCOST);
478 } /* }}} void usage_qos_exit */
480 static int set_opt_send_qos (const char *opt) /* {{{ */
485 if (strcasecmp ("help", opt) == 0)
486 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
487 /* DiffServ (RFC 2474): */
488 /* - Best effort (BE) */
489 else if (strcasecmp ("be", opt) == 0)
491 /* - Expedited Forwarding (EF, RFC 3246) */
492 else if (strcasecmp ("ef", opt) == 0)
493 opt_send_qos = 0xB8; /* == 0x2E << 2 */
494 /* - Voice Admit (VA, RFC 5865) */
495 else if (strcasecmp ("va", opt) == 0)
496 opt_send_qos = 0xB0; /* == 0x2D << 2 */
497 /* - Assured Forwarding (AF, RFC 2597) */
498 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
499 && (strlen (opt) == 4))
505 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
508 else if (opt[2] == '2')
510 else if (opt[2] == '3')
512 else if (opt[2] == '4')
515 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
517 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
520 else if (opt[3] == '2')
522 else if (opt[3] == '3')
525 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
527 dscp = (8 * class) + (2 * prec);
528 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
529 opt_send_qos = dscp << 2;
531 /* - Class Selector (CS) */
532 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
533 && (strlen (opt) == 3))
537 if ((opt[2] < '0') || (opt[2] > '7'))
538 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
540 /* Not exactly legal by the C standard, but I don't know of any
541 * system not supporting this hack. */
542 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
543 opt_send_qos = class << 5;
545 /* Type of Service (RFC 1349) */
546 else if (strcasecmp ("lowdelay", opt) == 0)
547 opt_send_qos = IPTOS_LOWDELAY;
548 else if (strcasecmp ("throughput", opt) == 0)
549 opt_send_qos = IPTOS_THROUGHPUT;
550 else if (strcasecmp ("reliability", opt) == 0)
551 opt_send_qos = IPTOS_RELIABILITY;
552 else if (strcasecmp ("mincost", opt) == 0)
553 opt_send_qos = IPTOS_MINCOST;
562 value = strtoul (opt, &endptr, /* base = */ 0);
563 if ((errno != 0) || (endptr == opt)
564 || (endptr == NULL) || (*endptr != 0)
566 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
568 opt_send_qos = (uint8_t) value;
572 } /* }}} int set_opt_send_qos */
574 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
586 case 0x00: dscp_str = "be"; break;
587 case 0x2e: dscp_str = "ef"; break;
588 case 0x2d: dscp_str = "va"; break;
589 case 0x0a: dscp_str = "af11"; break;
590 case 0x0c: dscp_str = "af12"; break;
591 case 0x0e: dscp_str = "af13"; break;
592 case 0x12: dscp_str = "af21"; break;
593 case 0x14: dscp_str = "af22"; break;
594 case 0x16: dscp_str = "af23"; break;
595 case 0x1a: dscp_str = "af31"; break;
596 case 0x1c: dscp_str = "af32"; break;
597 case 0x1e: dscp_str = "af33"; break;
598 case 0x22: dscp_str = "af41"; break;
599 case 0x24: dscp_str = "af42"; break;
600 case 0x26: dscp_str = "af43"; break;
601 case 0x08: dscp_str = "cs1"; break;
602 case 0x10: dscp_str = "cs2"; break;
603 case 0x18: dscp_str = "cs3"; break;
604 case 0x20: dscp_str = "cs4"; break;
605 case 0x28: dscp_str = "cs5"; break;
606 case 0x30: dscp_str = "cs6"; break;
607 case 0x38: dscp_str = "cs7"; break;
608 default: dscp_str = NULL;
613 case 0x01: ecn_str = ",ecn(1)"; break;
614 case 0x02: ecn_str = ",ecn(0)"; break;
615 case 0x03: ecn_str = ",ce"; break;
616 default: ecn_str = "";
619 if (dscp_str == NULL)
620 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
622 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
623 buffer[buffer_size - 1] = 0;
626 } /* }}} char *format_qos */
628 static int read_options (int argc, char **argv) /* {{{ */
634 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:P:"
647 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
653 new_count = atoi (optarg);
656 opt_count = new_count;
658 if ((opt_percentile < 0.0) && (opt_count < 20))
659 opt_percentile = 100.0 * (opt_count - 1) / opt_count;
662 fprintf(stderr, "Ignoring invalid count: %s\n",
669 if (opt_filename != NULL)
671 opt_filename = strdup (optarg);
678 new_interval = atof (optarg);
679 if (new_interval < 0.001)
680 fprintf (stderr, "Ignoring invalid interval: %s\n",
683 opt_interval = new_interval;
689 if (opt_srcaddr != NULL)
691 opt_srcaddr = strdup (optarg);
702 new_send_ttl = atoi (optarg);
703 if ((new_send_ttl > 0) && (new_send_ttl < 256))
704 opt_send_ttl = new_send_ttl;
706 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
712 set_opt_send_qos (optarg);
717 double new_percentile;
718 new_percentile = atof (optarg);
719 if (isnan (new_percentile)
720 || (new_percentile < 0.1)
721 || (new_percentile > 100.0))
722 fprintf (stderr, "Ignoring invalid percentile: %s\n",
725 opt_percentile = new_percentile;
731 if (strcasecmp ("none", optarg) == 0)
733 else if (strcasecmp ("prettyping", optarg) == 0)
735 else if (strcasecmp ("boxplot", optarg) == 0)
737 else if (strcasecmp ("histogram", optarg) == 0)
740 fprintf (stderr, "Unknown graph option: %s\n", optarg);
757 tmp = strtod (optarg, &endptr);
758 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
760 fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
761 fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
764 opt_exit_status_threshold = tmp / 100.0;
770 usage_exit (argv[0], 0);
774 usage_exit (argv[0], 1);
778 if (opt_percentile <= 0.0)
779 opt_percentile = OPING_DEFAULT_PERCENTILE;
782 } /* }}} read_options */
784 static void time_normalize (struct timespec *ts) /* {{{ */
786 while (ts->tv_nsec < 0)
795 ts->tv_nsec += 1000000000;
798 while (ts->tv_nsec >= 1000000000)
801 ts->tv_nsec -= 1000000000;
803 } /* }}} void time_normalize */
805 static void time_calc (struct timespec *ts_dest, /* {{{ */
806 const struct timespec *ts_int,
807 const struct timeval *tv_begin,
808 const struct timeval *tv_end)
810 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
811 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
812 time_normalize (ts_dest);
814 /* Assure that `(begin + interval) > end'.
815 * This may seem overly complicated, but `tv_sec' is of type `time_t'
816 * which may be `unsigned. *sigh* */
817 if ((tv_end->tv_sec > ts_dest->tv_sec)
818 || ((tv_end->tv_sec == ts_dest->tv_sec)
819 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
822 ts_dest->tv_nsec = 0;
826 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
827 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
828 time_normalize (ts_dest);
829 } /* }}} void time_calc */
832 static _Bool has_utf8() /* {{{ */
834 # if HAVE_NCURSESW_NCURSES_H
837 /* Automatically determine */
838 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
843 return ((_Bool) (opt_utf8 - 1));
847 } /* }}} _Bool has_utf8 */
849 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
859 if (ctx->history_received == 0)
862 x_max = (size_t) getmaxx (ctx->window);
867 counters = calloc (x_max, sizeof (*counters));
868 ratios = calloc (x_max, sizeof (*ratios));
871 for (i = 0; i < ctx->history_received; i++)
873 double latency = ctx->history_by_value[i] / 1000.0;
874 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
882 /* Sum and calc ratios */
883 ratios[0] = ((double) counters[0]) / ((double) ctx->history_received);
884 for (x = 1; x < x_max; x++)
886 counters[x] += counters[x - 1];
887 ratios[x] = ((double) counters[x]) / ((double) ctx->history_received);
890 for (x = 0; x < x_max; x++)
897 if (ratios[x] >= 0.5)
899 symbol = BOXPLOT_MEDIAN;
902 else if (ratios[x] > 0.25)
904 symbol = BOXPLOT_BOX;
907 else if (ratios[x] > 0.025)
908 symbol = BOXPLOT_WHISKER_BAR;
910 symbol = ' '; /* NOP */
914 if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
916 symbol = BOXPLOT_MEDIAN;
919 else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
920 || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
922 symbol = BOXPLOT_BOX;
925 else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
927 if (ratios[x - 1] < 0.025)
928 symbol = BOXPLOT_WHISKER_LEFT_END;
930 symbol = BOXPLOT_WHISKER_BAR;
932 else if ((ratios[x] > .5) && (ratios[x] < 0.975))
934 symbol = BOXPLOT_WHISKER_BAR;
936 else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
937 symbol = BOXPLOT_WHISKER_RIGHT_END;
941 wattron (ctx->window, A_REVERSE);
942 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
943 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
945 wattroff (ctx->window, A_REVERSE);
951 } /* }}} int update_graph_boxplot */
953 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
954 double latency, unsigned int sequence)
958 size_t history_offset;
960 x_max = (size_t) getmaxx (ctx->window);
966 if (((size_t) x_max) < ctx->history_size)
968 if (ctx->history_index > x_max)
969 history_offset = ctx->history_index - x_max;
970 else /* wrap around */
971 history_offset = ctx->history_index + x_max - ctx->history_size;
974 for (x = 0; x < x_max; x++)
979 int color = OPING_RED;
980 char const *symbol = "!";
983 if (x >= ctx->history_size)
985 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
989 index = (history_offset + x) % ctx->history_size;
990 latency = ctx->history_by_time[index];
996 size_t symbols_num = hist_symbols_acs_num;
997 size_t colors_num = 1;
999 size_t index_symbols;
1000 size_t index_colors;
1003 /* latency is in milliseconds, opt_interval is in seconds. */
1004 ratio = (latency * 0.001) / opt_interval;
1010 symbols_num = hist_symbols_utf8_num;
1012 if (has_colors () == TRUE)
1013 colors_num = hist_colors_num;
1015 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
1016 if (intensity >= (symbols_num * colors_num))
1017 intensity = (symbols_num * colors_num) - 1;
1019 index_symbols = intensity % symbols_num;
1020 assert (index_symbols < symbols_num);
1022 index_colors = intensity / symbols_num;
1023 assert (index_colors < colors_num);
1027 color = hist_colors_utf8[index_colors];
1028 symbol = hist_symbols_utf8[index_symbols];
1032 color = hist_colors_acs[index_colors];
1033 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
1036 else /* if (!(latency >= 0.0)) */
1037 wattron (ctx->window, A_BOLD);
1039 if (has_colors () == TRUE)
1040 wattron (ctx->window, COLOR_PAIR(color));
1043 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2, symbol);
1045 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, symbolc);
1047 if (has_colors () == TRUE)
1048 wattroff (ctx->window, COLOR_PAIR(color));
1050 /* Use negation here to handle NaN correctly. */
1051 if (!(latency >= 0.0))
1052 wattroff (ctx->window, A_BOLD);
1056 } /* }}} int update_graph_prettyping */
1058 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
1061 uint32_t *accumulated;
1067 size_t symbols_num = hist_symbols_acs_num;
1069 clean_history (ctx);
1071 if (ctx->history_received == 0)
1075 symbols_num = hist_symbols_utf8_num;
1077 x_max = (size_t) getmaxx (ctx->window);
1082 counters = calloc (x_max, sizeof (*counters));
1083 accumulated = calloc (x_max, sizeof (*accumulated));
1087 for (i = 0; i < ctx->history_received; i++)
1089 double latency = ctx->history_by_value[i] / 1000.0;
1090 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
1096 if (max < counters[index])
1097 max = counters[index];
1101 accumulated[0] = counters[0];
1102 for (x = 1; x < x_max; x++)
1103 accumulated[x] = counters[x] + accumulated[x - 1];
1105 /* Calculate ratios */
1106 for (x = 0; x < x_max; x++)
1108 double height = ((double) counters[x]) / ((double) max);
1109 double ratio_this = ((double) accumulated[x]) / ((double) ctx->history_received);
1110 double ratio_prev = 0.0;
1114 index = (size_t) (height * ((double) symbols_num));
1115 if (index >= symbols_num)
1116 index = symbols_num - 1;
1119 ratio_prev = ((double) accumulated[x - 1]) / ((double) ctx->history_received);
1121 if (has_colors () == TRUE)
1123 if ((ratio_this <= threshold_green)
1124 || ((ratio_prev < threshold_green)
1125 && (ratio_this > threshold_green)))
1126 color = OPING_GREEN;
1127 else if ((ratio_this <= threshold_yellow)
1128 || ((ratio_prev < threshold_yellow)
1129 && (ratio_this > threshold_yellow)))
1130 color = OPING_YELLOW;
1134 wattron (ctx->window, COLOR_PAIR(color));
1137 if (counters[x] == 0)
1138 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1139 else if (has_utf8 ())
1140 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1141 hist_symbols_utf8[index]);
1143 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1144 hist_symbols_acs[index] | A_ALTCHARSET);
1146 if (has_colors () == TRUE)
1147 wattroff (ctx->window, COLOR_PAIR(color));
1153 } /* }}} int update_graph_histogram */
1155 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1157 double latency = -1.0;
1158 size_t buffer_len = sizeof (latency);
1160 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1161 &latency, &buffer_len);
1163 unsigned int sequence = 0;
1164 buffer_len = sizeof (sequence);
1165 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1166 &sequence, &buffer_len);
1169 if ((ctx == NULL) || (ctx->window == NULL))
1172 /* werase (ctx->window); */
1174 box (ctx->window, 0, 0);
1175 wattron (ctx->window, A_BOLD);
1176 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1178 wattroff (ctx->window, A_BOLD);
1179 wprintw (ctx->window, "ping statistics ");
1180 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1181 "%i packets transmitted, %i received, %.2f%% packet "
1182 "loss, time %.1fms",
1183 ctx->req_sent, ctx->req_rcvd,
1184 context_get_packet_loss (ctx),
1185 ctx->latency_total);
1186 if (ctx->req_rcvd != 0)
1193 min = percentile_to_latency (ctx, 0.0);
1194 median = percentile_to_latency (ctx, 50.0);
1195 max = percentile_to_latency (ctx, 100.0);
1196 percentile = percentile_to_latency (ctx, opt_percentile);
1198 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1199 "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f",
1200 min, median, opt_percentile, percentile, max);
1203 if (opt_show_graph == 1)
1204 update_graph_prettyping (ctx, latency, sequence);
1205 else if (opt_show_graph == 2)
1206 update_graph_boxplot (ctx);
1207 else if (opt_show_graph == 3)
1208 update_graph_histogram (ctx);
1210 wrefresh (ctx->window);
1213 } /* }}} int update_stats_from_context */
1215 static int on_resize (pingobj_t *ping) /* {{{ */
1217 pingobj_iter_t *iter;
1220 int main_win_height;
1221 int box_height = (opt_show_graph == 0) ? 4 : 5;
1223 getmaxyx (stdscr, height, width);
1224 if ((height < 1) || (width < 1))
1227 main_win_height = height - (box_height * host_num);
1228 wresize (main_win, main_win_height, /* width = */ width);
1229 /* Allow scrolling */
1230 scrollok (main_win, TRUE);
1231 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1232 /* Allow hardware accelerated scrolling. */
1233 idlok (main_win, TRUE);
1234 wrefresh (main_win);
1236 for (iter = ping_iterator_get (ping);
1238 iter = ping_iterator_next (iter))
1240 ping_context_t *context;
1242 context = ping_iterator_get_context (iter);
1243 if (context == NULL)
1246 if (context->window != NULL)
1248 delwin (context->window);
1249 context->window = NULL;
1251 context->window = newwin (/* height = */ box_height,
1252 /* width = */ width,
1253 /* y = */ main_win_height + (box_height * context->index),
1260 static int check_resize (pingobj_t *ping) /* {{{ */
1262 int need_resize = 0;
1266 int key = wgetch (stdscr);
1269 else if (key == KEY_RESIZE)
1271 else if (key == 'g')
1273 if (opt_show_graph == 3)
1275 else if (opt_show_graph > 0)
1281 return (on_resize (ping));
1284 } /* }}} int check_resize */
1286 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1288 pingobj_iter_t *iter;
1291 int main_win_height;
1292 int box_height = (opt_show_graph == 0) ? 4 : 5;
1297 nodelay (stdscr, TRUE);
1299 getmaxyx (stdscr, height, width);
1300 if ((height < 1) || (width < 1))
1303 if (has_colors () == TRUE)
1306 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
1307 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1308 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
1309 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
1310 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1311 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
1314 main_win_height = height - (box_height * host_num);
1315 main_win = newwin (/* height = */ main_win_height,
1316 /* width = */ width,
1317 /* y = */ 0, /* x = */ 0);
1318 /* Allow scrolling */
1319 scrollok (main_win, TRUE);
1320 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1321 /* Allow hardware accelerated scrolling. */
1322 idlok (main_win, TRUE);
1323 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1324 wrefresh (main_win);
1326 for (iter = ping_iterator_get (ping);
1328 iter = ping_iterator_next (iter))
1330 ping_context_t *context;
1332 context = ping_iterator_get_context (iter);
1333 if (context == NULL)
1336 if (context->window != NULL)
1338 delwin (context->window);
1339 context->window = NULL;
1341 context->window = newwin (/* height = */ box_height,
1342 /* width = */ width,
1343 /* y = */ main_win_height + (box_height * context->index),
1348 /* Don't know what good this does exactly, but without this code
1349 * "check_resize" will be called right after startup and *somehow*
1350 * this leads to display errors. If we purge all initial characters
1351 * here, the problem goes away. "wgetch" is non-blocking due to
1352 * "nodelay" (see above). */
1353 while (wgetch (stdscr) != ERR)
1355 /* eat up characters */;
1359 } /* }}} int pre_loop_hook */
1361 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1363 return (check_resize (ping));
1364 } /* }}} int pre_sleep_hook */
1366 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1368 return (check_resize (ping));
1369 } /* }}} int pre_sleep_hook */
1370 #else /* if !USE_NCURSES */
1371 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1373 pingobj_iter_t *iter;
1375 for (iter = ping_iterator_get (ping);
1377 iter = ping_iterator_next (iter))
1379 ping_context_t *ctx;
1382 ctx = ping_iterator_get_context (iter);
1387 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1389 printf ("PING %s (%s) %zu bytes of data.\n",
1390 ctx->host, ctx->addr, buffer_size);
1394 } /* }}} int pre_loop_hook */
1396 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1401 } /* }}} int pre_sleep_hook */
1403 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1406 } /* }}} int post_sleep_hook */
1409 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1416 ctx->latency_total += latency;
1423 ctx->history_by_time[ctx->history_index] = latency;
1425 ctx->history_dirty = 1;
1427 /* Update index and size. */
1428 ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1429 if (ctx->history_size < HISTORY_SIZE_MAX)
1430 ctx->history_size++;
1431 } /* }}} void update_context */
1433 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1434 __attribute__((unused)) int index)
1437 unsigned int sequence;
1440 char recv_qos_str[16];
1443 ping_context_t *context;
1446 buffer_len = sizeof (latency);
1447 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1448 &latency, &buffer_len);
1451 buffer_len = sizeof (sequence);
1452 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1453 &sequence, &buffer_len);
1456 buffer_len = sizeof (recv_ttl);
1457 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1458 &recv_ttl, &buffer_len);
1461 buffer_len = sizeof (recv_qos);
1462 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1463 &recv_qos, &buffer_len);
1466 ping_iterator_get_info (iter, PING_INFO_DATA,
1469 context = (ping_context_t *) ping_iterator_get_context (iter);
1472 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1474 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1477 update_context (context, latency);
1482 if (has_colors () == TRUE)
1485 int color = OPING_GREEN;
1487 percentile = latency_to_percentile (context, latency);
1488 if (percentile < (100.0 * threshold_green))
1489 color = OPING_GREEN;
1490 else if (percentile < (100.0 * threshold_yellow))
1491 color = OPING_YELLOW;
1496 if ((ratio_this <= threshold_green)
1497 || ((ratio_prev < threshold_green)
1498 && (ratio_this > threshold_green)))
1499 color = OPING_GREEN;
1500 else if ((ratio_this <= threshold_yellow)
1501 || ((ratio_prev < threshold_yellow)
1502 && (ratio_this > threshold_yellow)))
1503 color = OPING_YELLOW;
1508 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1509 data_len, context->host, context->addr,
1511 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1512 if ((recv_qos != 0) || (opt_send_qos != 0))
1514 HOST_PRINTF ("qos=%s ",
1515 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1517 HOST_PRINTF ("time=");
1518 wattron (main_win, COLOR_PAIR(color));
1519 HOST_PRINTF ("%.2f", latency);
1520 wattroff (main_win, COLOR_PAIR(color));
1521 HOST_PRINTF (" ms\n");
1526 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1528 context->host, context->addr,
1529 sequence, recv_ttl);
1530 if ((recv_qos != 0) || (opt_send_qos != 0))
1532 HOST_PRINTF ("qos=%s ",
1533 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1535 HOST_PRINTF ("time=%.2f ms\n", latency);
1540 else /* if (!(latency > 0.0)) */
1543 if (has_colors () == TRUE)
1545 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1546 context->host, context->addr,
1548 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1549 HOST_PRINTF ("timeout");
1550 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1556 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1557 context->host, context->addr,
1565 update_stats_from_context (context, iter);
1566 wrefresh (main_win);
1568 } /* }}} void update_host_hook */
1570 /* Prints statistics for each host, cleans up the contexts and returns the
1571 * number of hosts which failed to return more than the fraction
1572 * opt_exit_status_threshold of pings. */
1573 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1575 pingobj_iter_t *iter;
1576 int failure_count = 0;
1582 for (iter = ping_iterator_get (ping);
1584 iter = ping_iterator_next (iter))
1586 ping_context_t *context;
1588 context = ping_iterator_get_context (iter);
1590 printf ("\n--- %s ping statistics ---\n"
1591 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1592 context->host, context->req_sent, context->req_rcvd,
1593 context_get_packet_loss (context),
1594 context->latency_total);
1597 double pct_failed = 1.0 - (((double) context->req_rcvd)
1598 / ((double) context->req_sent));
1599 if (pct_failed > opt_exit_status_threshold)
1603 if (context->req_rcvd != 0)
1610 min = percentile_to_latency (context, 0.0);
1611 median = percentile_to_latency (context, 50.0);
1612 max = percentile_to_latency (context, 100.0);
1613 percentile = percentile_to_latency (context, opt_percentile);
1615 printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1616 min, median, opt_percentile, percentile, max);
1619 ping_iterator_set_context (iter, NULL);
1620 context_destroy (context);
1623 return (failure_count);
1624 } /* }}} int post_loop_hook */
1626 int main (int argc, char **argv) /* {{{ */
1629 pingobj_iter_t *iter;
1631 struct sigaction sigint_action;
1633 struct timeval tv_begin;
1634 struct timeval tv_end;
1635 struct timespec ts_wait;
1636 struct timespec ts_int;
1641 #if _POSIX_SAVED_IDS
1642 uid_t saved_set_uid;
1644 /* Save the old effective user id */
1645 saved_set_uid = geteuid ();
1646 /* Set the effective user ID to the real user ID without changing the
1647 * saved set-user ID */
1648 status = seteuid (getuid ());
1651 fprintf (stderr, "Temporarily dropping privileges "
1652 "failed: %s\n", strerror (errno));
1653 exit (EXIT_FAILURE);
1657 setlocale(LC_ALL, "");
1658 optind = read_options (argc, argv);
1660 #if !_POSIX_SAVED_IDS
1661 /* Cannot temporarily drop privileges -> reject every file but "-". */
1662 if ((opt_filename != NULL)
1663 && (strcmp ("-", opt_filename) != 0)
1664 && (getuid () != geteuid ()))
1666 fprintf (stderr, "Your real and effective user IDs don't "
1667 "match. Reading from a file (option '-f')\n"
1668 "is therefore too risky. You can still read "
1669 "from STDIN using '-f -' if you like.\n"
1671 exit (EXIT_FAILURE);
1675 if ((optind >= argc) && (opt_filename == NULL)) {
1676 usage_exit (argv[0], 1);
1679 if ((ping = ping_construct ()) == NULL)
1681 fprintf (stderr, "ping_construct failed\n");
1685 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1687 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1688 opt_send_ttl, ping_get_error (ping));
1691 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1693 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1694 opt_send_qos, ping_get_error (ping));
1701 temp_nsec = modf (opt_interval, &temp_sec);
1702 ts_int.tv_sec = (time_t) temp_sec;
1703 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1705 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1708 if (opt_addrfamily != PING_DEF_AF)
1709 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1711 if (opt_srcaddr != NULL)
1713 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1715 fprintf (stderr, "Setting source address failed: %s\n",
1716 ping_get_error (ping));
1720 if (opt_device != NULL)
1722 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1724 fprintf (stderr, "Setting device failed: %s\n",
1725 ping_get_error (ping));
1729 if (opt_filename != NULL)
1735 if (strcmp (opt_filename, "-") == 0)
1737 infile = fdopen(0, "r");
1739 infile = fopen(opt_filename, "r");
1743 fprintf (stderr, "Opening %s failed: %s\n",
1744 (strcmp (opt_filename, "-") == 0)
1745 ? "STDIN" : opt_filename,
1750 #if _POSIX_SAVED_IDS
1751 /* Regain privileges */
1752 status = seteuid (saved_set_uid);
1755 fprintf (stderr, "Temporarily re-gaining privileges "
1756 "failed: %s\n", strerror (errno));
1757 exit (EXIT_FAILURE);
1761 while (fgets(line, sizeof(line), infile))
1763 /* Strip whitespace */
1764 if (sscanf(line, "%s", host) != 1)
1767 if ((host[0] == 0) || (host[0] == '#'))
1770 if (ping_host_add(ping, host) < 0)
1772 const char *errmsg = ping_get_error (ping);
1774 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1783 #if _POSIX_SAVED_IDS
1784 /* Drop privileges */
1785 status = seteuid (getuid ());
1788 fprintf (stderr, "Temporarily dropping privileges "
1789 "failed: %s\n", strerror (errno));
1790 exit (EXIT_FAILURE);
1797 #if _POSIX_SAVED_IDS
1798 /* Regain privileges */
1799 status = seteuid (saved_set_uid);
1802 fprintf (stderr, "Temporarily re-gaining privileges "
1803 "failed: %s\n", strerror (errno));
1804 exit (EXIT_FAILURE);
1808 for (i = optind; i < argc; i++)
1810 if (ping_host_add (ping, argv[i]) < 0)
1812 const char *errmsg = ping_get_error (ping);
1814 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1823 /* Permanently drop root privileges if we're setuid-root. */
1824 status = setuid (getuid ());
1827 fprintf (stderr, "Dropping privileges failed: %s\n",
1829 exit (EXIT_FAILURE);
1833 exit (EXIT_FAILURE);
1835 #if _POSIX_SAVED_IDS
1836 saved_set_uid = (uid_t) -1;
1839 ping_initialize_contexts (ping);
1844 memset (&sigint_action, '\0', sizeof (sigint_action));
1845 sigint_action.sa_handler = sigint_handler;
1846 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1848 perror ("sigaction");
1852 pre_loop_hook (ping);
1854 while (opt_count != 0)
1859 if (gettimeofday (&tv_begin, NULL) < 0)
1861 perror ("gettimeofday");
1865 status = ping_send (ping);
1866 if (status == -EINTR)
1870 else if (status < 0)
1872 fprintf (stderr, "ping_send failed: %s\n",
1873 ping_get_error (ping));
1878 for (iter = ping_iterator_get (ping);
1880 iter = ping_iterator_next (iter))
1882 update_host_hook (iter, index);
1886 pre_sleep_hook (ping);
1888 /* Don't sleep in the last iteration */
1892 if (gettimeofday (&tv_end, NULL) < 0)
1894 perror ("gettimeofday");
1898 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1900 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1901 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1909 perror ("nanosleep");
1914 post_sleep_hook (ping);
1918 } /* while (opt_count != 0) */
1920 /* Returns the number of failed hosts according to -Z. */
1921 status = post_loop_hook (ping);
1923 ping_destroy (ping);
1926 exit (EXIT_SUCCESS);
1933 } /* }}} int main */
1935 /* vim: set fdm=marker : */