Code

src/oping.c: Remove useless "strlen".
[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;
107 static int host_num = 0;
109 #if USE_NCURSES
110 static WINDOW *main_win = NULL;
111 #endif
113 static void sigint_handler (int signal) /* {{{ */
115         /* Make compiler happy */
116         signal = 0;
117         /* Exit the loop */
118         opt_count = 0;
119 } /* }}} void sigint_handler */
121 static ping_context_t *context_create (void) /* {{{ */
123         ping_context_t *ret;
125         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
126                 return (NULL);
128         memset (ret, '\0', sizeof (ping_context_t));
130         ret->latency_min   = -1.0;
131         ret->latency_max   = -1.0;
132         ret->latency_total = 0.0;
133         ret->latency_total_square = 0.0;
135 #if USE_NCURSES
136         ret->window = NULL;
137 #endif
139         return (ret);
140 } /* }}} ping_context_t *context_create */
142 static void context_destroy (ping_context_t *context) /* {{{ */
144         if (context == NULL)
145                 return;
147 #if USE_NCURSES
148         if (context->window != NULL)
149         {
150                 delwin (context->window);
151                 context->window = NULL;
152         }
153 #endif
155         free (context);
156 } /* }}} void context_destroy */
158 static double context_get_average (ping_context_t *ctx) /* {{{ */
160         double num_total;
162         if (ctx == NULL)
163                 return (-1.0);
165         if (ctx->req_rcvd < 1)
166                 return (-0.0);
168         num_total = (double) ctx->req_rcvd;
169         return (ctx->latency_total / num_total);
170 } /* }}} double context_get_average */
172 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
174         double num_total;
176         if (ctx == NULL)
177                 return (-1.0);
179         if (ctx->req_rcvd < 1)
180                 return (-0.0);
181         else if (ctx->req_rcvd < 2)
182                 return (0.0);
184         num_total = (double) ctx->req_rcvd;
185         return (sqrt (((num_total * ctx->latency_total_square)
186                                         - (ctx->latency_total * ctx->latency_total))
187                                 / (num_total * (num_total - 1.0))));
188 } /* }}} double context_get_stddev */
190 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
192         if (ctx == NULL)
193                 return (-1.0);
195         if (ctx->req_sent < 1)
196                 return (0.0);
198         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
199                         / ((double) ctx->req_sent));
200 } /* }}} double context_get_packet_loss */
202 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
204         pingobj_iter_t *iter;
205         int index;
207         if (ping == NULL)
208                 return (EINVAL);
210         index = 0;
211         for (iter = ping_iterator_get (ping);
212                         iter != NULL;
213                         iter = ping_iterator_next (iter))
214         {
215                 ping_context_t *context;
216                 size_t buffer_size;
218                 context = context_create ();
219                 context->index = index;
221                 buffer_size = sizeof (context->host);
222                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
224                 buffer_size = sizeof (context->addr);
225                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
227                 ping_iterator_set_context (iter, (void *) context);
229                 index++;
230         }
232         return (0);
233 } /* }}} int ping_initialize_contexts */
235 static void usage_exit (const char *name, int status) /* {{{ */
237         fprintf (stderr, "Usage: %s [OPTIONS] "
238                                 "-f filename | host [host [host ...]]\n"
240                         "\nAvailable options:\n"
241                         "  -4|-6        force the use of IPv4 or IPv6\n"
242                         "  -c count     number of ICMP packets to send\n"
243                         "  -i interval  interval with which to send ICMP packets\n"
244                         "  -t ttl       time to live for each ICMP packet\n"
245                         "  -I srcaddr   source address\n"
246                         "  -D device    outgoing interface name\n"
247                         "  -f filename  filename to read hosts from\n"
249                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
250                         "by Florian octo Forster <octo@verplant.org>\n"
251                         "for contributions see `AUTHORS'\n",
252                         name);
253         exit (status);
254 } /* }}} void usage_exit */
256 static int read_options (int argc, char **argv) /* {{{ */
258         int optchar;
260         while (1)
261         {
262                 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
264                 if (optchar == -1)
265                         break;
267                 switch (optchar)
268                 {
269                         case '4':
270                         case '6':
271                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
272                                 break;
274                         case 'c':
275                                 {
276                                         int new_count;
277                                         new_count = atoi (optarg);
278                                         if (new_count > 0)
279                                                 opt_count = new_count;
280                                         else
281                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
282                                                                 optarg);
283                                 }
284                                 break;
286                         case 'f':
287                                 {
288                                         if (opt_filename != NULL)
289                                                 free (opt_filename);
290                                         opt_filename = strdup (optarg);
291                                 }
292                                 break;
294                         case 'i':
295                                 {
296                                         double new_interval;
297                                         new_interval = atof (optarg);
298                                         if (new_interval < 0.001)
299                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
300                                                                 optarg);
301                                         else
302                                                 opt_interval = new_interval;
303                                 }
304                                 break;
305                         case 'I':
306                                 {
307                                         if (opt_srcaddr != NULL)
308                                                 free (opt_srcaddr);
309                                         opt_srcaddr = strdup (optarg);
310                                 }
311                                 break;
313                         case 'D':
314                                 opt_device = optarg;
315                                 break;
317                         case 't':
318                         {
319                                 int new_send_ttl;
320                                 new_send_ttl = atoi (optarg);
321                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
322                                         opt_send_ttl = new_send_ttl;
323                                 else
324                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
325                                                         optarg);
326                                 break;
327                         }
329                         case 'h':
330                                 usage_exit (argv[0], 0);
331                                 break;
332                         default:
333                                 usage_exit (argv[0], 1);
334                 }
335         }
337         return (optind);
338 } /* }}} read_options */
340 static void time_normalize (struct timespec *ts) /* {{{ */
342         while (ts->tv_nsec < 0)
343         {
344                 if (ts->tv_sec == 0)
345                 {
346                         ts->tv_nsec = 0;
347                         return;
348                 }
350                 ts->tv_sec  -= 1;
351                 ts->tv_nsec += 1000000000;
352         }
354         while (ts->tv_nsec >= 1000000000)
355         {
356                 ts->tv_sec  += 1;
357                 ts->tv_nsec -= 1000000000;
358         }
359 } /* }}} void time_normalize */
361 static void time_calc (struct timespec *ts_dest, /* {{{ */
362                 const struct timespec *ts_int,
363                 const struct timeval  *tv_begin,
364                 const struct timeval  *tv_end)
366         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
367         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
368         time_normalize (ts_dest);
370         /* Assure that `(begin + interval) > end'.
371          * This may seem overly complicated, but `tv_sec' is of type `time_t'
372          * which may be `unsigned. *sigh* */
373         if ((tv_end->tv_sec > ts_dest->tv_sec)
374                         || ((tv_end->tv_sec == ts_dest->tv_sec)
375                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
376         {
377                 ts_dest->tv_sec  = 0;
378                 ts_dest->tv_nsec = 0;
379                 return;
380         }
382         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
383         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
384         time_normalize (ts_dest);
385 } /* }}} void time_calc */
387 #if USE_NCURSES
388 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
390         if ((ctx == NULL) || (ctx->window == NULL))
391                 return (EINVAL);
393         werase (ctx->window);
395         box (ctx->window, 0, 0);
396         wattron (ctx->window, A_BOLD);
397         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
398                         " %s ", ctx->host);
399         wattroff (ctx->window, A_BOLD);
400         wprintw (ctx->window, "ping statistics ");
401         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
402                         "%i packets transmitted, %i received, %.2f%% packet "
403                         "loss, time %.1fms",
404                         ctx->req_sent, ctx->req_rcvd,
405                         context_get_packet_loss (ctx),
406                         ctx->latency_total);
407         if (ctx->req_rcvd != 0)
408         {
409                 double average;
410                 double deviation;
412                 average = context_get_average (ctx);
413                 deviation = context_get_stddev (ctx);
414                         
415                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
416                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
417                                 ctx->latency_min,
418                                 average,
419                                 ctx->latency_max,
420                                 deviation);
421         }
423         wrefresh (ctx->window);
425         return (0);
426 } /* }}} int update_stats_from_context */
428 static int on_resize (pingobj_t *ping) /* {{{ */
430         pingobj_iter_t *iter;
431         int width = 0;
432         int height = 0;
433         int main_win_height;
435         getmaxyx (stdscr, height, width);
436         if ((height < 1) || (width < 1))
437                 return (EINVAL);
439         main_win_height = height - (4 * host_num);
440         wresize (main_win, main_win_height, /* width = */ width);
441         /* Allow scrolling */
442         scrollok (main_win, TRUE);
443         /* wsetscrreg (main_win, 0, main_win_height - 1); */
444         /* Allow hardware accelerated scrolling. */
445         idlok (main_win, TRUE);
446         wrefresh (main_win);
448         for (iter = ping_iterator_get (ping);
449                         iter != NULL;
450                         iter = ping_iterator_next (iter))
451         {
452                 ping_context_t *context;
454                 context = ping_iterator_get_context (iter);
455                 if (context == NULL)
456                         continue;
458                 if (context->window != NULL)
459                 {
460                         delwin (context->window);
461                         context->window = NULL;
462                 }
463                 context->window = newwin (/* height = */ 4,
464                                 /* width = */ 0,
465                                 /* y = */ main_win_height + (4 * context->index),
466                                 /* x = */ 0);
467         }
469         return (0);
470 } /* }}} */
472 static int check_resize (pingobj_t *ping) /* {{{ */
474         int need_resize = 0;
476         while (42)
477         {
478                 int key = wgetch (stdscr);
479                 if (key == ERR)
480                         break;
481                 else if (key == KEY_RESIZE)
482                         need_resize = 1;
483         }
485         if (need_resize)
486                 return (on_resize (ping));
487         else
488                 return (0);
489 } /* }}} int check_resize */
491 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
493         pingobj_iter_t *iter;
494         int width = 0;
495         int height = 0;
496         int main_win_height;
498         initscr ();
499         cbreak ();
500         noecho ();
501         nodelay (stdscr, TRUE);
503         getmaxyx (stdscr, height, width);
504         if ((height < 1) || (width < 1))
505                 return (EINVAL);
507         if (has_colors () == TRUE)
508         {
509                 start_color ();
510                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
511                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
512                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
513         }
515         main_win_height = height - (4 * host_num);
516         main_win = newwin (/* height = */ main_win_height,
517                         /* width = */ 0,
518                         /* y = */ 0, /* x = */ 0);
519         /* Allow scrolling */
520         scrollok (main_win, TRUE);
521         /* wsetscrreg (main_win, 0, main_win_height - 1); */
522         /* Allow hardware accelerated scrolling. */
523         idlok (main_win, TRUE);
524         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
525         wrefresh (main_win);
527         for (iter = ping_iterator_get (ping);
528                         iter != NULL;
529                         iter = ping_iterator_next (iter))
530         {
531                 ping_context_t *context;
533                 context = ping_iterator_get_context (iter);
534                 if (context == NULL)
535                         continue;
537                 if (context->window != NULL)
538                 {
539                         delwin (context->window);
540                         context->window = NULL;
541                 }
542                 context->window = newwin (/* height = */ 4,
543                                 /* width = */ 0,
544                                 /* y = */ main_win_height + (4 * context->index),
545                                 /* x = */ 0);
546         }
549         /* Don't know what good this does exactly, but without this code
550          * "check_resize" will be called right after startup and *somehow*
551          * this leads to display errors. If we purge all initial characters
552          * here, the problem goes away. "wgetch" is non-blocking due to
553          * "nodelay" (see above). */
554         while (wgetch (stdscr) != ERR)
555         {
556                 /* eat up characters */;
557         }
559         return (0);
560 } /* }}} int pre_loop_hook */
562 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
564         return (check_resize (ping));
565 } /* }}} int pre_sleep_hook */
567 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
569         return (check_resize (ping));
570 } /* }}} int pre_sleep_hook */
571 #else /* if !USE_NCURSES */
572 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
574         pingobj_iter_t *iter;
576         for (iter = ping_iterator_get (ping);
577                         iter != NULL;
578                         iter = ping_iterator_next (iter))
579         {
580                 ping_context_t *ctx;
581                 size_t buffer_size;
583                 ctx = ping_iterator_get_context (iter);
584                 if (ctx == NULL)
585                         continue;
587                 buffer_size = 0;
588                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
590                 printf ("PING %s (%s) %zu bytes of data.\n",
591                                 ctx->host, ctx->addr, buffer_size);
592         }
594         return (0);
595 } /* }}} int pre_loop_hook */
597 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
599         fflush (stdout);
601         return (0);
602 } /* }}} int pre_sleep_hook */
604 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
606         return (0);
607 } /* }}} int post_sleep_hook */
608 #endif
610 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
611                 int index)
613         double          latency;
614         unsigned int    sequence;
615         int             recv_ttl;
616         size_t          buffer_len;
617         size_t          data_len;
618         ping_context_t *context;
620         latency = -1.0;
621         buffer_len = sizeof (latency);
622         ping_iterator_get_info (iter, PING_INFO_LATENCY,
623                         &latency, &buffer_len);
625         sequence = 0;
626         buffer_len = sizeof (sequence);
627         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
628                         &sequence, &buffer_len);
630         recv_ttl = -1;
631         buffer_len = sizeof (recv_ttl);
632         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
633                         &recv_ttl, &buffer_len);
635         data_len = 0;
636         ping_iterator_get_info (iter, PING_INFO_DATA,
637                         NULL, &data_len);
639         context = (ping_context_t *) ping_iterator_get_context (iter);
641 #if USE_NCURSES
642 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
643 #else
644 # define HOST_PRINTF(...) printf(__VA_ARGS__)
645 #endif
647         context->req_sent++;
648         if (latency > 0.0)
649         {
650                 context->req_rcvd++;
651                 context->latency_total += latency;
652                 context->latency_total_square += (latency * latency);
654                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
655                         context->latency_max = latency;
656                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
657                         context->latency_min = latency;
659 #if USE_NCURSES
660                 if (has_colors () == TRUE)
661                 {
662                         int color = OPING_GREEN;
663                         double average = context_get_average (context);
664                         double stddev = context_get_stddev (context);
666                         if ((latency < (average - (2 * stddev)))
667                                         || (latency > (average + (2 * stddev))))
668                                 color = OPING_RED;
669                         else if ((latency < (average - stddev))
670                                         || (latency > (average + stddev)))
671                                 color = OPING_YELLOW;
673                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
674                                         "time=",
675                                         data_len, context->host, context->addr,
676                                         sequence, recv_ttl);
677                         wattron (main_win, COLOR_PAIR(color));
678                         HOST_PRINTF ("%.2f", latency);
679                         wattroff (main_win, COLOR_PAIR(color));
680                         HOST_PRINTF (" ms\n");
681                 }
682                 else
683                 {
684 #endif
685                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
686                                 "time=%.2f ms\n",
687                                 data_len,
688                                 context->host, context->addr,
689                                 sequence, recv_ttl, latency);
690 #if USE_NCURSES
691                 }
692 #endif
693         }
694         else
695         {
696 #if USE_NCURSES
697                 if (has_colors () == TRUE)
698                 {
699                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
700                                         context->host, context->addr,
701                                         sequence);
702                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
703                         HOST_PRINTF ("timeout");
704                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
705                         HOST_PRINTF ("\n");
706                 }
707                 else
708                 {
709 #endif
710                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
711                                 context->host, context->addr,
712                                 sequence);
713 #if USE_NCURSES
714                 }
715 #endif
716         }
718 #if USE_NCURSES
719         update_stats_from_context (context);
720         wrefresh (main_win);
721 #endif
722 } /* }}} void update_host_hook */
724 static int post_loop_hook (pingobj_t *ping) /* {{{ */
726         pingobj_iter_t *iter;
728 #if USE_NCURSES
729         endwin ();
730 #endif
732         for (iter = ping_iterator_get (ping);
733                         iter != NULL;
734                         iter = ping_iterator_next (iter))
735         {
736                 ping_context_t *context;
738                 context = ping_iterator_get_context (iter);
740                 printf ("\n--- %s ping statistics ---\n"
741                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
742                                 context->host, context->req_sent, context->req_rcvd,
743                                 context_get_packet_loss (context),
744                                 context->latency_total);
746                 if (context->req_rcvd != 0)
747                 {
748                         double average;
749                         double deviation;
751                         average = context_get_average (context);
752                         deviation = context_get_stddev (context);
754                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
755                                         context->latency_min,
756                                         average,
757                                         context->latency_max,
758                                         deviation);
759                 }
761                 ping_iterator_set_context (iter, NULL);
762                 context_destroy (context);
763         }
765         return (0);
766 } /* }}} int post_loop_hook */
768 int main (int argc, char **argv) /* {{{ */
770         pingobj_t      *ping;
771         pingobj_iter_t *iter;
773         struct sigaction sigint_action;
775         struct timeval  tv_begin;
776         struct timeval  tv_end;
777         struct timespec ts_wait;
778         struct timespec ts_int;
780         int optind;
781         int i;
782         int status;
783 #if _POSIX_SAVED_IDS
784         uid_t saved_set_uid;
786         /* Save the old effective user id */
787         saved_set_uid = geteuid ();
788         /* Set the effective user ID to the real user ID without changing the
789          * saved set-user ID */
790         status = seteuid (getuid ());
791         if (status != 0)
792         {
793                 fprintf (stderr, "Temporarily dropping privileges "
794                                 "failed: %s\n", strerror (errno));
795                 exit (EXIT_FAILURE);
796         }
797 #endif
799         optind = read_options (argc, argv);
801 #if !_POSIX_SAVED_IDS
802         /* Cannot temporarily drop privileges -> reject every file but "-". */
803         if ((opt_filename != NULL)
804                         && (strcmp ("-", opt_filename) != 0)
805                         && (getuid () != geteuid ()))
806         {
807                 fprintf (stderr, "Your real and effective user IDs don't "
808                                 "match. Reading from a file (option '-f')\n"
809                                 "is therefore too risky. You can still read "
810                                 "from STDIN using '-f -' if you like.\n"
811                                 "Sorry.\n");
812                 exit (EXIT_FAILURE);
813         }
814 #endif
816         if ((optind >= argc) && (opt_filename == NULL)) {
817                 usage_exit (argv[0], 1);
818         }
820         if ((ping = ping_construct ()) == NULL)
821         {
822                 fprintf (stderr, "ping_construct failed\n");
823                 return (1);
824         }
826         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
827         {
828                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
829                                 opt_send_ttl, ping_get_error (ping));
830         }
832         {
833                 double temp_sec;
834                 double temp_nsec;
836                 temp_nsec = modf (opt_interval, &temp_sec);
837                 ts_int.tv_sec  = (time_t) temp_sec;
838                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
840                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
841         }
843         if (opt_addrfamily != PING_DEF_AF)
844                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
846         if (opt_srcaddr != NULL)
847         {
848                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
849                 {
850                         fprintf (stderr, "Setting source address failed: %s\n",
851                                         ping_get_error (ping));
852                 }
853         }
855         if (opt_device != NULL)
856         {
857                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
858                 {
859                         fprintf (stderr, "Setting device failed: %s\n",
860                                         ping_get_error (ping));
861                 }
862         }
864         if (opt_filename != NULL)
865         {
866                 FILE *infile;
867                 char line[256];
868                 char host[256];
870                 if (strcmp (opt_filename, "-") == 0)
871                         /* Open STDIN */
872                         infile = fdopen(0, "r");
873                 else
874                         infile = fopen(opt_filename, "r");
876                 if (infile == NULL)
877                 {
878                         fprintf (stderr, "Opening %s failed: %s\n",
879                                         (strcmp (opt_filename, "-") == 0)
880                                         ? "STDIN" : opt_filename,
881                                         strerror(errno));
882                         return (1);
883                 }
885 #if _POSIX_SAVED_IDS
886                 /* Regain privileges */
887                 status = seteuid (saved_set_uid);
888                 if (status != 0)
889                 {
890                         fprintf (stderr, "Temporarily re-gaining privileges "
891                                         "failed: %s\n", strerror (errno));
892                         exit (EXIT_FAILURE);
893                 }
894 #endif
896                 while (fgets(line, sizeof(line), infile))
897                 {
898                         /* Strip whitespace */
899                         if (sscanf(line, "%s", host) != 1)
900                                 continue;
902                         if ((host[0] == 0) || (host[0] == '#'))
903                                 continue;
905                         if (ping_host_add(ping, host) < 0)
906                         {
907                                 const char *errmsg = ping_get_error (ping);
909                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
910                                 continue;
911                         }
912                         else
913                         {
914                                 host_num++;
915                         }
916                 }
918 #if _POSIX_SAVED_IDS
919                 /* Drop privileges */
920                 status = seteuid (getuid ());
921                 if (status != 0)
922                 {
923                         fprintf (stderr, "Temporarily dropping privileges "
924                                         "failed: %s\n", strerror (errno));
925                         exit (EXIT_FAILURE);
926                 }
927 #endif
929                 fclose(infile);
930         }
932 #if _POSIX_SAVED_IDS
933         /* Regain privileges */
934         status = seteuid (saved_set_uid);
935         if (status != 0)
936         {
937                 fprintf (stderr, "Temporarily re-gaining privileges "
938                                 "failed: %s\n", strerror (errno));
939                 exit (EXIT_FAILURE);
940         }
941 #endif
943         for (i = optind; i < argc; i++)
944         {
945                 if (ping_host_add (ping, argv[i]) < 0)
946                 {
947                         const char *errmsg = ping_get_error (ping);
949                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
950                         continue;
951                 }
952                 else
953                 {
954                         host_num++;
955                 }
956         }
958         /* Permanently drop root privileges if we're setuid-root. */
959         status = setuid (getuid ());
960         if (status != 0)
961         {
962                 fprintf (stderr, "Dropping privileges failed: %s\n",
963                                 strerror (errno));
964                 exit (EXIT_FAILURE);
965         }
967 #if _POSIX_SAVED_IDS
968         saved_set_uid = (uid_t) -1;
969 #endif
971         ping_initialize_contexts (ping);
973         if (i == 0)
974                 return (1);
976         memset (&sigint_action, '\0', sizeof (sigint_action));
977         sigint_action.sa_handler = sigint_handler;
978         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
979         {
980                 perror ("sigaction");
981                 return (1);
982         }
984         pre_loop_hook (ping);
986         while (opt_count != 0)
987         {
988                 int index;
989                 int status;
991                 if (gettimeofday (&tv_begin, NULL) < 0)
992                 {
993                         perror ("gettimeofday");
994                         return (1);
995                 }
997                 if (ping_send (ping) < 0)
998                 {
999                         fprintf (stderr, "ping_send failed: %s\n",
1000                                         ping_get_error (ping));
1001                         return (1);
1002                 }
1004                 index = 0;
1005                 for (iter = ping_iterator_get (ping);
1006                                 iter != NULL;
1007                                 iter = ping_iterator_next (iter))
1008                 {
1009                         update_host_hook (iter, index);
1010                         index++;
1011                 }
1013                 pre_sleep_hook (ping);
1015                 /* Don't sleep in the last iteration */
1016                 if (opt_count == 1)
1017                         break;
1019                 if (gettimeofday (&tv_end, NULL) < 0)
1020                 {
1021                         perror ("gettimeofday");
1022                         return (1);
1023                 }
1025                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1027                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1028                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1029                 {
1030                         if (errno != EINTR)
1031                         {
1032                                 perror ("nanosleep");
1033                                 break;
1034                         }
1035                         else if (opt_count == 0)
1036                         {
1037                                 /* sigint */
1038                                 break;
1039                         }
1040                 }
1042                 post_sleep_hook (ping);
1044                 if (opt_count > 0)
1045                         opt_count--;
1046         } /* while (opt_count != 0) */
1048         post_loop_hook (ping);
1050         ping_destroy (ping);
1052         return (0);
1053 } /* }}} int main */
1055 /* vim: set fdm=marker : */