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