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];
171 /* Current number of entries in the history. This is a value between 0
172 * and HISTORY_SIZE_MAX. */
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. */
194 static double opt_interval = 1.0;
195 static int opt_addrfamily = PING_DEF_AF;
196 static char *opt_srcaddr = NULL;
197 static char *opt_device = NULL;
198 static char *opt_filename = NULL;
199 static int opt_count = -1;
200 static int opt_send_ttl = 64;
201 static uint8_t opt_send_qos = 0;
202 #define OPING_DEFAULT_PERCENTILE 95.0
203 static double opt_percentile = -1.0;
204 static double opt_exit_status_threshold = 1.0;
206 static int opt_show_graph = 1;
207 static int opt_utf8 = 0;
210 static int host_num = 0;
213 static WINDOW *main_win = NULL;
216 static void sigint_handler (int signal) /* {{{ */
218 /* Make compiler happy */
222 } /* }}} void sigint_handler */
224 static ping_context_t *context_create (void) /* {{{ */
228 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
231 memset (ret, '\0', sizeof (ping_context_t));
233 ret->latency_total = 0.0;
240 } /* }}} ping_context_t *context_create */
242 static void context_destroy (ping_context_t *context) /* {{{ */
248 if (context->window != NULL)
250 delwin (context->window);
251 context->window = NULL;
256 } /* }}} void context_destroy */
258 static int compare_double (void const *arg0, void const *arg1) /* {{{ */
260 double dbl0 = *((double *) arg0);
261 double dbl1 = *((double *) arg1);
270 else if (isnan (dbl1))
272 else if (dbl0 < dbl1)
274 else if (dbl0 > dbl1)
278 } /* }}} int compare_double */
280 static void clean_history (ping_context_t *ctx) /* {{{ */
284 if (!ctx->history_dirty)
287 /* Copy all values from by_time to by_value. */
288 memcpy (ctx->history_by_value, ctx->history_by_time,
289 sizeof (ctx->history_by_time));
292 qsort (ctx->history_by_value, ctx->history_size, sizeof
293 (ctx->history_by_value[0]), compare_double);
295 /* Update the number of received RTTs. */
296 ctx->history_received = 0;
297 for (i = 0; i < ctx->history_size; i++)
298 if (!isnan (ctx->history_by_value[i]))
299 ctx->history_received++;
302 ctx->history_dirty = 0;
303 } /* }}} void clean_history */
305 static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
312 /* Not a single packet was received successfully. */
313 if (ctx->history_received == 0)
316 if (percentile <= 0.0)
318 else if (percentile >= 100.0)
319 index = ctx->history_received - 1;
322 index = (size_t) ceil ((percentile / 100.0) * ((double) ctx->history_received));
327 return (ctx->history_by_value[index]);
328 } /* }}} double percentile_to_latency */
331 static double latency_to_ratio (ping_context_t *ctx, /* {{{ */
340 /* Not a single packet was received successfully. */
341 if (ctx->history_received == 0)
345 high = ctx->history_received - 1;
347 if (latency < ctx->history_by_value[low])
349 else if (latency >= ctx->history_by_value[high])
352 /* Do a binary search for the latency. This will work even when the
353 * exact latency is not in the array. If the latency is in the array
354 * multiple times, "low" will be set to the index of the last
355 * occurrence. The value at index "high" will be larger than the
356 * searched for latency (assured by the above "if" block. */
357 while ((high - low) > 1)
359 index = (high + low) / 2;
361 if (ctx->history_by_value[index] > latency)
367 assert (ctx->history_by_value[high] > latency);
368 assert (ctx->history_by_value[low] <= latency);
370 if (ctx->history_by_value[low] == latency)
375 return (((double) (index + 1)) / ((double) ctx->history_received));
376 } /* }}} double latency_to_ratio */
379 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
384 if (ctx->req_sent < 1)
387 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
388 / ((double) ctx->req_sent));
389 } /* }}} double context_get_packet_loss */
391 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
393 pingobj_iter_t *iter;
400 for (iter = ping_iterator_get (ping);
402 iter = ping_iterator_next (iter))
404 ping_context_t *context;
407 context = context_create ();
408 context->index = index;
410 buffer_size = sizeof (context->host);
411 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
413 buffer_size = sizeof (context->addr);
414 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
416 ping_iterator_set_context (iter, (void *) context);
422 } /* }}} int ping_initialize_contexts */
424 static void usage_exit (const char *name, int status) /* {{{ */
426 fprintf (stderr, "Usage: %s [OPTIONS] "
427 "-f filename | host [host [host ...]]\n"
429 "\nAvailable options:\n"
430 " -4|-6 force the use of IPv4 or IPv6\n"
431 " -c count number of ICMP packets to send\n"
432 " -i interval interval with which to send ICMP packets\n"
433 " -t ttl time to live for each ICMP packet\n"
434 " -Q qos Quality of Service (QoS) of outgoing packets\n"
435 " Use \"-Q help\" for a list of valid options.\n"
436 " -I srcaddr source address\n"
437 " -D device outgoing interface name\n"
438 " -f filename filename to read hosts from\n"
440 " -u / -U force / disable UTF-8 output\n"
441 " -g graph graph type to draw\n"
443 " -P percent Report the n'th percentile of latency\n"
444 " -Z percent Exit with non-zero exit status if more than this percentage of\n"
445 " probes timed out. (default: never)\n"
447 "\noping "PACKAGE_VERSION", http://noping.cc/\n"
448 "by Florian octo Forster <ff@octo.it>\n"
449 "for contributions see `AUTHORS'\n",
452 } /* }}} void usage_exit */
454 __attribute__((noreturn))
455 static void usage_qos_exit (const char *arg, int status) /* {{{ */
458 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
460 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
462 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
464 " be Best Effort (BE, default PHB).\n"
465 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
466 " (low delay, low loss, low jitter)\n"
467 " va Voice Admit (VA) DSCP (RFC 5865).\n"
468 " (capacity-admitted traffic)\n"
469 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
470 " For example: \"af12\" (class 1, precedence 2)\n"
471 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
472 " For example: \"cs1\" (priority traffic)\n"
474 " Type of Service (IPv4, RFC 1349, obsolete)\n"
476 " lowdelay (%#04x) minimize delay\n"
477 " throughput (%#04x) maximize throughput\n"
478 " reliability (%#04x) maximize reliability\n"
479 " mincost (%#04x) minimize monetary cost\n"
481 " Specify manually\n"
483 " 0x00 - 0xff Hexadecimal numeric specification.\n"
484 " 0 - 255 Decimal numeric specification.\n"
486 (unsigned int) IPTOS_LOWDELAY,
487 (unsigned int) IPTOS_THROUGHPUT,
488 (unsigned int) IPTOS_RELIABILITY,
489 (unsigned int) IPTOS_MINCOST);
492 } /* }}} void usage_qos_exit */
494 static int set_opt_send_qos (const char *opt) /* {{{ */
499 if (strcasecmp ("help", opt) == 0)
500 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
501 /* DiffServ (RFC 2474): */
502 /* - Best effort (BE) */
503 else if (strcasecmp ("be", opt) == 0)
505 /* - Expedited Forwarding (EF, RFC 3246) */
506 else if (strcasecmp ("ef", opt) == 0)
507 opt_send_qos = 0xB8; /* == 0x2E << 2 */
508 /* - Voice Admit (VA, RFC 5865) */
509 else if (strcasecmp ("va", opt) == 0)
510 opt_send_qos = 0xB0; /* == 0x2D << 2 */
511 /* - Assured Forwarding (AF, RFC 2597) */
512 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
513 && (strlen (opt) == 4))
519 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
522 else if (opt[2] == '2')
524 else if (opt[2] == '3')
526 else if (opt[2] == '4')
529 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
531 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
534 else if (opt[3] == '2')
536 else if (opt[3] == '3')
539 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
541 dscp = (8 * class) + (2 * prec);
542 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
543 opt_send_qos = dscp << 2;
545 /* - Class Selector (CS) */
546 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
547 && (strlen (opt) == 3))
551 if ((opt[2] < '0') || (opt[2] > '7'))
552 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
554 /* Not exactly legal by the C standard, but I don't know of any
555 * system not supporting this hack. */
556 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
557 opt_send_qos = class << 5;
559 /* Type of Service (RFC 1349) */
560 else if (strcasecmp ("lowdelay", opt) == 0)
561 opt_send_qos = IPTOS_LOWDELAY;
562 else if (strcasecmp ("throughput", opt) == 0)
563 opt_send_qos = IPTOS_THROUGHPUT;
564 else if (strcasecmp ("reliability", opt) == 0)
565 opt_send_qos = IPTOS_RELIABILITY;
566 else if (strcasecmp ("mincost", opt) == 0)
567 opt_send_qos = IPTOS_MINCOST;
576 value = strtoul (opt, &endptr, /* base = */ 0);
577 if ((errno != 0) || (endptr == opt)
578 || (endptr == NULL) || (*endptr != 0)
580 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
582 opt_send_qos = (uint8_t) value;
586 } /* }}} int set_opt_send_qos */
588 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
600 case 0x00: dscp_str = "be"; break;
601 case 0x2e: dscp_str = "ef"; break;
602 case 0x2d: dscp_str = "va"; break;
603 case 0x0a: dscp_str = "af11"; break;
604 case 0x0c: dscp_str = "af12"; break;
605 case 0x0e: dscp_str = "af13"; break;
606 case 0x12: dscp_str = "af21"; break;
607 case 0x14: dscp_str = "af22"; break;
608 case 0x16: dscp_str = "af23"; break;
609 case 0x1a: dscp_str = "af31"; break;
610 case 0x1c: dscp_str = "af32"; break;
611 case 0x1e: dscp_str = "af33"; break;
612 case 0x22: dscp_str = "af41"; break;
613 case 0x24: dscp_str = "af42"; break;
614 case 0x26: dscp_str = "af43"; break;
615 case 0x08: dscp_str = "cs1"; break;
616 case 0x10: dscp_str = "cs2"; break;
617 case 0x18: dscp_str = "cs3"; break;
618 case 0x20: dscp_str = "cs4"; break;
619 case 0x28: dscp_str = "cs5"; break;
620 case 0x30: dscp_str = "cs6"; break;
621 case 0x38: dscp_str = "cs7"; break;
622 default: dscp_str = NULL;
627 case 0x01: ecn_str = ",ecn(1)"; break;
628 case 0x02: ecn_str = ",ecn(0)"; break;
629 case 0x03: ecn_str = ",ce"; break;
630 default: ecn_str = "";
633 if (dscp_str == NULL)
634 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
636 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
637 buffer[buffer_size - 1] = 0;
640 } /* }}} char *format_qos */
642 static int read_options (int argc, char **argv) /* {{{ */
648 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:P:"
661 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
667 new_count = atoi (optarg);
670 opt_count = new_count;
672 if ((opt_percentile < 0.0) && (opt_count < 20))
673 opt_percentile = 100.0 * (opt_count - 1) / opt_count;
676 fprintf(stderr, "Ignoring invalid count: %s\n",
683 if (opt_filename != NULL)
685 opt_filename = strdup (optarg);
692 new_interval = atof (optarg);
693 if (new_interval < 0.001)
694 fprintf (stderr, "Ignoring invalid interval: %s\n",
697 opt_interval = new_interval;
703 if (opt_srcaddr != NULL)
705 opt_srcaddr = strdup (optarg);
716 new_send_ttl = atoi (optarg);
717 if ((new_send_ttl > 0) && (new_send_ttl < 256))
718 opt_send_ttl = new_send_ttl;
720 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
726 set_opt_send_qos (optarg);
731 double new_percentile;
732 new_percentile = atof (optarg);
733 if (isnan (new_percentile)
734 || (new_percentile < 0.1)
735 || (new_percentile > 100.0))
736 fprintf (stderr, "Ignoring invalid percentile: %s\n",
739 opt_percentile = new_percentile;
745 if (strcasecmp ("none", optarg) == 0)
747 else if (strcasecmp ("prettyping", optarg) == 0)
749 else if (strcasecmp ("histogram", optarg) == 0)
751 else if (strcasecmp ("boxplot", optarg) == 0)
754 fprintf (stderr, "Unknown graph option: %s\n", optarg);
771 tmp = strtod (optarg, &endptr);
772 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
774 fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
775 fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
778 opt_exit_status_threshold = tmp / 100.0;
784 usage_exit (argv[0], 0);
788 usage_exit (argv[0], 1);
792 if (opt_percentile <= 0.0)
793 opt_percentile = OPING_DEFAULT_PERCENTILE;
796 } /* }}} read_options */
798 static void time_normalize (struct timespec *ts) /* {{{ */
800 while (ts->tv_nsec < 0)
809 ts->tv_nsec += 1000000000;
812 while (ts->tv_nsec >= 1000000000)
815 ts->tv_nsec -= 1000000000;
817 } /* }}} void time_normalize */
819 static void time_calc (struct timespec *ts_dest, /* {{{ */
820 const struct timespec *ts_int,
821 const struct timeval *tv_begin,
822 const struct timeval *tv_end)
824 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
825 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
826 time_normalize (ts_dest);
828 /* Assure that `(begin + interval) > end'.
829 * This may seem overly complicated, but `tv_sec' is of type `time_t'
830 * which may be `unsigned. *sigh* */
831 if ((tv_end->tv_sec > ts_dest->tv_sec)
832 || ((tv_end->tv_sec == ts_dest->tv_sec)
833 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
836 ts_dest->tv_nsec = 0;
840 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
841 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
842 time_normalize (ts_dest);
843 } /* }}} void time_calc */
846 static _Bool has_utf8() /* {{{ */
848 # if HAVE_NCURSESW_NCURSES_H
851 /* Automatically determine */
852 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
857 return ((_Bool) (opt_utf8 - 1));
861 } /* }}} _Bool has_utf8 */
863 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
873 if (ctx->history_received == 0)
876 x_max = (size_t) getmaxx (ctx->window);
881 counters = calloc (x_max, sizeof (*counters));
882 ratios = calloc (x_max, sizeof (*ratios));
885 for (i = 0; i < ctx->history_received; i++)
887 double latency = ctx->history_by_value[i] / 1000.0;
888 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
896 /* Sum and calc ratios */
897 ratios[0] = ((double) counters[0]) / ((double) ctx->history_received);
898 for (x = 1; x < x_max; x++)
900 counters[x] += counters[x - 1];
901 ratios[x] = ((double) counters[x]) / ((double) ctx->history_received);
904 for (x = 0; x < x_max; x++)
911 if (ratios[x] >= 0.5)
913 symbol = BOXPLOT_MEDIAN;
916 else if (ratios[x] > 0.25)
918 symbol = BOXPLOT_BOX;
921 else if (ratios[x] > 0.025)
922 symbol = BOXPLOT_WHISKER_BAR;
924 symbol = ' '; /* NOP */
928 if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
930 symbol = BOXPLOT_MEDIAN;
933 else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
934 || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
936 symbol = BOXPLOT_BOX;
939 else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
941 if (ratios[x - 1] < 0.025)
942 symbol = BOXPLOT_WHISKER_LEFT_END;
944 symbol = BOXPLOT_WHISKER_BAR;
946 else if ((ratios[x] > .5) && (ratios[x] < 0.975))
948 symbol = BOXPLOT_WHISKER_BAR;
950 else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
951 symbol = BOXPLOT_WHISKER_RIGHT_END;
955 wattron (ctx->window, A_REVERSE);
956 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
957 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
959 wattroff (ctx->window, A_REVERSE);
965 } /* }}} int update_graph_boxplot */
967 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
968 double latency, unsigned int sequence)
972 size_t history_offset;
974 x_max = (size_t) getmaxx (ctx->window);
979 /* Determine the first index in the history we need to draw
982 if (((size_t) x_max) < ctx->history_size) /* window is smaller than history */
984 if (ctx->history_index > x_max)
985 history_offset = ctx->history_index - x_max;
986 else /* wrap around */
987 history_offset = ctx->history_index + ctx->history_size - x_max;
989 else /* window is larger than history */
991 if (ctx->history_index != ctx->history_size) /* no longer growing. */
992 history_offset = ctx->history_index;
997 for (x = 0; x < x_max; x++)
1002 int color = OPING_RED;
1003 char const *symbol = "!";
1006 if (x >= ctx->history_size)
1008 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1012 index = (history_offset + x) % ctx->history_size;
1013 latency = ctx->history_by_time[index];
1019 size_t symbols_num = hist_symbols_acs_num;
1020 size_t colors_num = 1;
1022 size_t index_symbols;
1023 size_t index_colors;
1026 /* latency is in milliseconds, opt_interval is in seconds. */
1027 ratio = (latency * 0.001) / opt_interval;
1033 symbols_num = hist_symbols_utf8_num;
1035 if (has_colors () == TRUE)
1036 colors_num = hist_colors_num;
1038 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
1039 if (intensity >= (symbols_num * colors_num))
1040 intensity = (symbols_num * colors_num) - 1;
1042 index_symbols = intensity % symbols_num;
1043 assert (index_symbols < symbols_num);
1045 index_colors = intensity / symbols_num;
1046 assert (index_colors < colors_num);
1050 color = hist_colors_utf8[index_colors];
1051 symbol = hist_symbols_utf8[index_symbols];
1055 color = hist_colors_acs[index_colors];
1056 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
1059 else /* if (!(latency >= 0.0)) */
1060 wattron (ctx->window, A_BOLD);
1062 if (has_colors () == TRUE)
1063 wattron (ctx->window, COLOR_PAIR(color));
1066 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2, symbol);
1068 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, symbolc);
1070 if (has_colors () == TRUE)
1071 wattroff (ctx->window, COLOR_PAIR(color));
1073 /* Use negation here to handle NaN correctly. */
1074 if (!(latency >= 0.0))
1075 wattroff (ctx->window, A_BOLD);
1079 } /* }}} int update_graph_prettyping */
1081 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
1084 uint32_t *accumulated;
1090 size_t symbols_num = hist_symbols_acs_num;
1092 clean_history (ctx);
1094 if (ctx->history_received == 0)
1098 symbols_num = hist_symbols_utf8_num;
1100 x_max = (size_t) getmaxx (ctx->window);
1105 counters = calloc (x_max, sizeof (*counters));
1106 accumulated = calloc (x_max, sizeof (*accumulated));
1110 for (i = 0; i < ctx->history_received; i++)
1112 double latency = ctx->history_by_value[i] / 1000.0;
1113 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
1119 if (max < counters[index])
1120 max = counters[index];
1124 accumulated[0] = counters[0];
1125 for (x = 1; x < x_max; x++)
1126 accumulated[x] = counters[x] + accumulated[x - 1];
1128 /* Calculate ratios */
1129 for (x = 0; x < x_max; x++)
1131 double height = ((double) counters[x]) / ((double) max);
1132 double ratio_this = ((double) accumulated[x]) / ((double) ctx->history_received);
1133 double ratio_prev = 0.0;
1137 index = (size_t) (height * ((double) symbols_num));
1138 if (index >= symbols_num)
1139 index = symbols_num - 1;
1142 ratio_prev = ((double) accumulated[x - 1]) / ((double) ctx->history_received);
1144 if (has_colors () == TRUE)
1146 if ((ratio_this <= threshold_green)
1147 || ((ratio_prev < threshold_green)
1148 && (ratio_this > threshold_green)))
1149 color = OPING_GREEN;
1150 else if ((ratio_this <= threshold_yellow)
1151 || ((ratio_prev < threshold_yellow)
1152 && (ratio_this > threshold_yellow)))
1153 color = OPING_YELLOW;
1157 wattron (ctx->window, COLOR_PAIR(color));
1160 if (counters[x] == 0)
1161 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1162 else if (has_utf8 ())
1163 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1164 hist_symbols_utf8[index]);
1166 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1167 hist_symbols_acs[index] | A_ALTCHARSET);
1169 if (has_colors () == TRUE)
1170 wattroff (ctx->window, COLOR_PAIR(color));
1176 } /* }}} int update_graph_histogram */
1178 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1180 double latency = -1.0;
1181 size_t buffer_len = sizeof (latency);
1183 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1184 &latency, &buffer_len);
1186 unsigned int sequence = 0;
1187 buffer_len = sizeof (sequence);
1188 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1189 &sequence, &buffer_len);
1192 if ((ctx == NULL) || (ctx->window == NULL))
1195 /* werase (ctx->window); */
1197 box (ctx->window, 0, 0);
1198 wattron (ctx->window, A_BOLD);
1199 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1201 wattroff (ctx->window, A_BOLD);
1202 wprintw (ctx->window, "ping statistics ");
1203 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1204 "%i packets transmitted, %i received, %.2f%% packet "
1205 "loss, time %.1fms",
1206 ctx->req_sent, ctx->req_rcvd,
1207 context_get_packet_loss (ctx),
1208 ctx->latency_total);
1209 if (ctx->req_rcvd != 0)
1216 min = percentile_to_latency (ctx, 0.0);
1217 median = percentile_to_latency (ctx, 50.0);
1218 max = percentile_to_latency (ctx, 100.0);
1219 percentile = percentile_to_latency (ctx, opt_percentile);
1221 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1222 "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f ",
1223 min, median, opt_percentile, percentile, max);
1226 if (opt_show_graph == 1)
1227 update_graph_prettyping (ctx, latency, sequence);
1228 else if (opt_show_graph == 2)
1229 update_graph_histogram (ctx);
1230 else if (opt_show_graph == 3)
1231 update_graph_boxplot (ctx);
1233 wrefresh (ctx->window);
1236 } /* }}} int update_stats_from_context */
1238 static int on_resize (pingobj_t *ping) /* {{{ */
1240 pingobj_iter_t *iter;
1243 int main_win_height;
1244 int box_height = (opt_show_graph == 0) ? 4 : 5;
1246 getmaxyx (stdscr, height, width);
1247 if ((height < 1) || (width < 1))
1250 main_win_height = height - (box_height * host_num);
1251 wresize (main_win, main_win_height, /* width = */ width);
1252 /* Allow scrolling */
1253 scrollok (main_win, TRUE);
1254 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1255 /* Allow hardware accelerated scrolling. */
1256 idlok (main_win, TRUE);
1257 wrefresh (main_win);
1259 for (iter = ping_iterator_get (ping);
1261 iter = ping_iterator_next (iter))
1263 ping_context_t *context;
1265 context = ping_iterator_get_context (iter);
1266 if (context == NULL)
1269 if (context->window != NULL)
1271 delwin (context->window);
1272 context->window = NULL;
1274 context->window = newwin (/* height = */ box_height,
1275 /* width = */ width,
1276 /* y = */ main_win_height + (box_height * context->index),
1283 static int check_resize (pingobj_t *ping) /* {{{ */
1285 int need_resize = 0;
1289 int key = wgetch (stdscr);
1292 else if (key == KEY_RESIZE)
1294 else if (key == 'g')
1296 if (opt_show_graph == 3)
1298 else if (opt_show_graph > 0)
1304 return (on_resize (ping));
1307 } /* }}} int check_resize */
1309 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1311 pingobj_iter_t *iter;
1314 int main_win_height;
1315 int box_height = (opt_show_graph == 0) ? 4 : 5;
1320 nodelay (stdscr, TRUE);
1322 getmaxyx (stdscr, height, width);
1323 if ((height < 1) || (width < 1))
1326 if (has_colors () == TRUE)
1329 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
1330 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1331 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
1332 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
1333 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1334 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
1337 main_win_height = height - (box_height * host_num);
1338 main_win = newwin (/* height = */ main_win_height,
1339 /* width = */ width,
1340 /* y = */ 0, /* x = */ 0);
1341 /* Allow scrolling */
1342 scrollok (main_win, TRUE);
1343 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1344 /* Allow hardware accelerated scrolling. */
1345 idlok (main_win, TRUE);
1346 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1347 wrefresh (main_win);
1349 for (iter = ping_iterator_get (ping);
1351 iter = ping_iterator_next (iter))
1353 ping_context_t *context;
1355 context = ping_iterator_get_context (iter);
1356 if (context == NULL)
1359 if (context->window != NULL)
1361 delwin (context->window);
1362 context->window = NULL;
1364 context->window = newwin (/* height = */ box_height,
1365 /* width = */ width,
1366 /* y = */ main_win_height + (box_height * context->index),
1371 /* Don't know what good this does exactly, but without this code
1372 * "check_resize" will be called right after startup and *somehow*
1373 * this leads to display errors. If we purge all initial characters
1374 * here, the problem goes away. "wgetch" is non-blocking due to
1375 * "nodelay" (see above). */
1376 while (wgetch (stdscr) != ERR)
1378 /* eat up characters */;
1382 } /* }}} int pre_loop_hook */
1384 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1386 return (check_resize (ping));
1387 } /* }}} int pre_sleep_hook */
1389 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1391 return (check_resize (ping));
1392 } /* }}} int pre_sleep_hook */
1393 #else /* if !USE_NCURSES */
1394 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1396 pingobj_iter_t *iter;
1398 for (iter = ping_iterator_get (ping);
1400 iter = ping_iterator_next (iter))
1402 ping_context_t *ctx;
1405 ctx = ping_iterator_get_context (iter);
1410 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1412 printf ("PING %s (%s) %zu bytes of data.\n",
1413 ctx->host, ctx->addr, buffer_size);
1417 } /* }}} int pre_loop_hook */
1419 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1424 } /* }}} int pre_sleep_hook */
1426 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1429 } /* }}} int post_sleep_hook */
1432 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1439 ctx->latency_total += latency;
1446 ctx->history_by_time[ctx->history_index] = latency;
1448 ctx->history_dirty = 1;
1450 /* Update index and size. */
1451 ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1452 if (ctx->history_size < HISTORY_SIZE_MAX)
1453 ctx->history_size++;
1454 } /* }}} void update_context */
1456 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1457 __attribute__((unused)) int index)
1460 unsigned int sequence;
1463 char recv_qos_str[16];
1466 ping_context_t *context;
1469 buffer_len = sizeof (latency);
1470 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1471 &latency, &buffer_len);
1474 buffer_len = sizeof (sequence);
1475 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1476 &sequence, &buffer_len);
1479 buffer_len = sizeof (recv_ttl);
1480 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1481 &recv_ttl, &buffer_len);
1484 buffer_len = sizeof (recv_qos);
1485 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1486 &recv_qos, &buffer_len);
1489 ping_iterator_get_info (iter, PING_INFO_DATA,
1492 context = (ping_context_t *) ping_iterator_get_context (iter);
1495 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1497 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1500 update_context (context, latency);
1505 if (has_colors () == TRUE)
1508 int color = OPING_GREEN;
1510 ratio = latency_to_ratio (context, latency);
1511 if (ratio < threshold_green)
1512 color = OPING_GREEN;
1513 else if (ratio < threshold_yellow)
1514 color = OPING_YELLOW;
1518 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1519 data_len, context->host, context->addr,
1521 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1522 if ((recv_qos != 0) || (opt_send_qos != 0))
1524 HOST_PRINTF ("qos=%s ",
1525 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1527 HOST_PRINTF ("time=");
1528 wattron (main_win, COLOR_PAIR(color));
1529 HOST_PRINTF ("%.2f", latency);
1530 wattroff (main_win, COLOR_PAIR(color));
1531 HOST_PRINTF (" ms\n");
1536 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1538 context->host, context->addr,
1539 sequence, recv_ttl);
1540 if ((recv_qos != 0) || (opt_send_qos != 0))
1542 HOST_PRINTF ("qos=%s ",
1543 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1545 HOST_PRINTF ("time=%.2f ms\n", latency);
1550 else /* if (!(latency > 0.0)) */
1553 if (has_colors () == TRUE)
1555 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1556 context->host, context->addr,
1558 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1559 HOST_PRINTF ("timeout");
1560 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1566 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1567 context->host, context->addr,
1575 update_stats_from_context (context, iter);
1576 wrefresh (main_win);
1578 } /* }}} void update_host_hook */
1580 /* Prints statistics for each host, cleans up the contexts and returns the
1581 * number of hosts which failed to return more than the fraction
1582 * opt_exit_status_threshold of pings. */
1583 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1585 pingobj_iter_t *iter;
1586 int failure_count = 0;
1592 for (iter = ping_iterator_get (ping);
1594 iter = ping_iterator_next (iter))
1596 ping_context_t *context;
1598 context = ping_iterator_get_context (iter);
1600 printf ("\n--- %s ping statistics ---\n"
1601 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1602 context->host, context->req_sent, context->req_rcvd,
1603 context_get_packet_loss (context),
1604 context->latency_total);
1607 double pct_failed = 1.0 - (((double) context->req_rcvd)
1608 / ((double) context->req_sent));
1609 if (pct_failed > opt_exit_status_threshold)
1613 if (context->req_rcvd != 0)
1620 min = percentile_to_latency (context, 0.0);
1621 median = percentile_to_latency (context, 50.0);
1622 max = percentile_to_latency (context, 100.0);
1623 percentile = percentile_to_latency (context, opt_percentile);
1625 printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1626 min, median, opt_percentile, percentile, max);
1629 ping_iterator_set_context (iter, NULL);
1630 context_destroy (context);
1633 return (failure_count);
1634 } /* }}} int post_loop_hook */
1636 int main (int argc, char **argv) /* {{{ */
1639 pingobj_iter_t *iter;
1641 struct sigaction sigint_action;
1643 struct timeval tv_begin;
1644 struct timeval tv_end;
1645 struct timespec ts_wait;
1646 struct timespec ts_int;
1651 #if _POSIX_SAVED_IDS
1652 uid_t saved_set_uid;
1654 /* Save the old effective user id */
1655 saved_set_uid = geteuid ();
1656 /* Set the effective user ID to the real user ID without changing the
1657 * saved set-user ID */
1658 status = seteuid (getuid ());
1661 fprintf (stderr, "Temporarily dropping privileges "
1662 "failed: %s\n", strerror (errno));
1663 exit (EXIT_FAILURE);
1667 setlocale(LC_ALL, "");
1668 optind = read_options (argc, argv);
1670 #if !_POSIX_SAVED_IDS
1671 /* Cannot temporarily drop privileges -> reject every file but "-". */
1672 if ((opt_filename != NULL)
1673 && (strcmp ("-", opt_filename) != 0)
1674 && (getuid () != geteuid ()))
1676 fprintf (stderr, "Your real and effective user IDs don't "
1677 "match. Reading from a file (option '-f')\n"
1678 "is therefore too risky. You can still read "
1679 "from STDIN using '-f -' if you like.\n"
1681 exit (EXIT_FAILURE);
1685 if ((optind >= argc) && (opt_filename == NULL)) {
1686 usage_exit (argv[0], 1);
1689 if ((ping = ping_construct ()) == NULL)
1691 fprintf (stderr, "ping_construct failed\n");
1695 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1697 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1698 opt_send_ttl, ping_get_error (ping));
1701 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1703 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1704 opt_send_qos, ping_get_error (ping));
1711 temp_nsec = modf (opt_interval, &temp_sec);
1712 ts_int.tv_sec = (time_t) temp_sec;
1713 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1715 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1718 if (opt_addrfamily != PING_DEF_AF)
1719 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1721 if (opt_srcaddr != NULL)
1723 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1725 fprintf (stderr, "Setting source address failed: %s\n",
1726 ping_get_error (ping));
1730 if (opt_device != NULL)
1732 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1734 fprintf (stderr, "Setting device failed: %s\n",
1735 ping_get_error (ping));
1739 if (opt_filename != NULL)
1745 if (strcmp (opt_filename, "-") == 0)
1747 infile = fdopen(0, "r");
1749 infile = fopen(opt_filename, "r");
1753 fprintf (stderr, "Opening %s failed: %s\n",
1754 (strcmp (opt_filename, "-") == 0)
1755 ? "STDIN" : opt_filename,
1760 #if _POSIX_SAVED_IDS
1761 /* Regain privileges */
1762 status = seteuid (saved_set_uid);
1765 fprintf (stderr, "Temporarily re-gaining privileges "
1766 "failed: %s\n", strerror (errno));
1767 exit (EXIT_FAILURE);
1771 while (fgets(line, sizeof(line), infile))
1773 /* Strip whitespace */
1774 if (sscanf(line, "%s", host) != 1)
1777 if ((host[0] == 0) || (host[0] == '#'))
1780 if (ping_host_add(ping, host) < 0)
1782 const char *errmsg = ping_get_error (ping);
1784 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1793 #if _POSIX_SAVED_IDS
1794 /* Drop privileges */
1795 status = seteuid (getuid ());
1798 fprintf (stderr, "Temporarily dropping privileges "
1799 "failed: %s\n", strerror (errno));
1800 exit (EXIT_FAILURE);
1807 #if _POSIX_SAVED_IDS
1808 /* Regain privileges */
1809 status = seteuid (saved_set_uid);
1812 fprintf (stderr, "Temporarily re-gaining privileges "
1813 "failed: %s\n", strerror (errno));
1814 exit (EXIT_FAILURE);
1818 for (i = optind; i < argc; i++)
1820 if (ping_host_add (ping, argv[i]) < 0)
1822 const char *errmsg = ping_get_error (ping);
1824 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1833 /* Permanently drop root privileges if we're setuid-root. */
1834 status = setuid (getuid ());
1837 fprintf (stderr, "Dropping privileges failed: %s\n",
1839 exit (EXIT_FAILURE);
1843 exit (EXIT_FAILURE);
1845 #if _POSIX_SAVED_IDS
1846 saved_set_uid = (uid_t) -1;
1849 ping_initialize_contexts (ping);
1854 memset (&sigint_action, '\0', sizeof (sigint_action));
1855 sigint_action.sa_handler = sigint_handler;
1856 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1858 perror ("sigaction");
1862 pre_loop_hook (ping);
1864 while (opt_count != 0)
1869 if (gettimeofday (&tv_begin, NULL) < 0)
1871 perror ("gettimeofday");
1875 status = ping_send (ping);
1876 if (status == -EINTR)
1880 else if (status < 0)
1882 fprintf (stderr, "ping_send failed: %s\n",
1883 ping_get_error (ping));
1888 for (iter = ping_iterator_get (ping);
1890 iter = ping_iterator_next (iter))
1892 update_host_hook (iter, index);
1896 pre_sleep_hook (ping);
1898 /* Don't sleep in the last iteration */
1902 if (gettimeofday (&tv_end, NULL) < 0)
1904 perror ("gettimeofday");
1908 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1910 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1911 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1919 perror ("nanosleep");
1924 post_sleep_hook (ping);
1928 } /* while (opt_count != 0) */
1930 /* Returns the number of failed hosts according to -Z. */
1931 status = post_loop_hook (ping);
1933 ping_destroy (ping);
1936 exit (EXIT_SUCCESS);
1943 } /* }}} int main */
1945 /* vim: set fdm=marker : */