Code

Add documentation for the "-u" and "-U" options.
[liboping.git] / src / oping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2011  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
84 # include <ncursesw/ncurses.h>
86 # define OPING_GREEN 1
87 # define OPING_YELLOW 2
88 # define OPING_RED 3
89 # define OPING_GREEN_HIST 4
90 # define OPING_YELLOW_HIST 5
91 # define OPING_RED_HIST 6
93 static char const * const hist_symbols_utf8[] = {
94         "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
95 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
96         / sizeof (hist_symbols_utf8[0]);
98 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
99 /* those are not the usual constants because those are not constant */
100 static int const hist_symbols_acs[] = {
101         115, /* ACS_S9 "⎽" */
102         114, /* ACS_S7 "⎼" */
103         113, /* ACS_S5 "─" */
104         112, /* ACS_S3 "⎻" */
105         111  /* ACS_S1 "⎺" */
106 };
107 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
108         / sizeof (hist_symbols_acs[0]);
110 /* use different colors without a background for scancodes */
111 static int const hist_colors_utf8[] = {
112         OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
113 static int const hist_colors_acs[] = {
114         OPING_GREEN, OPING_YELLOW, OPING_RED };
115 /* assuming that both arrays are the same size */
116 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
117         / sizeof (hist_colors_utf8[0]);
118 #endif
120 #include "oping.h"
122 #ifndef _POSIX_SAVED_IDS
123 # define _POSIX_SAVED_IDS 0
124 #endif
126 /* Remove GNU specific __attribute__ settings when using another compiler */
127 #if !__GNUC__
128 # define __attribute__(x) /**/
129 #endif
131 typedef struct ping_context
133         char host[NI_MAXHOST];
134         char addr[NI_MAXHOST];
136         int index;
137         int req_sent;
138         int req_rcvd;
140         double latency_min;
141         double latency_max;
142         double latency_total;
143         double latency_total_square;
145 #if USE_NCURSES
146         WINDOW *window;
147 #endif
148 } ping_context_t;
150 static double  opt_interval   = 1.0;
151 static int     opt_addrfamily = PING_DEF_AF;
152 static char   *opt_srcaddr    = NULL;
153 static char   *opt_device     = NULL;
154 static char   *opt_filename   = NULL;
155 static int     opt_count      = -1;
156 static int     opt_send_ttl   = 64;
157 static uint8_t opt_send_qos   = 0;
158 #if USE_NCURSES
159 static int     opt_utf8       = 0;
160 #endif
162 static int host_num = 0;
164 #if USE_NCURSES
165 static WINDOW *main_win = NULL;
166 #endif
168 static void sigint_handler (int signal) /* {{{ */
170         /* Make compiler happy */
171         signal = 0;
172         /* Exit the loop */
173         opt_count = 0;
174 } /* }}} void sigint_handler */
176 static ping_context_t *context_create (void) /* {{{ */
178         ping_context_t *ret;
180         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
181                 return (NULL);
183         memset (ret, '\0', sizeof (ping_context_t));
185         ret->latency_min   = -1.0;
186         ret->latency_max   = -1.0;
187         ret->latency_total = 0.0;
188         ret->latency_total_square = 0.0;
190 #if USE_NCURSES
191         ret->window = NULL;
192 #endif
194         return (ret);
195 } /* }}} ping_context_t *context_create */
197 static void context_destroy (ping_context_t *context) /* {{{ */
199         if (context == NULL)
200                 return;
202 #if USE_NCURSES
203         if (context->window != NULL)
204         {
205                 delwin (context->window);
206                 context->window = NULL;
207         }
208 #endif
210         free (context);
211 } /* }}} void context_destroy */
213 static double context_get_average (ping_context_t *ctx) /* {{{ */
215         double num_total;
217         if (ctx == NULL)
218                 return (-1.0);
220         if (ctx->req_rcvd < 1)
221                 return (-0.0);
223         num_total = (double) ctx->req_rcvd;
224         return (ctx->latency_total / num_total);
225 } /* }}} double context_get_average */
227 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
229         double num_total;
231         if (ctx == NULL)
232                 return (-1.0);
234         if (ctx->req_rcvd < 1)
235                 return (-0.0);
236         else if (ctx->req_rcvd < 2)
237                 return (0.0);
239         num_total = (double) ctx->req_rcvd;
240         return (sqrt (((num_total * ctx->latency_total_square)
241                                         - (ctx->latency_total * ctx->latency_total))
242                                 / (num_total * (num_total - 1.0))));
243 } /* }}} double context_get_stddev */
245 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
247         if (ctx == NULL)
248                 return (-1.0);
250         if (ctx->req_sent < 1)
251                 return (0.0);
253         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
254                         / ((double) ctx->req_sent));
255 } /* }}} double context_get_packet_loss */
257 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
259         pingobj_iter_t *iter;
260         int index;
262         if (ping == NULL)
263                 return (EINVAL);
265         index = 0;
266         for (iter = ping_iterator_get (ping);
267                         iter != NULL;
268                         iter = ping_iterator_next (iter))
269         {
270                 ping_context_t *context;
271                 size_t buffer_size;
273                 context = context_create ();
274                 context->index = index;
276                 buffer_size = sizeof (context->host);
277                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
279                 buffer_size = sizeof (context->addr);
280                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
282                 ping_iterator_set_context (iter, (void *) context);
284                 index++;
285         }
287         return (0);
288 } /* }}} int ping_initialize_contexts */
290 static void usage_exit (const char *name, int status) /* {{{ */
292         fprintf (stderr, "Usage: %s [OPTIONS] "
293                                 "-f filename | host [host [host ...]]\n"
295                         "\nAvailable options:\n"
296                         "  -4|-6        force the use of IPv4 or IPv6\n"
297                         "  -c count     number of ICMP packets to send\n"
298                         "  -i interval  interval with which to send ICMP packets\n"
299                         "  -t ttl       time to live for each ICMP packet\n"
300                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
301                         "               Use \"-Q help\" for a list of valid options.\n"
302                         "  -I srcaddr   source address\n"
303                         "  -D device    outgoing interface name\n"
304                         "  -f filename  filename to read hosts from\n"
305 #if USE_NCURSES
306                         "  -u / -U      force / disable UTF-8 output\n"
307 #endif
309                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
310                         "by Florian octo Forster <octo@verplant.org>\n"
311                         "for contributions see `AUTHORS'\n",
312                         name);
313         exit (status);
314 } /* }}} void usage_exit */
316 __attribute__((noreturn))
317 static void usage_qos_exit (const char *arg, int status) /* {{{ */
319         if (arg != 0)
320                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
322         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
323                         "\n"
324                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
325                         "\n"
326                         "    be                     Best Effort (BE, default PHB).\n"
327                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
328                         "                           (low delay, low loss, low jitter)\n"
329                         "    va                     Voice Admit (VA) DSCP (RFC 5865).\n"
330                         "                           (capacity-admitted traffic)\n"
331                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
332                         "                           For example: \"af12\" (class 1, precedence 2)\n"
333                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
334                         "                           For example: \"cs1\" (priority traffic)\n"
335                         "\n"
336                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
337                         "\n"
338                         "    lowdelay     (%#04x)    minimize delay\n"
339                         "    throughput   (%#04x)    maximize throughput\n"
340                         "    reliability  (%#04x)    maximize reliability\n"
341                         "    mincost      (%#04x)    minimize monetary cost\n"
342                         "\n"
343                         "  Specify manually\n"
344                         "\n"
345                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
346                         "       0 -  255            Decimal numeric specification.\n"
347                         "\n",
348                         (unsigned int) IPTOS_LOWDELAY,
349                         (unsigned int) IPTOS_THROUGHPUT,
350                         (unsigned int) IPTOS_RELIABILITY,
351                         (unsigned int) IPTOS_MINCOST);
353         exit (status);
354 } /* }}} void usage_qos_exit */
356 static int set_opt_send_qos (const char *opt) /* {{{ */
358         if (opt == NULL)
359                 return (EINVAL);
361         if (strcasecmp ("help", opt) == 0)
362                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
363         /* DiffServ (RFC 2474): */
364         /* - Best effort (BE) */
365         else if (strcasecmp ("be", opt) == 0)
366                 opt_send_qos = 0;
367         /* - Expedited Forwarding (EF, RFC 3246) */
368         else if (strcasecmp ("ef", opt) == 0)
369                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
370         /* - Voice Admit (VA, RFC 5865) */
371         else if (strcasecmp ("va", opt) == 0)
372                 opt_send_qos = 0xB0; /* == 0x2D << 2 */
373         /* - Assured Forwarding (AF, RFC 2597) */
374         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
375                         && (strlen (opt) == 4))
376         {
377                 uint8_t dscp;
378                 uint8_t class = 0;
379                 uint8_t prec = 0;
381                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
382                 if (opt[2] == '1')
383                         class = 1;
384                 else if (opt[2] == '2')
385                         class = 2;
386                 else if (opt[2] == '3')
387                         class = 3;
388                 else if (opt[2] == '4')
389                         class = 4;
390                 else
391                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
393                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
394                 if (opt[3] == '1')
395                         prec = 1;
396                 else if (opt[3] == '2')
397                         prec = 2;
398                 else if (opt[3] == '3')
399                         prec = 3;
400                 else
401                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
403                 dscp = (8 * class) + (2 * prec);
404                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
405                 opt_send_qos = dscp << 2;
406         }
407         /* - Class Selector (CS) */
408         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
409                         && (strlen (opt) == 3))
410         {
411                 uint8_t class;
413                 if ((opt[2] < '0') || (opt[2] > '7'))
414                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
416                 /* Not exactly legal by the C standard, but I don't know of any
417                  * system not supporting this hack. */
418                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
419                 opt_send_qos = class << 5;
420         }
421         /* Type of Service (RFC 1349) */
422         else if (strcasecmp ("lowdelay", opt) == 0)
423                 opt_send_qos = IPTOS_LOWDELAY;
424         else if (strcasecmp ("throughput", opt) == 0)
425                 opt_send_qos = IPTOS_THROUGHPUT;
426         else if (strcasecmp ("reliability", opt) == 0)
427                 opt_send_qos = IPTOS_RELIABILITY;
428         else if (strcasecmp ("mincost", opt) == 0)
429                 opt_send_qos = IPTOS_MINCOST;
430         /* Numeric value */
431         else
432         {
433                 unsigned long value;
434                 char *endptr;
436                 errno = 0;
437                 endptr = NULL;
438                 value = strtoul (opt, &endptr, /* base = */ 0);
439                 if ((errno != 0) || (endptr == opt)
440                                 || (endptr == NULL) || (*endptr != 0)
441                                 || (value > 0xff))
442                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
443                 
444                 opt_send_qos = (uint8_t) value;
445         }
447         return (0);
448 } /* }}} int set_opt_send_qos */
450 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
452         uint8_t dscp;
453         uint8_t ecn;
454         char *dscp_str;
455         char *ecn_str;
457         dscp = qos >> 2;
458         ecn = qos & 0x03;
460         switch (dscp)
461         {
462                 case 0x00: dscp_str = "be";  break;
463                 case 0x2e: dscp_str = "ef";  break;
464                 case 0x2d: dscp_str = "va";  break;
465                 case 0x0a: dscp_str = "af11"; break;
466                 case 0x0c: dscp_str = "af12"; break;
467                 case 0x0e: dscp_str = "af13"; break;
468                 case 0x12: dscp_str = "af21"; break;
469                 case 0x14: dscp_str = "af22"; break;
470                 case 0x16: dscp_str = "af23"; break;
471                 case 0x1a: dscp_str = "af31"; break;
472                 case 0x1c: dscp_str = "af32"; break;
473                 case 0x1e: dscp_str = "af33"; break;
474                 case 0x22: dscp_str = "af41"; break;
475                 case 0x24: dscp_str = "af42"; break;
476                 case 0x26: dscp_str = "af43"; break;
477                 case 0x08: dscp_str = "cs1";  break;
478                 case 0x10: dscp_str = "cs2";  break;
479                 case 0x18: dscp_str = "cs3";  break;
480                 case 0x20: dscp_str = "cs4";  break;
481                 case 0x28: dscp_str = "cs5";  break;
482                 case 0x30: dscp_str = "cs6";  break;
483                 case 0x38: dscp_str = "cs7";  break;
484                 default:   dscp_str = NULL;
485         }
487         switch (ecn)
488         {
489                 case 0x01: ecn_str = ",ecn(1)"; break;
490                 case 0x02: ecn_str = ",ecn(0)"; break;
491                 case 0x03: ecn_str = ",ce"; break;
492                 default:   ecn_str = "";
493         }
495         if (dscp_str == NULL)
496                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
497         else
498                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
499         buffer[buffer_size - 1] = 0;
501         return (buffer);
502 } /* }}} char *format_qos */
504 static int read_options (int argc, char **argv) /* {{{ */
506         int optchar;
508         while (1)
509         {
510                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:"
511 #if USE_NCURSES
512                                 "uU"
513 #endif
514                                 );
516                 if (optchar == -1)
517                         break;
519                 switch (optchar)
520                 {
521                         case '4':
522                         case '6':
523                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
524                                 break;
526                         case 'c':
527                                 {
528                                         int new_count;
529                                         new_count = atoi (optarg);
530                                         if (new_count > 0)
531                                                 opt_count = new_count;
532                                         else
533                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
534                                                                 optarg);
535                                 }
536                                 break;
538                         case 'f':
539                                 {
540                                         if (opt_filename != NULL)
541                                                 free (opt_filename);
542                                         opt_filename = strdup (optarg);
543                                 }
544                                 break;
546                         case 'i':
547                                 {
548                                         double new_interval;
549                                         new_interval = atof (optarg);
550                                         if (new_interval < 0.001)
551                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
552                                                                 optarg);
553                                         else
554                                                 opt_interval = new_interval;
555                                 }
556                                 break;
557                         case 'I':
558                                 {
559                                         if (opt_srcaddr != NULL)
560                                                 free (opt_srcaddr);
561                                         opt_srcaddr = strdup (optarg);
562                                 }
563                                 break;
565                         case 'D':
566                                 opt_device = optarg;
567                                 break;
569                         case 't':
570                         {
571                                 int new_send_ttl;
572                                 new_send_ttl = atoi (optarg);
573                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
574                                         opt_send_ttl = new_send_ttl;
575                                 else
576                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
577                                                         optarg);
578                                 break;
579                         }
581                         case 'Q':
582                                 set_opt_send_qos (optarg);
583                                 break;
585 #if USE_NCURSES
586                         case 'u':
587                                 opt_utf8 = 2;
588                                 break;
589                         case 'U':
590                                 opt_utf8 = 1;
591                                 break;
592 #endif
594                         case 'h':
595                                 usage_exit (argv[0], 0);
596                                 break;
597                         default:
598                                 usage_exit (argv[0], 1);
599                 }
600         }
602         return (optind);
603 } /* }}} read_options */
605 static void time_normalize (struct timespec *ts) /* {{{ */
607         while (ts->tv_nsec < 0)
608         {
609                 if (ts->tv_sec == 0)
610                 {
611                         ts->tv_nsec = 0;
612                         return;
613                 }
615                 ts->tv_sec  -= 1;
616                 ts->tv_nsec += 1000000000;
617         }
619         while (ts->tv_nsec >= 1000000000)
620         {
621                 ts->tv_sec  += 1;
622                 ts->tv_nsec -= 1000000000;
623         }
624 } /* }}} void time_normalize */
626 static void time_calc (struct timespec *ts_dest, /* {{{ */
627                 const struct timespec *ts_int,
628                 const struct timeval  *tv_begin,
629                 const struct timeval  *tv_end)
631         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
632         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
633         time_normalize (ts_dest);
635         /* Assure that `(begin + interval) > end'.
636          * This may seem overly complicated, but `tv_sec' is of type `time_t'
637          * which may be `unsigned. *sigh* */
638         if ((tv_end->tv_sec > ts_dest->tv_sec)
639                         || ((tv_end->tv_sec == ts_dest->tv_sec)
640                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
641         {
642                 ts_dest->tv_sec  = 0;
643                 ts_dest->tv_nsec = 0;
644                 return;
645         }
647         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
648         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
649         time_normalize (ts_dest);
650 } /* }}} void time_calc */
652 #if USE_NCURSES
653 static _Bool has_utf8() /* {{{ */
655         if (!opt_utf8)
656         {
657                 /* Automatically determine */
658                 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
659                         opt_utf8 = 2;
660                 else
661                         opt_utf8 = 1;
662         }
663         return ((_Bool) (opt_utf8 - 1));
664 } /* }}} _Bool has_utf8 */
666 static int update_prettyping_graph (ping_context_t *ctx, /* {{{ */
667                 double latency, unsigned int sequence)
669         int color = OPING_RED;
670         char const *symbol = "!";
671         int symbolc = '!';
672         size_t hist_symbols_num;
673         size_t index_symbols;
675         int x_max;
676         int x_pos;
678         x_max = getmaxx (ctx->window);
679         x_pos = ((sequence - 1) % (x_max - 4)) + 2;
681         if (has_utf8())
682         {
683                 hist_symbols_num = hist_symbols_utf8_num;
684         }
685         else {
686                 hist_symbols_num = hist_symbols_acs_num;
687         }
689         if (latency >= 0.0)
690         {
691                 double ratio;
692                 size_t intensity;
693                 size_t index_colors;
695                 ratio = latency / PING_DEF_TTL;
696                 if (ratio > 1) {
697                         ratio = 1.0;
698                 }
700                 intensity = (size_t) ((ratio * hist_symbols_num
701                                         * hist_colors_num) - 1);
703                 index_colors = intensity / hist_symbols_num;
704                 assert (index_colors < hist_colors_num);
706                 index_symbols = intensity % hist_symbols_num;
707                 if (has_utf8())
708                 {
709                         color = hist_colors_utf8[index_colors];
710                         symbol = hist_symbols_utf8[index_symbols];
711                 }
712                 else
713                 {
714                         color = hist_colors_acs[index_colors];
715                         symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
716                 }
717         }
718         else /* if (!(latency >= 0.0)) */
719                 wattron (ctx->window, A_BOLD);
721         wattron (ctx->window, COLOR_PAIR(color));
722         if (has_utf8())
723         {
724                 mvwprintw (ctx->window,
725                            /* y = */ 3,
726                            /* x = */ x_pos,
727                            symbol);
728         }
729         else {
730                 mvwaddch (ctx->window,
731                           /* y = */ 3,
732                           /* x = */ x_pos,
733                           symbolc);
734         }
735         wattroff (ctx->window, COLOR_PAIR(color));
737         /* Use negation here to handle NaN correctly. */
738         if (!(latency >= 0.0))
739                 wattroff (ctx->window, A_BOLD);
741         wprintw (ctx->window, " ");
742         return (0);
743 } /* }}} int update_prettyping_graph */
745 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
747         double latency = -1.0;
748         size_t buffer_len = sizeof (latency);
750         ping_iterator_get_info (iter, PING_INFO_LATENCY,
751                         &latency, &buffer_len);
753         unsigned int sequence = 0;
754         buffer_len = sizeof (sequence);
755         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
756                         &sequence, &buffer_len);
759         if ((ctx == NULL) || (ctx->window == NULL))
760                 return (EINVAL);
762         /* werase (ctx->window); */
764         box (ctx->window, 0, 0);
765         wattron (ctx->window, A_BOLD);
766         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
767                         " %s ", ctx->host);
768         wattroff (ctx->window, A_BOLD);
769         wprintw (ctx->window, "ping statistics ");
770         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
771                         "%i packets transmitted, %i received, %.2f%% packet "
772                         "loss, time %.1fms",
773                         ctx->req_sent, ctx->req_rcvd,
774                         context_get_packet_loss (ctx),
775                         ctx->latency_total);
776         if (ctx->req_rcvd != 0)
777         {
778                 double average;
779                 double deviation;
781                 average = context_get_average (ctx);
782                 deviation = context_get_stddev (ctx);
783                         
784                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
785                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
786                                 ctx->latency_min,
787                                 average,
788                                 ctx->latency_max,
789                                 deviation);
790         }
792         if (has_colors () == TRUE)
793                 update_prettyping_graph (ctx, latency, sequence);
795         wrefresh (ctx->window);
797         return (0);
798 } /* }}} int update_stats_from_context */
800 static int on_resize (pingobj_t *ping) /* {{{ */
802         pingobj_iter_t *iter;
803         int width = 0;
804         int height = 0;
805         int main_win_height;
807         getmaxyx (stdscr, height, width);
808         if ((height < 1) || (width < 1))
809                 return (EINVAL);
811         main_win_height = height - (5 * host_num);
812         wresize (main_win, main_win_height, /* width = */ width);
813         /* Allow scrolling */
814         scrollok (main_win, TRUE);
815         /* wsetscrreg (main_win, 0, main_win_height - 1); */
816         /* Allow hardware accelerated scrolling. */
817         idlok (main_win, TRUE);
818         wrefresh (main_win);
820         for (iter = ping_iterator_get (ping);
821                         iter != NULL;
822                         iter = ping_iterator_next (iter))
823         {
824                 ping_context_t *context;
826                 context = ping_iterator_get_context (iter);
827                 if (context == NULL)
828                         continue;
830                 if (context->window != NULL)
831                 {
832                         delwin (context->window);
833                         context->window = NULL;
834                 }
835                 context->window = newwin (/* height = */ 5,
836                                 /* width = */ width,
837                                 /* y = */ main_win_height + (5 * context->index),
838                                 /* x = */ 0);
839         }
841         return (0);
842 } /* }}} */
844 static int check_resize (pingobj_t *ping) /* {{{ */
846         int need_resize = 0;
848         while (42)
849         {
850                 int key = wgetch (stdscr);
851                 if (key == ERR)
852                         break;
853                 else if (key == KEY_RESIZE)
854                         need_resize = 1;
855         }
857         if (need_resize)
858                 return (on_resize (ping));
859         else
860                 return (0);
861 } /* }}} int check_resize */
863 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
865         pingobj_iter_t *iter;
866         int width = 0;
867         int height = 0;
868         int main_win_height;
870         initscr ();
871         cbreak ();
872         noecho ();
873         nodelay (stdscr, TRUE);
875         getmaxyx (stdscr, height, width);
876         if ((height < 1) || (width < 1))
877                 return (EINVAL);
879         if (has_colors () == TRUE)
880         {
881                 start_color ();
882                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
883                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
884                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
885                 init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
886                 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
887                 init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
888         }
890         main_win_height = height - (5 * host_num);
891         main_win = newwin (/* height = */ main_win_height,
892                         /* width = */ width,
893                         /* y = */ 0, /* x = */ 0);
894         /* Allow scrolling */
895         scrollok (main_win, TRUE);
896         /* wsetscrreg (main_win, 0, main_win_height - 1); */
897         /* Allow hardware accelerated scrolling. */
898         idlok (main_win, TRUE);
899         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
900         wrefresh (main_win);
902         for (iter = ping_iterator_get (ping);
903                         iter != NULL;
904                         iter = ping_iterator_next (iter))
905         {
906                 ping_context_t *context;
908                 context = ping_iterator_get_context (iter);
909                 if (context == NULL)
910                         continue;
912                 if (context->window != NULL)
913                 {
914                         delwin (context->window);
915                         context->window = NULL;
916                 }
917                 context->window = newwin (/* height = */ 5,
918                                 /* width = */ width,
919                                 /* y = */ main_win_height + (5 * context->index),
920                                 /* x = */ 0);
921         }
924         /* Don't know what good this does exactly, but without this code
925          * "check_resize" will be called right after startup and *somehow*
926          * this leads to display errors. If we purge all initial characters
927          * here, the problem goes away. "wgetch" is non-blocking due to
928          * "nodelay" (see above). */
929         while (wgetch (stdscr) != ERR)
930         {
931                 /* eat up characters */;
932         }
934         return (0);
935 } /* }}} int pre_loop_hook */
937 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
939         return (check_resize (ping));
940 } /* }}} int pre_sleep_hook */
942 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
944         return (check_resize (ping));
945 } /* }}} int pre_sleep_hook */
946 #else /* if !USE_NCURSES */
947 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
949         pingobj_iter_t *iter;
951         for (iter = ping_iterator_get (ping);
952                         iter != NULL;
953                         iter = ping_iterator_next (iter))
954         {
955                 ping_context_t *ctx;
956                 size_t buffer_size;
958                 ctx = ping_iterator_get_context (iter);
959                 if (ctx == NULL)
960                         continue;
962                 buffer_size = 0;
963                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
965                 printf ("PING %s (%s) %zu bytes of data.\n",
966                                 ctx->host, ctx->addr, buffer_size);
967         }
969         return (0);
970 } /* }}} int pre_loop_hook */
972 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
974         fflush (stdout);
976         return (0);
977 } /* }}} int pre_sleep_hook */
979 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
981         return (0);
982 } /* }}} int post_sleep_hook */
983 #endif
985 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
986                 __attribute__((unused)) int index)
988         double          latency;
989         unsigned int    sequence;
990         int             recv_ttl;
991         uint8_t         recv_qos;
992         char            recv_qos_str[16];
993         size_t          buffer_len;
994         size_t          data_len;
995         ping_context_t *context;
997         latency = -1.0;
998         buffer_len = sizeof (latency);
999         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1000                         &latency, &buffer_len);
1002         sequence = 0;
1003         buffer_len = sizeof (sequence);
1004         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1005                         &sequence, &buffer_len);
1007         recv_ttl = -1;
1008         buffer_len = sizeof (recv_ttl);
1009         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1010                         &recv_ttl, &buffer_len);
1012         recv_qos = 0;
1013         buffer_len = sizeof (recv_qos);
1014         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1015                         &recv_qos, &buffer_len);
1017         data_len = 0;
1018         ping_iterator_get_info (iter, PING_INFO_DATA,
1019                         NULL, &data_len);
1021         context = (ping_context_t *) ping_iterator_get_context (iter);
1023 #if USE_NCURSES
1024 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1025 #else
1026 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1027 #endif
1029         context->req_sent++;
1030         if (latency > 0.0)
1031         {
1032                 context->req_rcvd++;
1033                 context->latency_total += latency;
1034                 context->latency_total_square += (latency * latency);
1036                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
1037                         context->latency_max = latency;
1038                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
1039                         context->latency_min = latency;
1041 #if USE_NCURSES
1042                 if (has_colors () == TRUE)
1043                 {
1044                         int color = OPING_GREEN;
1045                         double average = context_get_average (context);
1046                         double stddev = context_get_stddev (context);
1048                         if ((latency < (average - (2 * stddev)))
1049                                         || (latency > (average + (2 * stddev))))
1050                                 color = OPING_RED;
1051                         else if ((latency < (average - stddev))
1052                                         || (latency > (average + stddev)))
1053                                 color = OPING_YELLOW;
1055                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1056                                         data_len, context->host, context->addr,
1057                                         sequence, recv_ttl,
1058                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1059                         if ((recv_qos != 0) || (opt_send_qos != 0))
1060                         {
1061                                 HOST_PRINTF ("qos=%s ",
1062                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1063                         }
1064                         HOST_PRINTF ("time=");
1065                         wattron (main_win, COLOR_PAIR(color));
1066                         HOST_PRINTF ("%.2f", latency);
1067                         wattroff (main_win, COLOR_PAIR(color));
1068                         HOST_PRINTF (" ms\n");
1069                 }
1070                 else
1071                 {
1072 #endif
1073                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1074                                 data_len,
1075                                 context->host, context->addr,
1076                                 sequence, recv_ttl);
1077                 if ((recv_qos != 0) || (opt_send_qos != 0))
1078                 {
1079                         HOST_PRINTF ("qos=%s ",
1080                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1081                 }
1082                 HOST_PRINTF ("time=%.2f ms\n", latency);
1083 #if USE_NCURSES
1084                 }
1085 #endif
1086         }
1087         else
1088         {
1089 #if USE_NCURSES
1090                 if (has_colors () == TRUE)
1091                 {
1092                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1093                                         context->host, context->addr,
1094                                         sequence);
1095                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1096                         HOST_PRINTF ("timeout");
1097                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1098                         HOST_PRINTF ("\n");
1099                 }
1100                 else
1101                 {
1102 #endif
1103                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1104                                 context->host, context->addr,
1105                                 sequence);
1106 #if USE_NCURSES
1107                 }
1108 #endif
1109         }
1111 #if USE_NCURSES
1112         update_stats_from_context (context, iter);
1113         wrefresh (main_win);
1114 #endif
1115 } /* }}} void update_host_hook */
1117 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1119         pingobj_iter_t *iter;
1121 #if USE_NCURSES
1122         endwin ();
1123 #endif
1125         for (iter = ping_iterator_get (ping);
1126                         iter != NULL;
1127                         iter = ping_iterator_next (iter))
1128         {
1129                 ping_context_t *context;
1131                 context = ping_iterator_get_context (iter);
1133                 printf ("\n--- %s ping statistics ---\n"
1134                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1135                                 context->host, context->req_sent, context->req_rcvd,
1136                                 context_get_packet_loss (context),
1137                                 context->latency_total);
1139                 if (context->req_rcvd != 0)
1140                 {
1141                         double average;
1142                         double deviation;
1144                         average = context_get_average (context);
1145                         deviation = context_get_stddev (context);
1147                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1148                                         context->latency_min,
1149                                         average,
1150                                         context->latency_max,
1151                                         deviation);
1152                 }
1154                 ping_iterator_set_context (iter, NULL);
1155                 context_destroy (context);
1156         }
1158         return (0);
1159 } /* }}} int post_loop_hook */
1161 int main (int argc, char **argv) /* {{{ */
1163         pingobj_t      *ping;
1164         pingobj_iter_t *iter;
1166         struct sigaction sigint_action;
1168         struct timeval  tv_begin;
1169         struct timeval  tv_end;
1170         struct timespec ts_wait;
1171         struct timespec ts_int;
1173         int optind;
1174         int i;
1175         int status;
1176 #if _POSIX_SAVED_IDS
1177         uid_t saved_set_uid;
1179         /* Save the old effective user id */
1180         saved_set_uid = geteuid ();
1181         /* Set the effective user ID to the real user ID without changing the
1182          * saved set-user ID */
1183         status = seteuid (getuid ());
1184         if (status != 0)
1185         {
1186                 fprintf (stderr, "Temporarily dropping privileges "
1187                                 "failed: %s\n", strerror (errno));
1188                 exit (EXIT_FAILURE);
1189         }
1190 #endif
1192         setlocale(LC_ALL, "");
1193         optind = read_options (argc, argv);
1195 #if !_POSIX_SAVED_IDS
1196         /* Cannot temporarily drop privileges -> reject every file but "-". */
1197         if ((opt_filename != NULL)
1198                         && (strcmp ("-", opt_filename) != 0)
1199                         && (getuid () != geteuid ()))
1200         {
1201                 fprintf (stderr, "Your real and effective user IDs don't "
1202                                 "match. Reading from a file (option '-f')\n"
1203                                 "is therefore too risky. You can still read "
1204                                 "from STDIN using '-f -' if you like.\n"
1205                                 "Sorry.\n");
1206                 exit (EXIT_FAILURE);
1207         }
1208 #endif
1210         if ((optind >= argc) && (opt_filename == NULL)) {
1211                 usage_exit (argv[0], 1);
1212         }
1214         if ((ping = ping_construct ()) == NULL)
1215         {
1216                 fprintf (stderr, "ping_construct failed\n");
1217                 return (1);
1218         }
1220         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1221         {
1222                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1223                                 opt_send_ttl, ping_get_error (ping));
1224         }
1226         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1227         {
1228                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1229                                 opt_send_qos, ping_get_error (ping));
1230         }
1232         {
1233                 double temp_sec;
1234                 double temp_nsec;
1236                 temp_nsec = modf (opt_interval, &temp_sec);
1237                 ts_int.tv_sec  = (time_t) temp_sec;
1238                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1240                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1241         }
1243         if (opt_addrfamily != PING_DEF_AF)
1244                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1246         if (opt_srcaddr != NULL)
1247         {
1248                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1249                 {
1250                         fprintf (stderr, "Setting source address failed: %s\n",
1251                                         ping_get_error (ping));
1252                 }
1253         }
1255         if (opt_device != NULL)
1256         {
1257                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1258                 {
1259                         fprintf (stderr, "Setting device failed: %s\n",
1260                                         ping_get_error (ping));
1261                 }
1262         }
1264         if (opt_filename != NULL)
1265         {
1266                 FILE *infile;
1267                 char line[256];
1268                 char host[256];
1270                 if (strcmp (opt_filename, "-") == 0)
1271                         /* Open STDIN */
1272                         infile = fdopen(0, "r");
1273                 else
1274                         infile = fopen(opt_filename, "r");
1276                 if (infile == NULL)
1277                 {
1278                         fprintf (stderr, "Opening %s failed: %s\n",
1279                                         (strcmp (opt_filename, "-") == 0)
1280                                         ? "STDIN" : opt_filename,
1281                                         strerror(errno));
1282                         return (1);
1283                 }
1285 #if _POSIX_SAVED_IDS
1286                 /* Regain privileges */
1287                 status = seteuid (saved_set_uid);
1288                 if (status != 0)
1289                 {
1290                         fprintf (stderr, "Temporarily re-gaining privileges "
1291                                         "failed: %s\n", strerror (errno));
1292                         exit (EXIT_FAILURE);
1293                 }
1294 #endif
1296                 while (fgets(line, sizeof(line), infile))
1297                 {
1298                         /* Strip whitespace */
1299                         if (sscanf(line, "%s", host) != 1)
1300                                 continue;
1302                         if ((host[0] == 0) || (host[0] == '#'))
1303                                 continue;
1305                         if (ping_host_add(ping, host) < 0)
1306                         {
1307                                 const char *errmsg = ping_get_error (ping);
1309                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1310                                 continue;
1311                         }
1312                         else
1313                         {
1314                                 host_num++;
1315                         }
1316                 }
1318 #if _POSIX_SAVED_IDS
1319                 /* Drop privileges */
1320                 status = seteuid (getuid ());
1321                 if (status != 0)
1322                 {
1323                         fprintf (stderr, "Temporarily dropping privileges "
1324                                         "failed: %s\n", strerror (errno));
1325                         exit (EXIT_FAILURE);
1326                 }
1327 #endif
1329                 fclose(infile);
1330         }
1332 #if _POSIX_SAVED_IDS
1333         /* Regain privileges */
1334         status = seteuid (saved_set_uid);
1335         if (status != 0)
1336         {
1337                 fprintf (stderr, "Temporarily re-gaining privileges "
1338                                 "failed: %s\n", strerror (errno));
1339                 exit (EXIT_FAILURE);
1340         }
1341 #endif
1343         for (i = optind; i < argc; i++)
1344         {
1345                 if (ping_host_add (ping, argv[i]) < 0)
1346                 {
1347                         const char *errmsg = ping_get_error (ping);
1349                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1350                         continue;
1351                 }
1352                 else
1353                 {
1354                         host_num++;
1355                 }
1356         }
1358         /* Permanently drop root privileges if we're setuid-root. */
1359         status = setuid (getuid ());
1360         if (status != 0)
1361         {
1362                 fprintf (stderr, "Dropping privileges failed: %s\n",
1363                                 strerror (errno));
1364                 exit (EXIT_FAILURE);
1365         }
1367 #if _POSIX_SAVED_IDS
1368         saved_set_uid = (uid_t) -1;
1369 #endif
1371         ping_initialize_contexts (ping);
1373         if (i == 0)
1374                 return (1);
1376         memset (&sigint_action, '\0', sizeof (sigint_action));
1377         sigint_action.sa_handler = sigint_handler;
1378         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1379         {
1380                 perror ("sigaction");
1381                 return (1);
1382         }
1384         pre_loop_hook (ping);
1386         while (opt_count != 0)
1387         {
1388                 int index;
1389                 int status;
1391                 if (gettimeofday (&tv_begin, NULL) < 0)
1392                 {
1393                         perror ("gettimeofday");
1394                         return (1);
1395                 }
1397                 if (ping_send (ping) < 0)
1398                 {
1399                         fprintf (stderr, "ping_send failed: %s\n",
1400                                         ping_get_error (ping));
1401                         return (1);
1402                 }
1404                 index = 0;
1405                 for (iter = ping_iterator_get (ping);
1406                                 iter != NULL;
1407                                 iter = ping_iterator_next (iter))
1408                 {
1409                         update_host_hook (iter, index);
1410                         index++;
1411                 }
1413                 pre_sleep_hook (ping);
1415                 /* Don't sleep in the last iteration */
1416                 if (opt_count == 1)
1417                         break;
1419                 if (gettimeofday (&tv_end, NULL) < 0)
1420                 {
1421                         perror ("gettimeofday");
1422                         return (1);
1423                 }
1425                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1427                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1428                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1429                 {
1430                         if (errno != EINTR)
1431                         {
1432                                 perror ("nanosleep");
1433                                 break;
1434                         }
1435                         else if (opt_count == 0)
1436                         {
1437                                 /* sigint */
1438                                 break;
1439                         }
1440                 }
1442                 post_sleep_hook (ping);
1444                 if (opt_count > 0)
1445                         opt_count--;
1446         } /* while (opt_count != 0) */
1448         post_loop_hook (ping);
1450         ping_destroy (ping);
1452         return (0);
1453 } /* }}} int main */
1455 /* vim: set fdm=marker : */