Code

src/oping.c: Add the "be" and "cs[0-7]" DSCPs.
[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         int name_length;
252         name_length = (int) strlen (name);
254         fprintf (stderr, "Usage: %s [OPTIONS] "
255                                 "-f filename | host [host [host ...]]\n"
257                         "\nAvailable options:\n"
258                         "  -4|-6        force the use of IPv4 or IPv6\n"
259                         "  -c count     number of ICMP packets to send\n"
260                         "  -i interval  interval with which to send ICMP packets\n"
261                         "  -t ttl       time to live for each ICMP packet\n"
262                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
263                         "               Use \"-Q help\" for a list of valid options.\n"
264                         "  -I srcaddr   source address\n"
265                         "  -D device    outgoing interface name\n"
266                         "  -f filename  filename to read hosts from\n"
268                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
269                         "by Florian octo Forster <octo@verplant.org>\n"
270                         "for contributions see `AUTHORS'\n",
271                         name);
272         exit (status);
273 } /* }}} void usage_exit */
275 static void usage_tos_exit (const char *arg, int status) /* {{{ */
277         if (arg != 0)
278                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
280         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
281                         "\n"
282                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
283                         "\n"
284                         "    be                     Best Effort (BE, default PHB).\n"
285                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
286                         "                           (low delay, low loss, low jitter)\n"
287                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
288                         "                           For example: \"af12\" (class 1, precedence 2)\n"
289                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
290                         "                           For example: \"cs1\" (priority traffic)\n"
291                         "\n"
292                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
293                         "\n"
294                         "    lowdelay     (%#04x)    minimize delay\n"
295                         "    throughput   (%#04x)    maximize throughput\n"
296                         "    reliability  (%#04x)    maximize reliability\n"
297                         "    mincost      (%#04x)    minimize monetary cost\n"
298                         "\n"
299                         "  Specify manually\n"
300                         "\n"
301                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
302                         "       0 -  255            Decimal numeric specification.\n"
303                         "\n",
304                         (unsigned int) IPTOS_LOWDELAY,
305                         (unsigned int) IPTOS_THROUGHPUT,
306                         (unsigned int) IPTOS_RELIABILITY,
307                         (unsigned int) IPTOS_MINCOST);
309         exit (status);
310 } /* }}} void usage_tos_exit */
312 static int set_opt_send_qos (const char *opt) /* {{{ */
314         if (opt == NULL)
315                 return (EINVAL);
317         if (strcasecmp ("help", opt) == 0)
318                 usage_tos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
319         /* DiffServ (RFC 2474): */
320         /* - Best effort (BE) */
321         else if (strcasecmp ("be", opt) == 0)
322                 opt_send_qos = 0;
323         /* - Expedited Forwarding (EF, RFC 3246) */
324         else if (strcasecmp ("ef", opt) == 0)
325                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
326         /* - Assured Forwarding (AF, RFC 2597) */
327         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
328                         && (strlen (opt) == 4))
329         {
330                 uint8_t dscp;
331                 uint8_t class;
332                 uint8_t prec;
334                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
335                 if (opt[2] == '1')
336                         class = 1;
337                 else if (opt[2] == '2')
338                         class = 2;
339                 else if (opt[2] == '3')
340                         class = 3;
341                 else if (opt[2] == '4')
342                         class = 4;
343                 else
344                         usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
346                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
347                 if (opt[3] == '1')
348                         prec = 1;
349                 else if (opt[3] == '2')
350                         prec = 2;
351                 else if (opt[3] == '3')
352                         prec = 3;
353                 else
354                         usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
356                 dscp = (8 * class) + (2 * prec);
357                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
358                 opt_send_qos = dscp << 2;
359         }
360         /* - Class Selector (CS) */
361         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
362                         && (strlen (opt) == 3))
363         {
364                 uint8_t class;
366                 if ((opt[2] < '0') || (opt[2] > '7'))
367                         usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
369                 /* Not exactly legal by the C standard, but I don't know of any
370                  * system not supporting this hack. */
371                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
372                 opt_send_qos = class << 5;
373         }
374         /* Type of Service (RFC 1349) */
375         else if (strcasecmp ("lowdelay", opt) == 0)
376                 opt_send_qos = IPTOS_LOWDELAY;
377         else if (strcasecmp ("throughput", opt) == 0)
378                 opt_send_qos = IPTOS_THROUGHPUT;
379         else if (strcasecmp ("reliability", opt) == 0)
380                 opt_send_qos = IPTOS_RELIABILITY;
381         else if (strcasecmp ("mincost", opt) == 0)
382                 opt_send_qos = IPTOS_MINCOST;
383         /* Numeric value */
384         else
385         {
386                 unsigned long value;
387                 char *endptr;
389                 errno = 0;
390                 endptr = NULL;
391                 value = strtoul (opt, &endptr, /* base = */ 0);
392                 if ((errno != 0) || (endptr == opt)
393                                 || (endptr == NULL) || (*endptr != 0)
394                                 || (value > 0xff))
395                         usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
396                 
397                 opt_send_qos = (uint8_t) value;
398         }
400         return (0);
401 } /* }}} int set_opt_send_qos */
403 static int read_options (int argc, char **argv) /* {{{ */
405         int optchar;
407         while (1)
408         {
409                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
411                 if (optchar == -1)
412                         break;
414                 switch (optchar)
415                 {
416                         case '4':
417                         case '6':
418                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
419                                 break;
421                         case 'c':
422                                 {
423                                         int new_count;
424                                         new_count = atoi (optarg);
425                                         if (new_count > 0)
426                                                 opt_count = new_count;
427                                         else
428                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
429                                                                 optarg);
430                                 }
431                                 break;
433                         case 'f':
434                                 {
435                                         if (opt_filename != NULL)
436                                                 free (opt_filename);
437                                         opt_filename = strdup (optarg);
438                                 }
439                                 break;
441                         case 'i':
442                                 {
443                                         double new_interval;
444                                         new_interval = atof (optarg);
445                                         if (new_interval < 0.001)
446                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
447                                                                 optarg);
448                                         else
449                                                 opt_interval = new_interval;
450                                 }
451                                 break;
452                         case 'I':
453                                 {
454                                         if (opt_srcaddr != NULL)
455                                                 free (opt_srcaddr);
456                                         opt_srcaddr = strdup (optarg);
457                                 }
458                                 break;
460                         case 'D':
461                                 opt_device = optarg;
462                                 break;
464                         case 't':
465                         {
466                                 int new_send_ttl;
467                                 new_send_ttl = atoi (optarg);
468                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
469                                         opt_send_ttl = new_send_ttl;
470                                 else
471                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
472                                                         optarg);
473                                 break;
474                         }
476                         case 'Q':
477                                 set_opt_send_qos (optarg);
478                                 break;
480                         case 'h':
481                                 usage_exit (argv[0], 0);
482                                 break;
483                         default:
484                                 usage_exit (argv[0], 1);
485                 }
486         }
488         return (optind);
489 } /* }}} read_options */
491 static void time_normalize (struct timespec *ts) /* {{{ */
493         while (ts->tv_nsec < 0)
494         {
495                 if (ts->tv_sec == 0)
496                 {
497                         ts->tv_nsec = 0;
498                         return;
499                 }
501                 ts->tv_sec  -= 1;
502                 ts->tv_nsec += 1000000000;
503         }
505         while (ts->tv_nsec >= 1000000000)
506         {
507                 ts->tv_sec  += 1;
508                 ts->tv_nsec -= 1000000000;
509         }
510 } /* }}} void time_normalize */
512 static void time_calc (struct timespec *ts_dest, /* {{{ */
513                 const struct timespec *ts_int,
514                 const struct timeval  *tv_begin,
515                 const struct timeval  *tv_end)
517         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
518         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
519         time_normalize (ts_dest);
521         /* Assure that `(begin + interval) > end'.
522          * This may seem overly complicated, but `tv_sec' is of type `time_t'
523          * which may be `unsigned. *sigh* */
524         if ((tv_end->tv_sec > ts_dest->tv_sec)
525                         || ((tv_end->tv_sec == ts_dest->tv_sec)
526                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
527         {
528                 ts_dest->tv_sec  = 0;
529                 ts_dest->tv_nsec = 0;
530                 return;
531         }
533         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
534         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
535         time_normalize (ts_dest);
536 } /* }}} void time_calc */
538 #if USE_NCURSES
539 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
541         if ((ctx == NULL) || (ctx->window == NULL))
542                 return (EINVAL);
544         werase (ctx->window);
546         box (ctx->window, 0, 0);
547         wattron (ctx->window, A_BOLD);
548         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
549                         " %s ", ctx->host);
550         wattroff (ctx->window, A_BOLD);
551         wprintw (ctx->window, "ping statistics ");
552         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
553                         "%i packets transmitted, %i received, %.2f%% packet "
554                         "loss, time %.1fms",
555                         ctx->req_sent, ctx->req_rcvd,
556                         context_get_packet_loss (ctx),
557                         ctx->latency_total);
558         if (ctx->req_rcvd != 0)
559         {
560                 double average;
561                 double deviation;
563                 average = context_get_average (ctx);
564                 deviation = context_get_stddev (ctx);
565                         
566                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
567                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
568                                 ctx->latency_min,
569                                 average,
570                                 ctx->latency_max,
571                                 deviation);
572         }
574         wrefresh (ctx->window);
576         return (0);
577 } /* }}} int update_stats_from_context */
579 static int on_resize (pingobj_t *ping) /* {{{ */
581         pingobj_iter_t *iter;
582         int width = 0;
583         int height = 0;
584         int main_win_height;
586         getmaxyx (stdscr, height, width);
587         if ((height < 1) || (width < 1))
588                 return (EINVAL);
590         main_win_height = height - (4 * host_num);
591         wresize (main_win, main_win_height, /* width = */ width);
592         /* Allow scrolling */
593         scrollok (main_win, TRUE);
594         /* wsetscrreg (main_win, 0, main_win_height - 1); */
595         /* Allow hardware accelerated scrolling. */
596         idlok (main_win, TRUE);
597         wrefresh (main_win);
599         for (iter = ping_iterator_get (ping);
600                         iter != NULL;
601                         iter = ping_iterator_next (iter))
602         {
603                 ping_context_t *context;
605                 context = ping_iterator_get_context (iter);
606                 if (context == NULL)
607                         continue;
609                 if (context->window != NULL)
610                 {
611                         delwin (context->window);
612                         context->window = NULL;
613                 }
614                 context->window = newwin (/* height = */ 4,
615                                 /* width = */ 0,
616                                 /* y = */ main_win_height + (4 * context->index),
617                                 /* x = */ 0);
618         }
620         return (0);
621 } /* }}} */
623 static int check_resize (pingobj_t *ping) /* {{{ */
625         int need_resize = 0;
627         while (42)
628         {
629                 int key = wgetch (stdscr);
630                 if (key == ERR)
631                         break;
632                 else if (key == KEY_RESIZE)
633                         need_resize = 1;
634         }
636         if (need_resize)
637                 return (on_resize (ping));
638         else
639                 return (0);
640 } /* }}} int check_resize */
642 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
644         pingobj_iter_t *iter;
645         int width = 0;
646         int height = 0;
647         int main_win_height;
649         initscr ();
650         cbreak ();
651         noecho ();
652         nodelay (stdscr, TRUE);
654         getmaxyx (stdscr, height, width);
655         if ((height < 1) || (width < 1))
656                 return (EINVAL);
658         if (has_colors () == TRUE)
659         {
660                 start_color ();
661                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
662                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
663                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
664         }
666         main_win_height = height - (4 * host_num);
667         main_win = newwin (/* height = */ main_win_height,
668                         /* width = */ 0,
669                         /* y = */ 0, /* x = */ 0);
670         /* Allow scrolling */
671         scrollok (main_win, TRUE);
672         /* wsetscrreg (main_win, 0, main_win_height - 1); */
673         /* Allow hardware accelerated scrolling. */
674         idlok (main_win, TRUE);
675         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
676         wrefresh (main_win);
678         for (iter = ping_iterator_get (ping);
679                         iter != NULL;
680                         iter = ping_iterator_next (iter))
681         {
682                 ping_context_t *context;
684                 context = ping_iterator_get_context (iter);
685                 if (context == NULL)
686                         continue;
688                 if (context->window != NULL)
689                 {
690                         delwin (context->window);
691                         context->window = NULL;
692                 }
693                 context->window = newwin (/* height = */ 4,
694                                 /* width = */ 0,
695                                 /* y = */ main_win_height + (4 * context->index),
696                                 /* x = */ 0);
697         }
700         /* Don't know what good this does exactly, but without this code
701          * "check_resize" will be called right after startup and *somehow*
702          * this leads to display errors. If we purge all initial characters
703          * here, the problem goes away. "wgetch" is non-blocking due to
704          * "nodelay" (see above). */
705         while (wgetch (stdscr) != ERR)
706         {
707                 /* eat up characters */;
708         }
710         return (0);
711 } /* }}} int pre_loop_hook */
713 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
715         return (check_resize (ping));
716 } /* }}} int pre_sleep_hook */
718 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
720         return (check_resize (ping));
721 } /* }}} int pre_sleep_hook */
722 #else /* if !USE_NCURSES */
723 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
725         pingobj_iter_t *iter;
727         for (iter = ping_iterator_get (ping);
728                         iter != NULL;
729                         iter = ping_iterator_next (iter))
730         {
731                 ping_context_t *ctx;
732                 size_t buffer_size;
734                 ctx = ping_iterator_get_context (iter);
735                 if (ctx == NULL)
736                         continue;
738                 buffer_size = 0;
739                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
741                 printf ("PING %s (%s) %zu bytes of data.\n",
742                                 ctx->host, ctx->addr, buffer_size);
743         }
745         return (0);
746 } /* }}} int pre_loop_hook */
748 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
750         fflush (stdout);
752         return (0);
753 } /* }}} int pre_sleep_hook */
755 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
757         return (0);
758 } /* }}} int post_sleep_hook */
759 #endif
761 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
762                 int index)
764         double          latency;
765         unsigned int    sequence;
766         int             recv_ttl;
767         uint8_t         recv_tos;
768         size_t          buffer_len;
769         size_t          data_len;
770         ping_context_t *context;
772         latency = -1.0;
773         buffer_len = sizeof (latency);
774         ping_iterator_get_info (iter, PING_INFO_LATENCY,
775                         &latency, &buffer_len);
777         sequence = 0;
778         buffer_len = sizeof (sequence);
779         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
780                         &sequence, &buffer_len);
782         recv_ttl = -1;
783         buffer_len = sizeof (recv_ttl);
784         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
785                         &recv_ttl, &buffer_len);
787         recv_tos = 0;
788         buffer_len = sizeof (recv_tos);
789         ping_iterator_get_info (iter, PING_INFO_RECV_TOS,
790                         &recv_tos, &buffer_len);
792         data_len = 0;
793         ping_iterator_get_info (iter, PING_INFO_DATA,
794                         NULL, &data_len);
796         context = (ping_context_t *) ping_iterator_get_context (iter);
798 #if USE_NCURSES
799 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
800 #else
801 # define HOST_PRINTF(...) printf(__VA_ARGS__)
802 #endif
804         context->req_sent++;
805         if (latency > 0.0)
806         {
807                 context->req_rcvd++;
808                 context->latency_total += latency;
809                 context->latency_total_square += (latency * latency);
811                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
812                         context->latency_max = latency;
813                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
814                         context->latency_min = latency;
816 #if USE_NCURSES
817                 if (has_colors () == TRUE)
818                 {
819                         int color = OPING_GREEN;
820                         double average = context_get_average (context);
821                         double stddev = context_get_stddev (context);
823                         if ((latency < (average - (2 * stddev)))
824                                         || (latency > (average + (2 * stddev))))
825                                 color = OPING_RED;
826                         else if ((latency < (average - stddev))
827                                         || (latency > (average + stddev)))
828                                 color = OPING_YELLOW;
830                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=0x%02"PRIx8
831                                         " time=",
832                                         data_len, context->host, context->addr,
833                                         sequence, recv_ttl, recv_tos);
834                         wattron (main_win, COLOR_PAIR(color));
835                         HOST_PRINTF ("%.2f", latency);
836                         wattroff (main_win, COLOR_PAIR(color));
837                         HOST_PRINTF (" ms\n");
838                 }
839                 else
840                 {
841 #endif
842                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=0x%02"PRIx8
843                                 " time=%.2f ms\n",
844                                 data_len,
845                                 context->host, context->addr,
846                                 sequence, recv_ttl, recv_tos, latency);
847 #if USE_NCURSES
848                 }
849 #endif
850         }
851         else
852         {
853 #if USE_NCURSES
854                 if (has_colors () == TRUE)
855                 {
856                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
857                                         context->host, context->addr,
858                                         sequence);
859                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
860                         HOST_PRINTF ("timeout");
861                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
862                         HOST_PRINTF ("\n");
863                 }
864                 else
865                 {
866 #endif
867                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
868                                 context->host, context->addr,
869                                 sequence);
870 #if USE_NCURSES
871                 }
872 #endif
873         }
875 #if USE_NCURSES
876         update_stats_from_context (context);
877         wrefresh (main_win);
878 #endif
879 } /* }}} void update_host_hook */
881 static int post_loop_hook (pingobj_t *ping) /* {{{ */
883         pingobj_iter_t *iter;
885 #if USE_NCURSES
886         endwin ();
887 #endif
889         for (iter = ping_iterator_get (ping);
890                         iter != NULL;
891                         iter = ping_iterator_next (iter))
892         {
893                 ping_context_t *context;
895                 context = ping_iterator_get_context (iter);
897                 printf ("\n--- %s ping statistics ---\n"
898                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
899                                 context->host, context->req_sent, context->req_rcvd,
900                                 context_get_packet_loss (context),
901                                 context->latency_total);
903                 if (context->req_rcvd != 0)
904                 {
905                         double average;
906                         double deviation;
908                         average = context_get_average (context);
909                         deviation = context_get_stddev (context);
911                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
912                                         context->latency_min,
913                                         average,
914                                         context->latency_max,
915                                         deviation);
916                 }
918                 ping_iterator_set_context (iter, NULL);
919                 context_destroy (context);
920         }
922         return (0);
923 } /* }}} int post_loop_hook */
925 int main (int argc, char **argv) /* {{{ */
927         pingobj_t      *ping;
928         pingobj_iter_t *iter;
930         struct sigaction sigint_action;
932         struct timeval  tv_begin;
933         struct timeval  tv_end;
934         struct timespec ts_wait;
935         struct timespec ts_int;
937         int optind;
938         int i;
939         int status;
940 #if _POSIX_SAVED_IDS
941         uid_t saved_set_uid;
943         /* Save the old effective user id */
944         saved_set_uid = geteuid ();
945         /* Set the effective user ID to the real user ID without changing the
946          * saved set-user ID */
947         status = seteuid (getuid ());
948         if (status != 0)
949         {
950                 fprintf (stderr, "Temporarily dropping privileges "
951                                 "failed: %s\n", strerror (errno));
952                 exit (EXIT_FAILURE);
953         }
954 #endif
956         optind = read_options (argc, argv);
958 #if !_POSIX_SAVED_IDS
959         /* Cannot temporarily drop privileges -> reject every file but "-". */
960         if ((opt_filename != NULL)
961                         && (strcmp ("-", opt_filename) != 0)
962                         && (getuid () != geteuid ()))
963         {
964                 fprintf (stderr, "Your real and effective user IDs don't "
965                                 "match. Reading from a file (option '-f')\n"
966                                 "is therefore too risky. You can still read "
967                                 "from STDIN using '-f -' if you like.\n"
968                                 "Sorry.\n");
969                 exit (EXIT_FAILURE);
970         }
971 #endif
973         if ((optind >= argc) && (opt_filename == NULL)) {
974                 usage_exit (argv[0], 1);
975         }
977         if ((ping = ping_construct ()) == NULL)
978         {
979                 fprintf (stderr, "ping_construct failed\n");
980                 return (1);
981         }
983         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
984         {
985                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
986                                 opt_send_ttl, ping_get_error (ping));
987         }
989         if (ping_setopt (ping, PING_OPT_TOS, &opt_send_qos) != 0)
990         {
991                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
992                                 opt_send_qos, ping_get_error (ping));
993         }
995         {
996                 double temp_sec;
997                 double temp_nsec;
999                 temp_nsec = modf (opt_interval, &temp_sec);
1000                 ts_int.tv_sec  = (time_t) temp_sec;
1001                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1003                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1004         }
1006         if (opt_addrfamily != PING_DEF_AF)
1007                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1009         if (opt_srcaddr != NULL)
1010         {
1011                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1012                 {
1013                         fprintf (stderr, "Setting source address failed: %s\n",
1014                                         ping_get_error (ping));
1015                 }
1016         }
1018         if (opt_device != NULL)
1019         {
1020                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1021                 {
1022                         fprintf (stderr, "Setting device failed: %s\n",
1023                                         ping_get_error (ping));
1024                 }
1025         }
1027         if (opt_filename != NULL)
1028         {
1029                 FILE *infile;
1030                 char line[256];
1031                 char host[256];
1033                 if (strcmp (opt_filename, "-") == 0)
1034                         /* Open STDIN */
1035                         infile = fdopen(0, "r");
1036                 else
1037                         infile = fopen(opt_filename, "r");
1039                 if (infile == NULL)
1040                 {
1041                         fprintf (stderr, "Opening %s failed: %s\n",
1042                                         (strcmp (opt_filename, "-") == 0)
1043                                         ? "STDIN" : opt_filename,
1044                                         strerror(errno));
1045                         return (1);
1046                 }
1048 #if _POSIX_SAVED_IDS
1049                 /* Regain privileges */
1050                 status = seteuid (saved_set_uid);
1051                 if (status != 0)
1052                 {
1053                         fprintf (stderr, "Temporarily re-gaining privileges "
1054                                         "failed: %s\n", strerror (errno));
1055                         exit (EXIT_FAILURE);
1056                 }
1057 #endif
1059                 while (fgets(line, sizeof(line), infile))
1060                 {
1061                         /* Strip whitespace */
1062                         if (sscanf(line, "%s", host) != 1)
1063                                 continue;
1065                         if ((host[0] == 0) || (host[0] == '#'))
1066                                 continue;
1068                         if (ping_host_add(ping, host) < 0)
1069                         {
1070                                 const char *errmsg = ping_get_error (ping);
1072                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1073                                 continue;
1074                         }
1075                         else
1076                         {
1077                                 host_num++;
1078                         }
1079                 }
1081 #if _POSIX_SAVED_IDS
1082                 /* Drop privileges */
1083                 status = seteuid (getuid ());
1084                 if (status != 0)
1085                 {
1086                         fprintf (stderr, "Temporarily dropping privileges "
1087                                         "failed: %s\n", strerror (errno));
1088                         exit (EXIT_FAILURE);
1089                 }
1090 #endif
1092                 fclose(infile);
1093         }
1095 #if _POSIX_SAVED_IDS
1096         /* Regain privileges */
1097         status = seteuid (saved_set_uid);
1098         if (status != 0)
1099         {
1100                 fprintf (stderr, "Temporarily re-gaining privileges "
1101                                 "failed: %s\n", strerror (errno));
1102                 exit (EXIT_FAILURE);
1103         }
1104 #endif
1106         for (i = optind; i < argc; i++)
1107         {
1108                 if (ping_host_add (ping, argv[i]) < 0)
1109                 {
1110                         const char *errmsg = ping_get_error (ping);
1112                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1113                         continue;
1114                 }
1115                 else
1116                 {
1117                         host_num++;
1118                 }
1119         }
1121         /* Permanently drop root privileges if we're setuid-root. */
1122         status = setuid (getuid ());
1123         if (status != 0)
1124         {
1125                 fprintf (stderr, "Dropping privileges failed: %s\n",
1126                                 strerror (errno));
1127                 exit (EXIT_FAILURE);
1128         }
1130 #if _POSIX_SAVED_IDS
1131         saved_set_uid = (uid_t) -1;
1132 #endif
1134         ping_initialize_contexts (ping);
1136         if (i == 0)
1137                 return (1);
1139         memset (&sigint_action, '\0', sizeof (sigint_action));
1140         sigint_action.sa_handler = sigint_handler;
1141         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1142         {
1143                 perror ("sigaction");
1144                 return (1);
1145         }
1147         pre_loop_hook (ping);
1149         while (opt_count != 0)
1150         {
1151                 int index;
1152                 int status;
1154                 if (gettimeofday (&tv_begin, NULL) < 0)
1155                 {
1156                         perror ("gettimeofday");
1157                         return (1);
1158                 }
1160                 if (ping_send (ping) < 0)
1161                 {
1162                         fprintf (stderr, "ping_send failed: %s\n",
1163                                         ping_get_error (ping));
1164                         return (1);
1165                 }
1167                 index = 0;
1168                 for (iter = ping_iterator_get (ping);
1169                                 iter != NULL;
1170                                 iter = ping_iterator_next (iter))
1171                 {
1172                         update_host_hook (iter, index);
1173                         index++;
1174                 }
1176                 pre_sleep_hook (ping);
1178                 /* Don't sleep in the last iteration */
1179                 if (opt_count == 1)
1180                         break;
1182                 if (gettimeofday (&tv_end, NULL) < 0)
1183                 {
1184                         perror ("gettimeofday");
1185                         return (1);
1186                 }
1188                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1190                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1191                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1192                 {
1193                         if (errno != EINTR)
1194                         {
1195                                 perror ("nanosleep");
1196                                 break;
1197                         }
1198                         else if (opt_count == 0)
1199                         {
1200                                 /* sigint */
1201                                 break;
1202                         }
1203                 }
1205                 post_sleep_hook (ping);
1207                 if (opt_count > 0)
1208                         opt_count--;
1209         } /* while (opt_count != 0) */
1211         post_loop_hook (ping);
1213         ping_destroy (ping);
1215         return (0);
1216 } /* }}} int main */
1218 /* vim: set fdm=marker : */