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