1 /**
2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2011 Florian octo Forster <ff at octo.it>
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 /* Remove GNU specific __attribute__ settings when using another compiler */
93 #if !__GNUC__
94 # define __attribute__(x) /**/
95 #endif
97 typedef struct ping_context
98 {
99 char host[NI_MAXHOST];
100 char addr[NI_MAXHOST];
102 int index;
103 int req_sent;
104 int req_rcvd;
106 double latency_min;
107 double latency_max;
108 double latency_total;
109 double latency_total_square;
111 #if USE_NCURSES
112 WINDOW *window;
113 #endif
114 } ping_context_t;
116 static double opt_interval = 1.0;
117 static int opt_addrfamily = PING_DEF_AF;
118 static char *opt_srcaddr = NULL;
119 static char *opt_device = NULL;
120 static char *opt_filename = NULL;
121 static int opt_count = -1;
122 static int opt_send_ttl = 64;
123 static uint8_t opt_send_qos = 0;
125 static int host_num = 0;
127 #if USE_NCURSES
128 static WINDOW *main_win = NULL;
129 #endif
131 static void sigint_handler (int signal) /* {{{ */
132 {
133 /* Make compiler happy */
134 signal = 0;
135 /* Exit the loop */
136 opt_count = 0;
137 } /* }}} void sigint_handler */
139 static ping_context_t *context_create (void) /* {{{ */
140 {
141 ping_context_t *ret;
143 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
144 return (NULL);
146 memset (ret, '\0', sizeof (ping_context_t));
148 ret->latency_min = -1.0;
149 ret->latency_max = -1.0;
150 ret->latency_total = 0.0;
151 ret->latency_total_square = 0.0;
153 #if USE_NCURSES
154 ret->window = NULL;
155 #endif
157 return (ret);
158 } /* }}} ping_context_t *context_create */
160 static void context_destroy (ping_context_t *context) /* {{{ */
161 {
162 if (context == NULL)
163 return;
165 #if USE_NCURSES
166 if (context->window != NULL)
167 {
168 delwin (context->window);
169 context->window = NULL;
170 }
171 #endif
173 free (context);
174 } /* }}} void context_destroy */
176 static double context_get_average (ping_context_t *ctx) /* {{{ */
177 {
178 double num_total;
180 if (ctx == NULL)
181 return (-1.0);
183 if (ctx->req_rcvd < 1)
184 return (-0.0);
186 num_total = (double) ctx->req_rcvd;
187 return (ctx->latency_total / num_total);
188 } /* }}} double context_get_average */
190 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
191 {
192 double num_total;
194 if (ctx == NULL)
195 return (-1.0);
197 if (ctx->req_rcvd < 1)
198 return (-0.0);
199 else if (ctx->req_rcvd < 2)
200 return (0.0);
202 num_total = (double) ctx->req_rcvd;
203 return (sqrt (((num_total * ctx->latency_total_square)
204 - (ctx->latency_total * ctx->latency_total))
205 / (num_total * (num_total - 1.0))));
206 } /* }}} double context_get_stddev */
208 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
209 {
210 if (ctx == NULL)
211 return (-1.0);
213 if (ctx->req_sent < 1)
214 return (0.0);
216 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
217 / ((double) ctx->req_sent));
218 } /* }}} double context_get_packet_loss */
220 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
221 {
222 pingobj_iter_t *iter;
223 int index;
225 if (ping == NULL)
226 return (EINVAL);
228 index = 0;
229 for (iter = ping_iterator_get (ping);
230 iter != NULL;
231 iter = ping_iterator_next (iter))
232 {
233 ping_context_t *context;
234 size_t buffer_size;
236 context = context_create ();
237 context->index = index;
239 buffer_size = sizeof (context->host);
240 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
242 buffer_size = sizeof (context->addr);
243 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
245 ping_iterator_set_context (iter, (void *) context);
247 index++;
248 }
250 return (0);
251 } /* }}} int ping_initialize_contexts */
253 static void usage_exit (const char *name, int status) /* {{{ */
254 {
255 fprintf (stderr, "Usage: %s [OPTIONS] "
256 "-f filename | host [host [host ...]]\n"
258 "\nAvailable options:\n"
259 " -4|-6 force the use of IPv4 or IPv6\n"
260 " -c count number of ICMP packets to send\n"
261 " -i interval interval with which to send ICMP packets\n"
262 " -t ttl time to live for each ICMP packet\n"
263 " -Q qos Quality of Service (QoS) of outgoing packets\n"
264 " Use \"-Q help\" for a list of valid options.\n"
265 " -I srcaddr source address\n"
266 " -D device outgoing interface name\n"
267 " -f filename filename to read hosts from\n"
269 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
270 "by Florian octo Forster <octo@verplant.org>\n"
271 "for contributions see `AUTHORS'\n",
272 name);
273 exit (status);
274 } /* }}} void usage_exit */
276 __attribute__((noreturn))
277 static void usage_qos_exit (const char *arg, int status) /* {{{ */
278 {
279 if (arg != 0)
280 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
282 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
283 "\n"
284 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
285 "\n"
286 " be Best Effort (BE, default PHB).\n"
287 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
288 " (low delay, low loss, low jitter)\n"
289 " va Voice Admit (VA) DSCP (RFC 5865).\n"
290 " (capacity-admitted traffic)\n"
291 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
292 " For example: \"af12\" (class 1, precedence 2)\n"
293 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
294 " For example: \"cs1\" (priority traffic)\n"
295 "\n"
296 " Type of Service (IPv4, RFC 1349, obsolete)\n"
297 "\n"
298 " lowdelay (%#04x) minimize delay\n"
299 " throughput (%#04x) maximize throughput\n"
300 " reliability (%#04x) maximize reliability\n"
301 " mincost (%#04x) minimize monetary cost\n"
302 "\n"
303 " Specify manually\n"
304 "\n"
305 " 0x00 - 0xff Hexadecimal numeric specification.\n"
306 " 0 - 255 Decimal numeric specification.\n"
307 "\n",
308 (unsigned int) IPTOS_LOWDELAY,
309 (unsigned int) IPTOS_THROUGHPUT,
310 (unsigned int) IPTOS_RELIABILITY,
311 (unsigned int) IPTOS_MINCOST);
313 exit (status);
314 } /* }}} void usage_qos_exit */
316 static int set_opt_send_qos (const char *opt) /* {{{ */
317 {
318 if (opt == NULL)
319 return (EINVAL);
321 if (strcasecmp ("help", opt) == 0)
322 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
323 /* DiffServ (RFC 2474): */
324 /* - Best effort (BE) */
325 else if (strcasecmp ("be", opt) == 0)
326 opt_send_qos = 0;
327 /* - Expedited Forwarding (EF, RFC 3246) */
328 else if (strcasecmp ("ef", opt) == 0)
329 opt_send_qos = 0xB8; /* == 0x2E << 2 */
330 /* - Voice Admit (VA, RFC 5865) */
331 else if (strcasecmp ("va", opt) == 0)
332 opt_send_qos = 0xB0; /* == 0x2D << 2 */
333 /* - Assured Forwarding (AF, RFC 2597) */
334 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
335 && (strlen (opt) == 4))
336 {
337 uint8_t dscp;
338 uint8_t class = 0;
339 uint8_t prec = 0;
341 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
342 if (opt[2] == '1')
343 class = 1;
344 else if (opt[2] == '2')
345 class = 2;
346 else if (opt[2] == '3')
347 class = 3;
348 else if (opt[2] == '4')
349 class = 4;
350 else
351 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
353 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
354 if (opt[3] == '1')
355 prec = 1;
356 else if (opt[3] == '2')
357 prec = 2;
358 else if (opt[3] == '3')
359 prec = 3;
360 else
361 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
363 dscp = (8 * class) + (2 * prec);
364 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
365 opt_send_qos = dscp << 2;
366 }
367 /* - Class Selector (CS) */
368 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
369 && (strlen (opt) == 3))
370 {
371 uint8_t class;
373 if ((opt[2] < '0') || (opt[2] > '7'))
374 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
376 /* Not exactly legal by the C standard, but I don't know of any
377 * system not supporting this hack. */
378 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
379 opt_send_qos = class << 5;
380 }
381 /* Type of Service (RFC 1349) */
382 else if (strcasecmp ("lowdelay", opt) == 0)
383 opt_send_qos = IPTOS_LOWDELAY;
384 else if (strcasecmp ("throughput", opt) == 0)
385 opt_send_qos = IPTOS_THROUGHPUT;
386 else if (strcasecmp ("reliability", opt) == 0)
387 opt_send_qos = IPTOS_RELIABILITY;
388 else if (strcasecmp ("mincost", opt) == 0)
389 opt_send_qos = IPTOS_MINCOST;
390 /* Numeric value */
391 else
392 {
393 unsigned long value;
394 char *endptr;
396 errno = 0;
397 endptr = NULL;
398 value = strtoul (opt, &endptr, /* base = */ 0);
399 if ((errno != 0) || (endptr == opt)
400 || (endptr == NULL) || (*endptr != 0)
401 || (value > 0xff))
402 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
404 opt_send_qos = (uint8_t) value;
405 }
407 return (0);
408 } /* }}} int set_opt_send_qos */
410 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
411 {
412 uint8_t dscp;
413 uint8_t ecn;
414 char *dscp_str;
415 char *ecn_str;
417 dscp = qos >> 2;
418 ecn = qos & 0x03;
420 switch (dscp)
421 {
422 case 0x00: dscp_str = "be"; break;
423 case 0x2e: dscp_str = "ef"; break;
424 case 0x2d: dscp_str = "va"; break;
425 case 0x0a: dscp_str = "af11"; break;
426 case 0x0c: dscp_str = "af12"; break;
427 case 0x0e: dscp_str = "af13"; break;
428 case 0x12: dscp_str = "af21"; break;
429 case 0x14: dscp_str = "af22"; break;
430 case 0x16: dscp_str = "af23"; break;
431 case 0x1a: dscp_str = "af31"; break;
432 case 0x1c: dscp_str = "af32"; break;
433 case 0x1e: dscp_str = "af33"; break;
434 case 0x22: dscp_str = "af41"; break;
435 case 0x24: dscp_str = "af42"; break;
436 case 0x26: dscp_str = "af43"; break;
437 case 0x08: dscp_str = "cs1"; break;
438 case 0x10: dscp_str = "cs2"; break;
439 case 0x18: dscp_str = "cs3"; break;
440 case 0x20: dscp_str = "cs4"; break;
441 case 0x28: dscp_str = "cs5"; break;
442 case 0x30: dscp_str = "cs6"; break;
443 case 0x38: dscp_str = "cs7"; break;
444 default: dscp_str = NULL;
445 }
447 switch (ecn)
448 {
449 case 0x01: ecn_str = ",ecn(1)"; break;
450 case 0x02: ecn_str = ",ecn(0)"; break;
451 case 0x03: ecn_str = ",ce"; break;
452 default: ecn_str = "";
453 }
455 if (dscp_str == NULL)
456 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
457 else
458 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
459 buffer[buffer_size - 1] = 0;
461 return (buffer);
462 } /* }}} char *format_qos */
464 static int read_options (int argc, char **argv) /* {{{ */
465 {
466 int optchar;
468 while (1)
469 {
470 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
472 if (optchar == -1)
473 break;
475 switch (optchar)
476 {
477 case '4':
478 case '6':
479 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
480 break;
482 case 'c':
483 {
484 int new_count;
485 new_count = atoi (optarg);
486 if (new_count > 0)
487 opt_count = new_count;
488 else
489 fprintf(stderr, "Ignoring invalid count: %s\n",
490 optarg);
491 }
492 break;
494 case 'f':
495 {
496 if (opt_filename != NULL)
497 free (opt_filename);
498 opt_filename = strdup (optarg);
499 }
500 break;
502 case 'i':
503 {
504 double new_interval;
505 new_interval = atof (optarg);
506 if (new_interval < 0.001)
507 fprintf (stderr, "Ignoring invalid interval: %s\n",
508 optarg);
509 else
510 opt_interval = new_interval;
511 }
512 break;
513 case 'I':
514 {
515 if (opt_srcaddr != NULL)
516 free (opt_srcaddr);
517 opt_srcaddr = strdup (optarg);
518 }
519 break;
521 case 'D':
522 opt_device = optarg;
523 break;
525 case 't':
526 {
527 int new_send_ttl;
528 new_send_ttl = atoi (optarg);
529 if ((new_send_ttl > 0) && (new_send_ttl < 256))
530 opt_send_ttl = new_send_ttl;
531 else
532 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
533 optarg);
534 break;
535 }
537 case 'Q':
538 set_opt_send_qos (optarg);
539 break;
541 case 'h':
542 usage_exit (argv[0], 0);
543 break;
544 default:
545 usage_exit (argv[0], 1);
546 }
547 }
549 return (optind);
550 } /* }}} read_options */
552 static void time_normalize (struct timespec *ts) /* {{{ */
553 {
554 while (ts->tv_nsec < 0)
555 {
556 if (ts->tv_sec == 0)
557 {
558 ts->tv_nsec = 0;
559 return;
560 }
562 ts->tv_sec -= 1;
563 ts->tv_nsec += 1000000000;
564 }
566 while (ts->tv_nsec >= 1000000000)
567 {
568 ts->tv_sec += 1;
569 ts->tv_nsec -= 1000000000;
570 }
571 } /* }}} void time_normalize */
573 static void time_calc (struct timespec *ts_dest, /* {{{ */
574 const struct timespec *ts_int,
575 const struct timeval *tv_begin,
576 const struct timeval *tv_end)
577 {
578 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
579 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
580 time_normalize (ts_dest);
582 /* Assure that `(begin + interval) > end'.
583 * This may seem overly complicated, but `tv_sec' is of type `time_t'
584 * which may be `unsigned. *sigh* */
585 if ((tv_end->tv_sec > ts_dest->tv_sec)
586 || ((tv_end->tv_sec == ts_dest->tv_sec)
587 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
588 {
589 ts_dest->tv_sec = 0;
590 ts_dest->tv_nsec = 0;
591 return;
592 }
594 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
595 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
596 time_normalize (ts_dest);
597 } /* }}} void time_calc */
599 #if USE_NCURSES
600 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
601 {
602 if ((ctx == NULL) || (ctx->window == NULL))
603 return (EINVAL);
605 werase (ctx->window);
607 box (ctx->window, 0, 0);
608 wattron (ctx->window, A_BOLD);
609 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
610 " %s ", ctx->host);
611 wattroff (ctx->window, A_BOLD);
612 wprintw (ctx->window, "ping statistics ");
613 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
614 "%i packets transmitted, %i received, %.2f%% packet "
615 "loss, time %.1fms",
616 ctx->req_sent, ctx->req_rcvd,
617 context_get_packet_loss (ctx),
618 ctx->latency_total);
619 if (ctx->req_rcvd != 0)
620 {
621 double average;
622 double deviation;
624 average = context_get_average (ctx);
625 deviation = context_get_stddev (ctx);
627 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
628 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
629 ctx->latency_min,
630 average,
631 ctx->latency_max,
632 deviation);
633 }
635 wrefresh (ctx->window);
637 return (0);
638 } /* }}} int update_stats_from_context */
640 static int on_resize (pingobj_t *ping) /* {{{ */
641 {
642 pingobj_iter_t *iter;
643 int width = 0;
644 int height = 0;
645 int main_win_height;
647 getmaxyx (stdscr, height, width);
648 if ((height < 1) || (width < 1))
649 return (EINVAL);
651 main_win_height = height - (4 * host_num);
652 wresize (main_win, main_win_height, /* width = */ width);
653 /* Allow scrolling */
654 scrollok (main_win, TRUE);
655 /* wsetscrreg (main_win, 0, main_win_height - 1); */
656 /* Allow hardware accelerated scrolling. */
657 idlok (main_win, TRUE);
658 wrefresh (main_win);
660 for (iter = ping_iterator_get (ping);
661 iter != NULL;
662 iter = ping_iterator_next (iter))
663 {
664 ping_context_t *context;
666 context = ping_iterator_get_context (iter);
667 if (context == NULL)
668 continue;
670 if (context->window != NULL)
671 {
672 delwin (context->window);
673 context->window = NULL;
674 }
675 context->window = newwin (/* height = */ 4,
676 /* width = */ width,
677 /* y = */ main_win_height + (4 * context->index),
678 /* x = */ 0);
679 }
681 return (0);
682 } /* }}} */
684 static int check_resize (pingobj_t *ping) /* {{{ */
685 {
686 int need_resize = 0;
688 while (42)
689 {
690 int key = wgetch (stdscr);
691 if (key == ERR)
692 break;
693 else if (key == KEY_RESIZE)
694 need_resize = 1;
695 }
697 if (need_resize)
698 return (on_resize (ping));
699 else
700 return (0);
701 } /* }}} int check_resize */
703 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
704 {
705 pingobj_iter_t *iter;
706 int width = 0;
707 int height = 0;
708 int main_win_height;
710 initscr ();
711 cbreak ();
712 noecho ();
713 nodelay (stdscr, TRUE);
715 getmaxyx (stdscr, height, width);
716 if ((height < 1) || (width < 1))
717 return (EINVAL);
719 if (has_colors () == TRUE)
720 {
721 start_color ();
722 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
723 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
724 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
725 }
727 main_win_height = height - (4 * host_num);
728 main_win = newwin (/* height = */ main_win_height,
729 /* width = */ width,
730 /* y = */ 0, /* x = */ 0);
731 /* Allow scrolling */
732 scrollok (main_win, TRUE);
733 /* wsetscrreg (main_win, 0, main_win_height - 1); */
734 /* Allow hardware accelerated scrolling. */
735 idlok (main_win, TRUE);
736 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
737 wrefresh (main_win);
739 for (iter = ping_iterator_get (ping);
740 iter != NULL;
741 iter = ping_iterator_next (iter))
742 {
743 ping_context_t *context;
745 context = ping_iterator_get_context (iter);
746 if (context == NULL)
747 continue;
749 if (context->window != NULL)
750 {
751 delwin (context->window);
752 context->window = NULL;
753 }
754 context->window = newwin (/* height = */ 4,
755 /* width = */ width,
756 /* y = */ main_win_height + (4 * context->index),
757 /* x = */ 0);
758 }
761 /* Don't know what good this does exactly, but without this code
762 * "check_resize" will be called right after startup and *somehow*
763 * this leads to display errors. If we purge all initial characters
764 * here, the problem goes away. "wgetch" is non-blocking due to
765 * "nodelay" (see above). */
766 while (wgetch (stdscr) != ERR)
767 {
768 /* eat up characters */;
769 }
771 return (0);
772 } /* }}} int pre_loop_hook */
774 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
775 {
776 return (check_resize (ping));
777 } /* }}} int pre_sleep_hook */
779 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
780 {
781 return (check_resize (ping));
782 } /* }}} int pre_sleep_hook */
783 #else /* if !USE_NCURSES */
784 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
785 {
786 pingobj_iter_t *iter;
788 for (iter = ping_iterator_get (ping);
789 iter != NULL;
790 iter = ping_iterator_next (iter))
791 {
792 ping_context_t *ctx;
793 size_t buffer_size;
795 ctx = ping_iterator_get_context (iter);
796 if (ctx == NULL)
797 continue;
799 buffer_size = 0;
800 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
802 printf ("PING %s (%s) %zu bytes of data.\n",
803 ctx->host, ctx->addr, buffer_size);
804 }
806 return (0);
807 } /* }}} int pre_loop_hook */
809 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
810 {
811 fflush (stdout);
813 return (0);
814 } /* }}} int pre_sleep_hook */
816 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
817 {
818 return (0);
819 } /* }}} int post_sleep_hook */
820 #endif
822 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
823 __attribute__((unused)) int index)
824 {
825 double latency;
826 unsigned int sequence;
827 int recv_ttl;
828 uint8_t recv_qos;
829 char recv_qos_str[16];
830 size_t buffer_len;
831 size_t data_len;
832 ping_context_t *context;
834 latency = -1.0;
835 buffer_len = sizeof (latency);
836 ping_iterator_get_info (iter, PING_INFO_LATENCY,
837 &latency, &buffer_len);
839 sequence = 0;
840 buffer_len = sizeof (sequence);
841 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
842 &sequence, &buffer_len);
844 recv_ttl = -1;
845 buffer_len = sizeof (recv_ttl);
846 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
847 &recv_ttl, &buffer_len);
849 recv_qos = 0;
850 buffer_len = sizeof (recv_qos);
851 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
852 &recv_qos, &buffer_len);
854 data_len = 0;
855 ping_iterator_get_info (iter, PING_INFO_DATA,
856 NULL, &data_len);
858 context = (ping_context_t *) ping_iterator_get_context (iter);
860 #if USE_NCURSES
861 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
862 #else
863 # define HOST_PRINTF(...) printf(__VA_ARGS__)
864 #endif
866 context->req_sent++;
867 if (latency > 0.0)
868 {
869 context->req_rcvd++;
870 context->latency_total += latency;
871 context->latency_total_square += (latency * latency);
873 if ((context->latency_max < 0.0) || (context->latency_max < latency))
874 context->latency_max = latency;
875 if ((context->latency_min < 0.0) || (context->latency_min > latency))
876 context->latency_min = latency;
878 #if USE_NCURSES
879 if (has_colors () == TRUE)
880 {
881 int color = OPING_GREEN;
882 double average = context_get_average (context);
883 double stddev = context_get_stddev (context);
885 if ((latency < (average - (2 * stddev)))
886 || (latency > (average + (2 * stddev))))
887 color = OPING_RED;
888 else if ((latency < (average - stddev))
889 || (latency > (average + stddev)))
890 color = OPING_YELLOW;
892 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
893 data_len, context->host, context->addr,
894 sequence, recv_ttl,
895 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
896 if ((recv_qos != 0) || (opt_send_qos != 0))
897 {
898 HOST_PRINTF ("qos=%s ",
899 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
900 }
901 HOST_PRINTF ("time=");
902 wattron (main_win, COLOR_PAIR(color));
903 HOST_PRINTF ("%.2f", latency);
904 wattroff (main_win, COLOR_PAIR(color));
905 HOST_PRINTF (" ms\n");
906 }
907 else
908 {
909 #endif
910 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
911 data_len,
912 context->host, context->addr,
913 sequence, recv_ttl);
914 if ((recv_qos != 0) || (opt_send_qos != 0))
915 {
916 HOST_PRINTF ("qos=%s ",
917 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
918 }
919 HOST_PRINTF ("time=%.2f ms\n", latency);
920 #if USE_NCURSES
921 }
922 #endif
923 }
924 else
925 {
926 #if USE_NCURSES
927 if (has_colors () == TRUE)
928 {
929 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
930 context->host, context->addr,
931 sequence);
932 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
933 HOST_PRINTF ("timeout");
934 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
935 HOST_PRINTF ("\n");
936 }
937 else
938 {
939 #endif
940 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
941 context->host, context->addr,
942 sequence);
943 #if USE_NCURSES
944 }
945 #endif
946 }
948 #if USE_NCURSES
949 update_stats_from_context (context);
950 wrefresh (main_win);
951 #endif
952 } /* }}} void update_host_hook */
954 static int post_loop_hook (pingobj_t *ping) /* {{{ */
955 {
956 pingobj_iter_t *iter;
958 #if USE_NCURSES
959 endwin ();
960 #endif
962 for (iter = ping_iterator_get (ping);
963 iter != NULL;
964 iter = ping_iterator_next (iter))
965 {
966 ping_context_t *context;
968 context = ping_iterator_get_context (iter);
970 printf ("\n--- %s ping statistics ---\n"
971 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
972 context->host, context->req_sent, context->req_rcvd,
973 context_get_packet_loss (context),
974 context->latency_total);
976 if (context->req_rcvd != 0)
977 {
978 double average;
979 double deviation;
981 average = context_get_average (context);
982 deviation = context_get_stddev (context);
984 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
985 context->latency_min,
986 average,
987 context->latency_max,
988 deviation);
989 }
991 ping_iterator_set_context (iter, NULL);
992 context_destroy (context);
993 }
995 return (0);
996 } /* }}} int post_loop_hook */
998 int main (int argc, char **argv) /* {{{ */
999 {
1000 pingobj_t *ping;
1001 pingobj_iter_t *iter;
1003 struct sigaction sigint_action;
1005 struct timeval tv_begin;
1006 struct timeval tv_end;
1007 struct timespec ts_wait;
1008 struct timespec ts_int;
1010 int optind;
1011 int i;
1012 int status;
1013 #if _POSIX_SAVED_IDS
1014 uid_t saved_set_uid;
1016 /* Save the old effective user id */
1017 saved_set_uid = geteuid ();
1018 /* Set the effective user ID to the real user ID without changing the
1019 * saved set-user ID */
1020 status = seteuid (getuid ());
1021 if (status != 0)
1022 {
1023 fprintf (stderr, "Temporarily dropping privileges "
1024 "failed: %s\n", strerror (errno));
1025 exit (EXIT_FAILURE);
1026 }
1027 #endif
1029 optind = read_options (argc, argv);
1031 #if !_POSIX_SAVED_IDS
1032 /* Cannot temporarily drop privileges -> reject every file but "-". */
1033 if ((opt_filename != NULL)
1034 && (strcmp ("-", opt_filename) != 0)
1035 && (getuid () != geteuid ()))
1036 {
1037 fprintf (stderr, "Your real and effective user IDs don't "
1038 "match. Reading from a file (option '-f')\n"
1039 "is therefore too risky. You can still read "
1040 "from STDIN using '-f -' if you like.\n"
1041 "Sorry.\n");
1042 exit (EXIT_FAILURE);
1043 }
1044 #endif
1046 if ((optind >= argc) && (opt_filename == NULL)) {
1047 usage_exit (argv[0], 1);
1048 }
1050 if ((ping = ping_construct ()) == NULL)
1051 {
1052 fprintf (stderr, "ping_construct failed\n");
1053 return (1);
1054 }
1056 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1057 {
1058 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1059 opt_send_ttl, ping_get_error (ping));
1060 }
1062 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1063 {
1064 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1065 opt_send_qos, ping_get_error (ping));
1066 }
1068 {
1069 double temp_sec;
1070 double temp_nsec;
1072 temp_nsec = modf (opt_interval, &temp_sec);
1073 ts_int.tv_sec = (time_t) temp_sec;
1074 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1076 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1077 }
1079 if (opt_addrfamily != PING_DEF_AF)
1080 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1082 if (opt_srcaddr != NULL)
1083 {
1084 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1085 {
1086 fprintf (stderr, "Setting source address failed: %s\n",
1087 ping_get_error (ping));
1088 }
1089 }
1091 if (opt_device != NULL)
1092 {
1093 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1094 {
1095 fprintf (stderr, "Setting device failed: %s\n",
1096 ping_get_error (ping));
1097 }
1098 }
1100 if (opt_filename != NULL)
1101 {
1102 FILE *infile;
1103 char line[256];
1104 char host[256];
1106 if (strcmp (opt_filename, "-") == 0)
1107 /* Open STDIN */
1108 infile = fdopen(0, "r");
1109 else
1110 infile = fopen(opt_filename, "r");
1112 if (infile == NULL)
1113 {
1114 fprintf (stderr, "Opening %s failed: %s\n",
1115 (strcmp (opt_filename, "-") == 0)
1116 ? "STDIN" : opt_filename,
1117 strerror(errno));
1118 return (1);
1119 }
1121 #if _POSIX_SAVED_IDS
1122 /* Regain privileges */
1123 status = seteuid (saved_set_uid);
1124 if (status != 0)
1125 {
1126 fprintf (stderr, "Temporarily re-gaining privileges "
1127 "failed: %s\n", strerror (errno));
1128 exit (EXIT_FAILURE);
1129 }
1130 #endif
1132 while (fgets(line, sizeof(line), infile))
1133 {
1134 /* Strip whitespace */
1135 if (sscanf(line, "%s", host) != 1)
1136 continue;
1138 if ((host[0] == 0) || (host[0] == '#'))
1139 continue;
1141 if (ping_host_add(ping, host) < 0)
1142 {
1143 const char *errmsg = ping_get_error (ping);
1145 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1146 continue;
1147 }
1148 else
1149 {
1150 host_num++;
1151 }
1152 }
1154 #if _POSIX_SAVED_IDS
1155 /* Drop privileges */
1156 status = seteuid (getuid ());
1157 if (status != 0)
1158 {
1159 fprintf (stderr, "Temporarily dropping privileges "
1160 "failed: %s\n", strerror (errno));
1161 exit (EXIT_FAILURE);
1162 }
1163 #endif
1165 fclose(infile);
1166 }
1168 #if _POSIX_SAVED_IDS
1169 /* Regain privileges */
1170 status = seteuid (saved_set_uid);
1171 if (status != 0)
1172 {
1173 fprintf (stderr, "Temporarily re-gaining privileges "
1174 "failed: %s\n", strerror (errno));
1175 exit (EXIT_FAILURE);
1176 }
1177 #endif
1179 for (i = optind; i < argc; i++)
1180 {
1181 if (ping_host_add (ping, argv[i]) < 0)
1182 {
1183 const char *errmsg = ping_get_error (ping);
1185 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1186 continue;
1187 }
1188 else
1189 {
1190 host_num++;
1191 }
1192 }
1194 /* Permanently drop root privileges if we're setuid-root. */
1195 status = setuid (getuid ());
1196 if (status != 0)
1197 {
1198 fprintf (stderr, "Dropping privileges failed: %s\n",
1199 strerror (errno));
1200 exit (EXIT_FAILURE);
1201 }
1203 #if _POSIX_SAVED_IDS
1204 saved_set_uid = (uid_t) -1;
1205 #endif
1207 ping_initialize_contexts (ping);
1209 if (i == 0)
1210 return (1);
1212 memset (&sigint_action, '\0', sizeof (sigint_action));
1213 sigint_action.sa_handler = sigint_handler;
1214 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1215 {
1216 perror ("sigaction");
1217 return (1);
1218 }
1220 pre_loop_hook (ping);
1222 while (opt_count != 0)
1223 {
1224 int index;
1225 int status;
1227 if (gettimeofday (&tv_begin, NULL) < 0)
1228 {
1229 perror ("gettimeofday");
1230 return (1);
1231 }
1233 if (ping_send (ping) < 0)
1234 {
1235 fprintf (stderr, "ping_send failed: %s\n",
1236 ping_get_error (ping));
1237 return (1);
1238 }
1240 index = 0;
1241 for (iter = ping_iterator_get (ping);
1242 iter != NULL;
1243 iter = ping_iterator_next (iter))
1244 {
1245 update_host_hook (iter, index);
1246 index++;
1247 }
1249 pre_sleep_hook (ping);
1251 /* Don't sleep in the last iteration */
1252 if (opt_count == 1)
1253 break;
1255 if (gettimeofday (&tv_end, NULL) < 0)
1256 {
1257 perror ("gettimeofday");
1258 return (1);
1259 }
1261 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1263 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1264 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1265 {
1266 if (errno != EINTR)
1267 {
1268 perror ("nanosleep");
1269 break;
1270 }
1271 else if (opt_count == 0)
1272 {
1273 /* sigint */
1274 break;
1275 }
1276 }
1278 post_sleep_hook (ping);
1280 if (opt_count > 0)
1281 opt_count--;
1282 } /* while (opt_count != 0) */
1284 post_loop_hook (ping);
1286 ping_destroy (ping);
1288 return (0);
1289 } /* }}} int main */
1291 /* vim: set fdm=marker : */