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