Code

Implement support for QoS / ToS fields.
[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 <errno.h>
29 # include <assert.h>
30 #else
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
34 #if HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
38 #if HAVE_MATH_H
39 # include <math.h>
40 #endif
42 #if TIME_WITH_SYS_TIME
43 # include <sys/time.h>
44 # include <time.h>
45 #else
46 # if HAVE_SYS_TIME_H
47 #  include <sys/time.h>
48 # else
49 #  include <time.h>
50 # endif
51 #endif
53 #if HAVE_NETDB_H
54 # include <netdb.h> /* NI_MAXHOST */
55 #endif
57 #if HAVE_SIGNAL_H
58 # include <signal.h>
59 #endif
61 #if HAVE_SYS_TYPES_H
62 #include <sys/types.h>
63 #endif
65 #if USE_NCURSES
66 # define NCURSES_OPAQUE 1
67 # include <ncurses.h>
69 # define OPING_GREEN 1
70 # define OPING_YELLOW 2
71 # define OPING_RED 3
72 #endif
74 #include "oping.h"
76 #ifndef _POSIX_SAVED_IDS
77 # define _POSIX_SAVED_IDS 0
78 #endif
80 typedef struct ping_context
81 {
82         char host[NI_MAXHOST];
83         char addr[NI_MAXHOST];
85         int index;
86         int req_sent;
87         int req_rcvd;
89         double latency_min;
90         double latency_max;
91         double latency_total;
92         double latency_total_square;
94 #if USE_NCURSES
95         WINDOW *window;
96 #endif
97 } ping_context_t;
99 static double  opt_interval   = 1.0;
100 static int     opt_addrfamily = PING_DEF_AF;
101 static char   *opt_srcaddr    = NULL;
102 static char   *opt_device     = NULL;
103 static char   *opt_filename   = NULL;
104 static int     opt_count      = -1;
105 static int     opt_send_ttl   = 64;
106 static unsigned opt_send_tos  = 0;
108 static int host_num = 0;
110 #if USE_NCURSES
111 static WINDOW *main_win = NULL;
112 #endif
114 static void sigint_handler (int signal) /* {{{ */
116         /* Make compiler happy */
117         signal = 0;
118         /* Exit the loop */
119         opt_count = 0;
120 } /* }}} void sigint_handler */
122 static ping_context_t *context_create (void) /* {{{ */
124         ping_context_t *ret;
126         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
127                 return (NULL);
129         memset (ret, '\0', sizeof (ping_context_t));
131         ret->latency_min   = -1.0;
132         ret->latency_max   = -1.0;
133         ret->latency_total = 0.0;
134         ret->latency_total_square = 0.0;
136 #if USE_NCURSES
137         ret->window = NULL;
138 #endif
140         return (ret);
141 } /* }}} ping_context_t *context_create */
143 static void context_destroy (ping_context_t *context) /* {{{ */
145         if (context == NULL)
146                 return;
148 #if USE_NCURSES
149         if (context->window != NULL)
150         {
151                 delwin (context->window);
152                 context->window = NULL;
153         }
154 #endif
156         free (context);
157 } /* }}} void context_destroy */
159 static double context_get_average (ping_context_t *ctx) /* {{{ */
161         double num_total;
163         if (ctx == NULL)
164                 return (-1.0);
166         if (ctx->req_rcvd < 1)
167                 return (-0.0);
169         num_total = (double) ctx->req_rcvd;
170         return (ctx->latency_total / num_total);
171 } /* }}} double context_get_average */
173 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
175         double num_total;
177         if (ctx == NULL)
178                 return (-1.0);
180         if (ctx->req_rcvd < 1)
181                 return (-0.0);
182         else if (ctx->req_rcvd < 2)
183                 return (0.0);
185         num_total = (double) ctx->req_rcvd;
186         return (sqrt (((num_total * ctx->latency_total_square)
187                                         - (ctx->latency_total * ctx->latency_total))
188                                 / (num_total * (num_total - 1.0))));
189 } /* }}} double context_get_stddev */
191 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
193         if (ctx == NULL)
194                 return (-1.0);
196         if (ctx->req_sent < 1)
197                 return (0.0);
199         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
200                         / ((double) ctx->req_sent));
201 } /* }}} double context_get_packet_loss */
203 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
205         pingobj_iter_t *iter;
206         int index;
208         if (ping == NULL)
209                 return (EINVAL);
211         index = 0;
212         for (iter = ping_iterator_get (ping);
213                         iter != NULL;
214                         iter = ping_iterator_next (iter))
215         {
216                 ping_context_t *context;
217                 size_t buffer_size;
219                 context = context_create ();
220                 context->index = index;
222                 buffer_size = sizeof (context->host);
223                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
225                 buffer_size = sizeof (context->addr);
226                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
228                 ping_iterator_set_context (iter, (void *) context);
230                 index++;
231         }
233         return (0);
234 } /* }}} int ping_initialize_contexts */
236 static void usage_exit (const char *name, int status) /* {{{ */
238         int name_length;
240         name_length = (int) strlen (name);
242         fprintf (stderr, "Usage: %s [OPTIONS] "
243                                 "-f filename | host [host [host ...]]\n"
245                         "\nAvailable options:\n"
246                         "  -4|-6        force the use of IPv4 or IPv6\n"
247                         "  -c count     number of ICMP packets to send\n"
248                         "  -i interval  interval with which to send ICMP packets\n"
249                         "  -t ttl       time to live for each ICMP packet\n"
250                         "  -z tos       Type-of-service/class-of-service for each ICMP packet\n"
251                         "  -I srcaddr   source address\n"
252                         "  -D device    outgoing interface name\n"
253                         "  -f filename  filename to read hosts from\n"
255                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
256                         "by Florian octo Forster <octo@verplant.org>\n"
257                         "for contributions see `AUTHORS'\n",
258                         name);
259         exit (status);
260 } /* }}} void usage_exit */
262 static int read_options (int argc, char **argv) /* {{{ */
264         int optchar;
266         while (1)
267         {
268                 optchar = getopt (argc, argv, "46c:hi:I:t:z:f:D:");
270                 if (optchar == -1)
271                         break;
273                 switch (optchar)
274                 {
275                         case '4':
276                         case '6':
277                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
278                                 break;
280                         case 'c':
281                                 {
282                                         int new_count;
283                                         new_count = atoi (optarg);
284                                         if (new_count > 0)
285                                                 opt_count = new_count;
286                                         else
287                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
288                                                                 optarg);
289                                 }
290                                 break;
292                         case 'f':
293                                 {
294                                         if (opt_filename != NULL)
295                                                 free (opt_filename);
296                                         opt_filename = strdup (optarg);
297                                 }
298                                 break;
300                         case 'i':
301                                 {
302                                         double new_interval;
303                                         new_interval = atof (optarg);
304                                         if (new_interval < 0.001)
305                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
306                                                                 optarg);
307                                         else
308                                                 opt_interval = new_interval;
309                                 }
310                                 break;
311                         case 'I':
312                                 {
313                                         if (opt_srcaddr != NULL)
314                                                 free (opt_srcaddr);
315                                         opt_srcaddr = strdup (optarg);
316                                 }
317                                 break;
319                         case 'D':
320                                 opt_device = optarg;
321                                 break;
323                         case 't':
324                         {
325                                 int new_send_ttl;
326                                 new_send_ttl = atoi (optarg);
327                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
328                                         opt_send_ttl = new_send_ttl;
329                                 else
330                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
331                                                         optarg);
332                                 break;
333                         }
335                         case 'z':
336                         {
337                                 int new_send_tos;
338                                 new_send_tos = atoi (optarg);
339                                 if ((new_send_tos > 0) && (new_send_tos < 256))
340                                         opt_send_tos = new_send_tos;
341                                 else
342                                         fprintf (stderr, "Ignoring invalid TOS argument: %s\n",
343                                                         optarg);
344                                 break;
345                         }
347                         case 'h':
348                                 usage_exit (argv[0], 0);
349                                 break;
350                         default:
351                                 usage_exit (argv[0], 1);
352                 }
353         }
355         return (optind);
356 } /* }}} read_options */
358 static void time_normalize (struct timespec *ts) /* {{{ */
360         while (ts->tv_nsec < 0)
361         {
362                 if (ts->tv_sec == 0)
363                 {
364                         ts->tv_nsec = 0;
365                         return;
366                 }
368                 ts->tv_sec  -= 1;
369                 ts->tv_nsec += 1000000000;
370         }
372         while (ts->tv_nsec >= 1000000000)
373         {
374                 ts->tv_sec  += 1;
375                 ts->tv_nsec -= 1000000000;
376         }
377 } /* }}} void time_normalize */
379 static void time_calc (struct timespec *ts_dest, /* {{{ */
380                 const struct timespec *ts_int,
381                 const struct timeval  *tv_begin,
382                 const struct timeval  *tv_end)
384         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
385         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
386         time_normalize (ts_dest);
388         /* Assure that `(begin + interval) > end'.
389          * This may seem overly complicated, but `tv_sec' is of type `time_t'
390          * which may be `unsigned. *sigh* */
391         if ((tv_end->tv_sec > ts_dest->tv_sec)
392                         || ((tv_end->tv_sec == ts_dest->tv_sec)
393                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
394         {
395                 ts_dest->tv_sec  = 0;
396                 ts_dest->tv_nsec = 0;
397                 return;
398         }
400         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
401         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
402         time_normalize (ts_dest);
403 } /* }}} void time_calc */
405 #if USE_NCURSES
406 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
408         if ((ctx == NULL) || (ctx->window == NULL))
409                 return (EINVAL);
411         werase (ctx->window);
413         box (ctx->window, 0, 0);
414         wattron (ctx->window, A_BOLD);
415         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
416                         " %s ", ctx->host);
417         wattroff (ctx->window, A_BOLD);
418         wprintw (ctx->window, "ping statistics ");
419         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
420                         "%i packets transmitted, %i received, %.2f%% packet "
421                         "loss, time %.1fms",
422                         ctx->req_sent, ctx->req_rcvd,
423                         context_get_packet_loss (ctx),
424                         ctx->latency_total);
425         if (ctx->req_rcvd != 0)
426         {
427                 double average;
428                 double deviation;
430                 average = context_get_average (ctx);
431                 deviation = context_get_stddev (ctx);
432                         
433                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
434                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
435                                 ctx->latency_min,
436                                 average,
437                                 ctx->latency_max,
438                                 deviation);
439         }
441         wrefresh (ctx->window);
443         return (0);
444 } /* }}} int update_stats_from_context */
446 static int on_resize (pingobj_t *ping) /* {{{ */
448         pingobj_iter_t *iter;
449         int width = 0;
450         int height = 0;
451         int main_win_height;
453         getmaxyx (stdscr, height, width);
454         if ((height < 1) || (width < 1))
455                 return (EINVAL);
457         main_win_height = height - (4 * host_num);
458         wresize (main_win, main_win_height, /* width = */ width);
459         /* Allow scrolling */
460         scrollok (main_win, TRUE);
461         /* wsetscrreg (main_win, 0, main_win_height - 1); */
462         /* Allow hardware accelerated scrolling. */
463         idlok (main_win, TRUE);
464         wrefresh (main_win);
466         for (iter = ping_iterator_get (ping);
467                         iter != NULL;
468                         iter = ping_iterator_next (iter))
469         {
470                 ping_context_t *context;
472                 context = ping_iterator_get_context (iter);
473                 if (context == NULL)
474                         continue;
476                 if (context->window != NULL)
477                 {
478                         delwin (context->window);
479                         context->window = NULL;
480                 }
481                 context->window = newwin (/* height = */ 4,
482                                 /* width = */ 0,
483                                 /* y = */ main_win_height + (4 * context->index),
484                                 /* x = */ 0);
485         }
487         return (0);
488 } /* }}} */
490 static int check_resize (pingobj_t *ping) /* {{{ */
492         int need_resize = 0;
494         while (42)
495         {
496                 int key = wgetch (stdscr);
497                 if (key == ERR)
498                         break;
499                 else if (key == KEY_RESIZE)
500                         need_resize = 1;
501         }
503         if (need_resize)
504                 return (on_resize (ping));
505         else
506                 return (0);
507 } /* }}} int check_resize */
509 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
511         pingobj_iter_t *iter;
512         int width = 0;
513         int height = 0;
514         int main_win_height;
516         initscr ();
517         cbreak ();
518         noecho ();
519         nodelay (stdscr, TRUE);
521         getmaxyx (stdscr, height, width);
522         if ((height < 1) || (width < 1))
523                 return (EINVAL);
525         if (has_colors () == TRUE)
526         {
527                 start_color ();
528                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
529                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
530                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
531         }
533         main_win_height = height - (4 * host_num);
534         main_win = newwin (/* height = */ main_win_height,
535                         /* width = */ 0,
536                         /* y = */ 0, /* x = */ 0);
537         /* Allow scrolling */
538         scrollok (main_win, TRUE);
539         /* wsetscrreg (main_win, 0, main_win_height - 1); */
540         /* Allow hardware accelerated scrolling. */
541         idlok (main_win, TRUE);
542         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
543         wrefresh (main_win);
545         for (iter = ping_iterator_get (ping);
546                         iter != NULL;
547                         iter = ping_iterator_next (iter))
548         {
549                 ping_context_t *context;
551                 context = ping_iterator_get_context (iter);
552                 if (context == NULL)
553                         continue;
555                 if (context->window != NULL)
556                 {
557                         delwin (context->window);
558                         context->window = NULL;
559                 }
560                 context->window = newwin (/* height = */ 4,
561                                 /* width = */ 0,
562                                 /* y = */ main_win_height + (4 * context->index),
563                                 /* x = */ 0);
564         }
567         /* Don't know what good this does exactly, but without this code
568          * "check_resize" will be called right after startup and *somehow*
569          * this leads to display errors. If we purge all initial characters
570          * here, the problem goes away. "wgetch" is non-blocking due to
571          * "nodelay" (see above). */
572         while (wgetch (stdscr) != ERR)
573         {
574                 /* eat up characters */;
575         }
577         return (0);
578 } /* }}} int pre_loop_hook */
580 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
582         return (check_resize (ping));
583 } /* }}} int pre_sleep_hook */
585 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
587         return (check_resize (ping));
588 } /* }}} int pre_sleep_hook */
589 #else /* if !USE_NCURSES */
590 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
592         pingobj_iter_t *iter;
594         for (iter = ping_iterator_get (ping);
595                         iter != NULL;
596                         iter = ping_iterator_next (iter))
597         {
598                 ping_context_t *ctx;
599                 size_t buffer_size;
601                 ctx = ping_iterator_get_context (iter);
602                 if (ctx == NULL)
603                         continue;
605                 buffer_size = 0;
606                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
608                 printf ("PING %s (%s) %zu bytes of data.\n",
609                                 ctx->host, ctx->addr, buffer_size);
610         }
612         return (0);
613 } /* }}} int pre_loop_hook */
615 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
617         fflush (stdout);
619         return (0);
620 } /* }}} int pre_sleep_hook */
622 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
624         return (0);
625 } /* }}} int post_sleep_hook */
626 #endif
628 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
629                 int index)
631         double          latency;
632         unsigned int    sequence;
633         int             recv_ttl;
634         unsigned        recv_tos;
635         size_t          buffer_len;
636         size_t          data_len;
637         ping_context_t *context;
639         latency = -1.0;
640         buffer_len = sizeof (latency);
641         ping_iterator_get_info (iter, PING_INFO_LATENCY,
642                         &latency, &buffer_len);
644         sequence = 0;
645         buffer_len = sizeof (sequence);
646         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
647                         &sequence, &buffer_len);
649         recv_ttl = -1;
650         buffer_len = sizeof (recv_ttl);
651         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
652                         &recv_ttl, &buffer_len);
654         recv_tos = 0;
655         buffer_len = sizeof (recv_tos);
656         ping_iterator_get_info (iter, PING_INFO_TOS,
657                         &recv_tos, &buffer_len);
659         data_len = 0;
660         ping_iterator_get_info (iter, PING_INFO_DATA,
661                         NULL, &data_len);
663         context = (ping_context_t *) ping_iterator_get_context (iter);
665 #if USE_NCURSES
666 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
667 #else
668 # define HOST_PRINTF(...) printf(__VA_ARGS__)
669 #endif
671         context->req_sent++;
672         if (latency > 0.0)
673         {
674                 context->req_rcvd++;
675                 context->latency_total += latency;
676                 context->latency_total_square += (latency * latency);
678                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
679                         context->latency_max = latency;
680                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
681                         context->latency_min = latency;
683 #if USE_NCURSES
684                 if (has_colors () == TRUE)
685                 {
686                         int color = OPING_GREEN;
687                         double average = context_get_average (context);
688                         double stddev = context_get_stddev (context);
690                         if ((latency < (average - (2 * stddev)))
691                                         || (latency > (average + (2 * stddev))))
692                                 color = OPING_RED;
693                         else if ((latency < (average - stddev))
694                                         || (latency > (average + stddev)))
695                                 color = OPING_YELLOW;
697                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=%u "
698                                         "time=",
699                                         data_len, context->host, context->addr,
700                                         sequence, recv_ttl, recv_tos);
701                         wattron (main_win, COLOR_PAIR(color));
702                         HOST_PRINTF ("%.2f", latency);
703                         wattroff (main_win, COLOR_PAIR(color));
704                         HOST_PRINTF (" ms\n");
705                 }
706                 else
707                 {
708 #endif
709                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=%u "
710                                 "time=%.2f ms\n",
711                                 data_len,
712                                 context->host, context->addr,
713                                 sequence, recv_ttl, recv_tos, latency);
714 #if USE_NCURSES
715                 }
716 #endif
717         }
718         else
719         {
720 #if USE_NCURSES
721                 if (has_colors () == TRUE)
722                 {
723                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
724                                         context->host, context->addr,
725                                         sequence);
726                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
727                         HOST_PRINTF ("timeout");
728                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
729                         HOST_PRINTF ("\n");
730                 }
731                 else
732                 {
733 #endif
734                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
735                                 context->host, context->addr,
736                                 sequence);
737 #if USE_NCURSES
738                 }
739 #endif
740         }
742 #if USE_NCURSES
743         update_stats_from_context (context);
744         wrefresh (main_win);
745 #endif
746 } /* }}} void update_host_hook */
748 static int post_loop_hook (pingobj_t *ping) /* {{{ */
750         pingobj_iter_t *iter;
752 #if USE_NCURSES
753         endwin ();
754 #endif
756         for (iter = ping_iterator_get (ping);
757                         iter != NULL;
758                         iter = ping_iterator_next (iter))
759         {
760                 ping_context_t *context;
762                 context = ping_iterator_get_context (iter);
764                 printf ("\n--- %s ping statistics ---\n"
765                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
766                                 context->host, context->req_sent, context->req_rcvd,
767                                 context_get_packet_loss (context),
768                                 context->latency_total);
770                 if (context->req_rcvd != 0)
771                 {
772                         double average;
773                         double deviation;
775                         average = context_get_average (context);
776                         deviation = context_get_stddev (context);
778                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
779                                         context->latency_min,
780                                         average,
781                                         context->latency_max,
782                                         deviation);
783                 }
785                 ping_iterator_set_context (iter, NULL);
786                 context_destroy (context);
787         }
789         return (0);
790 } /* }}} int post_loop_hook */
792 int main (int argc, char **argv) /* {{{ */
794         pingobj_t      *ping;
795         pingobj_iter_t *iter;
797         struct sigaction sigint_action;
799         struct timeval  tv_begin;
800         struct timeval  tv_end;
801         struct timespec ts_wait;
802         struct timespec ts_int;
804         int optind;
805         int i;
806         int status;
807 #if _POSIX_SAVED_IDS
808         uid_t saved_set_uid;
810         /* Save the old effective user id */
811         saved_set_uid = geteuid ();
812         /* Set the effective user ID to the real user ID without changing the
813          * saved set-user ID */
814         status = seteuid (getuid ());
815         if (status != 0)
816         {
817                 fprintf (stderr, "Temporarily dropping privileges "
818                                 "failed: %s\n", strerror (errno));
819                 exit (EXIT_FAILURE);
820         }
821 #endif
823         optind = read_options (argc, argv);
825 #if !_POSIX_SAVED_IDS
826         /* Cannot temporarily drop privileges -> reject every file but "-". */
827         if ((opt_filename != NULL)
828                         && (strcmp ("-", opt_filename) != 0)
829                         && (getuid () != geteuid ()))
830         {
831                 fprintf (stderr, "Your real and effective user IDs don't "
832                                 "match. Reading from a file (option '-f')\n"
833                                 "is therefore too risky. You can still read "
834                                 "from STDIN using '-f -' if you like.\n"
835                                 "Sorry.\n");
836                 exit (EXIT_FAILURE);
837         }
838 #endif
840         if ((optind >= argc) && (opt_filename == NULL)) {
841                 usage_exit (argv[0], 1);
842         }
844         if ((ping = ping_construct ()) == NULL)
845         {
846                 fprintf (stderr, "ping_construct failed\n");
847                 return (1);
848         }
850         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
851         {
852                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
853                                 opt_send_ttl, ping_get_error (ping));
854         }
856         if (ping_setopt (ping, PING_OPT_TOS, &opt_send_tos) != 0)
857         {
858                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
859                                 opt_send_tos, ping_get_error (ping));
860         }
862         {
863                 double temp_sec;
864                 double temp_nsec;
866                 temp_nsec = modf (opt_interval, &temp_sec);
867                 ts_int.tv_sec  = (time_t) temp_sec;
868                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
870                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
871         }
873         if (opt_addrfamily != PING_DEF_AF)
874                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
876         if (opt_srcaddr != NULL)
877         {
878                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
879                 {
880                         fprintf (stderr, "Setting source address failed: %s\n",
881                                         ping_get_error (ping));
882                 }
883         }
885         if (opt_device != NULL)
886         {
887                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
888                 {
889                         fprintf (stderr, "Setting device failed: %s\n",
890                                         ping_get_error (ping));
891                 }
892         }
894         if (opt_filename != NULL)
895         {
896                 FILE *infile;
897                 char line[256];
898                 char host[256];
900                 if (strcmp (opt_filename, "-") == 0)
901                         /* Open STDIN */
902                         infile = fdopen(0, "r");
903                 else
904                         infile = fopen(opt_filename, "r");
906                 if (infile == NULL)
907                 {
908                         fprintf (stderr, "Opening %s failed: %s\n",
909                                         (strcmp (opt_filename, "-") == 0)
910                                         ? "STDIN" : opt_filename,
911                                         strerror(errno));
912                         return (1);
913                 }
915 #if _POSIX_SAVED_IDS
916                 /* Regain privileges */
917                 status = seteuid (saved_set_uid);
918                 if (status != 0)
919                 {
920                         fprintf (stderr, "Temporarily re-gaining privileges "
921                                         "failed: %s\n", strerror (errno));
922                         exit (EXIT_FAILURE);
923                 }
924 #endif
926                 while (fgets(line, sizeof(line), infile))
927                 {
928                         /* Strip whitespace */
929                         if (sscanf(line, "%s", host) != 1)
930                                 continue;
932                         if ((host[0] == 0) || (host[0] == '#'))
933                                 continue;
935                         if (ping_host_add(ping, host) < 0)
936                         {
937                                 const char *errmsg = ping_get_error (ping);
939                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
940                                 continue;
941                         }
942                         else
943                         {
944                                 host_num++;
945                         }
946                 }
948 #if _POSIX_SAVED_IDS
949                 /* Drop privileges */
950                 status = seteuid (getuid ());
951                 if (status != 0)
952                 {
953                         fprintf (stderr, "Temporarily dropping privileges "
954                                         "failed: %s\n", strerror (errno));
955                         exit (EXIT_FAILURE);
956                 }
957 #endif
959                 fclose(infile);
960         }
962 #if _POSIX_SAVED_IDS
963         /* Regain privileges */
964         status = seteuid (saved_set_uid);
965         if (status != 0)
966         {
967                 fprintf (stderr, "Temporarily re-gaining privileges "
968                                 "failed: %s\n", strerror (errno));
969                 exit (EXIT_FAILURE);
970         }
971 #endif
973         for (i = optind; i < argc; i++)
974         {
975                 if (ping_host_add (ping, argv[i]) < 0)
976                 {
977                         const char *errmsg = ping_get_error (ping);
979                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
980                         continue;
981                 }
982                 else
983                 {
984                         host_num++;
985                 }
986         }
988         /* Permanently drop root privileges if we're setuid-root. */
989         status = setuid (getuid ());
990         if (status != 0)
991         {
992                 fprintf (stderr, "Dropping privileges failed: %s\n",
993                                 strerror (errno));
994                 exit (EXIT_FAILURE);
995         }
997 #if _POSIX_SAVED_IDS
998         saved_set_uid = (uid_t) -1;
999 #endif
1001         ping_initialize_contexts (ping);
1003         if (i == 0)
1004                 return (1);
1006         memset (&sigint_action, '\0', sizeof (sigint_action));
1007         sigint_action.sa_handler = sigint_handler;
1008         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1009         {
1010                 perror ("sigaction");
1011                 return (1);
1012         }
1014         pre_loop_hook (ping);
1016         while (opt_count != 0)
1017         {
1018                 int index;
1019                 int status;
1021                 if (gettimeofday (&tv_begin, NULL) < 0)
1022                 {
1023                         perror ("gettimeofday");
1024                         return (1);
1025                 }
1027                 if (ping_send (ping) < 0)
1028                 {
1029                         fprintf (stderr, "ping_send failed: %s\n",
1030                                         ping_get_error (ping));
1031                         return (1);
1032                 }
1034                 index = 0;
1035                 for (iter = ping_iterator_get (ping);
1036                                 iter != NULL;
1037                                 iter = ping_iterator_next (iter))
1038                 {
1039                         update_host_hook (iter, index);
1040                         index++;
1041                 }
1043                 pre_sleep_hook (ping);
1045                 /* Don't sleep in the last iteration */
1046                 if (opt_count == 1)
1047                         break;
1049                 if (gettimeofday (&tv_end, NULL) < 0)
1050                 {
1051                         perror ("gettimeofday");
1052                         return (1);
1053                 }
1055                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1057                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1058                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1059                 {
1060                         if (errno != EINTR)
1061                         {
1062                                 perror ("nanosleep");
1063                                 break;
1064                         }
1065                         else if (opt_count == 0)
1066                         {
1067                                 /* sigint */
1068                                 break;
1069                         }
1070                 }
1072                 post_sleep_hook (ping);
1074                 if (opt_count > 0)
1075                         opt_count--;
1076         } /* while (opt_count != 0) */
1078         post_loop_hook (ping);
1080         ping_destroy (ping);
1082         return (0);
1083 } /* }}} int main */
1085 /* vim: set fdm=marker : */