4946bf74dd6028d87abb03e1ec1bb14d4b3f9ab7
[liboping.git] / src / oping.c
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  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
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 */
33
34 #if HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #if HAVE_MATH_H
39 # include <math.h>
40 #endif
41
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
52
53 #if HAVE_NETDB_H
54 # include <netdb.h> /* NI_MAXHOST */
55 #endif
56
57 #if HAVE_SIGNAL_H
58 # include <signal.h>
59 #endif
60
61 #if HAVE_SYS_TYPES_H
62 #include <sys/types.h>
63 #endif
64
65 #if USE_NCURSES
66 # include <ncurses.h>
67 #endif
68
69 #include "oping.h"
70
71 #ifndef _POSIX_SAVED_IDS
72 # define _POSIX_SAVED_IDS 0
73 #endif
74
75 typedef struct ping_context
76 {
77         char host[NI_MAXHOST];
78         char addr[NI_MAXHOST];
79
80         int req_sent;
81         int req_rcvd;
82
83         double latency_min;
84         double latency_max;
85         double latency_total;
86         double latency_total_square;
87
88 #if USE_NCURSES
89         WINDOW *window;
90 #endif
91 } ping_context_t;
92
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;
100
101 #if USE_NCURSES
102 static WINDOW *main_win = NULL;
103 #endif
104
105 static void sigint_handler (int signal)
106 {
107         /* Make compiler happy */
108         signal = 0;
109         /* Exit the loop */
110         opt_count = 0;
111 }
112
113 static ping_context_t *context_create (void)
114 {
115         ping_context_t *ret;
116
117         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
118                 return (NULL);
119
120         memset (ret, '\0', sizeof (ping_context_t));
121
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;
126
127 #if USE_NCURSES
128         ret->window = NULL;
129 #endif
130
131         return (ret);
132 }
133
134 static void context_destroy (ping_context_t *context)
135 {
136         if (context == NULL)
137                 return;
138
139 #if USE_NCURSES
140         if (context->window != NULL)
141         {
142                 delwin (context->window);
143                 context->window = NULL;
144         }
145 #endif
146
147         free (context);
148 }
149
150 static double context_get_average (ping_context_t *ctx) /* {{{ */
151 {
152         double num_total;
153
154         if (ctx == NULL)
155                 return (-1.0);
156
157         if (ctx->req_rcvd < 1)
158                 return (-0.0);
159
160         num_total = (double) ctx->req_rcvd;
161         return (ctx->latency_total / num_total);
162 } /* }}} double context_get_average */
163
164 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
165 {
166         double num_total;
167
168         if (ctx == NULL)
169                 return (-1.0);
170
171         if (ctx->req_rcvd < 1)
172                 return (-0.0);
173         else if (ctx->req_rcvd < 2)
174                 return (0.0);
175
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 */
181
182 static void usage_exit (const char *name, int status)
183 {
184         int name_length;
185
186         name_length = (int) strlen (name);
187
188         fprintf (stderr, "Usage: %s [OPTIONS] "
189                                 "-f filename | host [host [host ...]]\n"
190
191                         "\nAvailable options:\n"
192                         "  -4|-6        force the use of IPv4 or IPv6\n"
193                         "  -c count     number of ICMP packets to send\n"
194                         "  -i interval  interval with which to send ICMP packets\n"
195                         "  -t ttl       time to live for each ICMP packet\n"
196                         "  -I srcaddr   source address\n"
197                         "  -D device    outgoing interface name\n"
198                         "  -f filename  filename to read hosts from\n"
199
200                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
201                         "by Florian octo Forster <octo@verplant.org>\n"
202                         "for contributions see `AUTHORS'\n",
203                         name);
204         exit (status);
205 }
206
207 static int read_options (int argc, char **argv)
208 {
209         int optchar;
210
211         while (1)
212         {
213                 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
214
215                 if (optchar == -1)
216                         break;
217
218                 switch (optchar)
219                 {
220                         case '4':
221                         case '6':
222                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
223                                 break;
224
225                         case 'c':
226                                 {
227                                         int new_count;
228                                         new_count = atoi (optarg);
229                                         if (new_count > 0)
230                                                 opt_count = new_count;
231                                         else
232                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
233                                                                 optarg);
234                                 }
235                                 break;
236
237                         case 'f':
238                                 {
239                                         if (opt_filename != NULL)
240                                                 free (opt_filename);
241                                         opt_filename = strdup (optarg);
242                                 }
243                                 break;
244
245                         case 'i':
246                                 {
247                                         double new_interval;
248                                         new_interval = atof (optarg);
249                                         if (new_interval < 0.001)
250                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
251                                                                 optarg);
252                                         else
253                                                 opt_interval = new_interval;
254                                 }
255                                 break;
256                         case 'I':
257                                 {
258                                         if (opt_srcaddr != NULL)
259                                                 free (opt_srcaddr);
260                                         opt_srcaddr = strdup (optarg);
261                                 }
262                                 break;
263
264                         case 'D':
265                                 opt_device = optarg;
266                                 break;
267
268                         case 't':
269                         {
270                                 int new_send_ttl;
271                                 new_send_ttl = atoi (optarg);
272                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
273                                         opt_send_ttl = new_send_ttl;
274                                 else
275                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
276                                                         optarg);
277                                 break;
278                         }
279
280                         case 'h':
281                                 usage_exit (argv[0], 0);
282                                 break;
283                         default:
284                                 usage_exit (argv[0], 1);
285                 }
286         }
287
288         return (optind);
289 }
290
291 static void print_host (pingobj_iter_t *iter)
292 {
293         double          latency;
294         unsigned int    sequence;
295         int             recv_ttl;
296         size_t          buffer_len;
297         size_t          data_len;
298         ping_context_t *context;
299
300         latency = -1.0;
301         buffer_len = sizeof (latency);
302         ping_iterator_get_info (iter, PING_INFO_LATENCY,
303                         &latency, &buffer_len);
304
305         sequence = 0;
306         buffer_len = sizeof (sequence);
307         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
308                         &sequence, &buffer_len);
309
310         recv_ttl = -1;
311         buffer_len = sizeof (recv_ttl);
312         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
313                         &recv_ttl, &buffer_len);
314
315         data_len = 0;
316         ping_iterator_get_info (iter, PING_INFO_DATA,
317                         NULL, &data_len);
318
319         context = (ping_context_t *) ping_iterator_get_context (iter);
320
321 #if USE_NCURSES
322 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
323 #else
324 # define HOST_PRINTF(...) printf(__VA_ARGS__)
325 #endif
326
327         context->req_sent++;
328         if (latency > 0.0)
329         {
330                 context->req_rcvd++;
331                 context->latency_total += latency;
332                 context->latency_total_square += (latency * latency);
333
334                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
335                         context->latency_max = latency;
336                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
337                         context->latency_min = latency;
338
339                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
340                                 "time=%.2f ms\n",
341                                 data_len,
342                                 context->host, context->addr,
343                                 sequence, recv_ttl, latency);
344         }
345         else
346         {
347                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
348                                 context->host, context->addr,
349                                 sequence);
350         }
351
352 #if USE_NCURSES
353         wrefresh (main_win);
354         werase (context->window);
355         box (context->window, 0, 0);
356         mvwprintw (context->window, /* y = */ 0, /* x = */ 5,
357                         " %s ping statistics ",
358                         context->host);
359         mvwprintw (context->window, /* y = */ 1, /* x = */ 2,
360                         "%i packets transmitted, %i received, %.2f%% packet "
361                         "loss, time %.1fms",
362                         context->req_sent, context->req_rcvd,
363                         100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
364                         context->latency_total);
365         if (context->req_rcvd != 0)
366         {
367                 double average;
368                 double deviation;
369
370                 average = context_get_average (context);
371                 deviation = context_get_stddev (context);
372                         
373                 mvwprintw (context->window, /* y = */ 2, /* x = */ 2,
374                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
375                                 context->latency_min,
376                                 average,
377                                 context->latency_max,
378                                 deviation);
379         }
380         wrefresh (context->window);
381 #endif
382 }
383
384 static void time_normalize (struct timespec *ts)
385 {
386         while (ts->tv_nsec < 0)
387         {
388                 if (ts->tv_sec == 0)
389                 {
390                         ts->tv_nsec = 0;
391                         return;
392                 }
393
394                 ts->tv_sec  -= 1;
395                 ts->tv_nsec += 1000000000;
396         }
397
398         while (ts->tv_nsec >= 1000000000)
399         {
400                 ts->tv_sec  += 1;
401                 ts->tv_nsec -= 1000000000;
402         }
403 }
404
405 static void time_calc (struct timespec *ts_dest, /* {{{ */
406                 const struct timespec *ts_int,
407                 const struct timeval  *tv_begin,
408                 const struct timeval  *tv_end)
409 {
410         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
411         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
412         time_normalize (ts_dest);
413
414         /* Assure that `(begin + interval) > end'.
415          * This may seem overly complicated, but `tv_sec' is of type `time_t'
416          * which may be `unsigned. *sigh* */
417         if ((tv_end->tv_sec > ts_dest->tv_sec)
418                         || ((tv_end->tv_sec == ts_dest->tv_sec)
419                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
420         {
421                 ts_dest->tv_sec  = 0;
422                 ts_dest->tv_nsec = 0;
423                 return;
424         }
425
426         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
427         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
428         time_normalize (ts_dest);
429 } /* }}} void time_calc */
430
431 static int print_header (pingobj_t *ping) /* {{{ */
432 {
433         pingobj_iter_t *iter;
434         int i;
435
436 #if USE_NCURSES
437         initscr ();
438         cbreak ();
439         noecho ();
440 #endif
441
442         i = 0;
443         for (iter = ping_iterator_get (ping);
444                         iter != NULL;
445                         iter = ping_iterator_next (iter))
446         {
447                 ping_context_t *context;
448                 size_t buffer_size;
449
450                 context = context_create ();
451
452                 buffer_size = sizeof (context->host);
453                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
454
455                 buffer_size = sizeof (context->addr);
456                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
457
458                 buffer_size = 0;
459                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
460
461 #if USE_NCURSES
462                 context->window = newwin (/* height = */ 4, COLS,
463                                 /* start y = */ 4*i, /* start x = */ 0);
464                 box (context->window, 0, 0);
465                 mvwprintw (context->window, /* y = */ 0, /* x = */ 5,
466                                 " %s ping statistics ",
467                                 context->host);
468                 wrefresh (context->window);
469 #else /* !USE_NCURSES */
470                 printf ("PING %s (%s) %zu bytes of data.\n",
471                                 context->host, context->addr, buffer_size);
472 #endif
473
474                 ping_iterator_set_context (iter, (void *) context);
475
476                 i++;
477         }
478
479 #if USE_NCURSES
480         delwin (main_win);
481         main_win = newwin (LINES - 4*i, COLS, 4*i, 0);
482         scrollok (main_win, TRUE);
483 #endif
484
485         return (0);
486 } /* }}} int print_header */
487
488 static int print_footer (pingobj_t *ping)
489 {
490         pingobj_iter_t *iter;
491
492 #if USE_NCURSES
493         endwin ();
494 #endif
495
496         for (iter = ping_iterator_get (ping);
497                         iter != NULL;
498                         iter = ping_iterator_next (iter))
499         {
500                 ping_context_t *context;
501
502                 context = ping_iterator_get_context (iter);
503
504                 printf ("\n--- %s ping statistics ---\n"
505                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
506                                 context->host, context->req_sent, context->req_rcvd,
507                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
508                                 context->latency_total);
509
510                 if (context->req_rcvd != 0)
511                 {
512                         double average;
513                         double deviation;
514
515                         average = context_get_average (context);
516                         deviation = context_get_stddev (context);
517
518                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
519                                         context->latency_min,
520                                         average,
521                                         context->latency_max,
522                                         deviation);
523                 }
524
525                 ping_iterator_set_context (iter, NULL);
526                 context_destroy (context);
527         }
528
529         return (0);
530 } /* }}} int print_footer */
531
532 int main (int argc, char **argv) /* {{{ */
533 {
534         pingobj_t      *ping;
535         pingobj_iter_t *iter;
536
537         struct sigaction sigint_action;
538
539         struct timeval  tv_begin;
540         struct timeval  tv_end;
541         struct timespec ts_wait;
542         struct timespec ts_int;
543
544         int optind;
545         int i;
546         int status;
547 #if _POSIX_SAVED_IDS
548         uid_t saved_set_uid;
549
550         /* Save the old effective user id */
551         saved_set_uid = geteuid ();
552         /* Set the effective user ID to the real user ID without changing the
553          * saved set-user ID */
554         status = seteuid (getuid ());
555         if (status != 0)
556         {
557                 fprintf (stderr, "Temporarily dropping privileges "
558                                 "failed: %s\n", strerror (errno));
559                 exit (EXIT_FAILURE);
560         }
561 #endif
562
563         optind = read_options (argc, argv);
564
565 #if !_POSIX_SAVED_IDS
566         /* Cannot temporarily drop privileges -> reject every file but "-". */
567         if ((opt_filename != NULL)
568                         && (strcmp ("-", opt_filename) != 0)
569                         && (getuid () != geteuid ()))
570         {
571                 fprintf (stderr, "Your real and effective user IDs don't "
572                                 "match. Reading from a file (option '-f')\n"
573                                 "is therefore too risky. You can still read "
574                                 "from STDIN using '-f -' if you like.\n"
575                                 "Sorry.\n");
576                 exit (EXIT_FAILURE);
577         }
578 #endif
579
580         if ((optind >= argc) && (opt_filename == NULL)) {
581                 usage_exit (argv[0], 1);
582         }
583
584         if ((ping = ping_construct ()) == NULL)
585         {
586                 fprintf (stderr, "ping_construct failed\n");
587                 return (1);
588         }
589
590         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
591         {
592                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
593                                 opt_send_ttl, ping_get_error (ping));
594         }
595
596         {
597                 double temp_sec;
598                 double temp_nsec;
599
600                 temp_nsec = modf (opt_interval, &temp_sec);
601                 ts_int.tv_sec  = (time_t) temp_sec;
602                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
603
604                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
605         }
606
607         if (opt_addrfamily != PING_DEF_AF)
608                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
609
610         if (opt_srcaddr != NULL)
611         {
612                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
613                 {
614                         fprintf (stderr, "Setting source address failed: %s\n",
615                                         ping_get_error (ping));
616                 }
617         }
618
619         if (opt_device != NULL)
620         {
621                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
622                 {
623                         fprintf (stderr, "Setting device failed: %s\n",
624                                         ping_get_error (ping));
625                 }
626         }
627
628         if (opt_filename != NULL)
629         {
630                 FILE *infile;
631                 char line[256];
632                 char host[256];
633
634                 if (strcmp (opt_filename, "-") == 0)
635                         /* Open STDIN */
636                         infile = fdopen(0, "r");
637                 else
638                         infile = fopen(opt_filename, "r");
639
640                 if (infile == NULL)
641                 {
642                         fprintf (stderr, "Opening %s failed: %s\n",
643                                         (strcmp (opt_filename, "-") == 0)
644                                         ? "STDIN" : opt_filename,
645                                         strerror(errno));
646                         return (1);
647                 }
648
649 #if _POSIX_SAVED_IDS
650                 /* Regain privileges */
651                 status = seteuid (saved_set_uid);
652                 if (status != 0)
653                 {
654                         fprintf (stderr, "Temporarily re-gaining privileges "
655                                         "failed: %s\n", strerror (errno));
656                         exit (EXIT_FAILURE);
657                 }
658 #endif
659
660                 while (fgets(line, sizeof(line), infile))
661                 {
662                         /* Strip whitespace */
663                         if (sscanf(line, "%s", host) != 1)
664                                 continue;
665
666                         if ((host[0] == 0) || (host[0] == '#'))
667                                 continue;
668
669                         if (ping_host_add(ping, host) < 0)
670                         {
671                                 const char *errmsg = ping_get_error (ping);
672
673                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
674                                 continue;
675                         }
676                 }
677
678 #if _POSIX_SAVED_IDS
679                 /* Drop privileges */
680                 status = seteuid (getuid ());
681                 if (status != 0)
682                 {
683                         fprintf (stderr, "Temporarily dropping privileges "
684                                         "failed: %s\n", strerror (errno));
685                         exit (EXIT_FAILURE);
686                 }
687 #endif
688
689                 fclose(infile);
690         }
691
692 #if _POSIX_SAVED_IDS
693         /* Regain privileges */
694         status = seteuid (saved_set_uid);
695         if (status != 0)
696         {
697                 fprintf (stderr, "Temporarily re-gaining privileges "
698                                 "failed: %s\n", strerror (errno));
699                 exit (EXIT_FAILURE);
700         }
701 #endif
702
703         for (i = optind; i < argc; i++)
704         {
705                 if (ping_host_add (ping, argv[i]) < 0)
706                 {
707                         const char *errmsg = ping_get_error (ping);
708
709                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
710                         continue;
711                 }
712         }
713
714         /* Permanently drop root privileges if we're setuid-root. */
715         status = setuid (getuid ());
716         if (status != 0)
717         {
718                 fprintf (stderr, "Dropping privileges failed: %s\n",
719                                 strerror (errno));
720                 exit (EXIT_FAILURE);
721         }
722
723 #if _POSIX_SAVED_IDS
724         saved_set_uid = (uid_t) -1;
725 #endif
726
727         print_header (ping);
728
729         if (i == 0)
730                 return (1);
731
732         memset (&sigint_action, '\0', sizeof (sigint_action));
733         sigint_action.sa_handler = sigint_handler;
734         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
735         {
736                 perror ("sigaction");
737                 return (1);
738         }
739
740         while (opt_count != 0)
741         {
742                 int status;
743
744                 if (gettimeofday (&tv_begin, NULL) < 0)
745                 {
746                         perror ("gettimeofday");
747                         return (1);
748                 }
749
750                 if (ping_send (ping) < 0)
751                 {
752                         fprintf (stderr, "ping_send failed: %s\n",
753                                         ping_get_error (ping));
754                         return (1);
755                 }
756
757                 for (iter = ping_iterator_get (ping);
758                                 iter != NULL;
759                                 iter = ping_iterator_next (iter))
760                 {
761                         print_host (iter);
762                 }
763                 fflush (stdout);
764
765                 /* Don't sleep in the last iteration */
766                 if (opt_count == 1)
767                         break;
768
769                 if (gettimeofday (&tv_end, NULL) < 0)
770                 {
771                         perror ("gettimeofday");
772                         return (1);
773                 }
774
775                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
776
777                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
778                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
779                 {
780                         if (errno != EINTR)
781                         {
782                                 perror ("nanosleep");
783                                 break;
784                         }
785                         else if (opt_count == 0)
786                         {
787                                 /* sigint */
788                                 break;
789                         }
790                 }
791
792                 if (opt_count > 0)
793                         opt_count--;
794         } /* while (opt_count != 0) */
795
796         print_footer (ping);
797
798         ping_destroy (ping);
799
800         return (0);
801 } /* }}} int main */
802
803 /* vim: set fdm=marker : */