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