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 <stdint.h>
29 # include <inttypes.h>
30 # include <errno.h>
31 # include <assert.h>
32 #else
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
40 #if HAVE_MATH_H
41 # include <math.h>
42 #endif
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
46 # include <time.h>
47 #else
48 # if HAVE_SYS_TIME_H
49 # include <sys/time.h>
50 # else
51 # include <time.h>
52 # endif
53 #endif
55 #if HAVE_SYS_SOCKET_H
56 # include <sys/socket.h>
57 #endif
58 #if HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #if HAVE_NETINET_IP_H
62 # include <netinet/ip.h>
63 #endif
65 #if HAVE_NETDB_H
66 # include <netdb.h> /* NI_MAXHOST */
67 #endif
69 #if HAVE_SIGNAL_H
70 # include <signal.h>
71 #endif
73 #if HAVE_SYS_TYPES_H
74 #include <sys/types.h>
75 #endif
77 #if USE_NCURSES
78 # define NCURSES_OPAQUE 1
79 # include <ncurses.h>
81 # define OPING_GREEN 1
82 # define OPING_YELLOW 2
83 # define OPING_RED 3
84 #endif
86 #include "oping.h"
88 #ifndef _POSIX_SAVED_IDS
89 # define _POSIX_SAVED_IDS 0
90 #endif
92 typedef struct ping_context
93 {
94 char host[NI_MAXHOST];
95 char addr[NI_MAXHOST];
97 int index;
98 int req_sent;
99 int req_rcvd;
101 double latency_min;
102 double latency_max;
103 double latency_total;
104 double latency_total_square;
106 #if USE_NCURSES
107 WINDOW *window;
108 #endif
109 } ping_context_t;
111 static double opt_interval = 1.0;
112 static int opt_addrfamily = PING_DEF_AF;
113 static char *opt_srcaddr = NULL;
114 static char *opt_device = NULL;
115 static char *opt_filename = NULL;
116 static int opt_count = -1;
117 static int opt_send_ttl = 64;
118 static uint8_t opt_send_qos = 0;
120 static int host_num = 0;
122 #if USE_NCURSES
123 static WINDOW *main_win = NULL;
124 #endif
126 static void sigint_handler (int signal) /* {{{ */
127 {
128 /* Make compiler happy */
129 signal = 0;
130 /* Exit the loop */
131 opt_count = 0;
132 } /* }}} void sigint_handler */
134 static ping_context_t *context_create (void) /* {{{ */
135 {
136 ping_context_t *ret;
138 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
139 return (NULL);
141 memset (ret, '\0', sizeof (ping_context_t));
143 ret->latency_min = -1.0;
144 ret->latency_max = -1.0;
145 ret->latency_total = 0.0;
146 ret->latency_total_square = 0.0;
148 #if USE_NCURSES
149 ret->window = NULL;
150 #endif
152 return (ret);
153 } /* }}} ping_context_t *context_create */
155 static void context_destroy (ping_context_t *context) /* {{{ */
156 {
157 if (context == NULL)
158 return;
160 #if USE_NCURSES
161 if (context->window != NULL)
162 {
163 delwin (context->window);
164 context->window = NULL;
165 }
166 #endif
168 free (context);
169 } /* }}} void context_destroy */
171 static double context_get_average (ping_context_t *ctx) /* {{{ */
172 {
173 double num_total;
175 if (ctx == NULL)
176 return (-1.0);
178 if (ctx->req_rcvd < 1)
179 return (-0.0);
181 num_total = (double) ctx->req_rcvd;
182 return (ctx->latency_total / num_total);
183 } /* }}} double context_get_average */
185 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
186 {
187 double num_total;
189 if (ctx == NULL)
190 return (-1.0);
192 if (ctx->req_rcvd < 1)
193 return (-0.0);
194 else if (ctx->req_rcvd < 2)
195 return (0.0);
197 num_total = (double) ctx->req_rcvd;
198 return (sqrt (((num_total * ctx->latency_total_square)
199 - (ctx->latency_total * ctx->latency_total))
200 / (num_total * (num_total - 1.0))));
201 } /* }}} double context_get_stddev */
203 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
204 {
205 if (ctx == NULL)
206 return (-1.0);
208 if (ctx->req_sent < 1)
209 return (0.0);
211 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
212 / ((double) ctx->req_sent));
213 } /* }}} double context_get_packet_loss */
215 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
216 {
217 pingobj_iter_t *iter;
218 int index;
220 if (ping == NULL)
221 return (EINVAL);
223 index = 0;
224 for (iter = ping_iterator_get (ping);
225 iter != NULL;
226 iter = ping_iterator_next (iter))
227 {
228 ping_context_t *context;
229 size_t buffer_size;
231 context = context_create ();
232 context->index = index;
234 buffer_size = sizeof (context->host);
235 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
237 buffer_size = sizeof (context->addr);
238 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
240 ping_iterator_set_context (iter, (void *) context);
242 index++;
243 }
245 return (0);
246 } /* }}} int ping_initialize_contexts */
248 static void usage_exit (const char *name, int status) /* {{{ */
249 {
250 fprintf (stderr, "Usage: %s [OPTIONS] "
251 "-f filename | host [host [host ...]]\n"
253 "\nAvailable options:\n"
254 " -4|-6 force the use of IPv4 or IPv6\n"
255 " -c count number of ICMP packets to send\n"
256 " -i interval interval with which to send ICMP packets\n"
257 " -t ttl time to live for each ICMP packet\n"
258 " -Q qos Quality of Service (QoS) of outgoing packets\n"
259 " Use \"-Q help\" for a list of valid options.\n"
260 " -I srcaddr source address\n"
261 " -D device outgoing interface name\n"
262 " -f filename filename to read hosts from\n"
264 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
265 "by Florian octo Forster <octo@verplant.org>\n"
266 "for contributions see `AUTHORS'\n",
267 name);
268 exit (status);
269 } /* }}} void usage_exit */
271 static void usage_qos_exit (const char *arg, int status) /* {{{ */
272 {
273 if (arg != 0)
274 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
276 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
277 "\n"
278 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
279 "\n"
280 " be Best Effort (BE, default PHB).\n"
281 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
282 " (low delay, low loss, low jitter)\n"
283 " va Voice Admit (VA) DSCP (RFC 5865).\n"
284 " (capacity-admitted traffic)\n"
285 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
286 " For example: \"af12\" (class 1, precedence 2)\n"
287 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
288 " For example: \"cs1\" (priority traffic)\n"
289 "\n"
290 " Type of Service (IPv4, RFC 1349, obsolete)\n"
291 "\n"
292 " lowdelay (%#04x) minimize delay\n"
293 " throughput (%#04x) maximize throughput\n"
294 " reliability (%#04x) maximize reliability\n"
295 " mincost (%#04x) minimize monetary cost\n"
296 "\n"
297 " Specify manually\n"
298 "\n"
299 " 0x00 - 0xff Hexadecimal numeric specification.\n"
300 " 0 - 255 Decimal numeric specification.\n"
301 "\n",
302 (unsigned int) IPTOS_LOWDELAY,
303 (unsigned int) IPTOS_THROUGHPUT,
304 (unsigned int) IPTOS_RELIABILITY,
305 (unsigned int) IPTOS_MINCOST);
307 exit (status);
308 } /* }}} void usage_qos_exit */
310 static int set_opt_send_qos (const char *opt) /* {{{ */
311 {
312 if (opt == NULL)
313 return (EINVAL);
315 if (strcasecmp ("help", opt) == 0)
316 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
317 /* DiffServ (RFC 2474): */
318 /* - Best effort (BE) */
319 else if (strcasecmp ("be", opt) == 0)
320 opt_send_qos = 0;
321 /* - Expedited Forwarding (EF, RFC 3246) */
322 else if (strcasecmp ("ef", opt) == 0)
323 opt_send_qos = 0xB8; /* == 0x2E << 2 */
324 /* - Voice Admit (VA, RFC 5865) */
325 else if (strcasecmp ("va", opt) == 0)
326 opt_send_qos = 0xB0; /* == 0x2D << 2 */
327 /* - Assured Forwarding (AF, RFC 2597) */
328 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
329 && (strlen (opt) == 4))
330 {
331 uint8_t dscp;
332 uint8_t class;
333 uint8_t prec;
335 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
336 if (opt[2] == '1')
337 class = 1;
338 else if (opt[2] == '2')
339 class = 2;
340 else if (opt[2] == '3')
341 class = 3;
342 else if (opt[2] == '4')
343 class = 4;
344 else
345 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
347 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
348 if (opt[3] == '1')
349 prec = 1;
350 else if (opt[3] == '2')
351 prec = 2;
352 else if (opt[3] == '3')
353 prec = 3;
354 else
355 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
357 dscp = (8 * class) + (2 * prec);
358 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
359 opt_send_qos = dscp << 2;
360 }
361 /* - Class Selector (CS) */
362 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
363 && (strlen (opt) == 3))
364 {
365 uint8_t class;
367 if ((opt[2] < '0') || (opt[2] > '7'))
368 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
370 /* Not exactly legal by the C standard, but I don't know of any
371 * system not supporting this hack. */
372 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
373 opt_send_qos = class << 5;
374 }
375 /* Type of Service (RFC 1349) */
376 else if (strcasecmp ("lowdelay", opt) == 0)
377 opt_send_qos = IPTOS_LOWDELAY;
378 else if (strcasecmp ("throughput", opt) == 0)
379 opt_send_qos = IPTOS_THROUGHPUT;
380 else if (strcasecmp ("reliability", opt) == 0)
381 opt_send_qos = IPTOS_RELIABILITY;
382 else if (strcasecmp ("mincost", opt) == 0)
383 opt_send_qos = IPTOS_MINCOST;
384 /* Numeric value */
385 else
386 {
387 unsigned long value;
388 char *endptr;
390 errno = 0;
391 endptr = NULL;
392 value = strtoul (opt, &endptr, /* base = */ 0);
393 if ((errno != 0) || (endptr == opt)
394 || (endptr == NULL) || (*endptr != 0)
395 || (value > 0xff))
396 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
398 opt_send_qos = (uint8_t) value;
399 }
401 return (0);
402 } /* }}} int set_opt_send_qos */
404 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
405 {
406 uint8_t dscp;
407 uint8_t ecn;
408 char *dscp_str;
409 char *ecn_str;
411 dscp = qos >> 2;
412 ecn = qos & 0x03;
414 switch (dscp)
415 {
416 case 0x00: dscp_str = "be"; break;
417 case 0x2e: dscp_str = "ef"; break;
418 case 0x2d: dscp_str = "va"; break;
419 case 0x0a: dscp_str = "af11"; break;
420 case 0x0c: dscp_str = "af12"; break;
421 case 0x0e: dscp_str = "af13"; break;
422 case 0x12: dscp_str = "af21"; break;
423 case 0x14: dscp_str = "af22"; break;
424 case 0x16: dscp_str = "af23"; break;
425 case 0x1a: dscp_str = "af31"; break;
426 case 0x1c: dscp_str = "af32"; break;
427 case 0x1e: dscp_str = "af33"; break;
428 case 0x22: dscp_str = "af41"; break;
429 case 0x24: dscp_str = "af42"; break;
430 case 0x26: dscp_str = "af43"; break;
431 case 0x08: dscp_str = "cs1"; break;
432 case 0x10: dscp_str = "cs2"; break;
433 case 0x18: dscp_str = "cs3"; break;
434 case 0x20: dscp_str = "cs4"; break;
435 case 0x28: dscp_str = "cs5"; break;
436 case 0x30: dscp_str = "cs6"; break;
437 case 0x38: dscp_str = "cs7"; break;
438 default: dscp_str = NULL;
439 }
441 switch (ecn)
442 {
443 case 0x01: ecn_str = ",ecn(1)"; break;
444 case 0x02: ecn_str = ",ecn(0)"; break;
445 case 0x03: ecn_str = ",ce"; break;
446 default: ecn_str = "";
447 }
449 if (dscp_str == NULL)
450 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
451 else
452 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
453 buffer[buffer_size - 1] = 0;
455 return (buffer);
456 } /* }}} char *format_qos */
458 static int read_options (int argc, char **argv) /* {{{ */
459 {
460 int optchar;
462 while (1)
463 {
464 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
466 if (optchar == -1)
467 break;
469 switch (optchar)
470 {
471 case '4':
472 case '6':
473 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
474 break;
476 case 'c':
477 {
478 int new_count;
479 new_count = atoi (optarg);
480 if (new_count > 0)
481 opt_count = new_count;
482 else
483 fprintf(stderr, "Ignoring invalid count: %s\n",
484 optarg);
485 }
486 break;
488 case 'f':
489 {
490 if (opt_filename != NULL)
491 free (opt_filename);
492 opt_filename = strdup (optarg);
493 }
494 break;
496 case 'i':
497 {
498 double new_interval;
499 new_interval = atof (optarg);
500 if (new_interval < 0.001)
501 fprintf (stderr, "Ignoring invalid interval: %s\n",
502 optarg);
503 else
504 opt_interval = new_interval;
505 }
506 break;
507 case 'I':
508 {
509 if (opt_srcaddr != NULL)
510 free (opt_srcaddr);
511 opt_srcaddr = strdup (optarg);
512 }
513 break;
515 case 'D':
516 opt_device = optarg;
517 break;
519 case 't':
520 {
521 int new_send_ttl;
522 new_send_ttl = atoi (optarg);
523 if ((new_send_ttl > 0) && (new_send_ttl < 256))
524 opt_send_ttl = new_send_ttl;
525 else
526 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
527 optarg);
528 break;
529 }
531 case 'Q':
532 set_opt_send_qos (optarg);
533 break;
535 case 'h':
536 usage_exit (argv[0], 0);
537 break;
538 default:
539 usage_exit (argv[0], 1);
540 }
541 }
543 return (optind);
544 } /* }}} read_options */
546 static void time_normalize (struct timespec *ts) /* {{{ */
547 {
548 while (ts->tv_nsec < 0)
549 {
550 if (ts->tv_sec == 0)
551 {
552 ts->tv_nsec = 0;
553 return;
554 }
556 ts->tv_sec -= 1;
557 ts->tv_nsec += 1000000000;
558 }
560 while (ts->tv_nsec >= 1000000000)
561 {
562 ts->tv_sec += 1;
563 ts->tv_nsec -= 1000000000;
564 }
565 } /* }}} void time_normalize */
567 static void time_calc (struct timespec *ts_dest, /* {{{ */
568 const struct timespec *ts_int,
569 const struct timeval *tv_begin,
570 const struct timeval *tv_end)
571 {
572 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
573 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
574 time_normalize (ts_dest);
576 /* Assure that `(begin + interval) > end'.
577 * This may seem overly complicated, but `tv_sec' is of type `time_t'
578 * which may be `unsigned. *sigh* */
579 if ((tv_end->tv_sec > ts_dest->tv_sec)
580 || ((tv_end->tv_sec == ts_dest->tv_sec)
581 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
582 {
583 ts_dest->tv_sec = 0;
584 ts_dest->tv_nsec = 0;
585 return;
586 }
588 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
589 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
590 time_normalize (ts_dest);
591 } /* }}} void time_calc */
593 #if USE_NCURSES
594 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
595 {
596 if ((ctx == NULL) || (ctx->window == NULL))
597 return (EINVAL);
599 werase (ctx->window);
601 box (ctx->window, 0, 0);
602 wattron (ctx->window, A_BOLD);
603 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
604 " %s ", ctx->host);
605 wattroff (ctx->window, A_BOLD);
606 wprintw (ctx->window, "ping statistics ");
607 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
608 "%i packets transmitted, %i received, %.2f%% packet "
609 "loss, time %.1fms",
610 ctx->req_sent, ctx->req_rcvd,
611 context_get_packet_loss (ctx),
612 ctx->latency_total);
613 if (ctx->req_rcvd != 0)
614 {
615 double average;
616 double deviation;
618 average = context_get_average (ctx);
619 deviation = context_get_stddev (ctx);
621 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
622 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
623 ctx->latency_min,
624 average,
625 ctx->latency_max,
626 deviation);
627 }
629 wrefresh (ctx->window);
631 return (0);
632 } /* }}} int update_stats_from_context */
634 static int on_resize (pingobj_t *ping) /* {{{ */
635 {
636 pingobj_iter_t *iter;
637 int width = 0;
638 int height = 0;
639 int main_win_height;
641 getmaxyx (stdscr, height, width);
642 if ((height < 1) || (width < 1))
643 return (EINVAL);
645 main_win_height = height - (4 * host_num);
646 wresize (main_win, main_win_height, /* width = */ width);
647 /* Allow scrolling */
648 scrollok (main_win, TRUE);
649 /* wsetscrreg (main_win, 0, main_win_height - 1); */
650 /* Allow hardware accelerated scrolling. */
651 idlok (main_win, TRUE);
652 wrefresh (main_win);
654 for (iter = ping_iterator_get (ping);
655 iter != NULL;
656 iter = ping_iterator_next (iter))
657 {
658 ping_context_t *context;
660 context = ping_iterator_get_context (iter);
661 if (context == NULL)
662 continue;
664 if (context->window != NULL)
665 {
666 delwin (context->window);
667 context->window = NULL;
668 }
669 context->window = newwin (/* height = */ 4,
670 /* width = */ 0,
671 /* y = */ main_win_height + (4 * context->index),
672 /* x = */ 0);
673 }
675 return (0);
676 } /* }}} */
678 static int check_resize (pingobj_t *ping) /* {{{ */
679 {
680 int need_resize = 0;
682 while (42)
683 {
684 int key = wgetch (stdscr);
685 if (key == ERR)
686 break;
687 else if (key == KEY_RESIZE)
688 need_resize = 1;
689 }
691 if (need_resize)
692 return (on_resize (ping));
693 else
694 return (0);
695 } /* }}} int check_resize */
697 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
698 {
699 pingobj_iter_t *iter;
700 int width = 0;
701 int height = 0;
702 int main_win_height;
704 initscr ();
705 cbreak ();
706 noecho ();
707 nodelay (stdscr, TRUE);
709 getmaxyx (stdscr, height, width);
710 if ((height < 1) || (width < 1))
711 return (EINVAL);
713 if (has_colors () == TRUE)
714 {
715 start_color ();
716 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
717 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
718 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
719 }
721 main_win_height = height - (4 * host_num);
722 main_win = newwin (/* height = */ main_win_height,
723 /* width = */ 0,
724 /* y = */ 0, /* x = */ 0);
725 /* Allow scrolling */
726 scrollok (main_win, TRUE);
727 /* wsetscrreg (main_win, 0, main_win_height - 1); */
728 /* Allow hardware accelerated scrolling. */
729 idlok (main_win, TRUE);
730 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
731 wrefresh (main_win);
733 for (iter = ping_iterator_get (ping);
734 iter != NULL;
735 iter = ping_iterator_next (iter))
736 {
737 ping_context_t *context;
739 context = ping_iterator_get_context (iter);
740 if (context == NULL)
741 continue;
743 if (context->window != NULL)
744 {
745 delwin (context->window);
746 context->window = NULL;
747 }
748 context->window = newwin (/* height = */ 4,
749 /* width = */ 0,
750 /* y = */ main_win_height + (4 * context->index),
751 /* x = */ 0);
752 }
755 /* Don't know what good this does exactly, but without this code
756 * "check_resize" will be called right after startup and *somehow*
757 * this leads to display errors. If we purge all initial characters
758 * here, the problem goes away. "wgetch" is non-blocking due to
759 * "nodelay" (see above). */
760 while (wgetch (stdscr) != ERR)
761 {
762 /* eat up characters */;
763 }
765 return (0);
766 } /* }}} int pre_loop_hook */
768 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
769 {
770 return (check_resize (ping));
771 } /* }}} int pre_sleep_hook */
773 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
774 {
775 return (check_resize (ping));
776 } /* }}} int pre_sleep_hook */
777 #else /* if !USE_NCURSES */
778 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
779 {
780 pingobj_iter_t *iter;
782 for (iter = ping_iterator_get (ping);
783 iter != NULL;
784 iter = ping_iterator_next (iter))
785 {
786 ping_context_t *ctx;
787 size_t buffer_size;
789 ctx = ping_iterator_get_context (iter);
790 if (ctx == NULL)
791 continue;
793 buffer_size = 0;
794 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
796 printf ("PING %s (%s) %zu bytes of data.\n",
797 ctx->host, ctx->addr, buffer_size);
798 }
800 return (0);
801 } /* }}} int pre_loop_hook */
803 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
804 {
805 fflush (stdout);
807 return (0);
808 } /* }}} int pre_sleep_hook */
810 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
811 {
812 return (0);
813 } /* }}} int post_sleep_hook */
814 #endif
816 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
817 int index)
818 {
819 double latency;
820 unsigned int sequence;
821 int recv_ttl;
822 uint8_t recv_qos;
823 char recv_qos_str[16];
824 size_t buffer_len;
825 size_t data_len;
826 ping_context_t *context;
828 latency = -1.0;
829 buffer_len = sizeof (latency);
830 ping_iterator_get_info (iter, PING_INFO_LATENCY,
831 &latency, &buffer_len);
833 sequence = 0;
834 buffer_len = sizeof (sequence);
835 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
836 &sequence, &buffer_len);
838 recv_ttl = -1;
839 buffer_len = sizeof (recv_ttl);
840 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
841 &recv_ttl, &buffer_len);
843 recv_qos = 0;
844 buffer_len = sizeof (recv_qos);
845 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
846 &recv_qos, &buffer_len);
848 data_len = 0;
849 ping_iterator_get_info (iter, PING_INFO_DATA,
850 NULL, &data_len);
852 context = (ping_context_t *) ping_iterator_get_context (iter);
854 #if USE_NCURSES
855 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
856 #else
857 # define HOST_PRINTF(...) printf(__VA_ARGS__)
858 #endif
860 context->req_sent++;
861 if (latency > 0.0)
862 {
863 context->req_rcvd++;
864 context->latency_total += latency;
865 context->latency_total_square += (latency * latency);
867 if ((context->latency_max < 0.0) || (context->latency_max < latency))
868 context->latency_max = latency;
869 if ((context->latency_min < 0.0) || (context->latency_min > latency))
870 context->latency_min = latency;
872 #if USE_NCURSES
873 if (has_colors () == TRUE)
874 {
875 int color = OPING_GREEN;
876 double average = context_get_average (context);
877 double stddev = context_get_stddev (context);
879 if ((latency < (average - (2 * stddev)))
880 || (latency > (average + (2 * stddev))))
881 color = OPING_RED;
882 else if ((latency < (average - stddev))
883 || (latency > (average + stddev)))
884 color = OPING_YELLOW;
886 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
887 data_len, context->host, context->addr,
888 sequence, recv_ttl,
889 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
890 if ((recv_qos != 0) || (opt_send_qos != 0))
891 {
892 HOST_PRINTF ("qos=%s ",
893 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
894 }
895 HOST_PRINTF ("time=");
896 wattron (main_win, COLOR_PAIR(color));
897 HOST_PRINTF ("%.2f", latency);
898 wattroff (main_win, COLOR_PAIR(color));
899 HOST_PRINTF (" ms\n");
900 }
901 else
902 {
903 #endif
904 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
905 data_len,
906 context->host, context->addr,
907 sequence, recv_ttl);
908 if ((recv_qos != 0) || (opt_send_qos != 0))
909 {
910 HOST_PRINTF ("qos=%s ",
911 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
912 }
913 HOST_PRINTF ("time=%.2f ms\n", latency);
914 #if USE_NCURSES
915 }
916 #endif
917 }
918 else
919 {
920 #if USE_NCURSES
921 if (has_colors () == TRUE)
922 {
923 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
924 context->host, context->addr,
925 sequence);
926 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
927 HOST_PRINTF ("timeout");
928 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
929 HOST_PRINTF ("\n");
930 }
931 else
932 {
933 #endif
934 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
935 context->host, context->addr,
936 sequence);
937 #if USE_NCURSES
938 }
939 #endif
940 }
942 #if USE_NCURSES
943 update_stats_from_context (context);
944 wrefresh (main_win);
945 #endif
946 } /* }}} void update_host_hook */
948 static int post_loop_hook (pingobj_t *ping) /* {{{ */
949 {
950 pingobj_iter_t *iter;
952 #if USE_NCURSES
953 endwin ();
954 #endif
956 for (iter = ping_iterator_get (ping);
957 iter != NULL;
958 iter = ping_iterator_next (iter))
959 {
960 ping_context_t *context;
962 context = ping_iterator_get_context (iter);
964 printf ("\n--- %s ping statistics ---\n"
965 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
966 context->host, context->req_sent, context->req_rcvd,
967 context_get_packet_loss (context),
968 context->latency_total);
970 if (context->req_rcvd != 0)
971 {
972 double average;
973 double deviation;
975 average = context_get_average (context);
976 deviation = context_get_stddev (context);
978 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
979 context->latency_min,
980 average,
981 context->latency_max,
982 deviation);
983 }
985 ping_iterator_set_context (iter, NULL);
986 context_destroy (context);
987 }
989 return (0);
990 } /* }}} int post_loop_hook */
992 int main (int argc, char **argv) /* {{{ */
993 {
994 pingobj_t *ping;
995 pingobj_iter_t *iter;
997 struct sigaction sigint_action;
999 struct timeval tv_begin;
1000 struct timeval tv_end;
1001 struct timespec ts_wait;
1002 struct timespec ts_int;
1004 int optind;
1005 int i;
1006 int status;
1007 #if _POSIX_SAVED_IDS
1008 uid_t saved_set_uid;
1010 /* Save the old effective user id */
1011 saved_set_uid = geteuid ();
1012 /* Set the effective user ID to the real user ID without changing the
1013 * saved set-user ID */
1014 status = seteuid (getuid ());
1015 if (status != 0)
1016 {
1017 fprintf (stderr, "Temporarily dropping privileges "
1018 "failed: %s\n", strerror (errno));
1019 exit (EXIT_FAILURE);
1020 }
1021 #endif
1023 optind = read_options (argc, argv);
1025 #if !_POSIX_SAVED_IDS
1026 /* Cannot temporarily drop privileges -> reject every file but "-". */
1027 if ((opt_filename != NULL)
1028 && (strcmp ("-", opt_filename) != 0)
1029 && (getuid () != geteuid ()))
1030 {
1031 fprintf (stderr, "Your real and effective user IDs don't "
1032 "match. Reading from a file (option '-f')\n"
1033 "is therefore too risky. You can still read "
1034 "from STDIN using '-f -' if you like.\n"
1035 "Sorry.\n");
1036 exit (EXIT_FAILURE);
1037 }
1038 #endif
1040 if ((optind >= argc) && (opt_filename == NULL)) {
1041 usage_exit (argv[0], 1);
1042 }
1044 if ((ping = ping_construct ()) == NULL)
1045 {
1046 fprintf (stderr, "ping_construct failed\n");
1047 return (1);
1048 }
1050 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1051 {
1052 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1053 opt_send_ttl, ping_get_error (ping));
1054 }
1056 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1057 {
1058 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1059 opt_send_qos, ping_get_error (ping));
1060 }
1062 {
1063 double temp_sec;
1064 double temp_nsec;
1066 temp_nsec = modf (opt_interval, &temp_sec);
1067 ts_int.tv_sec = (time_t) temp_sec;
1068 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1070 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1071 }
1073 if (opt_addrfamily != PING_DEF_AF)
1074 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1076 if (opt_srcaddr != NULL)
1077 {
1078 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1079 {
1080 fprintf (stderr, "Setting source address failed: %s\n",
1081 ping_get_error (ping));
1082 }
1083 }
1085 if (opt_device != NULL)
1086 {
1087 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1088 {
1089 fprintf (stderr, "Setting device failed: %s\n",
1090 ping_get_error (ping));
1091 }
1092 }
1094 if (opt_filename != NULL)
1095 {
1096 FILE *infile;
1097 char line[256];
1098 char host[256];
1100 if (strcmp (opt_filename, "-") == 0)
1101 /* Open STDIN */
1102 infile = fdopen(0, "r");
1103 else
1104 infile = fopen(opt_filename, "r");
1106 if (infile == NULL)
1107 {
1108 fprintf (stderr, "Opening %s failed: %s\n",
1109 (strcmp (opt_filename, "-") == 0)
1110 ? "STDIN" : opt_filename,
1111 strerror(errno));
1112 return (1);
1113 }
1115 #if _POSIX_SAVED_IDS
1116 /* Regain privileges */
1117 status = seteuid (saved_set_uid);
1118 if (status != 0)
1119 {
1120 fprintf (stderr, "Temporarily re-gaining privileges "
1121 "failed: %s\n", strerror (errno));
1122 exit (EXIT_FAILURE);
1123 }
1124 #endif
1126 while (fgets(line, sizeof(line), infile))
1127 {
1128 /* Strip whitespace */
1129 if (sscanf(line, "%s", host) != 1)
1130 continue;
1132 if ((host[0] == 0) || (host[0] == '#'))
1133 continue;
1135 if (ping_host_add(ping, host) < 0)
1136 {
1137 const char *errmsg = ping_get_error (ping);
1139 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1140 continue;
1141 }
1142 else
1143 {
1144 host_num++;
1145 }
1146 }
1148 #if _POSIX_SAVED_IDS
1149 /* Drop privileges */
1150 status = seteuid (getuid ());
1151 if (status != 0)
1152 {
1153 fprintf (stderr, "Temporarily dropping privileges "
1154 "failed: %s\n", strerror (errno));
1155 exit (EXIT_FAILURE);
1156 }
1157 #endif
1159 fclose(infile);
1160 }
1162 #if _POSIX_SAVED_IDS
1163 /* Regain privileges */
1164 status = seteuid (saved_set_uid);
1165 if (status != 0)
1166 {
1167 fprintf (stderr, "Temporarily re-gaining privileges "
1168 "failed: %s\n", strerror (errno));
1169 exit (EXIT_FAILURE);
1170 }
1171 #endif
1173 for (i = optind; i < argc; i++)
1174 {
1175 if (ping_host_add (ping, argv[i]) < 0)
1176 {
1177 const char *errmsg = ping_get_error (ping);
1179 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1180 continue;
1181 }
1182 else
1183 {
1184 host_num++;
1185 }
1186 }
1188 /* Permanently drop root privileges if we're setuid-root. */
1189 status = setuid (getuid ());
1190 if (status != 0)
1191 {
1192 fprintf (stderr, "Dropping privileges failed: %s\n",
1193 strerror (errno));
1194 exit (EXIT_FAILURE);
1195 }
1197 #if _POSIX_SAVED_IDS
1198 saved_set_uid = (uid_t) -1;
1199 #endif
1201 ping_initialize_contexts (ping);
1203 if (i == 0)
1204 return (1);
1206 memset (&sigint_action, '\0', sizeof (sigint_action));
1207 sigint_action.sa_handler = sigint_handler;
1208 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1209 {
1210 perror ("sigaction");
1211 return (1);
1212 }
1214 pre_loop_hook (ping);
1216 while (opt_count != 0)
1217 {
1218 int index;
1219 int status;
1221 if (gettimeofday (&tv_begin, NULL) < 0)
1222 {
1223 perror ("gettimeofday");
1224 return (1);
1225 }
1227 if (ping_send (ping) < 0)
1228 {
1229 fprintf (stderr, "ping_send failed: %s\n",
1230 ping_get_error (ping));
1231 return (1);
1232 }
1234 index = 0;
1235 for (iter = ping_iterator_get (ping);
1236 iter != NULL;
1237 iter = ping_iterator_next (iter))
1238 {
1239 update_host_hook (iter, index);
1240 index++;
1241 }
1243 pre_sleep_hook (ping);
1245 /* Don't sleep in the last iteration */
1246 if (opt_count == 1)
1247 break;
1249 if (gettimeofday (&tv_end, NULL) < 0)
1250 {
1251 perror ("gettimeofday");
1252 return (1);
1253 }
1255 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1257 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1258 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1259 {
1260 if (errno != EINTR)
1261 {
1262 perror ("nanosleep");
1263 break;
1264 }
1265 else if (opt_count == 0)
1266 {
1267 /* sigint */
1268 break;
1269 }
1270 }
1272 post_sleep_hook (ping);
1274 if (opt_count > 0)
1275 opt_count--;
1276 } /* while (opt_count != 0) */
1278 post_loop_hook (ping);
1280 ping_destroy (ping);
1282 return (0);
1283 } /* }}} int main */
1285 /* vim: set fdm=marker : */