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 */
111 } /* }}} void sigint_handler */
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 double context_get_average (ping_context_t *ctx) /* {{{ */
157 if (ctx->req_rcvd < 1)
160 num_total = (double) ctx->req_rcvd;
161 return (ctx->latency_total / num_total);
162 } /* }}} double context_get_average */
164 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
171 if (ctx->req_rcvd < 1)
173 else if (ctx->req_rcvd < 2)
176 num_total = (double) ctx->req_rcvd;
177 return (sqrt (((num_total * ctx->latency_total_square)
178 - (ctx->latency_total * ctx->latency_total))
179 / (num_total * (num_total - 1.0))));
180 } /* }}} double context_get_stddev */
182 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
187 if (ctx->req_sent < 1)
190 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
191 / ((double) ctx->req_sent));
192 } /* }}} double context_get_packet_loss */
194 static void usage_exit (const char *name, int status)
198 name_length = (int) strlen (name);
200 fprintf (stderr, "Usage: %s [OPTIONS] "
201 "-f filename | host [host [host ...]]\n"
203 "\nAvailable options:\n"
204 " -4|-6 force the use of IPv4 or IPv6\n"
205 " -c count number of ICMP packets to send\n"
206 " -i interval interval with which to send ICMP packets\n"
207 " -t ttl time to live for each ICMP packet\n"
208 " -I srcaddr source address\n"
209 " -D device outgoing interface name\n"
210 " -f filename filename to read hosts from\n"
212 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
213 "by Florian octo Forster <octo@verplant.org>\n"
214 "for contributions see `AUTHORS'\n",
219 static int read_options (int argc, char **argv) /* {{{ */
225 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
234 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
240 new_count = atoi (optarg);
242 opt_count = new_count;
244 fprintf(stderr, "Ignoring invalid count: %s\n",
251 if (opt_filename != NULL)
253 opt_filename = strdup (optarg);
260 new_interval = atof (optarg);
261 if (new_interval < 0.001)
262 fprintf (stderr, "Ignoring invalid interval: %s\n",
265 opt_interval = new_interval;
270 if (opt_srcaddr != NULL)
272 opt_srcaddr = strdup (optarg);
283 new_send_ttl = atoi (optarg);
284 if ((new_send_ttl > 0) && (new_send_ttl < 256))
285 opt_send_ttl = new_send_ttl;
287 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
293 usage_exit (argv[0], 0);
296 usage_exit (argv[0], 1);
301 } /* }}} read_options */
303 static void time_normalize (struct timespec *ts) /* {{{ */
305 while (ts->tv_nsec < 0)
314 ts->tv_nsec += 1000000000;
317 while (ts->tv_nsec >= 1000000000)
320 ts->tv_nsec -= 1000000000;
322 } /* }}} void time_normalize */
324 static void time_calc (struct timespec *ts_dest, /* {{{ */
325 const struct timespec *ts_int,
326 const struct timeval *tv_begin,
327 const struct timeval *tv_end)
329 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
330 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
331 time_normalize (ts_dest);
333 /* Assure that `(begin + interval) > end'.
334 * This may seem overly complicated, but `tv_sec' is of type `time_t'
335 * which may be `unsigned. *sigh* */
336 if ((tv_end->tv_sec > ts_dest->tv_sec)
337 || ((tv_end->tv_sec == ts_dest->tv_sec)
338 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
341 ts_dest->tv_nsec = 0;
345 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
346 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
347 time_normalize (ts_dest);
348 } /* }}} void time_calc */
351 static int context_window_repaint (ping_context_t *ctx, /* {{{ */
357 if (ctx->window == NULL)
359 ctx->window = newwin (/* height = */ 4, /* width = */ 0,
360 /* start y = */ 4 * index, /* start x = */ 0);
362 else /* if (ctx->window != NULL) */
364 werase (ctx->window);
367 box (ctx->window, 0, 0);
368 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
369 " %s ping statistics ",
371 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
372 "%i packets transmitted, %i received, %.2f%% packet "
374 ctx->req_sent, ctx->req_rcvd,
375 context_get_packet_loss (ctx),
377 if (ctx->req_rcvd != 0)
382 average = context_get_average (ctx);
383 deviation = context_get_stddev (ctx);
385 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
386 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
393 wrefresh (ctx->window);
396 } /* }}} int context_window_repaint */
398 static int resize_windows (pingobj_t *ping) /* {{{ */
401 pingobj_iter_t *iter;
408 int key = wgetch (stdscr);
411 else if (key == KEY_RESIZE)
418 getmaxyx (stdscr, height, width);
419 if ((height < 1) || (width < 1))
423 for (iter = ping_iterator_get (ping);
425 iter = ping_iterator_next (iter))
427 ping_context_t *ctx = ping_iterator_get_context (iter);
429 if (ctx->window == NULL)
435 wresize (ctx->window, 4, width);
436 context_window_repaint (ctx, index);
441 if (main_win != NULL)
443 wresize (main_win, height - (4 * index), width);
444 /* touchwin (main_win); */
445 /* wrefresh (main_win); */
446 clearok (main_win, TRUE);
450 } /* }}} int resize_windows */
453 static void print_host (pingobj_iter_t *iter, /* {{{ */
457 unsigned int sequence;
461 ping_context_t *context;
464 buffer_len = sizeof (latency);
465 ping_iterator_get_info (iter, PING_INFO_LATENCY,
466 &latency, &buffer_len);
469 buffer_len = sizeof (sequence);
470 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
471 &sequence, &buffer_len);
474 buffer_len = sizeof (recv_ttl);
475 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
476 &recv_ttl, &buffer_len);
479 ping_iterator_get_info (iter, PING_INFO_DATA,
482 context = (ping_context_t *) ping_iterator_get_context (iter);
485 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
487 # define HOST_PRINTF(...) printf(__VA_ARGS__)
494 context->latency_total += latency;
495 context->latency_total_square += (latency * latency);
497 if ((context->latency_max < 0.0) || (context->latency_max < latency))
498 context->latency_max = latency;
499 if ((context->latency_min < 0.0) || (context->latency_min > latency))
500 context->latency_min = latency;
502 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
505 context->host, context->addr,
506 sequence, recv_ttl, latency);
510 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
511 context->host, context->addr,
516 context_window_repaint (context, index);
519 } /* }}} void print_host */
521 static int print_header (pingobj_t *ping) /* {{{ */
523 pingobj_iter_t *iter;
530 nodelay (stdscr, TRUE);
534 for (iter = ping_iterator_get (ping);
536 iter = ping_iterator_next (iter))
538 ping_context_t *context;
541 context = context_create ();
543 buffer_size = sizeof (context->host);
544 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
546 buffer_size = sizeof (context->addr);
547 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
550 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
553 context_window_repaint (context, index);
554 #else /* !USE_NCURSES */
555 printf ("PING %s (%s) %zu bytes of data.\n",
556 context->host, context->addr, buffer_size);
559 ping_iterator_set_context (iter, (void *) context);
565 main_win = newwin (/* height = */ 0, /* width = */ 0,
566 /* y = */ 4 * index, /* x = */ 0);
567 /* Allow scrolling */
568 scrollok (main_win, TRUE);
569 /* Allow hardware accelerated scrolling. */
570 idlok (main_win, TRUE);
572 /* Don't know what good this does exactly, but without this code
573 * "resize_windows" will be called right after startup and *somehow*
574 * this leads to display errors. If we purge all initial characters
575 * here, the problem goes away. "wgetch" is non-blocking due to
576 * "nodelay" (see above). */
577 while (wgetch (stdscr) != ERR)
579 /* eat up characters */;
584 } /* }}} int print_header */
586 static int print_footer (pingobj_t *ping) /* {{{ */
588 pingobj_iter_t *iter;
594 for (iter = ping_iterator_get (ping);
596 iter = ping_iterator_next (iter))
598 ping_context_t *context;
600 context = ping_iterator_get_context (iter);
602 printf ("\n--- %s ping statistics ---\n"
603 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
604 context->host, context->req_sent, context->req_rcvd,
605 context_get_packet_loss (context),
606 context->latency_total);
608 if (context->req_rcvd != 0)
613 average = context_get_average (context);
614 deviation = context_get_stddev (context);
616 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
617 context->latency_min,
619 context->latency_max,
623 ping_iterator_set_context (iter, NULL);
624 context_destroy (context);
628 } /* }}} int print_footer */
630 int main (int argc, char **argv) /* {{{ */
633 pingobj_iter_t *iter;
635 struct sigaction sigint_action;
637 struct timeval tv_begin;
638 struct timeval tv_end;
639 struct timespec ts_wait;
640 struct timespec ts_int;
648 /* Save the old effective user id */
649 saved_set_uid = geteuid ();
650 /* Set the effective user ID to the real user ID without changing the
651 * saved set-user ID */
652 status = seteuid (getuid ());
655 fprintf (stderr, "Temporarily dropping privileges "
656 "failed: %s\n", strerror (errno));
661 optind = read_options (argc, argv);
663 #if !_POSIX_SAVED_IDS
664 /* Cannot temporarily drop privileges -> reject every file but "-". */
665 if ((opt_filename != NULL)
666 && (strcmp ("-", opt_filename) != 0)
667 && (getuid () != geteuid ()))
669 fprintf (stderr, "Your real and effective user IDs don't "
670 "match. Reading from a file (option '-f')\n"
671 "is therefore too risky. You can still read "
672 "from STDIN using '-f -' if you like.\n"
678 if ((optind >= argc) && (opt_filename == NULL)) {
679 usage_exit (argv[0], 1);
682 if ((ping = ping_construct ()) == NULL)
684 fprintf (stderr, "ping_construct failed\n");
688 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
690 fprintf (stderr, "Setting TTL to %i failed: %s\n",
691 opt_send_ttl, ping_get_error (ping));
698 temp_nsec = modf (opt_interval, &temp_sec);
699 ts_int.tv_sec = (time_t) temp_sec;
700 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
702 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
705 if (opt_addrfamily != PING_DEF_AF)
706 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
708 if (opt_srcaddr != NULL)
710 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
712 fprintf (stderr, "Setting source address failed: %s\n",
713 ping_get_error (ping));
717 if (opt_device != NULL)
719 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
721 fprintf (stderr, "Setting device failed: %s\n",
722 ping_get_error (ping));
726 if (opt_filename != NULL)
732 if (strcmp (opt_filename, "-") == 0)
734 infile = fdopen(0, "r");
736 infile = fopen(opt_filename, "r");
740 fprintf (stderr, "Opening %s failed: %s\n",
741 (strcmp (opt_filename, "-") == 0)
742 ? "STDIN" : opt_filename,
748 /* Regain privileges */
749 status = seteuid (saved_set_uid);
752 fprintf (stderr, "Temporarily re-gaining privileges "
753 "failed: %s\n", strerror (errno));
758 while (fgets(line, sizeof(line), infile))
760 /* Strip whitespace */
761 if (sscanf(line, "%s", host) != 1)
764 if ((host[0] == 0) || (host[0] == '#'))
767 if (ping_host_add(ping, host) < 0)
769 const char *errmsg = ping_get_error (ping);
771 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
777 /* Drop privileges */
778 status = seteuid (getuid ());
781 fprintf (stderr, "Temporarily dropping privileges "
782 "failed: %s\n", strerror (errno));
791 /* Regain privileges */
792 status = seteuid (saved_set_uid);
795 fprintf (stderr, "Temporarily re-gaining privileges "
796 "failed: %s\n", strerror (errno));
801 for (i = optind; i < argc; i++)
803 if (ping_host_add (ping, argv[i]) < 0)
805 const char *errmsg = ping_get_error (ping);
807 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
812 /* Permanently drop root privileges if we're setuid-root. */
813 status = setuid (getuid ());
816 fprintf (stderr, "Dropping privileges failed: %s\n",
822 saved_set_uid = (uid_t) -1;
830 memset (&sigint_action, '\0', sizeof (sigint_action));
831 sigint_action.sa_handler = sigint_handler;
832 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
834 perror ("sigaction");
838 while (opt_count != 0)
843 if (gettimeofday (&tv_begin, NULL) < 0)
845 perror ("gettimeofday");
849 if (ping_send (ping) < 0)
851 fprintf (stderr, "ping_send failed: %s\n",
852 ping_get_error (ping));
857 for (iter = ping_iterator_get (ping);
859 iter = ping_iterator_next (iter))
861 print_host (iter, index);
868 /* Don't sleep in the last iteration */
872 if (gettimeofday (&tv_end, NULL) < 0)
874 perror ("gettimeofday");
878 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
880 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
881 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
885 perror ("nanosleep");
888 else if (opt_count == 0)
895 resize_windows (ping);
900 resize_windows (ping);
905 } /* while (opt_count != 0) */
914 /* vim: set fdm=marker : */