Code

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