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