Code

5e63392092acbaa7b3dea0d76be3161c5e846cbd
[liboping.git] / src / oping.c
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 static char const * const hist_symbols_utf8[] = {
99         "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
100 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
101         / sizeof (hist_symbols_utf8[0]);
103 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
104 /* those are not the usual constants because those are not constant */
105 static int const hist_symbols_acs[] = {
106         115, /* ACS_S9 "⎽" */
107         114, /* ACS_S7 "⎼" */
108         113, /* ACS_S5 "─" */
109         112, /* ACS_S3 "⎻" */
110         111  /* ACS_S1 "⎺" */
111 };
112 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
113         / sizeof (hist_symbols_acs[0]);
115 /* use different colors without a background for scancodes */
116 static int const hist_colors_utf8[] = {
117         OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
118 static int const hist_colors_acs[] = {
119         OPING_GREEN, OPING_YELLOW, OPING_RED };
120 /* assuming that both arrays are the same size */
121 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
122         / sizeof (hist_colors_utf8[0]);
123 #endif
125 /* "─" */
126 #define BOXPLOT_WHISKER_BAR       (113 | A_ALTCHARSET)
127 /* "├" */
128 #define BOXPLOT_WHISKER_LEFT_END  (116 | A_ALTCHARSET)
129 /* "┤" */
130 #define BOXPLOT_WHISKER_RIGHT_END (117 | A_ALTCHARSET)
131 /* Inverted */
132 #define BOXPLOT_BOX               ' '
133 /* "│", inverted */
134 #define BOXPLOT_MEDIAN            (120 | A_ALTCHARSET)
136 #include "oping.h"
138 #ifndef _POSIX_SAVED_IDS
139 # define _POSIX_SAVED_IDS 0
140 #endif
142 #ifndef IPTOS_MINCOST
143 # define IPTOS_MINCOST 0x02
144 #endif
146 /* Remove GNU specific __attribute__ settings when using another compiler */
147 #if !__GNUC__
148 # define __attribute__(x) /**/
149 #endif
151 typedef struct ping_context
153         char host[NI_MAXHOST];
154         char addr[NI_MAXHOST];
156         int index;
157         int req_sent;
158         int req_rcvd;
160         double latency_min;
161         double latency_max;
162         double latency_total;
163         double latency_total_square;
165 /* 1000 + one "infinity" bucket. */
166 #define OPING_HISTOGRAM_BUCKETS 1001
167         uint32_t *histogram_counters;
168         uint32_t *histogram_accumulated;
169         double *histogram_ratio;
170         size_t latency_histogram_size;
172 #if USE_NCURSES
173         WINDOW *window;
174 #endif
175 } ping_context_t;
177 static double  opt_interval   = 1.0;
178 static int     opt_addrfamily = PING_DEF_AF;
179 static char   *opt_srcaddr    = NULL;
180 static char   *opt_device     = NULL;
181 static char   *opt_filename   = NULL;
182 static int     opt_count      = -1;
183 static int     opt_send_ttl   = 64;
184 static uint8_t opt_send_qos   = 0;
185 #define OPING_DEFAULT_PERCENTILE 95.0
186 static double  opt_percentile = -1.0;
187 static double  opt_exit_status_threshold = 1.0;
188 #if USE_NCURSES
189 static int     opt_show_graph = 1;
190 static int     opt_utf8       = 0;
191 #endif
193 static int host_num = 0;
195 #if USE_NCURSES
196 static WINDOW *main_win = NULL;
197 #endif
199 static void sigint_handler (int signal) /* {{{ */
201         /* Make compiler happy */
202         signal = 0;
203         /* Exit the loop */
204         opt_count = 0;
205 } /* }}} void sigint_handler */
207 static ping_context_t *context_create (void) /* {{{ */
209         ping_context_t *ret;
211         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
212                 return (NULL);
214         memset (ret, '\0', sizeof (ping_context_t));
216         ret->latency_min   = -1.0;
217         ret->latency_max   = -1.0;
218         ret->latency_total = 0.0;
219         ret->latency_total_square = 0.0;
221         ret->latency_histogram_size = (size_t) OPING_HISTOGRAM_BUCKETS;
222         ret->histogram_counters = calloc (ret->latency_histogram_size,
223                         sizeof (*ret->histogram_counters));
224         ret->histogram_accumulated = calloc (ret->latency_histogram_size,
225                         sizeof (*ret->histogram_accumulated));
226         ret->histogram_ratio = calloc (ret->latency_histogram_size,
227                         sizeof (*ret->histogram_ratio));
229 #if USE_NCURSES
230         ret->window = NULL;
231 #endif
233         return (ret);
234 } /* }}} ping_context_t *context_create */
236 static void context_destroy (ping_context_t *context) /* {{{ */
238         if (context == NULL)
239                 return;
241 #if USE_NCURSES
242         if (context->window != NULL)
243         {
244                 delwin (context->window);
245                 context->window = NULL;
246         }
247 #endif
249         free (context->histogram_counters);
250         context->histogram_counters = NULL;
252         free (context->histogram_accumulated);
253         context->histogram_accumulated = NULL;
255         free (context->histogram_ratio);
256         context->histogram_ratio = NULL;
258         free (context);
259 } /* }}} void context_destroy */
261 static double context_get_average (ping_context_t *ctx) /* {{{ */
263         double num_total;
265         if (ctx == NULL)
266                 return (-1.0);
268         if (ctx->req_rcvd < 1)
269                 return (-0.0);
271         num_total = (double) ctx->req_rcvd;
272         return (ctx->latency_total / num_total);
273 } /* }}} double context_get_average */
275 static double context_get_percentile (ping_context_t *ctx, /* {{{ */
276                 double percentile)
278         double threshold = percentile / 100.0;
279         double index_to_ms_factor;
280         size_t i;
281         double ret;
283         if (ctx->histogram_ratio == NULL)
284                 return (NAN);
286         for (i = 0; i < ctx->latency_histogram_size; i++)
287                 if (ctx->histogram_ratio[i] >= threshold)
288                         break;
290         if (i >= ctx->latency_histogram_size)
291                 return (NAN);
292         else if (i == (ctx->latency_histogram_size - 1))
293                 return (INFINITY);
295         index_to_ms_factor = (1000.0 * opt_interval) / (ctx->latency_histogram_size - 1);
297         /* Multiply with i+1, because we're interested in the _upper_ bound of
298          * each bucket. */
299         ret = (index_to_ms_factor * ((double) (i + 1)));
301         /* Avoid reporting a higher latency than latency_max. */
302         if (ret > ctx->latency_max)
303                 ret = ctx->latency_max;
305         return (ret);
306 } /* }}} double context_get_percentile */
308 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
310         double num_total;
312         if (ctx == NULL)
313                 return (-1.0);
315         if (ctx->req_rcvd < 1)
316                 return (-0.0);
317         else if (ctx->req_rcvd < 2)
318                 return (0.0);
320         num_total = (double) ctx->req_rcvd;
321         return (sqrt (((num_total * ctx->latency_total_square)
322                                         - (ctx->latency_total * ctx->latency_total))
323                                 / (num_total * (num_total - 1.0))));
324 } /* }}} double context_get_stddev */
326 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
328         if (ctx == NULL)
329                 return (-1.0);
331         if (ctx->req_sent < 1)
332                 return (0.0);
334         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
335                         / ((double) ctx->req_sent));
336 } /* }}} double context_get_packet_loss */
338 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
340         pingobj_iter_t *iter;
341         int index;
343         if (ping == NULL)
344                 return (EINVAL);
346         index = 0;
347         for (iter = ping_iterator_get (ping);
348                         iter != NULL;
349                         iter = ping_iterator_next (iter))
350         {
351                 ping_context_t *context;
352                 size_t buffer_size;
354                 context = context_create ();
355                 context->index = index;
357                 buffer_size = sizeof (context->host);
358                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
360                 buffer_size = sizeof (context->addr);
361                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
363                 ping_iterator_set_context (iter, (void *) context);
365                 index++;
366         }
368         return (0);
369 } /* }}} int ping_initialize_contexts */
371 static void usage_exit (const char *name, int status) /* {{{ */
373         fprintf (stderr, "Usage: %s [OPTIONS] "
374                                 "-f filename | host [host [host ...]]\n"
376                         "\nAvailable options:\n"
377                         "  -4|-6        force the use of IPv4 or IPv6\n"
378                         "  -c count     number of ICMP packets to send\n"
379                         "  -i interval  interval with which to send ICMP packets\n"
380                         "  -t ttl       time to live for each ICMP packet\n"
381                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
382                         "               Use \"-Q help\" for a list of valid options.\n"
383                         "  -I srcaddr   source address\n"
384                         "  -D device    outgoing interface name\n"
385                         "  -f filename  filename to read hosts from\n"
386 #if USE_NCURSES
387                         "  -u / -U      force / disable UTF-8 output\n"
388                         "  -g graph     graph type to draw\n"
389 #endif
390                         "  -P percent   Report the n'th percentile of latency\n"
391                         "  -Z percent   Exit with non-zero exit status if more than this percentage of\n"
392                         "               probes timed out. (default: never)\n"
394                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
395                         "by Florian octo Forster <octo@verplant.org>\n"
396                         "for contributions see `AUTHORS'\n",
397                         name);
398         exit (status);
399 } /* }}} void usage_exit */
401 __attribute__((noreturn))
402 static void usage_qos_exit (const char *arg, int status) /* {{{ */
404         if (arg != 0)
405                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
407         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
408                         "\n"
409                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
410                         "\n"
411                         "    be                     Best Effort (BE, default PHB).\n"
412                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
413                         "                           (low delay, low loss, low jitter)\n"
414                         "    va                     Voice Admit (VA) DSCP (RFC 5865).\n"
415                         "                           (capacity-admitted traffic)\n"
416                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
417                         "                           For example: \"af12\" (class 1, precedence 2)\n"
418                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
419                         "                           For example: \"cs1\" (priority traffic)\n"
420                         "\n"
421                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
422                         "\n"
423                         "    lowdelay     (%#04x)    minimize delay\n"
424                         "    throughput   (%#04x)    maximize throughput\n"
425                         "    reliability  (%#04x)    maximize reliability\n"
426                         "    mincost      (%#04x)    minimize monetary cost\n"
427                         "\n"
428                         "  Specify manually\n"
429                         "\n"
430                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
431                         "       0 -  255            Decimal numeric specification.\n"
432                         "\n",
433                         (unsigned int) IPTOS_LOWDELAY,
434                         (unsigned int) IPTOS_THROUGHPUT,
435                         (unsigned int) IPTOS_RELIABILITY,
436                         (unsigned int) IPTOS_MINCOST);
438         exit (status);
439 } /* }}} void usage_qos_exit */
441 static int set_opt_send_qos (const char *opt) /* {{{ */
443         if (opt == NULL)
444                 return (EINVAL);
446         if (strcasecmp ("help", opt) == 0)
447                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
448         /* DiffServ (RFC 2474): */
449         /* - Best effort (BE) */
450         else if (strcasecmp ("be", opt) == 0)
451                 opt_send_qos = 0;
452         /* - Expedited Forwarding (EF, RFC 3246) */
453         else if (strcasecmp ("ef", opt) == 0)
454                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
455         /* - Voice Admit (VA, RFC 5865) */
456         else if (strcasecmp ("va", opt) == 0)
457                 opt_send_qos = 0xB0; /* == 0x2D << 2 */
458         /* - Assured Forwarding (AF, RFC 2597) */
459         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
460                         && (strlen (opt) == 4))
461         {
462                 uint8_t dscp;
463                 uint8_t class = 0;
464                 uint8_t prec = 0;
466                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
467                 if (opt[2] == '1')
468                         class = 1;
469                 else if (opt[2] == '2')
470                         class = 2;
471                 else if (opt[2] == '3')
472                         class = 3;
473                 else if (opt[2] == '4')
474                         class = 4;
475                 else
476                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
478                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
479                 if (opt[3] == '1')
480                         prec = 1;
481                 else if (opt[3] == '2')
482                         prec = 2;
483                 else if (opt[3] == '3')
484                         prec = 3;
485                 else
486                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
488                 dscp = (8 * class) + (2 * prec);
489                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
490                 opt_send_qos = dscp << 2;
491         }
492         /* - Class Selector (CS) */
493         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
494                         && (strlen (opt) == 3))
495         {
496                 uint8_t class;
498                 if ((opt[2] < '0') || (opt[2] > '7'))
499                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
501                 /* Not exactly legal by the C standard, but I don't know of any
502                  * system not supporting this hack. */
503                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
504                 opt_send_qos = class << 5;
505         }
506         /* Type of Service (RFC 1349) */
507         else if (strcasecmp ("lowdelay", opt) == 0)
508                 opt_send_qos = IPTOS_LOWDELAY;
509         else if (strcasecmp ("throughput", opt) == 0)
510                 opt_send_qos = IPTOS_THROUGHPUT;
511         else if (strcasecmp ("reliability", opt) == 0)
512                 opt_send_qos = IPTOS_RELIABILITY;
513         else if (strcasecmp ("mincost", opt) == 0)
514                 opt_send_qos = IPTOS_MINCOST;
515         /* Numeric value */
516         else
517         {
518                 unsigned long value;
519                 char *endptr;
521                 errno = 0;
522                 endptr = NULL;
523                 value = strtoul (opt, &endptr, /* base = */ 0);
524                 if ((errno != 0) || (endptr == opt)
525                                 || (endptr == NULL) || (*endptr != 0)
526                                 || (value > 0xff))
527                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
528                 
529                 opt_send_qos = (uint8_t) value;
530         }
532         return (0);
533 } /* }}} int set_opt_send_qos */
535 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
537         uint8_t dscp;
538         uint8_t ecn;
539         char *dscp_str;
540         char *ecn_str;
542         dscp = qos >> 2;
543         ecn = qos & 0x03;
545         switch (dscp)
546         {
547                 case 0x00: dscp_str = "be";  break;
548                 case 0x2e: dscp_str = "ef";  break;
549                 case 0x2d: dscp_str = "va";  break;
550                 case 0x0a: dscp_str = "af11"; break;
551                 case 0x0c: dscp_str = "af12"; break;
552                 case 0x0e: dscp_str = "af13"; break;
553                 case 0x12: dscp_str = "af21"; break;
554                 case 0x14: dscp_str = "af22"; break;
555                 case 0x16: dscp_str = "af23"; break;
556                 case 0x1a: dscp_str = "af31"; break;
557                 case 0x1c: dscp_str = "af32"; break;
558                 case 0x1e: dscp_str = "af33"; break;
559                 case 0x22: dscp_str = "af41"; break;
560                 case 0x24: dscp_str = "af42"; break;
561                 case 0x26: dscp_str = "af43"; break;
562                 case 0x08: dscp_str = "cs1";  break;
563                 case 0x10: dscp_str = "cs2";  break;
564                 case 0x18: dscp_str = "cs3";  break;
565                 case 0x20: dscp_str = "cs4";  break;
566                 case 0x28: dscp_str = "cs5";  break;
567                 case 0x30: dscp_str = "cs6";  break;
568                 case 0x38: dscp_str = "cs7";  break;
569                 default:   dscp_str = NULL;
570         }
572         switch (ecn)
573         {
574                 case 0x01: ecn_str = ",ecn(1)"; break;
575                 case 0x02: ecn_str = ",ecn(0)"; break;
576                 case 0x03: ecn_str = ",ce"; break;
577                 default:   ecn_str = "";
578         }
580         if (dscp_str == NULL)
581                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
582         else
583                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
584         buffer[buffer_size - 1] = 0;
586         return (buffer);
587 } /* }}} char *format_qos */
589 static int read_options (int argc, char **argv) /* {{{ */
591         int optchar;
593         while (1)
594         {
595                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:P:"
596 #if USE_NCURSES
597                                 "uUg:"
598 #endif
599                                 );
601                 if (optchar == -1)
602                         break;
604                 switch (optchar)
605                 {
606                         case '4':
607                         case '6':
608                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
609                                 break;
611                         case 'c':
612                                 {
613                                         int new_count;
614                                         new_count = atoi (optarg);
615                                         if (new_count > 0)
616                                         {
617                                                 opt_count = new_count;
619                                                 if ((opt_percentile < 0.0) && (opt_count < 20))
620                                                         opt_percentile = 100.0 * (opt_count - 1) / opt_count;
621                                         }
622                                         else
623                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
624                                                                 optarg);
625                                 }
626                                 break;
628                         case 'f':
629                                 {
630                                         if (opt_filename != NULL)
631                                                 free (opt_filename);
632                                         opt_filename = strdup (optarg);
633                                 }
634                                 break;
636                         case 'i':
637                                 {
638                                         double new_interval;
639                                         new_interval = atof (optarg);
640                                         if (new_interval < 0.001)
641                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
642                                                                 optarg);
643                                         else
644                                                 opt_interval = new_interval;
645                                 }
646                                 break;
648                         case 'I':
649                                 {
650                                         if (opt_srcaddr != NULL)
651                                                 free (opt_srcaddr);
652                                         opt_srcaddr = strdup (optarg);
653                                 }
654                                 break;
656                         case 'D':
657                                 opt_device = optarg;
658                                 break;
660                         case 't':
661                         {
662                                 int new_send_ttl;
663                                 new_send_ttl = atoi (optarg);
664                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
665                                         opt_send_ttl = new_send_ttl;
666                                 else
667                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
668                                                         optarg);
669                                 break;
670                         }
672                         case 'Q':
673                                 set_opt_send_qos (optarg);
674                                 break;
676                         case 'P':
677                                 {
678                                         double new_percentile;
679                                         new_percentile = atof (optarg);
680                                         if (isnan (new_percentile)
681                                                         || (new_percentile < 0.1)
682                                                         || (new_percentile > 100.0))
683                                                 fprintf (stderr, "Ignoring invalid percentile: %s\n",
684                                                                 optarg);
685                                         else
686                                                 opt_percentile = new_percentile;
687                                 }
688                                 break;
690 #if USE_NCURSES
691                         case 'g':
692                                 if (strcasecmp ("none", optarg) == 0)
693                                         opt_show_graph = 0;
694                                 else if (strcasecmp ("prettyping", optarg) == 0)
695                                         opt_show_graph = 1;
696                                 else if (strcasecmp ("boxplot", optarg) == 0)
697                                         opt_show_graph = 2;
698                                 else if (strcasecmp ("histogram", optarg) == 0)
699                                         opt_show_graph = 3;
700                                 else
701                                         fprintf (stderr, "Unknown graph option: %s\n", optarg);
702                                 break;
704                         case 'u':
705                                 opt_utf8 = 2;
706                                 break;
707                         case 'U':
708                                 opt_utf8 = 1;
709                                 break;
710 #endif
712                         case 'Z':
713                         {
714                                 char *endptr = NULL;
715                                 double tmp;
717                                 errno = 0;
718                                 tmp = strtod (optarg, &endptr);
719                                 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
720                                 {
721                                         fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
722                                         fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
723                                 }
724                                 else
725                                         opt_exit_status_threshold = tmp / 100.0;
727                                 break;
728                         }
730                         case 'h':
731                                 usage_exit (argv[0], 0);
732                                 break;
734                         default:
735                                 usage_exit (argv[0], 1);
736                 }
737         }
739         if (opt_percentile <= 0.0)
740                 opt_percentile = OPING_DEFAULT_PERCENTILE;
742         return (optind);
743 } /* }}} read_options */
745 static void time_normalize (struct timespec *ts) /* {{{ */
747         while (ts->tv_nsec < 0)
748         {
749                 if (ts->tv_sec == 0)
750                 {
751                         ts->tv_nsec = 0;
752                         return;
753                 }
755                 ts->tv_sec  -= 1;
756                 ts->tv_nsec += 1000000000;
757         }
759         while (ts->tv_nsec >= 1000000000)
760         {
761                 ts->tv_sec  += 1;
762                 ts->tv_nsec -= 1000000000;
763         }
764 } /* }}} void time_normalize */
766 static void time_calc (struct timespec *ts_dest, /* {{{ */
767                 const struct timespec *ts_int,
768                 const struct timeval  *tv_begin,
769                 const struct timeval  *tv_end)
771         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
772         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
773         time_normalize (ts_dest);
775         /* Assure that `(begin + interval) > end'.
776          * This may seem overly complicated, but `tv_sec' is of type `time_t'
777          * which may be `unsigned. *sigh* */
778         if ((tv_end->tv_sec > ts_dest->tv_sec)
779                         || ((tv_end->tv_sec == ts_dest->tv_sec)
780                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
781         {
782                 ts_dest->tv_sec  = 0;
783                 ts_dest->tv_nsec = 0;
784                 return;
785         }
787         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
788         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
789         time_normalize (ts_dest);
790 } /* }}} void time_calc */
792 #if USE_NCURSES
793 static _Bool has_utf8() /* {{{ */
795 # if HAVE_NCURSESW_NCURSES_H
796         if (!opt_utf8)
797         {
798                 /* Automatically determine */
799                 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
800                         opt_utf8 = 2;
801                 else
802                         opt_utf8 = 1;
803         }
804         return ((_Bool) (opt_utf8 - 1));
805 # else
806         return (0);
807 # endif
808 } /* }}} _Bool has_utf8 */
810 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
812         double *ratios;
813         size_t i;
814         size_t x_max;
815         size_t x;
817         x_max = (size_t) getmaxx (ctx->window);
818         if (x_max <= 8)
819                 return (EINVAL);
820         x_max -= 4;
822         ratios = calloc (x_max, sizeof (*ratios));
824         /* Downsample */
825         for (i = 0; i < ctx->latency_histogram_size; i++)
826         {
827                 x = i * x_max / ctx->latency_histogram_size;
828                 ratios[x] = ctx->histogram_ratio[i];
829         }
831         for (x = 0; x < x_max; x++)
832         {
833                 int symbol = ' ';
834                 _Bool reverse = 0;
836                 if (x == 0)
837                 {
838                         if (ratios[x] >= 0.5)
839                         {
840                                 symbol = BOXPLOT_MEDIAN;
841                                 reverse = 1;
842                         }
843                         else if (ratios[x] > 0.25)
844                         {
845                                 symbol = BOXPLOT_BOX;
846                                 reverse = 1;
847                         }
848                         else if (ratios[x] > 0.025)
849                                 symbol = BOXPLOT_WHISKER_BAR;
850                         else
851                                 symbol = ' '; /* NOP */
852                 }
853                 else /* (x != 0) */
854                 {
855                         if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
856                         {
857                                 symbol = BOXPLOT_MEDIAN;
858                                 reverse = 1;
859                         }
860                         else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
861                                         || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
862                         {
863                                 symbol = BOXPLOT_BOX;
864                                 reverse = 1;
865                         }
866                         else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
867                         {
868                                 if (ratios[x - 1] < 0.025)
869                                         symbol = BOXPLOT_WHISKER_LEFT_END;
870                                 else
871                                         symbol = BOXPLOT_WHISKER_BAR;
872                         }
873                         else if ((ratios[x] > .5) && (ratios[x] < 0.975))
874                         {
875                                 symbol = BOXPLOT_WHISKER_BAR;
876                         }
877                         else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
878                                 symbol = BOXPLOT_WHISKER_RIGHT_END;
879                 }
881                 if (reverse)
882                         wattron (ctx->window, A_REVERSE);
883                 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
884                 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
885                 if (reverse)
886                         wattroff (ctx->window, A_REVERSE);
887         }
889         free (ratios);
890         return (0);
891 } /* }}} int update_graph_boxplot */
893 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
894                 double latency, unsigned int sequence)
896         int color = OPING_RED;
897         char const *symbol = "!";
898         int symbolc = '!';
900         int x_max;
901         int x_pos;
903         x_max = getmaxx (ctx->window);
904         x_pos = ((sequence - 1) % (x_max - 4)) + 2;
906         if (latency >= 0.0)
907         {
908                 double ratio;
910                 size_t symbols_num = hist_symbols_acs_num;
911                 size_t colors_num = 1;
913                 size_t index_symbols;
914                 size_t index_colors;
915                 size_t intensity;
917                 /* latency is in milliseconds, opt_interval is in seconds. */
918                 ratio = (latency * 0.001) / opt_interval;
919                 if (ratio > 1) {
920                         ratio = 1.0;
921                 }
923                 if (has_utf8 ())
924                         symbols_num = hist_symbols_utf8_num;
926                 if (has_colors () == TRUE)
927                         colors_num = hist_colors_num;
929                 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
930                 if (intensity >= (symbols_num * colors_num))
931                         intensity = (symbols_num * colors_num) - 1;
933                 index_symbols = intensity % symbols_num;
934                 assert (index_symbols < symbols_num);
936                 index_colors = intensity / symbols_num;
937                 assert (index_colors < colors_num);
939                 if (has_utf8())
940                 {
941                         color = hist_colors_utf8[index_colors];
942                         symbol = hist_symbols_utf8[index_symbols];
943                 }
944                 else
945                 {
946                         color = hist_colors_acs[index_colors];
947                         symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
948                 }
949         }
950         else /* if (!(latency >= 0.0)) */
951                 wattron (ctx->window, A_BOLD);
953         if (has_colors () == TRUE)
954                 wattron (ctx->window, COLOR_PAIR(color));
956         if (has_utf8())
957                 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x_pos, symbol);
958         else
959                 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x_pos, symbolc);
961         if (has_colors () == TRUE)
962                 wattroff (ctx->window, COLOR_PAIR(color));
964         /* Use negation here to handle NaN correctly. */
965         if (!(latency >= 0.0))
966                 wattroff (ctx->window, A_BOLD);
968         wprintw (ctx->window, " ");
969         return (0);
970 } /* }}} int update_graph_prettyping */
972 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
974         uint32_t *counters;
975         uint32_t *accumulated;
976         uint32_t num;
977         uint32_t max;
978         size_t i;
979         size_t x_max;
980         size_t x;
982         size_t symbols_num = hist_symbols_acs_num;
984         if (has_utf8 ())
985                 symbols_num = hist_symbols_utf8_num;
987         x_max = (size_t) getmaxx (ctx->window);
988         if (x_max <= 4)
989                 return (EINVAL);
990         x_max -= 4;
992         counters = calloc (x_max, sizeof (*counters));
993         accumulated = calloc (x_max, sizeof (*accumulated));
995         /* Downsample */
996         max = 0;
997         for (i = 0; i < ctx->latency_histogram_size; i++)
998         {
999                 x = i * x_max / ctx->latency_histogram_size;
1000                 counters[x] += ctx->histogram_counters[i];
1001                 accumulated[x] = counters[x];
1003                 if (max < counters[x])
1004                         max = counters[x];
1005         }
1007         /* Sum */
1008         for (x = 1; x < x_max; x++)
1009                 accumulated[x] += accumulated[x - 1];
1010         num = accumulated[x_max - 1];
1012         /* Calculate ratios */
1013         for (x = 0; x < x_max; x++)
1014         {
1015                 double height = ((double) counters[x]) / ((double) max);
1016                 double ratio_this = ((double) accumulated[x]) / ((double) num);
1017                 double ratio_prev = 0.0;
1018                 size_t index;
1019                 int color = 0;
1021                 index = (size_t) (height * ((double) symbols_num));
1022                 if (index >= symbols_num)
1023                         index = symbols_num - 1;
1025                 if (x > 0)
1026                         ratio_prev = ((double) accumulated[x - 1]) / ((double) num);
1028                 if (has_colors () == TRUE)
1029                 {
1030                         if ((ratio_this <= 0.5) || ((ratio_prev < 0.5) && (ratio_this > 0.5)))
1031                                 color = OPING_GREEN;
1032                         else if ((ratio_this <= 0.95) || ((ratio_prev < 0.95) && (ratio_this > 0.95)))
1033                                 color = OPING_YELLOW;
1034                         else
1035                                 color = OPING_RED;
1037                         wattron (ctx->window, COLOR_PAIR(color));
1038                 }
1040                 if (counters[x] == 0)
1041                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1042                 else if (has_utf8 ())
1043                         mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1044                                         hist_symbols_utf8[index]);
1045                 else
1046                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1047                                         hist_symbols_acs[index] | A_ALTCHARSET);
1049                 if (has_colors () == TRUE)
1050                         wattroff (ctx->window, COLOR_PAIR(color));
1052         }
1054         free (accumulated);
1055         return (0);
1056 } /* }}} int update_graph_histogram */
1058 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1060         double latency = -1.0;
1061         size_t buffer_len = sizeof (latency);
1063         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1064                         &latency, &buffer_len);
1066         unsigned int sequence = 0;
1067         buffer_len = sizeof (sequence);
1068         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1069                         &sequence, &buffer_len);
1072         if ((ctx == NULL) || (ctx->window == NULL))
1073                 return (EINVAL);
1075         /* werase (ctx->window); */
1077         box (ctx->window, 0, 0);
1078         wattron (ctx->window, A_BOLD);
1079         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1080                         " %s ", ctx->host);
1081         wattroff (ctx->window, A_BOLD);
1082         wprintw (ctx->window, "ping statistics ");
1083         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1084                         "%i packets transmitted, %i received, %.2f%% packet "
1085                         "loss, time %.1fms",
1086                         ctx->req_sent, ctx->req_rcvd,
1087                         context_get_packet_loss (ctx),
1088                         ctx->latency_total);
1089         if (ctx->req_rcvd != 0)
1090         {
1091                 double average;
1092                 double deviation;
1093                 double percentile;
1095                 average = context_get_average (ctx);
1096                 deviation = context_get_stddev (ctx);
1097                 percentile = context_get_percentile (ctx, opt_percentile);
1099                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1100                                 "rtt min/avg/%.0f%%/max/sdev = "
1101                                 "%.3f/%.3f/%.0f/%.3f/%.3f ms\n",
1102                                 opt_percentile,
1103                                 ctx->latency_min,
1104                                 average,
1105                                 percentile,
1106                                 ctx->latency_max,
1107                                 deviation);
1108         }
1110         if (opt_show_graph == 1)
1111                 update_graph_prettyping (ctx, latency, sequence);
1112         else if (opt_show_graph == 2)
1113                 update_graph_boxplot (ctx);
1114         else if (opt_show_graph == 3)
1115                 update_graph_histogram (ctx);
1117         wrefresh (ctx->window);
1119         return (0);
1120 } /* }}} int update_stats_from_context */
1122 static int on_resize (pingobj_t *ping) /* {{{ */
1124         pingobj_iter_t *iter;
1125         int width = 0;
1126         int height = 0;
1127         int main_win_height;
1128         int box_height = (opt_show_graph == 0) ? 4 : 5;
1130         getmaxyx (stdscr, height, width);
1131         if ((height < 1) || (width < 1))
1132                 return (EINVAL);
1134         main_win_height = height - (box_height * host_num);
1135         wresize (main_win, main_win_height, /* width = */ width);
1136         /* Allow scrolling */
1137         scrollok (main_win, TRUE);
1138         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1139         /* Allow hardware accelerated scrolling. */
1140         idlok (main_win, TRUE);
1141         wrefresh (main_win);
1143         for (iter = ping_iterator_get (ping);
1144                         iter != NULL;
1145                         iter = ping_iterator_next (iter))
1146         {
1147                 ping_context_t *context;
1149                 context = ping_iterator_get_context (iter);
1150                 if (context == NULL)
1151                         continue;
1153                 if (context->window != NULL)
1154                 {
1155                         delwin (context->window);
1156                         context->window = NULL;
1157                 }
1158                 context->window = newwin (/* height = */ box_height,
1159                                 /* width = */ width,
1160                                 /* y = */ main_win_height + (box_height * context->index),
1161                                 /* x = */ 0);
1162         }
1164         return (0);
1165 } /* }}} */
1167 static int check_resize (pingobj_t *ping) /* {{{ */
1169         int need_resize = 0;
1171         while (42)
1172         {
1173                 int key = wgetch (stdscr);
1174                 if (key == ERR)
1175                         break;
1176                 else if (key == KEY_RESIZE)
1177                         need_resize = 1;
1178         }
1180         if (need_resize)
1181                 return (on_resize (ping));
1182         else
1183                 return (0);
1184 } /* }}} int check_resize */
1186 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1188         pingobj_iter_t *iter;
1189         int width = 0;
1190         int height = 0;
1191         int main_win_height;
1192         int box_height = (opt_show_graph == 0) ? 4 : 5;
1194         initscr ();
1195         cbreak ();
1196         noecho ();
1197         nodelay (stdscr, TRUE);
1199         getmaxyx (stdscr, height, width);
1200         if ((height < 1) || (width < 1))
1201                 return (EINVAL);
1203         if (has_colors () == TRUE)
1204         {
1205                 start_color ();
1206                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
1207                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1208                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
1209                 init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
1210                 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1211                 init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
1212         }
1214         main_win_height = height - (box_height * host_num);
1215         main_win = newwin (/* height = */ main_win_height,
1216                         /* width = */ width,
1217                         /* y = */ 0, /* x = */ 0);
1218         /* Allow scrolling */
1219         scrollok (main_win, TRUE);
1220         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1221         /* Allow hardware accelerated scrolling. */
1222         idlok (main_win, TRUE);
1223         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1224         wrefresh (main_win);
1226         for (iter = ping_iterator_get (ping);
1227                         iter != NULL;
1228                         iter = ping_iterator_next (iter))
1229         {
1230                 ping_context_t *context;
1232                 context = ping_iterator_get_context (iter);
1233                 if (context == NULL)
1234                         continue;
1236                 if (context->window != NULL)
1237                 {
1238                         delwin (context->window);
1239                         context->window = NULL;
1240                 }
1241                 context->window = newwin (/* height = */ box_height,
1242                                 /* width = */ width,
1243                                 /* y = */ main_win_height + (box_height * context->index),
1244                                 /* x = */ 0);
1245         }
1248         /* Don't know what good this does exactly, but without this code
1249          * "check_resize" will be called right after startup and *somehow*
1250          * this leads to display errors. If we purge all initial characters
1251          * here, the problem goes away. "wgetch" is non-blocking due to
1252          * "nodelay" (see above). */
1253         while (wgetch (stdscr) != ERR)
1254         {
1255                 /* eat up characters */;
1256         }
1258         return (0);
1259 } /* }}} int pre_loop_hook */
1261 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1263         return (check_resize (ping));
1264 } /* }}} int pre_sleep_hook */
1266 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1268         return (check_resize (ping));
1269 } /* }}} int pre_sleep_hook */
1270 #else /* if !USE_NCURSES */
1271 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1273         pingobj_iter_t *iter;
1275         for (iter = ping_iterator_get (ping);
1276                         iter != NULL;
1277                         iter = ping_iterator_next (iter))
1278         {
1279                 ping_context_t *ctx;
1280                 size_t buffer_size;
1282                 ctx = ping_iterator_get_context (iter);
1283                 if (ctx == NULL)
1284                         continue;
1286                 buffer_size = 0;
1287                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1289                 printf ("PING %s (%s) %zu bytes of data.\n",
1290                                 ctx->host, ctx->addr, buffer_size);
1291         }
1293         return (0);
1294 } /* }}} int pre_loop_hook */
1296 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1298         fflush (stdout);
1300         return (0);
1301 } /* }}} int pre_sleep_hook */
1303 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1305         return (0);
1306 } /* }}} int post_sleep_hook */
1307 #endif
1309 static size_t latency_to_bucket (ping_context_t *ctx, double latency) /* {{{ */
1311         size_t bucket;
1313         /* latency is in ms, opt_interval is in s. */
1314         bucket = (size_t) ((latency * (ctx->latency_histogram_size - 1))
1315                         / (1000.0 * opt_interval));
1316         if (bucket >= ctx->latency_histogram_size)
1317                 bucket = ctx->latency_histogram_size - 1;
1319         return (bucket);
1320 } /* }}} size_t latency_to_bucket */
1322 static void update_context (ping_context_t *context, double latency) /* {{{ */
1324         size_t bucket;
1325         size_t i;
1326         double num;
1328         context->req_rcvd++;
1329         context->latency_total += latency;
1330         context->latency_total_square += (latency * latency);
1332         if ((context->latency_max < 0.0) || (context->latency_max < latency))
1333                 context->latency_max = latency;
1334         if ((context->latency_min < 0.0) || (context->latency_min > latency))
1335                 context->latency_min = latency;
1337         bucket = latency_to_bucket (context, latency);
1338         num = (double) context->req_rcvd;
1340         context->histogram_counters[bucket]++;
1342         context->histogram_accumulated[0] = context->histogram_counters[0];
1343         context->histogram_ratio[0] = ((double) context->histogram_accumulated[0]) / num;
1344         for (i = 1; i < context->latency_histogram_size; i++)
1345         {
1346                 context->histogram_accumulated[i] = context->histogram_accumulated[i - 1]
1347                         + context->histogram_counters[i];
1348                 context->histogram_ratio[i] = ((double) context->histogram_accumulated[i]) / num;
1349         }
1350 } /* }}} void update_context */
1352 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1353                 __attribute__((unused)) int index)
1355         double          latency;
1356         unsigned int    sequence;
1357         int             recv_ttl;
1358         uint8_t         recv_qos;
1359         char            recv_qos_str[16];
1360         size_t          buffer_len;
1361         size_t          data_len;
1362         ping_context_t *context;
1364         latency = -1.0;
1365         buffer_len = sizeof (latency);
1366         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1367                         &latency, &buffer_len);
1369         sequence = 0;
1370         buffer_len = sizeof (sequence);
1371         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1372                         &sequence, &buffer_len);
1374         recv_ttl = -1;
1375         buffer_len = sizeof (recv_ttl);
1376         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1377                         &recv_ttl, &buffer_len);
1379         recv_qos = 0;
1380         buffer_len = sizeof (recv_qos);
1381         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1382                         &recv_qos, &buffer_len);
1384         data_len = 0;
1385         ping_iterator_get_info (iter, PING_INFO_DATA,
1386                         NULL, &data_len);
1388         context = (ping_context_t *) ping_iterator_get_context (iter);
1390 #if USE_NCURSES
1391 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1392 #else
1393 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1394 #endif
1396         context->req_sent++;
1397         if (latency > 0.0)
1398         {
1399                 update_context (context, latency);
1401 #if USE_NCURSES
1402                 if (has_colors () == TRUE)
1403                 {
1404                         size_t bucket;
1405                         double ratio_this;
1406                         double ratio_prev;
1407                         int color = OPING_GREEN;
1409                         bucket = latency_to_bucket (context, latency);
1410                         ratio_this = context->histogram_ratio[bucket];
1411                         if (bucket > 0)
1412                                 ratio_prev = context->histogram_ratio[bucket - 1];
1413                         else
1414                                 ratio_prev = 0.0;
1416                         if ((ratio_this <= 0.5) ||
1417                                         ((ratio_prev < 0.5) && (ratio_this > 0.5)))
1418                                 color = OPING_GREEN;
1419                         else if ((ratio_this <= 0.95) ||
1420                                         ((ratio_prev < 0.95) && (ratio_this > 0.95)))
1421                                 color = OPING_YELLOW;
1422                         else
1423                                 color = OPING_RED;
1425                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1426                                         data_len, context->host, context->addr,
1427                                         sequence, recv_ttl,
1428                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1429                         if ((recv_qos != 0) || (opt_send_qos != 0))
1430                         {
1431                                 HOST_PRINTF ("qos=%s ",
1432                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1433                         }
1434                         HOST_PRINTF ("time=");
1435                         wattron (main_win, COLOR_PAIR(color));
1436                         HOST_PRINTF ("%.2f", latency);
1437                         wattroff (main_win, COLOR_PAIR(color));
1438                         HOST_PRINTF (" ms\n");
1439                 }
1440                 else
1441                 {
1442 #endif
1443                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1444                                 data_len,
1445                                 context->host, context->addr,
1446                                 sequence, recv_ttl);
1447                 if ((recv_qos != 0) || (opt_send_qos != 0))
1448                 {
1449                         HOST_PRINTF ("qos=%s ",
1450                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1451                 }
1452                 HOST_PRINTF ("time=%.2f ms\n", latency);
1453 #if USE_NCURSES
1454                 }
1455 #endif
1456         }
1457         else
1458         {
1459 #if USE_NCURSES
1460                 if (has_colors () == TRUE)
1461                 {
1462                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1463                                         context->host, context->addr,
1464                                         sequence);
1465                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1466                         HOST_PRINTF ("timeout");
1467                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1468                         HOST_PRINTF ("\n");
1469                 }
1470                 else
1471                 {
1472 #endif
1473                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1474                                 context->host, context->addr,
1475                                 sequence);
1476 #if USE_NCURSES
1477                 }
1478 #endif
1479         }
1481 #if USE_NCURSES
1482         update_stats_from_context (context, iter);
1483         wrefresh (main_win);
1484 #endif
1485 } /* }}} void update_host_hook */
1487 /* Prints statistics for each host, cleans up the contexts and returns the
1488  * number of hosts which failed to return more than the fraction
1489  * opt_exit_status_threshold of pings. */
1490 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1492         pingobj_iter_t *iter;
1493         int failure_count = 0;
1495 #if USE_NCURSES
1496         endwin ();
1497 #endif
1499         for (iter = ping_iterator_get (ping);
1500                         iter != NULL;
1501                         iter = ping_iterator_next (iter))
1502         {
1503                 ping_context_t *context;
1505                 context = ping_iterator_get_context (iter);
1507                 printf ("\n--- %s ping statistics ---\n"
1508                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1509                                 context->host, context->req_sent, context->req_rcvd,
1510                                 context_get_packet_loss (context),
1511                                 context->latency_total);
1513                 {
1514                         double pct_failed = 1.0 - (((double) context->req_rcvd)
1515                                         / ((double) context->req_sent));
1516                         if (pct_failed > opt_exit_status_threshold)
1517                                 failure_count++;
1518                 }
1520                 if (context->req_rcvd != 0)
1521                 {
1522                         double average;
1523                         double deviation;
1524                         double percentile;
1526                         average = context_get_average (context);
1527                         deviation = context_get_stddev (context);
1528                         percentile = context_get_percentile (context, opt_percentile);
1530                         printf ("rtt min/avg/%.0f%%/max/sdev = "
1531                                         "%.3f/%.3f/%.0f/%.3f/%.3f ms\n",
1532                                         opt_percentile,
1533                                         context->latency_min,
1534                                         average,
1535                                         percentile,
1536                                         context->latency_max,
1537                                         deviation);
1538                 }
1540                 ping_iterator_set_context (iter, NULL);
1541                 context_destroy (context);
1542         }
1544         return (failure_count);
1545 } /* }}} int post_loop_hook */
1547 int main (int argc, char **argv) /* {{{ */
1549         pingobj_t      *ping;
1550         pingobj_iter_t *iter;
1552         struct sigaction sigint_action;
1554         struct timeval  tv_begin;
1555         struct timeval  tv_end;
1556         struct timespec ts_wait;
1557         struct timespec ts_int;
1559         int optind;
1560         int i;
1561         int status;
1562 #if _POSIX_SAVED_IDS
1563         uid_t saved_set_uid;
1565         /* Save the old effective user id */
1566         saved_set_uid = geteuid ();
1567         /* Set the effective user ID to the real user ID without changing the
1568          * saved set-user ID */
1569         status = seteuid (getuid ());
1570         if (status != 0)
1571         {
1572                 fprintf (stderr, "Temporarily dropping privileges "
1573                                 "failed: %s\n", strerror (errno));
1574                 exit (EXIT_FAILURE);
1575         }
1576 #endif
1578         setlocale(LC_ALL, "");
1579         optind = read_options (argc, argv);
1581 #if !_POSIX_SAVED_IDS
1582         /* Cannot temporarily drop privileges -> reject every file but "-". */
1583         if ((opt_filename != NULL)
1584                         && (strcmp ("-", opt_filename) != 0)
1585                         && (getuid () != geteuid ()))
1586         {
1587                 fprintf (stderr, "Your real and effective user IDs don't "
1588                                 "match. Reading from a file (option '-f')\n"
1589                                 "is therefore too risky. You can still read "
1590                                 "from STDIN using '-f -' if you like.\n"
1591                                 "Sorry.\n");
1592                 exit (EXIT_FAILURE);
1593         }
1594 #endif
1596         if ((optind >= argc) && (opt_filename == NULL)) {
1597                 usage_exit (argv[0], 1);
1598         }
1600         if ((ping = ping_construct ()) == NULL)
1601         {
1602                 fprintf (stderr, "ping_construct failed\n");
1603                 return (1);
1604         }
1606         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1607         {
1608                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1609                                 opt_send_ttl, ping_get_error (ping));
1610         }
1612         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1613         {
1614                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1615                                 opt_send_qos, ping_get_error (ping));
1616         }
1618         {
1619                 double temp_sec;
1620                 double temp_nsec;
1622                 temp_nsec = modf (opt_interval, &temp_sec);
1623                 ts_int.tv_sec  = (time_t) temp_sec;
1624                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1626                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1627         }
1629         if (opt_addrfamily != PING_DEF_AF)
1630                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1632         if (opt_srcaddr != NULL)
1633         {
1634                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1635                 {
1636                         fprintf (stderr, "Setting source address failed: %s\n",
1637                                         ping_get_error (ping));
1638                 }
1639         }
1641         if (opt_device != NULL)
1642         {
1643                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1644                 {
1645                         fprintf (stderr, "Setting device failed: %s\n",
1646                                         ping_get_error (ping));
1647                 }
1648         }
1650         if (opt_filename != NULL)
1651         {
1652                 FILE *infile;
1653                 char line[256];
1654                 char host[256];
1656                 if (strcmp (opt_filename, "-") == 0)
1657                         /* Open STDIN */
1658                         infile = fdopen(0, "r");
1659                 else
1660                         infile = fopen(opt_filename, "r");
1662                 if (infile == NULL)
1663                 {
1664                         fprintf (stderr, "Opening %s failed: %s\n",
1665                                         (strcmp (opt_filename, "-") == 0)
1666                                         ? "STDIN" : opt_filename,
1667                                         strerror(errno));
1668                         return (1);
1669                 }
1671 #if _POSIX_SAVED_IDS
1672                 /* Regain privileges */
1673                 status = seteuid (saved_set_uid);
1674                 if (status != 0)
1675                 {
1676                         fprintf (stderr, "Temporarily re-gaining privileges "
1677                                         "failed: %s\n", strerror (errno));
1678                         exit (EXIT_FAILURE);
1679                 }
1680 #endif
1682                 while (fgets(line, sizeof(line), infile))
1683                 {
1684                         /* Strip whitespace */
1685                         if (sscanf(line, "%s", host) != 1)
1686                                 continue;
1688                         if ((host[0] == 0) || (host[0] == '#'))
1689                                 continue;
1691                         if (ping_host_add(ping, host) < 0)
1692                         {
1693                                 const char *errmsg = ping_get_error (ping);
1695                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1696                                 continue;
1697                         }
1698                         else
1699                         {
1700                                 host_num++;
1701                         }
1702                 }
1704 #if _POSIX_SAVED_IDS
1705                 /* Drop privileges */
1706                 status = seteuid (getuid ());
1707                 if (status != 0)
1708                 {
1709                         fprintf (stderr, "Temporarily dropping privileges "
1710                                         "failed: %s\n", strerror (errno));
1711                         exit (EXIT_FAILURE);
1712                 }
1713 #endif
1715                 fclose(infile);
1716         }
1718 #if _POSIX_SAVED_IDS
1719         /* Regain privileges */
1720         status = seteuid (saved_set_uid);
1721         if (status != 0)
1722         {
1723                 fprintf (stderr, "Temporarily re-gaining privileges "
1724                                 "failed: %s\n", strerror (errno));
1725                 exit (EXIT_FAILURE);
1726         }
1727 #endif
1729         for (i = optind; i < argc; i++)
1730         {
1731                 if (ping_host_add (ping, argv[i]) < 0)
1732                 {
1733                         const char *errmsg = ping_get_error (ping);
1735                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1736                         continue;
1737                 }
1738                 else
1739                 {
1740                         host_num++;
1741                 }
1742         }
1744         /* Permanently drop root privileges if we're setuid-root. */
1745         status = setuid (getuid ());
1746         if (status != 0)
1747         {
1748                 fprintf (stderr, "Dropping privileges failed: %s\n",
1749                                 strerror (errno));
1750                 exit (EXIT_FAILURE);
1751         }
1753 #if _POSIX_SAVED_IDS
1754         saved_set_uid = (uid_t) -1;
1755 #endif
1757         ping_initialize_contexts (ping);
1759         if (i == 0)
1760                 return (1);
1762         memset (&sigint_action, '\0', sizeof (sigint_action));
1763         sigint_action.sa_handler = sigint_handler;
1764         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1765         {
1766                 perror ("sigaction");
1767                 return (1);
1768         }
1770         pre_loop_hook (ping);
1772         while (opt_count != 0)
1773         {
1774                 int index;
1775                 int status;
1777                 if (gettimeofday (&tv_begin, NULL) < 0)
1778                 {
1779                         perror ("gettimeofday");
1780                         return (1);
1781                 }
1783                 status = ping_send (ping);
1784                 if (status == -EINTR)
1785                 {
1786                         continue;
1787                 }
1788                 else if (status < 0)
1789                 {
1790                         fprintf (stderr, "ping_send failed: %s\n",
1791                                         ping_get_error (ping));
1792                         return (1);
1793                 }
1795                 index = 0;
1796                 for (iter = ping_iterator_get (ping);
1797                                 iter != NULL;
1798                                 iter = ping_iterator_next (iter))
1799                 {
1800                         update_host_hook (iter, index);
1801                         index++;
1802                 }
1804                 pre_sleep_hook (ping);
1806                 /* Don't sleep in the last iteration */
1807                 if (opt_count == 1)
1808                         break;
1810                 if (gettimeofday (&tv_end, NULL) < 0)
1811                 {
1812                         perror ("gettimeofday");
1813                         return (1);
1814                 }
1816                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1818                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1819                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1820                 {
1821                         if (errno == EINTR)
1822                         {
1823                                 continue;
1824                         }
1825                         else
1826                         {
1827                                 perror ("nanosleep");
1828                                 break;
1829                         }
1830                 }
1832                 post_sleep_hook (ping);
1834                 if (opt_count > 0)
1835                         opt_count--;
1836         } /* while (opt_count != 0) */
1838         /* Returns the number of failed hosts according to -Z. */
1839         status = post_loop_hook (ping);
1841         ping_destroy (ping);
1843         if (status == 0)
1844                 exit (EXIT_SUCCESS);
1845         else
1846         {
1847                 if (status > 255)
1848                         status = 255;
1849                 exit (status);
1850         }
1851 } /* }}} int main */
1853 /* vim: set fdm=marker : */