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