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