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) /* {{{ */
114 {
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) /* {{{ */
122 {
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) /* {{{ */
143 {
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) /* {{{ */
159 {
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) /* {{{ */
173 {
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) /* {{{ */
191 {
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) /* {{{ */
203 {
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) /* {{{ */
236 {
237 int name_length;
239 name_length = (int) strlen (name);
241 fprintf (stderr, "Usage: %s [OPTIONS] "
242 "-f filename | host [host [host ...]]\n"
244 "\nAvailable options:\n"
245 " -4|-6 force the use of IPv4 or IPv6\n"
246 " -c count number of ICMP packets to send\n"
247 " -i interval interval with which to send ICMP packets\n"
248 " -t ttl time to live for each ICMP packet\n"
249 " -I srcaddr source address\n"
250 " -D device outgoing interface name\n"
251 " -f filename filename to read hosts from\n"
253 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
254 "by Florian octo Forster <octo@verplant.org>\n"
255 "for contributions see `AUTHORS'\n",
256 name);
257 exit (status);
258 } /* }}} void usage_exit */
260 static int read_options (int argc, char **argv) /* {{{ */
261 {
262 int optchar;
264 while (1)
265 {
266 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
268 if (optchar == -1)
269 break;
271 switch (optchar)
272 {
273 case '4':
274 case '6':
275 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
276 break;
278 case 'c':
279 {
280 int new_count;
281 new_count = atoi (optarg);
282 if (new_count > 0)
283 opt_count = new_count;
284 else
285 fprintf(stderr, "Ignoring invalid count: %s\n",
286 optarg);
287 }
288 break;
290 case 'f':
291 {
292 if (opt_filename != NULL)
293 free (opt_filename);
294 opt_filename = strdup (optarg);
295 }
296 break;
298 case 'i':
299 {
300 double new_interval;
301 new_interval = atof (optarg);
302 if (new_interval < 0.001)
303 fprintf (stderr, "Ignoring invalid interval: %s\n",
304 optarg);
305 else
306 opt_interval = new_interval;
307 }
308 break;
309 case 'I':
310 {
311 if (opt_srcaddr != NULL)
312 free (opt_srcaddr);
313 opt_srcaddr = strdup (optarg);
314 }
315 break;
317 case 'D':
318 opt_device = optarg;
319 break;
321 case 't':
322 {
323 int new_send_ttl;
324 new_send_ttl = atoi (optarg);
325 if ((new_send_ttl > 0) && (new_send_ttl < 256))
326 opt_send_ttl = new_send_ttl;
327 else
328 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
329 optarg);
330 break;
331 }
333 case 'h':
334 usage_exit (argv[0], 0);
335 break;
336 default:
337 usage_exit (argv[0], 1);
338 }
339 }
341 return (optind);
342 } /* }}} read_options */
344 static void time_normalize (struct timespec *ts) /* {{{ */
345 {
346 while (ts->tv_nsec < 0)
347 {
348 if (ts->tv_sec == 0)
349 {
350 ts->tv_nsec = 0;
351 return;
352 }
354 ts->tv_sec -= 1;
355 ts->tv_nsec += 1000000000;
356 }
358 while (ts->tv_nsec >= 1000000000)
359 {
360 ts->tv_sec += 1;
361 ts->tv_nsec -= 1000000000;
362 }
363 } /* }}} void time_normalize */
365 static void time_calc (struct timespec *ts_dest, /* {{{ */
366 const struct timespec *ts_int,
367 const struct timeval *tv_begin,
368 const struct timeval *tv_end)
369 {
370 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
371 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
372 time_normalize (ts_dest);
374 /* Assure that `(begin + interval) > end'.
375 * This may seem overly complicated, but `tv_sec' is of type `time_t'
376 * which may be `unsigned. *sigh* */
377 if ((tv_end->tv_sec > ts_dest->tv_sec)
378 || ((tv_end->tv_sec == ts_dest->tv_sec)
379 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
380 {
381 ts_dest->tv_sec = 0;
382 ts_dest->tv_nsec = 0;
383 return;
384 }
386 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
387 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
388 time_normalize (ts_dest);
389 } /* }}} void time_calc */
391 #if USE_NCURSES
392 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
393 {
394 if ((ctx == NULL) || (ctx->window == NULL))
395 return (EINVAL);
397 werase (ctx->window);
399 box (ctx->window, 0, 0);
400 wattron (ctx->window, A_BOLD);
401 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
402 " %s ", ctx->host);
403 wattroff (ctx->window, A_BOLD);
404 wprintw (ctx->window, "ping statistics ");
405 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
406 "%i packets transmitted, %i received, %.2f%% packet "
407 "loss, time %.1fms",
408 ctx->req_sent, ctx->req_rcvd,
409 context_get_packet_loss (ctx),
410 ctx->latency_total);
411 if (ctx->req_rcvd != 0)
412 {
413 double average;
414 double deviation;
416 average = context_get_average (ctx);
417 deviation = context_get_stddev (ctx);
419 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
420 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
421 ctx->latency_min,
422 average,
423 ctx->latency_max,
424 deviation);
425 }
427 wrefresh (ctx->window);
429 return (0);
430 } /* }}} int update_stats_from_context */
432 static int on_resize (pingobj_t *ping) /* {{{ */
433 {
434 pingobj_iter_t *iter;
435 int width = 0;
436 int height = 0;
437 int main_win_height;
439 getmaxyx (stdscr, height, width);
440 if ((height < 1) || (width < 1))
441 return (EINVAL);
443 main_win_height = height - (4 * host_num);
444 wresize (main_win, main_win_height, /* width = */ width);
445 /* Allow scrolling */
446 scrollok (main_win, TRUE);
447 /* wsetscrreg (main_win, 0, main_win_height - 1); */
448 /* Allow hardware accelerated scrolling. */
449 idlok (main_win, TRUE);
450 wrefresh (main_win);
452 for (iter = ping_iterator_get (ping);
453 iter != NULL;
454 iter = ping_iterator_next (iter))
455 {
456 ping_context_t *context;
458 context = ping_iterator_get_context (iter);
459 if (context == NULL)
460 continue;
462 if (context->window != NULL)
463 {
464 delwin (context->window);
465 context->window = NULL;
466 }
467 context->window = newwin (/* height = */ 4,
468 /* width = */ 0,
469 /* y = */ main_win_height + (4 * context->index),
470 /* x = */ 0);
471 }
473 return (0);
474 } /* }}} */
476 static int check_resize (pingobj_t *ping) /* {{{ */
477 {
478 int need_resize = 0;
480 while (42)
481 {
482 int key = wgetch (stdscr);
483 if (key == ERR)
484 break;
485 else if (key == KEY_RESIZE)
486 need_resize = 1;
487 }
489 if (need_resize)
490 return (on_resize (ping));
491 else
492 return (0);
493 } /* }}} int check_resize */
495 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
496 {
497 pingobj_iter_t *iter;
498 int width = 0;
499 int height = 0;
500 int main_win_height;
502 initscr ();
503 cbreak ();
504 noecho ();
505 nodelay (stdscr, TRUE);
507 getmaxyx (stdscr, height, width);
508 if ((height < 1) || (width < 1))
509 return (EINVAL);
511 if (has_colors () == TRUE)
512 {
513 start_color ();
514 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
515 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
516 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
517 }
519 main_win_height = height - (4 * host_num);
520 main_win = newwin (/* height = */ main_win_height,
521 /* width = */ 0,
522 /* y = */ 0, /* x = */ 0);
523 /* Allow scrolling */
524 scrollok (main_win, TRUE);
525 /* wsetscrreg (main_win, 0, main_win_height - 1); */
526 /* Allow hardware accelerated scrolling. */
527 idlok (main_win, TRUE);
528 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
529 wrefresh (main_win);
531 for (iter = ping_iterator_get (ping);
532 iter != NULL;
533 iter = ping_iterator_next (iter))
534 {
535 ping_context_t *context;
537 context = ping_iterator_get_context (iter);
538 if (context == NULL)
539 continue;
541 if (context->window != NULL)
542 {
543 delwin (context->window);
544 context->window = NULL;
545 }
546 context->window = newwin (/* height = */ 4,
547 /* width = */ 0,
548 /* y = */ main_win_height + (4 * context->index),
549 /* x = */ 0);
550 }
553 /* Don't know what good this does exactly, but without this code
554 * "check_resize" will be called right after startup and *somehow*
555 * this leads to display errors. If we purge all initial characters
556 * here, the problem goes away. "wgetch" is non-blocking due to
557 * "nodelay" (see above). */
558 while (wgetch (stdscr) != ERR)
559 {
560 /* eat up characters */;
561 }
563 return (0);
564 } /* }}} int pre_loop_hook */
566 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
567 {
568 return (check_resize (ping));
569 } /* }}} int pre_sleep_hook */
571 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
572 {
573 return (check_resize (ping));
574 } /* }}} int pre_sleep_hook */
575 #else /* if !USE_NCURSES */
576 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
577 {
578 pingobj_iter_t *iter;
580 for (iter = ping_iterator_get (ping);
581 iter != NULL;
582 iter = ping_iterator_next (iter))
583 {
584 ping_context_t *ctx;
585 size_t buffer_size;
587 ctx = ping_iterator_get_context (iter);
588 if (ctx == NULL)
589 continue;
591 buffer_size = 0;
592 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
594 printf ("PING %s (%s) %zu bytes of data.\n",
595 ctx->host, ctx->addr, buffer_size);
596 }
598 return (0);
599 } /* }}} int pre_loop_hook */
601 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
602 {
603 fflush (stdout);
605 return (0);
606 } /* }}} int pre_sleep_hook */
608 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
609 {
610 return (0);
611 } /* }}} int post_sleep_hook */
612 #endif
614 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
615 int index)
616 {
617 double latency;
618 unsigned int sequence;
619 int recv_ttl;
620 size_t buffer_len;
621 size_t data_len;
622 ping_context_t *context;
624 latency = -1.0;
625 buffer_len = sizeof (latency);
626 ping_iterator_get_info (iter, PING_INFO_LATENCY,
627 &latency, &buffer_len);
629 sequence = 0;
630 buffer_len = sizeof (sequence);
631 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
632 &sequence, &buffer_len);
634 recv_ttl = -1;
635 buffer_len = sizeof (recv_ttl);
636 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
637 &recv_ttl, &buffer_len);
639 data_len = 0;
640 ping_iterator_get_info (iter, PING_INFO_DATA,
641 NULL, &data_len);
643 context = (ping_context_t *) ping_iterator_get_context (iter);
645 #if USE_NCURSES
646 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
647 #else
648 # define HOST_PRINTF(...) printf(__VA_ARGS__)
649 #endif
651 context->req_sent++;
652 if (latency > 0.0)
653 {
654 context->req_rcvd++;
655 context->latency_total += latency;
656 context->latency_total_square += (latency * latency);
658 if ((context->latency_max < 0.0) || (context->latency_max < latency))
659 context->latency_max = latency;
660 if ((context->latency_min < 0.0) || (context->latency_min > latency))
661 context->latency_min = latency;
663 #if USE_NCURSES
664 if (has_colors () == TRUE)
665 {
666 int color = OPING_GREEN;
667 double average = context_get_average (context);
668 double stddev = context_get_stddev (context);
670 if ((latency < (average - (2 * stddev)))
671 || (latency > (average + (2 * stddev))))
672 color = OPING_RED;
673 else if ((latency < (average - stddev))
674 || (latency > (average + stddev)))
675 color = OPING_YELLOW;
677 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
678 "time=",
679 data_len, context->host, context->addr,
680 sequence, recv_ttl);
681 wattron (main_win, COLOR_PAIR(color));
682 HOST_PRINTF ("%.2f", latency);
683 wattroff (main_win, COLOR_PAIR(color));
684 HOST_PRINTF (" ms\n");
685 }
686 else
687 {
688 #endif
689 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
690 "time=%.2f ms\n",
691 data_len,
692 context->host, context->addr,
693 sequence, recv_ttl, latency);
694 #if USE_NCURSES
695 }
696 #endif
697 }
698 else
699 {
700 #if USE_NCURSES
701 if (has_colors () == TRUE)
702 {
703 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
704 context->host, context->addr,
705 sequence);
706 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
707 HOST_PRINTF ("timeout");
708 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
709 HOST_PRINTF ("\n");
710 }
711 else
712 {
713 #endif
714 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
715 context->host, context->addr,
716 sequence);
717 #if USE_NCURSES
718 }
719 #endif
720 }
722 #if USE_NCURSES
723 update_stats_from_context (context);
724 wrefresh (main_win);
725 #endif
726 } /* }}} void update_host_hook */
728 static int post_loop_hook (pingobj_t *ping) /* {{{ */
729 {
730 pingobj_iter_t *iter;
732 #if USE_NCURSES
733 endwin ();
734 #endif
736 for (iter = ping_iterator_get (ping);
737 iter != NULL;
738 iter = ping_iterator_next (iter))
739 {
740 ping_context_t *context;
742 context = ping_iterator_get_context (iter);
744 printf ("\n--- %s ping statistics ---\n"
745 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
746 context->host, context->req_sent, context->req_rcvd,
747 context_get_packet_loss (context),
748 context->latency_total);
750 if (context->req_rcvd != 0)
751 {
752 double average;
753 double deviation;
755 average = context_get_average (context);
756 deviation = context_get_stddev (context);
758 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
759 context->latency_min,
760 average,
761 context->latency_max,
762 deviation);
763 }
765 ping_iterator_set_context (iter, NULL);
766 context_destroy (context);
767 }
769 return (0);
770 } /* }}} int post_loop_hook */
772 int main (int argc, char **argv) /* {{{ */
773 {
774 pingobj_t *ping;
775 pingobj_iter_t *iter;
777 struct sigaction sigint_action;
779 struct timeval tv_begin;
780 struct timeval tv_end;
781 struct timespec ts_wait;
782 struct timespec ts_int;
784 int optind;
785 int i;
786 int status;
787 #if _POSIX_SAVED_IDS
788 uid_t saved_set_uid;
790 /* Save the old effective user id */
791 saved_set_uid = geteuid ();
792 /* Set the effective user ID to the real user ID without changing the
793 * saved set-user ID */
794 status = seteuid (getuid ());
795 if (status != 0)
796 {
797 fprintf (stderr, "Temporarily dropping privileges "
798 "failed: %s\n", strerror (errno));
799 exit (EXIT_FAILURE);
800 }
801 #endif
803 optind = read_options (argc, argv);
805 #if !_POSIX_SAVED_IDS
806 /* Cannot temporarily drop privileges -> reject every file but "-". */
807 if ((opt_filename != NULL)
808 && (strcmp ("-", opt_filename) != 0)
809 && (getuid () != geteuid ()))
810 {
811 fprintf (stderr, "Your real and effective user IDs don't "
812 "match. Reading from a file (option '-f')\n"
813 "is therefore too risky. You can still read "
814 "from STDIN using '-f -' if you like.\n"
815 "Sorry.\n");
816 exit (EXIT_FAILURE);
817 }
818 #endif
820 if ((optind >= argc) && (opt_filename == NULL)) {
821 usage_exit (argv[0], 1);
822 }
824 if ((ping = ping_construct ()) == NULL)
825 {
826 fprintf (stderr, "ping_construct failed\n");
827 return (1);
828 }
830 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
831 {
832 fprintf (stderr, "Setting TTL to %i failed: %s\n",
833 opt_send_ttl, ping_get_error (ping));
834 }
836 {
837 double temp_sec;
838 double temp_nsec;
840 temp_nsec = modf (opt_interval, &temp_sec);
841 ts_int.tv_sec = (time_t) temp_sec;
842 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
844 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
845 }
847 if (opt_addrfamily != PING_DEF_AF)
848 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
850 if (opt_srcaddr != NULL)
851 {
852 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
853 {
854 fprintf (stderr, "Setting source address failed: %s\n",
855 ping_get_error (ping));
856 }
857 }
859 if (opt_device != NULL)
860 {
861 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
862 {
863 fprintf (stderr, "Setting device failed: %s\n",
864 ping_get_error (ping));
865 }
866 }
868 if (opt_filename != NULL)
869 {
870 FILE *infile;
871 char line[256];
872 char host[256];
874 if (strcmp (opt_filename, "-") == 0)
875 /* Open STDIN */
876 infile = fdopen(0, "r");
877 else
878 infile = fopen(opt_filename, "r");
880 if (infile == NULL)
881 {
882 fprintf (stderr, "Opening %s failed: %s\n",
883 (strcmp (opt_filename, "-") == 0)
884 ? "STDIN" : opt_filename,
885 strerror(errno));
886 return (1);
887 }
889 #if _POSIX_SAVED_IDS
890 /* Regain privileges */
891 status = seteuid (saved_set_uid);
892 if (status != 0)
893 {
894 fprintf (stderr, "Temporarily re-gaining privileges "
895 "failed: %s\n", strerror (errno));
896 exit (EXIT_FAILURE);
897 }
898 #endif
900 while (fgets(line, sizeof(line), infile))
901 {
902 /* Strip whitespace */
903 if (sscanf(line, "%s", host) != 1)
904 continue;
906 if ((host[0] == 0) || (host[0] == '#'))
907 continue;
909 if (ping_host_add(ping, host) < 0)
910 {
911 const char *errmsg = ping_get_error (ping);
913 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
914 continue;
915 }
916 else
917 {
918 host_num++;
919 }
920 }
922 #if _POSIX_SAVED_IDS
923 /* Drop privileges */
924 status = seteuid (getuid ());
925 if (status != 0)
926 {
927 fprintf (stderr, "Temporarily dropping privileges "
928 "failed: %s\n", strerror (errno));
929 exit (EXIT_FAILURE);
930 }
931 #endif
933 fclose(infile);
934 }
936 #if _POSIX_SAVED_IDS
937 /* Regain privileges */
938 status = seteuid (saved_set_uid);
939 if (status != 0)
940 {
941 fprintf (stderr, "Temporarily re-gaining privileges "
942 "failed: %s\n", strerror (errno));
943 exit (EXIT_FAILURE);
944 }
945 #endif
947 for (i = optind; i < argc; i++)
948 {
949 if (ping_host_add (ping, argv[i]) < 0)
950 {
951 const char *errmsg = ping_get_error (ping);
953 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
954 continue;
955 }
956 else
957 {
958 host_num++;
959 }
960 }
962 /* Permanently drop root privileges if we're setuid-root. */
963 status = setuid (getuid ());
964 if (status != 0)
965 {
966 fprintf (stderr, "Dropping privileges failed: %s\n",
967 strerror (errno));
968 exit (EXIT_FAILURE);
969 }
971 #if _POSIX_SAVED_IDS
972 saved_set_uid = (uid_t) -1;
973 #endif
975 ping_initialize_contexts (ping);
977 if (i == 0)
978 return (1);
980 memset (&sigint_action, '\0', sizeof (sigint_action));
981 sigint_action.sa_handler = sigint_handler;
982 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
983 {
984 perror ("sigaction");
985 return (1);
986 }
988 pre_loop_hook (ping);
990 while (opt_count != 0)
991 {
992 int index;
993 int status;
995 if (gettimeofday (&tv_begin, NULL) < 0)
996 {
997 perror ("gettimeofday");
998 return (1);
999 }
1001 if (ping_send (ping) < 0)
1002 {
1003 fprintf (stderr, "ping_send failed: %s\n",
1004 ping_get_error (ping));
1005 return (1);
1006 }
1008 index = 0;
1009 for (iter = ping_iterator_get (ping);
1010 iter != NULL;
1011 iter = ping_iterator_next (iter))
1012 {
1013 update_host_hook (iter, index);
1014 index++;
1015 }
1017 pre_sleep_hook (ping);
1019 /* Don't sleep in the last iteration */
1020 if (opt_count == 1)
1021 break;
1023 if (gettimeofday (&tv_end, NULL) < 0)
1024 {
1025 perror ("gettimeofday");
1026 return (1);
1027 }
1029 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1031 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1032 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1033 {
1034 if (errno != EINTR)
1035 {
1036 perror ("nanosleep");
1037 break;
1038 }
1039 else if (opt_count == 0)
1040 {
1041 /* sigint */
1042 break;
1043 }
1044 }
1046 post_sleep_hook (ping);
1048 if (opt_count > 0)
1049 opt_count--;
1050 } /* while (opt_count != 0) */
1052 post_loop_hook (ping);
1054 ping_destroy (ping);
1056 return (0);
1057 } /* }}} int main */
1059 /* vim: set fdm=marker : */