Code

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