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