Code

Merge branch 'vm/qos'
[liboping.git] / src / oping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2010  Florian octo Forster <octo at verplant.org>
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 #if USE_NCURSES
78 # define NCURSES_OPAQUE 1
79 # include <ncurses.h>
81 # define OPING_GREEN 1
82 # define OPING_YELLOW 2
83 # define OPING_RED 3
84 #endif
86 #include "oping.h"
88 #ifndef _POSIX_SAVED_IDS
89 # define _POSIX_SAVED_IDS 0
90 #endif
92 typedef struct ping_context
93 {
94         char host[NI_MAXHOST];
95         char addr[NI_MAXHOST];
97         int index;
98         int req_sent;
99         int req_rcvd;
101         double latency_min;
102         double latency_max;
103         double latency_total;
104         double latency_total_square;
106 #if USE_NCURSES
107         WINDOW *window;
108 #endif
109 } ping_context_t;
111 static double  opt_interval   = 1.0;
112 static int     opt_addrfamily = PING_DEF_AF;
113 static char   *opt_srcaddr    = NULL;
114 static char   *opt_device     = NULL;
115 static char   *opt_filename   = NULL;
116 static int     opt_count      = -1;
117 static int     opt_send_ttl   = 64;
118 static uint8_t opt_send_qos   = 0;
120 static int host_num = 0;
122 #if USE_NCURSES
123 static WINDOW *main_win = NULL;
124 #endif
126 static void sigint_handler (int signal) /* {{{ */
128         /* Make compiler happy */
129         signal = 0;
130         /* Exit the loop */
131         opt_count = 0;
132 } /* }}} void sigint_handler */
134 static ping_context_t *context_create (void) /* {{{ */
136         ping_context_t *ret;
138         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
139                 return (NULL);
141         memset (ret, '\0', sizeof (ping_context_t));
143         ret->latency_min   = -1.0;
144         ret->latency_max   = -1.0;
145         ret->latency_total = 0.0;
146         ret->latency_total_square = 0.0;
148 #if USE_NCURSES
149         ret->window = NULL;
150 #endif
152         return (ret);
153 } /* }}} ping_context_t *context_create */
155 static void context_destroy (ping_context_t *context) /* {{{ */
157         if (context == NULL)
158                 return;
160 #if USE_NCURSES
161         if (context->window != NULL)
162         {
163                 delwin (context->window);
164                 context->window = NULL;
165         }
166 #endif
168         free (context);
169 } /* }}} void context_destroy */
171 static double context_get_average (ping_context_t *ctx) /* {{{ */
173         double num_total;
175         if (ctx == NULL)
176                 return (-1.0);
178         if (ctx->req_rcvd < 1)
179                 return (-0.0);
181         num_total = (double) ctx->req_rcvd;
182         return (ctx->latency_total / num_total);
183 } /* }}} double context_get_average */
185 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
187         double num_total;
189         if (ctx == NULL)
190                 return (-1.0);
192         if (ctx->req_rcvd < 1)
193                 return (-0.0);
194         else if (ctx->req_rcvd < 2)
195                 return (0.0);
197         num_total = (double) ctx->req_rcvd;
198         return (sqrt (((num_total * ctx->latency_total_square)
199                                         - (ctx->latency_total * ctx->latency_total))
200                                 / (num_total * (num_total - 1.0))));
201 } /* }}} double context_get_stddev */
203 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
205         if (ctx == NULL)
206                 return (-1.0);
208         if (ctx->req_sent < 1)
209                 return (0.0);
211         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
212                         / ((double) ctx->req_sent));
213 } /* }}} double context_get_packet_loss */
215 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
217         pingobj_iter_t *iter;
218         int index;
220         if (ping == NULL)
221                 return (EINVAL);
223         index = 0;
224         for (iter = ping_iterator_get (ping);
225                         iter != NULL;
226                         iter = ping_iterator_next (iter))
227         {
228                 ping_context_t *context;
229                 size_t buffer_size;
231                 context = context_create ();
232                 context->index = index;
234                 buffer_size = sizeof (context->host);
235                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
237                 buffer_size = sizeof (context->addr);
238                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
240                 ping_iterator_set_context (iter, (void *) context);
242                 index++;
243         }
245         return (0);
246 } /* }}} int ping_initialize_contexts */
248 static void usage_exit (const char *name, int status) /* {{{ */
250         fprintf (stderr, "Usage: %s [OPTIONS] "
251                                 "-f filename | host [host [host ...]]\n"
253                         "\nAvailable options:\n"
254                         "  -4|-6        force the use of IPv4 or IPv6\n"
255                         "  -c count     number of ICMP packets to send\n"
256                         "  -i interval  interval with which to send ICMP packets\n"
257                         "  -t ttl       time to live for each ICMP packet\n"
258                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
259                         "               Use \"-Q help\" for a list of valid options.\n"
260                         "  -I srcaddr   source address\n"
261                         "  -D device    outgoing interface name\n"
262                         "  -f filename  filename to read hosts from\n"
264                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
265                         "by Florian octo Forster <octo@verplant.org>\n"
266                         "for contributions see `AUTHORS'\n",
267                         name);
268         exit (status);
269 } /* }}} void usage_exit */
271 static void usage_qos_exit (const char *arg, int status) /* {{{ */
273         if (arg != 0)
274                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
276         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
277                         "\n"
278                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
279                         "\n"
280                         "    be                     Best Effort (BE, default PHB).\n"
281                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
282                         "                           (low delay, low loss, low jitter)\n"
283                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
284                         "                           For example: \"af12\" (class 1, precedence 2)\n"
285                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
286                         "                           For example: \"cs1\" (priority traffic)\n"
287                         "\n"
288                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
289                         "\n"
290                         "    lowdelay     (%#04x)    minimize delay\n"
291                         "    throughput   (%#04x)    maximize throughput\n"
292                         "    reliability  (%#04x)    maximize reliability\n"
293                         "    mincost      (%#04x)    minimize monetary cost\n"
294                         "\n"
295                         "  Specify manually\n"
296                         "\n"
297                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
298                         "       0 -  255            Decimal numeric specification.\n"
299                         "\n",
300                         (unsigned int) IPTOS_LOWDELAY,
301                         (unsigned int) IPTOS_THROUGHPUT,
302                         (unsigned int) IPTOS_RELIABILITY,
303                         (unsigned int) IPTOS_MINCOST);
305         exit (status);
306 } /* }}} void usage_qos_exit */
308 static int set_opt_send_qos (const char *opt) /* {{{ */
310         if (opt == NULL)
311                 return (EINVAL);
313         if (strcasecmp ("help", opt) == 0)
314                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
315         /* DiffServ (RFC 2474): */
316         /* - Best effort (BE) */
317         else if (strcasecmp ("be", opt) == 0)
318                 opt_send_qos = 0;
319         /* - Expedited Forwarding (EF, RFC 3246) */
320         else if (strcasecmp ("ef", opt) == 0)
321                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
322         /* - Assured Forwarding (AF, RFC 2597) */
323         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
324                         && (strlen (opt) == 4))
325         {
326                 uint8_t dscp;
327                 uint8_t class;
328                 uint8_t prec;
330                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
331                 if (opt[2] == '1')
332                         class = 1;
333                 else if (opt[2] == '2')
334                         class = 2;
335                 else if (opt[2] == '3')
336                         class = 3;
337                 else if (opt[2] == '4')
338                         class = 4;
339                 else
340                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
342                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
343                 if (opt[3] == '1')
344                         prec = 1;
345                 else if (opt[3] == '2')
346                         prec = 2;
347                 else if (opt[3] == '3')
348                         prec = 3;
349                 else
350                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
352                 dscp = (8 * class) + (2 * prec);
353                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
354                 opt_send_qos = dscp << 2;
355         }
356         /* - Class Selector (CS) */
357         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
358                         && (strlen (opt) == 3))
359         {
360                 uint8_t class;
362                 if ((opt[2] < '0') || (opt[2] > '7'))
363                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
365                 /* Not exactly legal by the C standard, but I don't know of any
366                  * system not supporting this hack. */
367                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
368                 opt_send_qos = class << 5;
369         }
370         /* Type of Service (RFC 1349) */
371         else if (strcasecmp ("lowdelay", opt) == 0)
372                 opt_send_qos = IPTOS_LOWDELAY;
373         else if (strcasecmp ("throughput", opt) == 0)
374                 opt_send_qos = IPTOS_THROUGHPUT;
375         else if (strcasecmp ("reliability", opt) == 0)
376                 opt_send_qos = IPTOS_RELIABILITY;
377         else if (strcasecmp ("mincost", opt) == 0)
378                 opt_send_qos = IPTOS_MINCOST;
379         /* Numeric value */
380         else
381         {
382                 unsigned long value;
383                 char *endptr;
385                 errno = 0;
386                 endptr = NULL;
387                 value = strtoul (opt, &endptr, /* base = */ 0);
388                 if ((errno != 0) || (endptr == opt)
389                                 || (endptr == NULL) || (*endptr != 0)
390                                 || (value > 0xff))
391                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
392                 
393                 opt_send_qos = (uint8_t) value;
394         }
396         return (0);
397 } /* }}} int set_opt_send_qos */
399 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
401         uint8_t dscp;
402         uint8_t ecn;
403         char *dscp_str;
404         char *ecn_str;
406         dscp = qos >> 2;
407         ecn = qos & 0x03;
409         switch (dscp)
410         {
411                 case 0x00: dscp_str = "be";  break;
412                 case 0x2e: dscp_str = "ef";  break;
413                 case 0x0a: dscp_str = "af11"; break;
414                 case 0x0c: dscp_str = "af12"; break;
415                 case 0x0e: dscp_str = "af13"; break;
416                 case 0x12: dscp_str = "af21"; break;
417                 case 0x14: dscp_str = "af22"; break;
418                 case 0x16: dscp_str = "af23"; break;
419                 case 0x1a: dscp_str = "af31"; break;
420                 case 0x1c: dscp_str = "af32"; break;
421                 case 0x1e: dscp_str = "af33"; break;
422                 case 0x22: dscp_str = "af41"; break;
423                 case 0x24: dscp_str = "af42"; break;
424                 case 0x26: dscp_str = "af43"; break;
425                 case 0x08: dscp_str = "cs1";  break;
426                 case 0x10: dscp_str = "cs2";  break;
427                 case 0x18: dscp_str = "cs3";  break;
428                 case 0x20: dscp_str = "cs4";  break;
429                 case 0x28: dscp_str = "cs5";  break;
430                 case 0x30: dscp_str = "cs6";  break;
431                 case 0x38: dscp_str = "cs7";  break;
432                 default:   dscp_str = NULL;
433         }
435         switch (ecn)
436         {
437                 case 0x01: ecn_str = ",ecn(1)"; break;
438                 case 0x02: ecn_str = ",ecn(0)"; break;
439                 case 0x03: ecn_str = ",ce"; break;
440                 default:   ecn_str = "";
441         }
443         if (dscp_str == NULL)
444                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
445         else
446                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
447         buffer[buffer_size - 1] = 0;
449         return (buffer);
450 } /* }}} char *format_qos */
452 static int read_options (int argc, char **argv) /* {{{ */
454         int optchar;
456         while (1)
457         {
458                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
460                 if (optchar == -1)
461                         break;
463                 switch (optchar)
464                 {
465                         case '4':
466                         case '6':
467                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
468                                 break;
470                         case 'c':
471                                 {
472                                         int new_count;
473                                         new_count = atoi (optarg);
474                                         if (new_count > 0)
475                                                 opt_count = new_count;
476                                         else
477                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
478                                                                 optarg);
479                                 }
480                                 break;
482                         case 'f':
483                                 {
484                                         if (opt_filename != NULL)
485                                                 free (opt_filename);
486                                         opt_filename = strdup (optarg);
487                                 }
488                                 break;
490                         case 'i':
491                                 {
492                                         double new_interval;
493                                         new_interval = atof (optarg);
494                                         if (new_interval < 0.001)
495                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
496                                                                 optarg);
497                                         else
498                                                 opt_interval = new_interval;
499                                 }
500                                 break;
501                         case 'I':
502                                 {
503                                         if (opt_srcaddr != NULL)
504                                                 free (opt_srcaddr);
505                                         opt_srcaddr = strdup (optarg);
506                                 }
507                                 break;
509                         case 'D':
510                                 opt_device = optarg;
511                                 break;
513                         case 't':
514                         {
515                                 int new_send_ttl;
516                                 new_send_ttl = atoi (optarg);
517                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
518                                         opt_send_ttl = new_send_ttl;
519                                 else
520                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
521                                                         optarg);
522                                 break;
523                         }
525                         case 'Q':
526                                 set_opt_send_qos (optarg);
527                                 break;
529                         case 'h':
530                                 usage_exit (argv[0], 0);
531                                 break;
532                         default:
533                                 usage_exit (argv[0], 1);
534                 }
535         }
537         return (optind);
538 } /* }}} read_options */
540 static void time_normalize (struct timespec *ts) /* {{{ */
542         while (ts->tv_nsec < 0)
543         {
544                 if (ts->tv_sec == 0)
545                 {
546                         ts->tv_nsec = 0;
547                         return;
548                 }
550                 ts->tv_sec  -= 1;
551                 ts->tv_nsec += 1000000000;
552         }
554         while (ts->tv_nsec >= 1000000000)
555         {
556                 ts->tv_sec  += 1;
557                 ts->tv_nsec -= 1000000000;
558         }
559 } /* }}} void time_normalize */
561 static void time_calc (struct timespec *ts_dest, /* {{{ */
562                 const struct timespec *ts_int,
563                 const struct timeval  *tv_begin,
564                 const struct timeval  *tv_end)
566         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
567         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
568         time_normalize (ts_dest);
570         /* Assure that `(begin + interval) > end'.
571          * This may seem overly complicated, but `tv_sec' is of type `time_t'
572          * which may be `unsigned. *sigh* */
573         if ((tv_end->tv_sec > ts_dest->tv_sec)
574                         || ((tv_end->tv_sec == ts_dest->tv_sec)
575                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
576         {
577                 ts_dest->tv_sec  = 0;
578                 ts_dest->tv_nsec = 0;
579                 return;
580         }
582         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
583         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
584         time_normalize (ts_dest);
585 } /* }}} void time_calc */
587 #if USE_NCURSES
588 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
590         if ((ctx == NULL) || (ctx->window == NULL))
591                 return (EINVAL);
593         werase (ctx->window);
595         box (ctx->window, 0, 0);
596         wattron (ctx->window, A_BOLD);
597         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
598                         " %s ", ctx->host);
599         wattroff (ctx->window, A_BOLD);
600         wprintw (ctx->window, "ping statistics ");
601         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
602                         "%i packets transmitted, %i received, %.2f%% packet "
603                         "loss, time %.1fms",
604                         ctx->req_sent, ctx->req_rcvd,
605                         context_get_packet_loss (ctx),
606                         ctx->latency_total);
607         if (ctx->req_rcvd != 0)
608         {
609                 double average;
610                 double deviation;
612                 average = context_get_average (ctx);
613                 deviation = context_get_stddev (ctx);
614                         
615                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
616                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
617                                 ctx->latency_min,
618                                 average,
619                                 ctx->latency_max,
620                                 deviation);
621         }
623         wrefresh (ctx->window);
625         return (0);
626 } /* }}} int update_stats_from_context */
628 static int on_resize (pingobj_t *ping) /* {{{ */
630         pingobj_iter_t *iter;
631         int width = 0;
632         int height = 0;
633         int main_win_height;
635         getmaxyx (stdscr, height, width);
636         if ((height < 1) || (width < 1))
637                 return (EINVAL);
639         main_win_height = height - (4 * host_num);
640         wresize (main_win, main_win_height, /* width = */ width);
641         /* Allow scrolling */
642         scrollok (main_win, TRUE);
643         /* wsetscrreg (main_win, 0, main_win_height - 1); */
644         /* Allow hardware accelerated scrolling. */
645         idlok (main_win, TRUE);
646         wrefresh (main_win);
648         for (iter = ping_iterator_get (ping);
649                         iter != NULL;
650                         iter = ping_iterator_next (iter))
651         {
652                 ping_context_t *context;
654                 context = ping_iterator_get_context (iter);
655                 if (context == NULL)
656                         continue;
658                 if (context->window != NULL)
659                 {
660                         delwin (context->window);
661                         context->window = NULL;
662                 }
663                 context->window = newwin (/* height = */ 4,
664                                 /* width = */ 0,
665                                 /* y = */ main_win_height + (4 * context->index),
666                                 /* x = */ 0);
667         }
669         return (0);
670 } /* }}} */
672 static int check_resize (pingobj_t *ping) /* {{{ */
674         int need_resize = 0;
676         while (42)
677         {
678                 int key = wgetch (stdscr);
679                 if (key == ERR)
680                         break;
681                 else if (key == KEY_RESIZE)
682                         need_resize = 1;
683         }
685         if (need_resize)
686                 return (on_resize (ping));
687         else
688                 return (0);
689 } /* }}} int check_resize */
691 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
693         pingobj_iter_t *iter;
694         int width = 0;
695         int height = 0;
696         int main_win_height;
698         initscr ();
699         cbreak ();
700         noecho ();
701         nodelay (stdscr, TRUE);
703         getmaxyx (stdscr, height, width);
704         if ((height < 1) || (width < 1))
705                 return (EINVAL);
707         if (has_colors () == TRUE)
708         {
709                 start_color ();
710                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
711                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
712                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
713         }
715         main_win_height = height - (4 * host_num);
716         main_win = newwin (/* height = */ main_win_height,
717                         /* width = */ 0,
718                         /* y = */ 0, /* x = */ 0);
719         /* Allow scrolling */
720         scrollok (main_win, TRUE);
721         /* wsetscrreg (main_win, 0, main_win_height - 1); */
722         /* Allow hardware accelerated scrolling. */
723         idlok (main_win, TRUE);
724         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
725         wrefresh (main_win);
727         for (iter = ping_iterator_get (ping);
728                         iter != NULL;
729                         iter = ping_iterator_next (iter))
730         {
731                 ping_context_t *context;
733                 context = ping_iterator_get_context (iter);
734                 if (context == NULL)
735                         continue;
737                 if (context->window != NULL)
738                 {
739                         delwin (context->window);
740                         context->window = NULL;
741                 }
742                 context->window = newwin (/* height = */ 4,
743                                 /* width = */ 0,
744                                 /* y = */ main_win_height + (4 * context->index),
745                                 /* x = */ 0);
746         }
749         /* Don't know what good this does exactly, but without this code
750          * "check_resize" will be called right after startup and *somehow*
751          * this leads to display errors. If we purge all initial characters
752          * here, the problem goes away. "wgetch" is non-blocking due to
753          * "nodelay" (see above). */
754         while (wgetch (stdscr) != ERR)
755         {
756                 /* eat up characters */;
757         }
759         return (0);
760 } /* }}} int pre_loop_hook */
762 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
764         return (check_resize (ping));
765 } /* }}} int pre_sleep_hook */
767 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
769         return (check_resize (ping));
770 } /* }}} int pre_sleep_hook */
771 #else /* if !USE_NCURSES */
772 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
774         pingobj_iter_t *iter;
776         for (iter = ping_iterator_get (ping);
777                         iter != NULL;
778                         iter = ping_iterator_next (iter))
779         {
780                 ping_context_t *ctx;
781                 size_t buffer_size;
783                 ctx = ping_iterator_get_context (iter);
784                 if (ctx == NULL)
785                         continue;
787                 buffer_size = 0;
788                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
790                 printf ("PING %s (%s) %zu bytes of data.\n",
791                                 ctx->host, ctx->addr, buffer_size);
792         }
794         return (0);
795 } /* }}} int pre_loop_hook */
797 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
799         fflush (stdout);
801         return (0);
802 } /* }}} int pre_sleep_hook */
804 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
806         return (0);
807 } /* }}} int post_sleep_hook */
808 #endif
810 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
811                 int index)
813         double          latency;
814         unsigned int    sequence;
815         int             recv_ttl;
816         uint8_t         recv_qos;
817         char            recv_qos_str[16];
818         size_t          buffer_len;
819         size_t          data_len;
820         ping_context_t *context;
822         latency = -1.0;
823         buffer_len = sizeof (latency);
824         ping_iterator_get_info (iter, PING_INFO_LATENCY,
825                         &latency, &buffer_len);
827         sequence = 0;
828         buffer_len = sizeof (sequence);
829         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
830                         &sequence, &buffer_len);
832         recv_ttl = -1;
833         buffer_len = sizeof (recv_ttl);
834         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
835                         &recv_ttl, &buffer_len);
837         recv_qos = 0;
838         buffer_len = sizeof (recv_qos);
839         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
840                         &recv_qos, &buffer_len);
842         data_len = 0;
843         ping_iterator_get_info (iter, PING_INFO_DATA,
844                         NULL, &data_len);
846         context = (ping_context_t *) ping_iterator_get_context (iter);
848 #if USE_NCURSES
849 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
850 #else
851 # define HOST_PRINTF(...) printf(__VA_ARGS__)
852 #endif
854         context->req_sent++;
855         if (latency > 0.0)
856         {
857                 context->req_rcvd++;
858                 context->latency_total += latency;
859                 context->latency_total_square += (latency * latency);
861                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
862                         context->latency_max = latency;
863                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
864                         context->latency_min = latency;
866 #if USE_NCURSES
867                 if (has_colors () == TRUE)
868                 {
869                         int color = OPING_GREEN;
870                         double average = context_get_average (context);
871                         double stddev = context_get_stddev (context);
873                         if ((latency < (average - (2 * stddev)))
874                                         || (latency > (average + (2 * stddev))))
875                                 color = OPING_RED;
876                         else if ((latency < (average - stddev))
877                                         || (latency > (average + stddev)))
878                                 color = OPING_YELLOW;
880                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
881                                         data_len, context->host, context->addr,
882                                         sequence, recv_ttl,
883                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
884                         if ((recv_qos != 0) || (opt_send_qos != 0))
885                         {
886                                 HOST_PRINTF ("qos=%s ",
887                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
888                         }
889                         HOST_PRINTF ("time=");
890                         wattron (main_win, COLOR_PAIR(color));
891                         HOST_PRINTF ("%.2f", latency);
892                         wattroff (main_win, COLOR_PAIR(color));
893                         HOST_PRINTF (" ms\n");
894                 }
895                 else
896                 {
897 #endif
898                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
899                                 data_len,
900                                 context->host, context->addr,
901                                 sequence, recv_ttl);
902                 if ((recv_qos != 0) || (opt_send_qos != 0))
903                 {
904                         HOST_PRINTF ("qos=%s ",
905                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
906                 }
907                 HOST_PRINTF ("time=%.2f ms\n", latency);
908 #if USE_NCURSES
909                 }
910 #endif
911         }
912         else
913         {
914 #if USE_NCURSES
915                 if (has_colors () == TRUE)
916                 {
917                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
918                                         context->host, context->addr,
919                                         sequence);
920                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
921                         HOST_PRINTF ("timeout");
922                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
923                         HOST_PRINTF ("\n");
924                 }
925                 else
926                 {
927 #endif
928                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
929                                 context->host, context->addr,
930                                 sequence);
931 #if USE_NCURSES
932                 }
933 #endif
934         }
936 #if USE_NCURSES
937         update_stats_from_context (context);
938         wrefresh (main_win);
939 #endif
940 } /* }}} void update_host_hook */
942 static int post_loop_hook (pingobj_t *ping) /* {{{ */
944         pingobj_iter_t *iter;
946 #if USE_NCURSES
947         endwin ();
948 #endif
950         for (iter = ping_iterator_get (ping);
951                         iter != NULL;
952                         iter = ping_iterator_next (iter))
953         {
954                 ping_context_t *context;
956                 context = ping_iterator_get_context (iter);
958                 printf ("\n--- %s ping statistics ---\n"
959                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
960                                 context->host, context->req_sent, context->req_rcvd,
961                                 context_get_packet_loss (context),
962                                 context->latency_total);
964                 if (context->req_rcvd != 0)
965                 {
966                         double average;
967                         double deviation;
969                         average = context_get_average (context);
970                         deviation = context_get_stddev (context);
972                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
973                                         context->latency_min,
974                                         average,
975                                         context->latency_max,
976                                         deviation);
977                 }
979                 ping_iterator_set_context (iter, NULL);
980                 context_destroy (context);
981         }
983         return (0);
984 } /* }}} int post_loop_hook */
986 int main (int argc, char **argv) /* {{{ */
988         pingobj_t      *ping;
989         pingobj_iter_t *iter;
991         struct sigaction sigint_action;
993         struct timeval  tv_begin;
994         struct timeval  tv_end;
995         struct timespec ts_wait;
996         struct timespec ts_int;
998         int optind;
999         int i;
1000         int status;
1001 #if _POSIX_SAVED_IDS
1002         uid_t saved_set_uid;
1004         /* Save the old effective user id */
1005         saved_set_uid = geteuid ();
1006         /* Set the effective user ID to the real user ID without changing the
1007          * saved set-user ID */
1008         status = seteuid (getuid ());
1009         if (status != 0)
1010         {
1011                 fprintf (stderr, "Temporarily dropping privileges "
1012                                 "failed: %s\n", strerror (errno));
1013                 exit (EXIT_FAILURE);
1014         }
1015 #endif
1017         optind = read_options (argc, argv);
1019 #if !_POSIX_SAVED_IDS
1020         /* Cannot temporarily drop privileges -> reject every file but "-". */
1021         if ((opt_filename != NULL)
1022                         && (strcmp ("-", opt_filename) != 0)
1023                         && (getuid () != geteuid ()))
1024         {
1025                 fprintf (stderr, "Your real and effective user IDs don't "
1026                                 "match. Reading from a file (option '-f')\n"
1027                                 "is therefore too risky. You can still read "
1028                                 "from STDIN using '-f -' if you like.\n"
1029                                 "Sorry.\n");
1030                 exit (EXIT_FAILURE);
1031         }
1032 #endif
1034         if ((optind >= argc) && (opt_filename == NULL)) {
1035                 usage_exit (argv[0], 1);
1036         }
1038         if ((ping = ping_construct ()) == NULL)
1039         {
1040                 fprintf (stderr, "ping_construct failed\n");
1041                 return (1);
1042         }
1044         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1045         {
1046                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1047                                 opt_send_ttl, ping_get_error (ping));
1048         }
1050         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1051         {
1052                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1053                                 opt_send_qos, ping_get_error (ping));
1054         }
1056         {
1057                 double temp_sec;
1058                 double temp_nsec;
1060                 temp_nsec = modf (opt_interval, &temp_sec);
1061                 ts_int.tv_sec  = (time_t) temp_sec;
1062                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1064                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1065         }
1067         if (opt_addrfamily != PING_DEF_AF)
1068                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1070         if (opt_srcaddr != NULL)
1071         {
1072                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1073                 {
1074                         fprintf (stderr, "Setting source address failed: %s\n",
1075                                         ping_get_error (ping));
1076                 }
1077         }
1079         if (opt_device != NULL)
1080         {
1081                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1082                 {
1083                         fprintf (stderr, "Setting device failed: %s\n",
1084                                         ping_get_error (ping));
1085                 }
1086         }
1088         if (opt_filename != NULL)
1089         {
1090                 FILE *infile;
1091                 char line[256];
1092                 char host[256];
1094                 if (strcmp (opt_filename, "-") == 0)
1095                         /* Open STDIN */
1096                         infile = fdopen(0, "r");
1097                 else
1098                         infile = fopen(opt_filename, "r");
1100                 if (infile == NULL)
1101                 {
1102                         fprintf (stderr, "Opening %s failed: %s\n",
1103                                         (strcmp (opt_filename, "-") == 0)
1104                                         ? "STDIN" : opt_filename,
1105                                         strerror(errno));
1106                         return (1);
1107                 }
1109 #if _POSIX_SAVED_IDS
1110                 /* Regain privileges */
1111                 status = seteuid (saved_set_uid);
1112                 if (status != 0)
1113                 {
1114                         fprintf (stderr, "Temporarily re-gaining privileges "
1115                                         "failed: %s\n", strerror (errno));
1116                         exit (EXIT_FAILURE);
1117                 }
1118 #endif
1120                 while (fgets(line, sizeof(line), infile))
1121                 {
1122                         /* Strip whitespace */
1123                         if (sscanf(line, "%s", host) != 1)
1124                                 continue;
1126                         if ((host[0] == 0) || (host[0] == '#'))
1127                                 continue;
1129                         if (ping_host_add(ping, host) < 0)
1130                         {
1131                                 const char *errmsg = ping_get_error (ping);
1133                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1134                                 continue;
1135                         }
1136                         else
1137                         {
1138                                 host_num++;
1139                         }
1140                 }
1142 #if _POSIX_SAVED_IDS
1143                 /* Drop privileges */
1144                 status = seteuid (getuid ());
1145                 if (status != 0)
1146                 {
1147                         fprintf (stderr, "Temporarily dropping privileges "
1148                                         "failed: %s\n", strerror (errno));
1149                         exit (EXIT_FAILURE);
1150                 }
1151 #endif
1153                 fclose(infile);
1154         }
1156 #if _POSIX_SAVED_IDS
1157         /* Regain privileges */
1158         status = seteuid (saved_set_uid);
1159         if (status != 0)
1160         {
1161                 fprintf (stderr, "Temporarily re-gaining privileges "
1162                                 "failed: %s\n", strerror (errno));
1163                 exit (EXIT_FAILURE);
1164         }
1165 #endif
1167         for (i = optind; i < argc; i++)
1168         {
1169                 if (ping_host_add (ping, argv[i]) < 0)
1170                 {
1171                         const char *errmsg = ping_get_error (ping);
1173                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1174                         continue;
1175                 }
1176                 else
1177                 {
1178                         host_num++;
1179                 }
1180         }
1182         /* Permanently drop root privileges if we're setuid-root. */
1183         status = setuid (getuid ());
1184         if (status != 0)
1185         {
1186                 fprintf (stderr, "Dropping privileges failed: %s\n",
1187                                 strerror (errno));
1188                 exit (EXIT_FAILURE);
1189         }
1191 #if _POSIX_SAVED_IDS
1192         saved_set_uid = (uid_t) -1;
1193 #endif
1195         ping_initialize_contexts (ping);
1197         if (i == 0)
1198                 return (1);
1200         memset (&sigint_action, '\0', sizeof (sigint_action));
1201         sigint_action.sa_handler = sigint_handler;
1202         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1203         {
1204                 perror ("sigaction");
1205                 return (1);
1206         }
1208         pre_loop_hook (ping);
1210         while (opt_count != 0)
1211         {
1212                 int index;
1213                 int status;
1215                 if (gettimeofday (&tv_begin, NULL) < 0)
1216                 {
1217                         perror ("gettimeofday");
1218                         return (1);
1219                 }
1221                 if (ping_send (ping) < 0)
1222                 {
1223                         fprintf (stderr, "ping_send failed: %s\n",
1224                                         ping_get_error (ping));
1225                         return (1);
1226                 }
1228                 index = 0;
1229                 for (iter = ping_iterator_get (ping);
1230                                 iter != NULL;
1231                                 iter = ping_iterator_next (iter))
1232                 {
1233                         update_host_hook (iter, index);
1234                         index++;
1235                 }
1237                 pre_sleep_hook (ping);
1239                 /* Don't sleep in the last iteration */
1240                 if (opt_count == 1)
1241                         break;
1243                 if (gettimeofday (&tv_end, NULL) < 0)
1244                 {
1245                         perror ("gettimeofday");
1246                         return (1);
1247                 }
1249                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1251                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1252                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1253                 {
1254                         if (errno != EINTR)
1255                         {
1256                                 perror ("nanosleep");
1257                                 break;
1258                         }
1259                         else if (opt_count == 0)
1260                         {
1261                                 /* sigint */
1262                                 break;
1263                         }
1264                 }
1266                 post_sleep_hook (ping);
1268                 if (opt_count > 0)
1269                         opt_count--;
1270         } /* while (opt_count != 0) */
1272         post_loop_hook (ping);
1274         ping_destroy (ping);
1276         return (0);
1277 } /* }}} int main */
1279 /* vim: set fdm=marker : */