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