Code

oping: Improve parsing of the "-z" argument.
[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_tos   = 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                         "  -z tos       Type-of-service/class-of-service for each ICMP packet\n"
263                         "  -I srcaddr   source address\n"
264                         "  -D device    outgoing interface name\n"
265                         "  -f filename  filename to read hosts from\n"
267                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
268                         "by Florian octo Forster <octo@verplant.org>\n"
269                         "for contributions see `AUTHORS'\n",
270                         name);
271         exit (status);
272 } /* }}} void usage_exit */
274 static void usage_tos_exit (const char *arg, int status) /* {{{ */
276         if (arg != 0)
277                 fprintf (stderr, "Invalid ToS argument: \"%s\"\n\n", arg);
279         fprintf (stderr, "Valid ToS arguments (option \"-z\") are:\n"
280                         "\n"
281                         "    lowdelay     (%#04x)    minimize delays\n"
282                         "    throughput   (%#04x)    optimize throughput\n"
283                         "    reliability  (%#04x)    optimize reliability\n"
284                         "    mincost      (%#04x)    minimize cost\n"
285                         "    0x00 - 0xff            specify manually\n"
286                         "\n",
287                         (unsigned int) IPTOS_LOWDELAY,
288                         (unsigned int) IPTOS_THROUGHPUT,
289                         (unsigned int) IPTOS_RELIABILITY,
290                         (unsigned int) IPTOS_MINCOST);
292         exit (status);
293 } /* }}} void usage_tos_exit */
295 static int set_opt_send_tos (const char *opt) /* {{{ */
297         if (opt == NULL)
298                 return (EINVAL);
300         if (strcasecmp ("lowdelay", opt) == 0)
301                 opt_send_tos = IPTOS_LOWDELAY;
302         else if (strcasecmp ("throughput", opt) == 0)
303                 opt_send_tos = IPTOS_THROUGHPUT;
304         else if (strcasecmp ("reliability", opt) == 0)
305                 opt_send_tos = IPTOS_RELIABILITY;
306         else if (strcasecmp ("mincost", opt) == 0)
307                 opt_send_tos = IPTOS_MINCOST;
308         else if (strcasecmp ("help", opt) == 0)
309                 usage_tos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
310         else
311         {
312                 unsigned long value;
313                 char *endptr;
315                 errno = 0;
316                 endptr = NULL;
317                 value = strtoul (opt, &endptr, /* base = */ 0);
318                 if ((errno != 0) || (endptr == opt)
319                                 || (endptr == NULL) || (*endptr != 0)
320                                 || (value >= 0xff))
321                         usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
322                 
323                 opt_send_tos = (uint8_t) value;
324         }
326         return (0);
327 } /* }}} int set_opt_send_tos */
329 static int read_options (int argc, char **argv) /* {{{ */
331         int optchar;
333         while (1)
334         {
335                 optchar = getopt (argc, argv, "46c:hi:I:t:z:f:D:");
337                 if (optchar == -1)
338                         break;
340                 switch (optchar)
341                 {
342                         case '4':
343                         case '6':
344                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
345                                 break;
347                         case 'c':
348                                 {
349                                         int new_count;
350                                         new_count = atoi (optarg);
351                                         if (new_count > 0)
352                                                 opt_count = new_count;
353                                         else
354                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
355                                                                 optarg);
356                                 }
357                                 break;
359                         case 'f':
360                                 {
361                                         if (opt_filename != NULL)
362                                                 free (opt_filename);
363                                         opt_filename = strdup (optarg);
364                                 }
365                                 break;
367                         case 'i':
368                                 {
369                                         double new_interval;
370                                         new_interval = atof (optarg);
371                                         if (new_interval < 0.001)
372                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
373                                                                 optarg);
374                                         else
375                                                 opt_interval = new_interval;
376                                 }
377                                 break;
378                         case 'I':
379                                 {
380                                         if (opt_srcaddr != NULL)
381                                                 free (opt_srcaddr);
382                                         opt_srcaddr = strdup (optarg);
383                                 }
384                                 break;
386                         case 'D':
387                                 opt_device = optarg;
388                                 break;
390                         case 't':
391                         {
392                                 int new_send_ttl;
393                                 new_send_ttl = atoi (optarg);
394                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
395                                         opt_send_ttl = new_send_ttl;
396                                 else
397                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
398                                                         optarg);
399                                 break;
400                         }
402                         case 'z':
403                                 set_opt_send_tos (optarg);
404                                 break;
406                         case 'h':
407                                 usage_exit (argv[0], 0);
408                                 break;
409                         default:
410                                 usage_exit (argv[0], 1);
411                 }
412         }
414         return (optind);
415 } /* }}} read_options */
417 static void time_normalize (struct timespec *ts) /* {{{ */
419         while (ts->tv_nsec < 0)
420         {
421                 if (ts->tv_sec == 0)
422                 {
423                         ts->tv_nsec = 0;
424                         return;
425                 }
427                 ts->tv_sec  -= 1;
428                 ts->tv_nsec += 1000000000;
429         }
431         while (ts->tv_nsec >= 1000000000)
432         {
433                 ts->tv_sec  += 1;
434                 ts->tv_nsec -= 1000000000;
435         }
436 } /* }}} void time_normalize */
438 static void time_calc (struct timespec *ts_dest, /* {{{ */
439                 const struct timespec *ts_int,
440                 const struct timeval  *tv_begin,
441                 const struct timeval  *tv_end)
443         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
444         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
445         time_normalize (ts_dest);
447         /* Assure that `(begin + interval) > end'.
448          * This may seem overly complicated, but `tv_sec' is of type `time_t'
449          * which may be `unsigned. *sigh* */
450         if ((tv_end->tv_sec > ts_dest->tv_sec)
451                         || ((tv_end->tv_sec == ts_dest->tv_sec)
452                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
453         {
454                 ts_dest->tv_sec  = 0;
455                 ts_dest->tv_nsec = 0;
456                 return;
457         }
459         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
460         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
461         time_normalize (ts_dest);
462 } /* }}} void time_calc */
464 #if USE_NCURSES
465 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
467         if ((ctx == NULL) || (ctx->window == NULL))
468                 return (EINVAL);
470         werase (ctx->window);
472         box (ctx->window, 0, 0);
473         wattron (ctx->window, A_BOLD);
474         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
475                         " %s ", ctx->host);
476         wattroff (ctx->window, A_BOLD);
477         wprintw (ctx->window, "ping statistics ");
478         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
479                         "%i packets transmitted, %i received, %.2f%% packet "
480                         "loss, time %.1fms",
481                         ctx->req_sent, ctx->req_rcvd,
482                         context_get_packet_loss (ctx),
483                         ctx->latency_total);
484         if (ctx->req_rcvd != 0)
485         {
486                 double average;
487                 double deviation;
489                 average = context_get_average (ctx);
490                 deviation = context_get_stddev (ctx);
491                         
492                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
493                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
494                                 ctx->latency_min,
495                                 average,
496                                 ctx->latency_max,
497                                 deviation);
498         }
500         wrefresh (ctx->window);
502         return (0);
503 } /* }}} int update_stats_from_context */
505 static int on_resize (pingobj_t *ping) /* {{{ */
507         pingobj_iter_t *iter;
508         int width = 0;
509         int height = 0;
510         int main_win_height;
512         getmaxyx (stdscr, height, width);
513         if ((height < 1) || (width < 1))
514                 return (EINVAL);
516         main_win_height = height - (4 * host_num);
517         wresize (main_win, main_win_height, /* width = */ width);
518         /* Allow scrolling */
519         scrollok (main_win, TRUE);
520         /* wsetscrreg (main_win, 0, main_win_height - 1); */
521         /* Allow hardware accelerated scrolling. */
522         idlok (main_win, TRUE);
523         wrefresh (main_win);
525         for (iter = ping_iterator_get (ping);
526                         iter != NULL;
527                         iter = ping_iterator_next (iter))
528         {
529                 ping_context_t *context;
531                 context = ping_iterator_get_context (iter);
532                 if (context == NULL)
533                         continue;
535                 if (context->window != NULL)
536                 {
537                         delwin (context->window);
538                         context->window = NULL;
539                 }
540                 context->window = newwin (/* height = */ 4,
541                                 /* width = */ 0,
542                                 /* y = */ main_win_height + (4 * context->index),
543                                 /* x = */ 0);
544         }
546         return (0);
547 } /* }}} */
549 static int check_resize (pingobj_t *ping) /* {{{ */
551         int need_resize = 0;
553         while (42)
554         {
555                 int key = wgetch (stdscr);
556                 if (key == ERR)
557                         break;
558                 else if (key == KEY_RESIZE)
559                         need_resize = 1;
560         }
562         if (need_resize)
563                 return (on_resize (ping));
564         else
565                 return (0);
566 } /* }}} int check_resize */
568 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
570         pingobj_iter_t *iter;
571         int width = 0;
572         int height = 0;
573         int main_win_height;
575         initscr ();
576         cbreak ();
577         noecho ();
578         nodelay (stdscr, TRUE);
580         getmaxyx (stdscr, height, width);
581         if ((height < 1) || (width < 1))
582                 return (EINVAL);
584         if (has_colors () == TRUE)
585         {
586                 start_color ();
587                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
588                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
589                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
590         }
592         main_win_height = height - (4 * host_num);
593         main_win = newwin (/* height = */ main_win_height,
594                         /* width = */ 0,
595                         /* y = */ 0, /* x = */ 0);
596         /* Allow scrolling */
597         scrollok (main_win, TRUE);
598         /* wsetscrreg (main_win, 0, main_win_height - 1); */
599         /* Allow hardware accelerated scrolling. */
600         idlok (main_win, TRUE);
601         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
602         wrefresh (main_win);
604         for (iter = ping_iterator_get (ping);
605                         iter != NULL;
606                         iter = ping_iterator_next (iter))
607         {
608                 ping_context_t *context;
610                 context = ping_iterator_get_context (iter);
611                 if (context == NULL)
612                         continue;
614                 if (context->window != NULL)
615                 {
616                         delwin (context->window);
617                         context->window = NULL;
618                 }
619                 context->window = newwin (/* height = */ 4,
620                                 /* width = */ 0,
621                                 /* y = */ main_win_height + (4 * context->index),
622                                 /* x = */ 0);
623         }
626         /* Don't know what good this does exactly, but without this code
627          * "check_resize" will be called right after startup and *somehow*
628          * this leads to display errors. If we purge all initial characters
629          * here, the problem goes away. "wgetch" is non-blocking due to
630          * "nodelay" (see above). */
631         while (wgetch (stdscr) != ERR)
632         {
633                 /* eat up characters */;
634         }
636         return (0);
637 } /* }}} int pre_loop_hook */
639 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
641         return (check_resize (ping));
642 } /* }}} int pre_sleep_hook */
644 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
646         return (check_resize (ping));
647 } /* }}} int pre_sleep_hook */
648 #else /* if !USE_NCURSES */
649 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
651         pingobj_iter_t *iter;
653         for (iter = ping_iterator_get (ping);
654                         iter != NULL;
655                         iter = ping_iterator_next (iter))
656         {
657                 ping_context_t *ctx;
658                 size_t buffer_size;
660                 ctx = ping_iterator_get_context (iter);
661                 if (ctx == NULL)
662                         continue;
664                 buffer_size = 0;
665                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
667                 printf ("PING %s (%s) %zu bytes of data.\n",
668                                 ctx->host, ctx->addr, buffer_size);
669         }
671         return (0);
672 } /* }}} int pre_loop_hook */
674 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
676         fflush (stdout);
678         return (0);
679 } /* }}} int pre_sleep_hook */
681 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
683         return (0);
684 } /* }}} int post_sleep_hook */
685 #endif
687 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
688                 int index)
690         double          latency;
691         unsigned int    sequence;
692         int             recv_ttl;
693         uint8_t         recv_tos;
694         size_t          buffer_len;
695         size_t          data_len;
696         ping_context_t *context;
698         latency = -1.0;
699         buffer_len = sizeof (latency);
700         ping_iterator_get_info (iter, PING_INFO_LATENCY,
701                         &latency, &buffer_len);
703         sequence = 0;
704         buffer_len = sizeof (sequence);
705         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
706                         &sequence, &buffer_len);
708         recv_ttl = -1;
709         buffer_len = sizeof (recv_ttl);
710         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
711                         &recv_ttl, &buffer_len);
713         recv_tos = 0;
714         buffer_len = sizeof (recv_tos);
715         ping_iterator_get_info (iter, PING_INFO_RECV_TOS,
716                         &recv_tos, &buffer_len);
718         data_len = 0;
719         ping_iterator_get_info (iter, PING_INFO_DATA,
720                         NULL, &data_len);
722         context = (ping_context_t *) ping_iterator_get_context (iter);
724 #if USE_NCURSES
725 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
726 #else
727 # define HOST_PRINTF(...) printf(__VA_ARGS__)
728 #endif
730         context->req_sent++;
731         if (latency > 0.0)
732         {
733                 context->req_rcvd++;
734                 context->latency_total += latency;
735                 context->latency_total_square += (latency * latency);
737                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
738                         context->latency_max = latency;
739                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
740                         context->latency_min = latency;
742 #if USE_NCURSES
743                 if (has_colors () == TRUE)
744                 {
745                         int color = OPING_GREEN;
746                         double average = context_get_average (context);
747                         double stddev = context_get_stddev (context);
749                         if ((latency < (average - (2 * stddev)))
750                                         || (latency > (average + (2 * stddev))))
751                                 color = OPING_RED;
752                         else if ((latency < (average - stddev))
753                                         || (latency > (average + stddev)))
754                                 color = OPING_YELLOW;
756                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=0x%02"PRIx8
757                                         " time=",
758                                         data_len, context->host, context->addr,
759                                         sequence, recv_ttl, recv_tos);
760                         wattron (main_win, COLOR_PAIR(color));
761                         HOST_PRINTF ("%.2f", latency);
762                         wattroff (main_win, COLOR_PAIR(color));
763                         HOST_PRINTF (" ms\n");
764                 }
765                 else
766                 {
767 #endif
768                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=0x%02"PRIx8
769                                 " time=%.2f ms\n",
770                                 data_len,
771                                 context->host, context->addr,
772                                 sequence, recv_ttl, recv_tos, latency);
773 #if USE_NCURSES
774                 }
775 #endif
776         }
777         else
778         {
779 #if USE_NCURSES
780                 if (has_colors () == TRUE)
781                 {
782                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
783                                         context->host, context->addr,
784                                         sequence);
785                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
786                         HOST_PRINTF ("timeout");
787                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
788                         HOST_PRINTF ("\n");
789                 }
790                 else
791                 {
792 #endif
793                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
794                                 context->host, context->addr,
795                                 sequence);
796 #if USE_NCURSES
797                 }
798 #endif
799         }
801 #if USE_NCURSES
802         update_stats_from_context (context);
803         wrefresh (main_win);
804 #endif
805 } /* }}} void update_host_hook */
807 static int post_loop_hook (pingobj_t *ping) /* {{{ */
809         pingobj_iter_t *iter;
811 #if USE_NCURSES
812         endwin ();
813 #endif
815         for (iter = ping_iterator_get (ping);
816                         iter != NULL;
817                         iter = ping_iterator_next (iter))
818         {
819                 ping_context_t *context;
821                 context = ping_iterator_get_context (iter);
823                 printf ("\n--- %s ping statistics ---\n"
824                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
825                                 context->host, context->req_sent, context->req_rcvd,
826                                 context_get_packet_loss (context),
827                                 context->latency_total);
829                 if (context->req_rcvd != 0)
830                 {
831                         double average;
832                         double deviation;
834                         average = context_get_average (context);
835                         deviation = context_get_stddev (context);
837                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
838                                         context->latency_min,
839                                         average,
840                                         context->latency_max,
841                                         deviation);
842                 }
844                 ping_iterator_set_context (iter, NULL);
845                 context_destroy (context);
846         }
848         return (0);
849 } /* }}} int post_loop_hook */
851 int main (int argc, char **argv) /* {{{ */
853         pingobj_t      *ping;
854         pingobj_iter_t *iter;
856         struct sigaction sigint_action;
858         struct timeval  tv_begin;
859         struct timeval  tv_end;
860         struct timespec ts_wait;
861         struct timespec ts_int;
863         int optind;
864         int i;
865         int status;
866 #if _POSIX_SAVED_IDS
867         uid_t saved_set_uid;
869         /* Save the old effective user id */
870         saved_set_uid = geteuid ();
871         /* Set the effective user ID to the real user ID without changing the
872          * saved set-user ID */
873         status = seteuid (getuid ());
874         if (status != 0)
875         {
876                 fprintf (stderr, "Temporarily dropping privileges "
877                                 "failed: %s\n", strerror (errno));
878                 exit (EXIT_FAILURE);
879         }
880 #endif
882         optind = read_options (argc, argv);
884 #if !_POSIX_SAVED_IDS
885         /* Cannot temporarily drop privileges -> reject every file but "-". */
886         if ((opt_filename != NULL)
887                         && (strcmp ("-", opt_filename) != 0)
888                         && (getuid () != geteuid ()))
889         {
890                 fprintf (stderr, "Your real and effective user IDs don't "
891                                 "match. Reading from a file (option '-f')\n"
892                                 "is therefore too risky. You can still read "
893                                 "from STDIN using '-f -' if you like.\n"
894                                 "Sorry.\n");
895                 exit (EXIT_FAILURE);
896         }
897 #endif
899         if ((optind >= argc) && (opt_filename == NULL)) {
900                 usage_exit (argv[0], 1);
901         }
903         if ((ping = ping_construct ()) == NULL)
904         {
905                 fprintf (stderr, "ping_construct failed\n");
906                 return (1);
907         }
909         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
910         {
911                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
912                                 opt_send_ttl, ping_get_error (ping));
913         }
915         if (ping_setopt (ping, PING_OPT_TOS, &opt_send_tos) != 0)
916         {
917                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
918                                 opt_send_tos, ping_get_error (ping));
919         }
921         {
922                 double temp_sec;
923                 double temp_nsec;
925                 temp_nsec = modf (opt_interval, &temp_sec);
926                 ts_int.tv_sec  = (time_t) temp_sec;
927                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
929                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
930         }
932         if (opt_addrfamily != PING_DEF_AF)
933                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
935         if (opt_srcaddr != NULL)
936         {
937                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
938                 {
939                         fprintf (stderr, "Setting source address failed: %s\n",
940                                         ping_get_error (ping));
941                 }
942         }
944         if (opt_device != NULL)
945         {
946                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
947                 {
948                         fprintf (stderr, "Setting device failed: %s\n",
949                                         ping_get_error (ping));
950                 }
951         }
953         if (opt_filename != NULL)
954         {
955                 FILE *infile;
956                 char line[256];
957                 char host[256];
959                 if (strcmp (opt_filename, "-") == 0)
960                         /* Open STDIN */
961                         infile = fdopen(0, "r");
962                 else
963                         infile = fopen(opt_filename, "r");
965                 if (infile == NULL)
966                 {
967                         fprintf (stderr, "Opening %s failed: %s\n",
968                                         (strcmp (opt_filename, "-") == 0)
969                                         ? "STDIN" : opt_filename,
970                                         strerror(errno));
971                         return (1);
972                 }
974 #if _POSIX_SAVED_IDS
975                 /* Regain privileges */
976                 status = seteuid (saved_set_uid);
977                 if (status != 0)
978                 {
979                         fprintf (stderr, "Temporarily re-gaining privileges "
980                                         "failed: %s\n", strerror (errno));
981                         exit (EXIT_FAILURE);
982                 }
983 #endif
985                 while (fgets(line, sizeof(line), infile))
986                 {
987                         /* Strip whitespace */
988                         if (sscanf(line, "%s", host) != 1)
989                                 continue;
991                         if ((host[0] == 0) || (host[0] == '#'))
992                                 continue;
994                         if (ping_host_add(ping, host) < 0)
995                         {
996                                 const char *errmsg = ping_get_error (ping);
998                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
999                                 continue;
1000                         }
1001                         else
1002                         {
1003                                 host_num++;
1004                         }
1005                 }
1007 #if _POSIX_SAVED_IDS
1008                 /* Drop privileges */
1009                 status = seteuid (getuid ());
1010                 if (status != 0)
1011                 {
1012                         fprintf (stderr, "Temporarily dropping privileges "
1013                                         "failed: %s\n", strerror (errno));
1014                         exit (EXIT_FAILURE);
1015                 }
1016 #endif
1018                 fclose(infile);
1019         }
1021 #if _POSIX_SAVED_IDS
1022         /* Regain privileges */
1023         status = seteuid (saved_set_uid);
1024         if (status != 0)
1025         {
1026                 fprintf (stderr, "Temporarily re-gaining privileges "
1027                                 "failed: %s\n", strerror (errno));
1028                 exit (EXIT_FAILURE);
1029         }
1030 #endif
1032         for (i = optind; i < argc; i++)
1033         {
1034                 if (ping_host_add (ping, argv[i]) < 0)
1035                 {
1036                         const char *errmsg = ping_get_error (ping);
1038                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1039                         continue;
1040                 }
1041                 else
1042                 {
1043                         host_num++;
1044                 }
1045         }
1047         /* Permanently drop root privileges if we're setuid-root. */
1048         status = setuid (getuid ());
1049         if (status != 0)
1050         {
1051                 fprintf (stderr, "Dropping privileges failed: %s\n",
1052                                 strerror (errno));
1053                 exit (EXIT_FAILURE);
1054         }
1056 #if _POSIX_SAVED_IDS
1057         saved_set_uid = (uid_t) -1;
1058 #endif
1060         ping_initialize_contexts (ping);
1062         if (i == 0)
1063                 return (1);
1065         memset (&sigint_action, '\0', sizeof (sigint_action));
1066         sigint_action.sa_handler = sigint_handler;
1067         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1068         {
1069                 perror ("sigaction");
1070                 return (1);
1071         }
1073         pre_loop_hook (ping);
1075         while (opt_count != 0)
1076         {
1077                 int index;
1078                 int status;
1080                 if (gettimeofday (&tv_begin, NULL) < 0)
1081                 {
1082                         perror ("gettimeofday");
1083                         return (1);
1084                 }
1086                 if (ping_send (ping) < 0)
1087                 {
1088                         fprintf (stderr, "ping_send failed: %s\n",
1089                                         ping_get_error (ping));
1090                         return (1);
1091                 }
1093                 index = 0;
1094                 for (iter = ping_iterator_get (ping);
1095                                 iter != NULL;
1096                                 iter = ping_iterator_next (iter))
1097                 {
1098                         update_host_hook (iter, index);
1099                         index++;
1100                 }
1102                 pre_sleep_hook (ping);
1104                 /* Don't sleep in the last iteration */
1105                 if (opt_count == 1)
1106                         break;
1108                 if (gettimeofday (&tv_end, NULL) < 0)
1109                 {
1110                         perror ("gettimeofday");
1111                         return (1);
1112                 }
1114                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1116                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1117                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1118                 {
1119                         if (errno != EINTR)
1120                         {
1121                                 perror ("nanosleep");
1122                                 break;
1123                         }
1124                         else if (opt_count == 0)
1125                         {
1126                                 /* sigint */
1127                                 break;
1128                         }
1129                 }
1131                 post_sleep_hook (ping);
1133                 if (opt_count > 0)
1134                         opt_count--;
1135         } /* while (opt_count != 0) */
1137         post_loop_hook (ping);
1139         ping_destroy (ping);
1141         return (0);
1142 } /* }}} int main */
1144 /* vim: set fdm=marker : */