Code

src/oping.c: Move printing header and footer into separate functions.
[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  */
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 <errno.h>
29 # include <assert.h>
30 #else
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
34 #if HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
38 #if HAVE_MATH_H
39 # include <math.h>
40 #endif
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
53 #if HAVE_NETDB_H
54 # include <netdb.h> /* NI_MAXHOST */
55 #endif
57 #if HAVE_SIGNAL_H
58 # include <signal.h>
59 #endif
61 #if HAVE_SYS_TYPES_H
62 #include <sys/types.h>
63 #endif
65 #include "oping.h"
67 #ifndef _POSIX_SAVED_IDS
68 # define _POSIX_SAVED_IDS 0
69 #endif
71 typedef struct ping_context
72 {
73         char host[NI_MAXHOST];
74         char addr[NI_MAXHOST];
76         int req_sent;
77         int req_rcvd;
79         double latency_min;
80         double latency_max;
81         double latency_total;
82         double latency_total_square;
83 } ping_context_t;
85 static double  opt_interval   = 1.0;
86 static int     opt_addrfamily = PING_DEF_AF;
87 static char   *opt_srcaddr    = NULL;
88 static char   *opt_device     = NULL;
89 static char   *opt_filename   = NULL;
90 static int     opt_count      = -1;
91 static int     opt_send_ttl   = 64;
93 static void sigint_handler (int signal)
94 {
95         /* Make compiler happy */
96         signal = 0;
97         /* Exit the loop */
98         opt_count = 0;
99 }
101 static ping_context_t *context_create (void)
103         ping_context_t *ret;
105         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
106                 return (NULL);
108         memset (ret, '\0', sizeof (ping_context_t));
110         ret->latency_min   = -1.0;
111         ret->latency_max   = -1.0;
112         ret->latency_total = 0.0;
113         ret->latency_total_square = 0.0;
115         return (ret);
118 static void context_destroy (ping_context_t *context)
120         if (context == NULL)
121                 return;
123         free (context);
126 static void usage_exit (const char *name, int status)
128         int name_length;
130         name_length = (int) strlen (name);
132         fprintf (stderr, "Usage: %s [OPTIONS] "
133                                 "-f filename | host [host [host ...]]\n"
135                         "\nAvailable options:\n"
136                         "  -4|-6        force the use of IPv4 or IPv6\n"
137                         "  -c count     number of ICMP packets to send\n"
138                         "  -i interval  interval with which to send ICMP packets\n"
139                         "  -t ttl       time to live for each ICMP packet\n"
140                         "  -I srcaddr   source address\n"
141                         "  -D device    outgoing interface name\n"
142                         "  -f filename  filename to read hosts from\n"
144                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
145                         "by Florian octo Forster <octo@verplant.org>\n"
146                         "for contributions see `AUTHORS'\n",
147                         name);
148         exit (status);
151 static int read_options (int argc, char **argv)
153         int optchar;
155         while (1)
156         {
157                 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
159                 if (optchar == -1)
160                         break;
162                 switch (optchar)
163                 {
164                         case '4':
165                         case '6':
166                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
167                                 break;
169                         case 'c':
170                                 {
171                                         int new_count;
172                                         new_count = atoi (optarg);
173                                         if (new_count > 0)
174                                                 opt_count = new_count;
175                                         else
176                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
177                                                                 optarg);
178                                 }
179                                 break;
181                         case 'f':
182                                 {
183                                         if (opt_filename != NULL)
184                                                 free (opt_filename);
185                                         opt_filename = strdup (optarg);
186                                 }
187                                 break;
189                         case 'i':
190                                 {
191                                         double new_interval;
192                                         new_interval = atof (optarg);
193                                         if (new_interval < 0.001)
194                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
195                                                                 optarg);
196                                         else
197                                                 opt_interval = new_interval;
198                                 }
199                                 break;
200                         case 'I':
201                                 {
202                                         if (opt_srcaddr != NULL)
203                                                 free (opt_srcaddr);
204                                         opt_srcaddr = strdup (optarg);
205                                 }
206                                 break;
208                         case 'D':
209                                 opt_device = optarg;
210                                 break;
212                         case 't':
213                         {
214                                 int new_send_ttl;
215                                 new_send_ttl = atoi (optarg);
216                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
217                                         opt_send_ttl = new_send_ttl;
218                                 else
219                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
220                                                         optarg);
221                                 break;
222                         }
224                         case 'h':
225                                 usage_exit (argv[0], 0);
226                                 break;
227                         default:
228                                 usage_exit (argv[0], 1);
229                 }
230         }
232         return (optind);
235 static void print_host (pingobj_iter_t *iter)
237         double          latency;
238         unsigned int    sequence;
239         int             recv_ttl;
240         size_t          buffer_len;
241         size_t          data_len;
242         ping_context_t *context;
244         latency = -1.0;
245         buffer_len = sizeof (latency);
246         ping_iterator_get_info (iter, PING_INFO_LATENCY,
247                         &latency, &buffer_len);
249         sequence = 0;
250         buffer_len = sizeof (sequence);
251         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
252                         &sequence, &buffer_len);
254         recv_ttl = -1;
255         buffer_len = sizeof (recv_ttl);
256         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
257                         &recv_ttl, &buffer_len);
259         data_len = 0;
260         ping_iterator_get_info (iter, PING_INFO_DATA,
261                         NULL, &data_len);
263         context = (ping_context_t *) ping_iterator_get_context (iter);
265         context->req_sent++;
266         if (latency > 0.0)
267         {
268                 context->req_rcvd++;
269                 context->latency_total += latency;
270                 context->latency_total_square += (latency * latency);
272                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
273                         context->latency_max = latency;
274                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
275                         context->latency_min = latency;
277                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
278                                 data_len,
279                                 context->host, context->addr,
280                                 sequence, recv_ttl, latency);
281         }
282         else
283         {
284                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
285                                 context->host, context->addr,
286                                 sequence);
287         }
290 static void time_normalize (struct timespec *ts)
292         while (ts->tv_nsec < 0)
293         {
294                 if (ts->tv_sec == 0)
295                 {
296                         ts->tv_nsec = 0;
297                         return;
298                 }
300                 ts->tv_sec  -= 1;
301                 ts->tv_nsec += 1000000000;
302         }
304         while (ts->tv_nsec >= 1000000000)
305         {
306                 ts->tv_sec  += 1;
307                 ts->tv_nsec -= 1000000000;
308         }
311 static void time_calc (struct timespec *ts_dest, /* {{{ */
312                 const struct timespec *ts_int,
313                 const struct timeval  *tv_begin,
314                 const struct timeval  *tv_end)
316         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
317         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
318         time_normalize (ts_dest);
320         /* Assure that `(begin + interval) > end'.
321          * This may seem overly complicated, but `tv_sec' is of type `time_t'
322          * which may be `unsigned. *sigh* */
323         if ((tv_end->tv_sec > ts_dest->tv_sec)
324                         || ((tv_end->tv_sec == ts_dest->tv_sec)
325                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
326         {
327                 ts_dest->tv_sec  = 0;
328                 ts_dest->tv_nsec = 0;
329                 return;
330         }
332         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
333         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
334         time_normalize (ts_dest);
335 } /* }}} void time_calc */
337 static int print_header (pingobj_t *ping) /* {{{ */
339         pingobj_iter_t *iter;
340         int i;
342         i = 0;
343         for (iter = ping_iterator_get (ping);
344                         iter != NULL;
345                         iter = ping_iterator_next (iter))
346         {
347                 ping_context_t *context;
348                 size_t buffer_size;
350                 context = context_create ();
352                 buffer_size = sizeof (context->host);
353                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
355                 buffer_size = sizeof (context->addr);
356                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
358                 buffer_size = 0;
359                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
361                 printf ("PING %s (%s) %zu bytes of data.\n",
362                                 context->host, context->addr, buffer_size);
364                 ping_iterator_set_context (iter, (void *) context);
366                 i++;
367         }
369         return (0);
370 } /* }}} int print_header */
372 static int print_footer (pingobj_t *ping)
374         pingobj_iter_t *iter;
376         for (iter = ping_iterator_get (ping);
377                         iter != NULL;
378                         iter = ping_iterator_next (iter))
379         {
380                 ping_context_t *context;
382                 context = ping_iterator_get_context (iter);
384                 printf ("\n--- %s ping statistics ---\n"
385                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
386                                 context->host, context->req_sent, context->req_rcvd,
387                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
388                                 context->latency_total);
390                 if (context->req_rcvd != 0)
391                 {
392                         double num_total;
393                         double average;
394                         double deviation;
396                         num_total = (double) context->req_rcvd;
398                         average = context->latency_total / num_total;
399                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
400                                         / (num_total * (num_total - 1.0)));
402                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
403                                         context->latency_min,
404                                         average,
405                                         context->latency_max,
406                                         deviation);
407                 }
409                 ping_iterator_set_context (iter, NULL);
410                 context_destroy (context);
411         }
413         return (0);
414 } /* }}} int print_footer */
416 int main (int argc, char **argv) /* {{{ */
418         pingobj_t      *ping;
419         pingobj_iter_t *iter;
421         struct sigaction sigint_action;
423         struct timeval  tv_begin;
424         struct timeval  tv_end;
425         struct timespec ts_wait;
426         struct timespec ts_int;
428         int optind;
429         int i;
430         int status;
431 #if _POSIX_SAVED_IDS
432         uid_t saved_set_uid;
434         /* Save the old effective user id */
435         saved_set_uid = geteuid ();
436         /* Set the effective user ID to the real user ID without changing the
437          * saved set-user ID */
438         status = seteuid (getuid ());
439         if (status != 0)
440         {
441                 fprintf (stderr, "Temporarily dropping privileges "
442                                 "failed: %s\n", strerror (errno));
443                 exit (EXIT_FAILURE);
444         }
445 #endif
447         optind = read_options (argc, argv);
449 #if !_POSIX_SAVED_IDS
450         /* Cannot temporarily drop privileges -> reject every file but "-". */
451         if ((opt_filename != NULL)
452                         && (strcmp ("-", opt_filename) != 0)
453                         && (getuid () != geteuid ()))
454         {
455                 fprintf (stderr, "Your real and effective user IDs don't "
456                                 "match. Reading from a file (option '-f')\n"
457                                 "is therefore too risky. You can still read "
458                                 "from STDIN using '-f -' if you like.\n"
459                                 "Sorry.\n");
460                 exit (EXIT_FAILURE);
461         }
462 #endif
464         if ((optind >= argc) && (opt_filename == NULL)) {
465                 usage_exit (argv[0], 1);
466         }
468         if ((ping = ping_construct ()) == NULL)
469         {
470                 fprintf (stderr, "ping_construct failed\n");
471                 return (1);
472         }
474         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
475         {
476                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
477                                 opt_send_ttl, ping_get_error (ping));
478         }
480         {
481                 double temp_sec;
482                 double temp_nsec;
484                 temp_nsec = modf (opt_interval, &temp_sec);
485                 ts_int.tv_sec  = (time_t) temp_sec;
486                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
488                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
489         }
491         if (opt_addrfamily != PING_DEF_AF)
492                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
494         if (opt_srcaddr != NULL)
495         {
496                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
497                 {
498                         fprintf (stderr, "Setting source address failed: %s\n",
499                                         ping_get_error (ping));
500                 }
501         }
503         if (opt_device != NULL)
504         {
505                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
506                 {
507                         fprintf (stderr, "Setting device failed: %s\n",
508                                         ping_get_error (ping));
509                 }
510         }
512         if (opt_filename != NULL)
513         {
514                 FILE *infile;
515                 char line[256];
516                 char host[256];
518                 if (strcmp (opt_filename, "-") == 0)
519                         /* Open STDIN */
520                         infile = fdopen(0, "r");
521                 else
522                         infile = fopen(opt_filename, "r");
524                 if (infile == NULL)
525                 {
526                         fprintf (stderr, "Opening %s failed: %s\n",
527                                         (strcmp (opt_filename, "-") == 0)
528                                         ? "STDIN" : opt_filename,
529                                         strerror(errno));
530                         return (1);
531                 }
533 #if _POSIX_SAVED_IDS
534                 /* Regain privileges */
535                 status = seteuid (saved_set_uid);
536                 if (status != 0)
537                 {
538                         fprintf (stderr, "Temporarily re-gaining privileges "
539                                         "failed: %s\n", strerror (errno));
540                         exit (EXIT_FAILURE);
541                 }
542 #endif
544                 while (fgets(line, sizeof(line), infile))
545                 {
546                         /* Strip whitespace */
547                         if (sscanf(line, "%s", host) != 1)
548                                 continue;
550                         if ((host[0] == 0) || (host[0] == '#'))
551                                 continue;
553                         if (ping_host_add(ping, host) < 0)
554                         {
555                                 const char *errmsg = ping_get_error (ping);
557                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
558                                 continue;
559                         }
560                 }
562 #if _POSIX_SAVED_IDS
563                 /* Drop privileges */
564                 status = seteuid (getuid ());
565                 if (status != 0)
566                 {
567                         fprintf (stderr, "Temporarily dropping privileges "
568                                         "failed: %s\n", strerror (errno));
569                         exit (EXIT_FAILURE);
570                 }
571 #endif
573                 fclose(infile);
574         }
576 #if _POSIX_SAVED_IDS
577         /* Regain privileges */
578         status = seteuid (saved_set_uid);
579         if (status != 0)
580         {
581                 fprintf (stderr, "Temporarily re-gaining privileges "
582                                 "failed: %s\n", strerror (errno));
583                 exit (EXIT_FAILURE);
584         }
585 #endif
587         for (i = optind; i < argc; i++)
588         {
589                 if (ping_host_add (ping, argv[i]) < 0)
590                 {
591                         const char *errmsg = ping_get_error (ping);
593                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
594                         continue;
595                 }
596         }
598         /* Permanently drop root privileges if we're setuid-root. */
599         status = setuid (getuid ());
600         if (status != 0)
601         {
602                 fprintf (stderr, "Dropping privileges failed: %s\n",
603                                 strerror (errno));
604                 exit (EXIT_FAILURE);
605         }
607 #if _POSIX_SAVED_IDS
608         saved_set_uid = (uid_t) -1;
609 #endif
611         print_header (ping);
613         if (i == 0)
614                 return (1);
616         memset (&sigint_action, '\0', sizeof (sigint_action));
617         sigint_action.sa_handler = sigint_handler;
618         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
619         {
620                 perror ("sigaction");
621                 return (1);
622         }
624         while (opt_count != 0)
625         {
626                 int status;
628                 if (gettimeofday (&tv_begin, NULL) < 0)
629                 {
630                         perror ("gettimeofday");
631                         return (1);
632                 }
634                 if (ping_send (ping) < 0)
635                 {
636                         fprintf (stderr, "ping_send failed: %s\n",
637                                         ping_get_error (ping));
638                         return (1);
639                 }
641                 for (iter = ping_iterator_get (ping);
642                                 iter != NULL;
643                                 iter = ping_iterator_next (iter))
644                 {
645                         print_host (iter);
646                 }
647                 fflush (stdout);
649                 /* Don't sleep in the last iteration */
650                 if (opt_count == 1)
651                         break;
653                 if (gettimeofday (&tv_end, NULL) < 0)
654                 {
655                         perror ("gettimeofday");
656                         return (1);
657                 }
659                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
661                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
662                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
663                 {
664                         if (errno != EINTR)
665                         {
666                                 perror ("nanosleep");
667                                 break;
668                         }
669                         else if (opt_count == 0)
670                         {
671                                 /* sigint */
672                                 break;
673                         }
674                 }
676                 if (opt_count > 0)
677                         opt_count--;
678         } /* while (opt_count != 0) */
680         print_footer (ping);
682         ping_destroy (ping);
684         return (0);
685 } /* }}} int main */
687 /* vim: set fdm=marker : */