2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2010 Florian octo Forster <octo at verplant.org>
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
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.
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
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
42 #if TIME_WITH_SYS_TIME
43 # include <sys/time.h>
47 # include <sys/time.h>
54 # include <netdb.h> /* NI_MAXHOST */
62 #include <sys/types.h>
71 #ifndef _POSIX_SAVED_IDS
72 # define _POSIX_SAVED_IDS 0
75 typedef struct ping_context
77 char host[NI_MAXHOST];
78 char addr[NI_MAXHOST];
86 double latency_total_square;
93 static double opt_interval = 1.0;
94 static int opt_addrfamily = PING_DEF_AF;
95 static char *opt_srcaddr = NULL;
96 static char *opt_device = NULL;
97 static char *opt_filename = NULL;
98 static int opt_count = -1;
99 static int opt_send_ttl = 64;
102 static WINDOW *main_win = NULL;
105 static void sigint_handler (int signal)
107 /* Make compiler happy */
113 static ping_context_t *context_create (void)
117 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
120 memset (ret, '\0', sizeof (ping_context_t));
122 ret->latency_min = -1.0;
123 ret->latency_max = -1.0;
124 ret->latency_total = 0.0;
125 ret->latency_total_square = 0.0;
134 static void context_destroy (ping_context_t *context)
140 if (context->window != NULL)
142 delwin (context->window);
143 context->window = NULL;
150 static void usage_exit (const char *name, int status)
154 name_length = (int) strlen (name);
156 fprintf (stderr, "Usage: %s [OPTIONS] "
157 "-f filename | host [host [host ...]]\n"
159 "\nAvailable options:\n"
160 " -4|-6 force the use of IPv4 or IPv6\n"
161 " -c count number of ICMP packets to send\n"
162 " -i interval interval with which to send ICMP packets\n"
163 " -t ttl time to live for each ICMP packet\n"
164 " -I srcaddr source address\n"
165 " -D device outgoing interface name\n"
166 " -f filename filename to read hosts from\n"
168 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
169 "by Florian octo Forster <octo@verplant.org>\n"
170 "for contributions see `AUTHORS'\n",
175 static int read_options (int argc, char **argv)
181 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
190 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
196 new_count = atoi (optarg);
198 opt_count = new_count;
200 fprintf(stderr, "Ignoring invalid count: %s\n",
207 if (opt_filename != NULL)
209 opt_filename = strdup (optarg);
216 new_interval = atof (optarg);
217 if (new_interval < 0.001)
218 fprintf (stderr, "Ignoring invalid interval: %s\n",
221 opt_interval = new_interval;
226 if (opt_srcaddr != NULL)
228 opt_srcaddr = strdup (optarg);
239 new_send_ttl = atoi (optarg);
240 if ((new_send_ttl > 0) && (new_send_ttl < 256))
241 opt_send_ttl = new_send_ttl;
243 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
249 usage_exit (argv[0], 0);
252 usage_exit (argv[0], 1);
259 static void print_host (pingobj_iter_t *iter)
262 unsigned int sequence;
266 ping_context_t *context;
269 buffer_len = sizeof (latency);
270 ping_iterator_get_info (iter, PING_INFO_LATENCY,
271 &latency, &buffer_len);
274 buffer_len = sizeof (sequence);
275 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
276 &sequence, &buffer_len);
279 buffer_len = sizeof (recv_ttl);
280 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
281 &recv_ttl, &buffer_len);
284 ping_iterator_get_info (iter, PING_INFO_DATA,
287 context = (ping_context_t *) ping_iterator_get_context (iter);
290 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
292 # define HOST_PRINTF(...) printf(__VA_ARGS__)
299 context->latency_total += latency;
300 context->latency_total_square += (latency * latency);
302 if ((context->latency_max < 0.0) || (context->latency_max < latency))
303 context->latency_max = latency;
304 if ((context->latency_min < 0.0) || (context->latency_min > latency))
305 context->latency_min = latency;
307 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
310 context->host, context->addr,
311 sequence, recv_ttl, latency);
315 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
316 context->host, context->addr,
322 werase (context->window);
323 box (context->window, 0, 0);
324 mvwprintw (context->window, /* y = */ 0, /* x = */ 5,
325 " %s ping statistics ",
327 mvwprintw (context->window, /* y = */ 1, /* x = */ 2,
328 "%i packets transmitted, %i received, %.2f%% packet "
330 context->req_sent, context->req_rcvd,
331 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
332 context->latency_total);
333 if (context->req_rcvd != 0)
339 num_total = (double) context->req_rcvd;
341 average = context->latency_total / num_total;
342 deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
343 / (num_total * (num_total - 1.0)));
345 mvwprintw (context->window, /* y = */ 2, /* x = */ 2,
346 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
347 context->latency_min,
349 context->latency_max,
352 wrefresh (context->window);
356 static void time_normalize (struct timespec *ts)
358 while (ts->tv_nsec < 0)
367 ts->tv_nsec += 1000000000;
370 while (ts->tv_nsec >= 1000000000)
373 ts->tv_nsec -= 1000000000;
377 static void time_calc (struct timespec *ts_dest, /* {{{ */
378 const struct timespec *ts_int,
379 const struct timeval *tv_begin,
380 const struct timeval *tv_end)
382 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
383 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
384 time_normalize (ts_dest);
386 /* Assure that `(begin + interval) > end'.
387 * This may seem overly complicated, but `tv_sec' is of type `time_t'
388 * which may be `unsigned. *sigh* */
389 if ((tv_end->tv_sec > ts_dest->tv_sec)
390 || ((tv_end->tv_sec == ts_dest->tv_sec)
391 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
394 ts_dest->tv_nsec = 0;
398 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
399 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
400 time_normalize (ts_dest);
401 } /* }}} void time_calc */
403 static int print_header (pingobj_t *ping) /* {{{ */
405 pingobj_iter_t *iter;
415 for (iter = ping_iterator_get (ping);
417 iter = ping_iterator_next (iter))
419 ping_context_t *context;
422 context = context_create ();
424 buffer_size = sizeof (context->host);
425 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
427 buffer_size = sizeof (context->addr);
428 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
431 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
434 context->window = newwin (/* height = */ 4, COLS,
435 /* start y = */ 4*i, /* start x = */ 0);
436 box (context->window, 0, 0);
437 mvwprintw (context->window, /* y = */ 0, /* x = */ 5,
438 " %s ping statistics ",
440 wrefresh (context->window);
441 #else /* !USE_NCURSES */
442 printf ("PING %s (%s) %zu bytes of data.\n",
443 context->host, context->addr, buffer_size);
446 ping_iterator_set_context (iter, (void *) context);
453 main_win = newwin (LINES - 4*i, COLS, 4*i, 0);
454 scrollok (main_win, TRUE);
458 } /* }}} int print_header */
460 static int print_footer (pingobj_t *ping)
462 pingobj_iter_t *iter;
468 for (iter = ping_iterator_get (ping);
470 iter = ping_iterator_next (iter))
472 ping_context_t *context;
474 context = ping_iterator_get_context (iter);
476 printf ("\n--- %s ping statistics ---\n"
477 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
478 context->host, context->req_sent, context->req_rcvd,
479 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
480 context->latency_total);
482 if (context->req_rcvd != 0)
488 num_total = (double) context->req_rcvd;
490 average = context->latency_total / num_total;
491 deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
492 / (num_total * (num_total - 1.0)));
494 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
495 context->latency_min,
497 context->latency_max,
501 ping_iterator_set_context (iter, NULL);
502 context_destroy (context);
506 } /* }}} int print_footer */
508 int main (int argc, char **argv) /* {{{ */
511 pingobj_iter_t *iter;
513 struct sigaction sigint_action;
515 struct timeval tv_begin;
516 struct timeval tv_end;
517 struct timespec ts_wait;
518 struct timespec ts_int;
526 /* Save the old effective user id */
527 saved_set_uid = geteuid ();
528 /* Set the effective user ID to the real user ID without changing the
529 * saved set-user ID */
530 status = seteuid (getuid ());
533 fprintf (stderr, "Temporarily dropping privileges "
534 "failed: %s\n", strerror (errno));
539 optind = read_options (argc, argv);
541 #if !_POSIX_SAVED_IDS
542 /* Cannot temporarily drop privileges -> reject every file but "-". */
543 if ((opt_filename != NULL)
544 && (strcmp ("-", opt_filename) != 0)
545 && (getuid () != geteuid ()))
547 fprintf (stderr, "Your real and effective user IDs don't "
548 "match. Reading from a file (option '-f')\n"
549 "is therefore too risky. You can still read "
550 "from STDIN using '-f -' if you like.\n"
556 if ((optind >= argc) && (opt_filename == NULL)) {
557 usage_exit (argv[0], 1);
560 if ((ping = ping_construct ()) == NULL)
562 fprintf (stderr, "ping_construct failed\n");
566 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
568 fprintf (stderr, "Setting TTL to %i failed: %s\n",
569 opt_send_ttl, ping_get_error (ping));
576 temp_nsec = modf (opt_interval, &temp_sec);
577 ts_int.tv_sec = (time_t) temp_sec;
578 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
580 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
583 if (opt_addrfamily != PING_DEF_AF)
584 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
586 if (opt_srcaddr != NULL)
588 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
590 fprintf (stderr, "Setting source address failed: %s\n",
591 ping_get_error (ping));
595 if (opt_device != NULL)
597 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
599 fprintf (stderr, "Setting device failed: %s\n",
600 ping_get_error (ping));
604 if (opt_filename != NULL)
610 if (strcmp (opt_filename, "-") == 0)
612 infile = fdopen(0, "r");
614 infile = fopen(opt_filename, "r");
618 fprintf (stderr, "Opening %s failed: %s\n",
619 (strcmp (opt_filename, "-") == 0)
620 ? "STDIN" : opt_filename,
626 /* Regain privileges */
627 status = seteuid (saved_set_uid);
630 fprintf (stderr, "Temporarily re-gaining privileges "
631 "failed: %s\n", strerror (errno));
636 while (fgets(line, sizeof(line), infile))
638 /* Strip whitespace */
639 if (sscanf(line, "%s", host) != 1)
642 if ((host[0] == 0) || (host[0] == '#'))
645 if (ping_host_add(ping, host) < 0)
647 const char *errmsg = ping_get_error (ping);
649 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
655 /* Drop privileges */
656 status = seteuid (getuid ());
659 fprintf (stderr, "Temporarily dropping privileges "
660 "failed: %s\n", strerror (errno));
669 /* Regain privileges */
670 status = seteuid (saved_set_uid);
673 fprintf (stderr, "Temporarily re-gaining privileges "
674 "failed: %s\n", strerror (errno));
679 for (i = optind; i < argc; i++)
681 if (ping_host_add (ping, argv[i]) < 0)
683 const char *errmsg = ping_get_error (ping);
685 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
690 /* Permanently drop root privileges if we're setuid-root. */
691 status = setuid (getuid ());
694 fprintf (stderr, "Dropping privileges failed: %s\n",
700 saved_set_uid = (uid_t) -1;
708 memset (&sigint_action, '\0', sizeof (sigint_action));
709 sigint_action.sa_handler = sigint_handler;
710 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
712 perror ("sigaction");
716 while (opt_count != 0)
720 if (gettimeofday (&tv_begin, NULL) < 0)
722 perror ("gettimeofday");
726 if (ping_send (ping) < 0)
728 fprintf (stderr, "ping_send failed: %s\n",
729 ping_get_error (ping));
733 for (iter = ping_iterator_get (ping);
735 iter = ping_iterator_next (iter))
741 /* Don't sleep in the last iteration */
745 if (gettimeofday (&tv_end, NULL) < 0)
747 perror ("gettimeofday");
751 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
753 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
754 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
758 perror ("nanosleep");
761 else if (opt_count == 0)
770 } /* while (opt_count != 0) */
779 /* vim: set fdm=marker : */