3d1edddccb4819479d125387b8a5da3c40428622
[liboping.git] / src / oping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006  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 # include <unistd.h>
31 #else
32 # error "You don't have the standard C99 header files installed"
33 #endif /* STDC_HEADERS */
34
35 #if HAVE_MATH_H
36 # include <math.h>
37 #endif
38
39 #if TIME_WITH_SYS_TIME
40 # include <sys/time.h>
41 # include <time.h>
42 #else
43 # if HAVE_SYS_TIME_H
44 #  include <sys/time.h>
45 # else
46 #  include <time.h>
47 # endif
48 #endif
49
50 #if HAVE_NETDB_H
51 # include <netdb.h> /* NI_MAXHOST */
52 #endif
53
54 #if HAVE_SIGNAL_H
55 # include <signal.h>
56 #endif
57
58 #include "oping.h"
59
60 typedef struct ping_context
61 {
62         char host[NI_MAXHOST];
63         char addr[NI_MAXHOST];
64
65         int req_sent;
66         int req_rcvd;
67
68         double latency_min;
69         double latency_max;
70         double latency_total;
71         double latency_total_square;
72 } ping_context_t;
73
74 static double  opt_interval   = 1.0;
75 static int     opt_addrfamily = PING_DEF_AF;
76 static char   *opt_srcaddr    = NULL;
77 static char   *opt_device     = NULL;
78 static char   *opt_filename   = NULL;
79 static int     opt_count      = -1;
80 static int     opt_send_ttl   = 64;
81
82 static void sigint_handler (int signal)
83 {
84         /* Make compiler happy */
85         signal = 0;
86         /* Exit the loop */
87         opt_count = 0;
88 }
89
90 static ping_context_t *context_create (void)
91 {
92         ping_context_t *ret;
93
94         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
95                 return (NULL);
96
97         memset (ret, '\0', sizeof (ping_context_t));
98
99         ret->latency_min   = -1.0;
100         ret->latency_max   = -1.0;
101         ret->latency_total = 0.0;
102         ret->latency_total_square = 0.0;
103
104         return (ret);
105 }
106
107 static void context_destroy (ping_context_t *context)
108 {
109         free (context);
110 }
111
112 static void usage_exit (const char *name, int status)
113 {
114         int name_length;
115
116         name_length = (int) strlen (name);
117
118         fprintf (stderr, "Usage: %s [OPTIONS] "
119                                 "-f filename | host [host [host ...]]\n"
120
121                         "\nAvailable options:\n"
122                         "  -4|-6        force the use of IPv4 or IPv6\n"
123                         "  -c count     number of ICMP packets to send\n"
124                         "  -i interval  interval with which to send ICMP packets\n"
125                         "  -t ttl       time to live for each ICMP packet\n"
126                         "  -I srcaddr   source address\n"
127                         "  -D device    outgoing interface name\n"
128                         "  -f filename  filename to read hosts from\n"
129
130                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
131                         "by Florian octo Forster <octo@verplant.org>\n"
132                         "for contributions see `AUTHORS'\n",
133                         name);
134         exit (status);
135 }
136
137 static _Bool is_setuid (void)
138 {
139         return (getuid () != geteuid ());
140 }
141
142 static int read_options (int argc, char **argv)
143 {
144         int optchar;
145
146         while (1)
147         {
148                 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
149
150                 if (optchar == -1)
151                         break;
152
153                 switch (optchar)
154                 {
155                         case '4':
156                         case '6':
157                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
158                                 break;
159
160                         case 'c':
161                                 {
162                                         int new_count;
163                                         new_count = atoi (optarg);
164                                         if (new_count > 0)
165                                                 opt_count = new_count;
166                                         else
167                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
168                                                                 optarg);
169                                 }
170                                 break;
171
172                         case 'f':
173                                 if (is_setuid () && (strcmp ("-", optarg) != 0))
174                                 {
175                                         fprintf (stderr, "For security reasons the `-f' option "
176                                                         "is disabled if real and effective "
177                                                         "user IDs don't match. Sorry.\n");
178                                 }
179                                 else
180                                 {
181                                         if (opt_filename != NULL)
182                                                 free (opt_filename);
183                                         opt_filename = strdup (optarg);
184                                 }
185                                 break;
186
187                         case 'i':
188                                 {
189                                         double new_interval;
190                                         new_interval = atof (optarg);
191                                         if (new_interval < 0.001)
192                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
193                                                                 optarg);
194                                         else
195                                                 opt_interval = new_interval;
196                                 }
197                                 break;
198                         case 'I':
199                                 {
200                                         if (opt_srcaddr != NULL)
201                                                 free (opt_srcaddr);
202                                         opt_srcaddr = strdup (optarg);
203                                 }
204                                 break;
205
206                         case 'D':
207                                 opt_device = optarg;
208                                 break;
209
210                         case 't':
211                         {
212                                 int new_send_ttl;
213                                 new_send_ttl = atoi (optarg);
214                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
215                                         opt_send_ttl = new_send_ttl;
216                                 else
217                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
218                                                         optarg);
219                                 break;
220                         }
221
222                         case 'h':
223                                 usage_exit (argv[0], 0);
224                                 break;
225                         default:
226                                 usage_exit (argv[0], 1);
227                 }
228         }
229
230         return (optind);
231 }
232
233 static void print_host (pingobj_iter_t *iter)
234 {
235         double          latency;
236         unsigned int    sequence;
237         int             recv_ttl;
238         size_t          buffer_len;
239         size_t          data_len;
240         ping_context_t *context;
241
242         latency = -1.0;
243         buffer_len = sizeof (latency);
244         ping_iterator_get_info (iter, PING_INFO_LATENCY,
245                         &latency, &buffer_len);
246
247         sequence = 0;
248         buffer_len = sizeof (sequence);
249         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
250                         &sequence, &buffer_len);
251
252         recv_ttl = -1;
253         buffer_len = sizeof (recv_ttl);
254         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
255                         &recv_ttl, &buffer_len);
256
257         data_len = 0;
258         ping_iterator_get_info (iter, PING_INFO_DATA,
259                         NULL, &data_len);
260
261         context = (ping_context_t *) ping_iterator_get_context (iter);
262
263         context->req_sent++;
264         if (latency > 0.0)
265         {
266                 context->req_rcvd++;
267                 context->latency_total += latency;
268                 context->latency_total_square += (latency * latency);
269
270                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
271                         context->latency_max = latency;
272                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
273                         context->latency_min = latency;
274
275                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
276                                 data_len,
277                                 context->host, context->addr,
278                                 sequence, recv_ttl, latency);
279         }
280         else
281         {
282                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
283                                 context->host, context->addr,
284                                 sequence);
285         }
286 }
287
288 static void time_normalize (struct timespec *ts)
289 {
290         while (ts->tv_nsec < 0)
291         {
292                 if (ts->tv_sec == 0)
293                 {
294                         ts->tv_nsec = 0;
295                         return;
296                 }
297
298                 ts->tv_sec  -= 1;
299                 ts->tv_nsec += 1000000000;
300         }
301
302         while (ts->tv_nsec >= 1000000000)
303         {
304                 ts->tv_sec  += 1;
305                 ts->tv_nsec -= 1000000000;
306         }
307 }
308
309 static void time_calc (struct timespec *ts_dest,
310                 const struct timespec *ts_int,
311                 const struct timeval  *tv_begin,
312                 const struct timeval  *tv_end)
313 {
314         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
315         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
316         time_normalize (ts_dest);
317
318         /* Assure that `(begin + interval) > end'.
319          * This may seem overly complicated, but `tv_sec' is of type `time_t'
320          * which may be `unsigned. *sigh* */
321         if ((tv_end->tv_sec > ts_dest->tv_sec)
322                         || ((tv_end->tv_sec == ts_dest->tv_sec)
323                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
324         {
325                 ts_dest->tv_sec  = 0;
326                 ts_dest->tv_nsec = 0;
327                 return;
328         }
329
330         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
331         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
332         time_normalize (ts_dest);
333 }
334
335 int main (int argc, char **argv)
336 {
337         pingobj_t      *ping;
338         pingobj_iter_t *iter;
339
340         struct sigaction sigint_action;
341
342         struct timeval  tv_begin;
343         struct timeval  tv_end;
344         struct timespec ts_wait;
345         struct timespec ts_int;
346
347         int optind;
348         int i;
349
350         optind = read_options (argc, argv);
351
352         if ((optind >= argc) && (opt_filename == NULL)) {
353                 usage_exit (argv[0], 1);
354         }
355
356         if (geteuid () != 0)
357         {
358                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
359                 return (1);
360         }
361
362         if ((ping = ping_construct ()) == NULL)
363         {
364                 fprintf (stderr, "ping_construct failed\n");
365                 return (1);
366         }
367
368         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
369         {
370                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
371                                 opt_send_ttl, ping_get_error (ping));
372         }
373
374         {
375                 double temp_sec;
376                 double temp_nsec;
377
378                 temp_nsec = modf (opt_interval, &temp_sec);
379                 ts_int.tv_sec  = (time_t) temp_sec;
380                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
381
382                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
383         }
384
385         if (opt_addrfamily != PING_DEF_AF)
386                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
387
388         if (opt_srcaddr != NULL)
389         {
390                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
391                 {
392                         fprintf (stderr, "Setting source address failed: %s\n",
393                                         ping_get_error (ping));
394                 }
395         }
396
397         if (opt_device != NULL)
398         {
399                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
400                 {
401                         fprintf (stderr, "Setting device failed: %s\n",
402                                         ping_get_error (ping));
403                 }
404         }
405
406         if (opt_filename != NULL)
407         {
408                 FILE *infile;
409                 char line[256];
410                 char host[256];
411
412                 if (strcmp (opt_filename, "-") == 0)
413                         /* Open STDIN */
414                         infile = fdopen(0, "r");
415                 else
416                         infile = fopen(opt_filename, "r");
417
418                 if (infile == NULL)
419                 {
420                         fprintf (stderr, "Opening %s failed: %s\n",
421                                         (strcmp (opt_filename, "-") == 0)
422                                         ? "STDIN" : opt_filename,
423                                         strerror(errno));
424                         return (1);
425                 }
426
427                 while (fgets(line, sizeof(line), infile))
428                 {
429                         /* Strip whitespace */
430                         if (sscanf(line, "%s", host) != 1)
431                                 continue;
432
433                         if ((host[0] == 0) || (host[0] == '#'))
434                                 continue;
435
436                         if (ping_host_add(ping, host) < 0)
437                         {
438                                 const char *errmsg = ping_get_error (ping);
439
440                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
441                                 continue;
442                         }
443                 }
444
445                 fclose(infile);
446         }
447
448         for (i = optind; i < argc; i++)
449         {
450                 if (ping_host_add (ping, argv[i]) < 0)
451                 {
452                         const char *errmsg = ping_get_error (ping);
453
454                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
455                         continue;
456                 }
457         }
458
459         /* Drop root privileges if we're setuid-root. */
460         setuid (getuid ());
461
462         i = 0;
463         for (iter = ping_iterator_get (ping);
464                         iter != NULL;
465                         iter = ping_iterator_next (iter))
466         {
467                 ping_context_t *context;
468                 size_t buffer_size;
469
470                 context = context_create ();
471
472                 buffer_size = sizeof (context->host);
473                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
474
475                 buffer_size = sizeof (context->addr);
476                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
477
478                 buffer_size = 0;
479                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
480
481                 printf ("PING %s (%s) %zu bytes of data.\n",
482                                 context->host, context->addr, buffer_size);
483
484                 ping_iterator_set_context (iter, (void *) context);
485
486                 i++;
487         }
488
489         if (i == 0)
490                 return (1);
491
492         memset (&sigint_action, '\0', sizeof (sigint_action));
493         sigint_action.sa_handler = sigint_handler;
494         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
495         {
496                 perror ("sigaction");
497                 return (1);
498         }
499
500         while (opt_count != 0)
501         {
502                 int status;
503
504                 if (gettimeofday (&tv_begin, NULL) < 0)
505                 {
506                         perror ("gettimeofday");
507                         return (1);
508                 }
509
510                 if (ping_send (ping) < 0)
511                 {
512                         fprintf (stderr, "ping_send failed: %s\n",
513                                         ping_get_error (ping));
514                         return (1);
515                 }
516
517                 for (iter = ping_iterator_get (ping);
518                                 iter != NULL;
519                                 iter = ping_iterator_next (iter))
520                 {
521                         print_host (iter);
522                 }
523                 fflush (stdout);
524
525                 /* Don't sleep in the last iteration */
526                 if (opt_count == 1)
527                         break;
528
529                 if (gettimeofday (&tv_end, NULL) < 0)
530                 {
531                         perror ("gettimeofday");
532                         return (1);
533                 }
534
535                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
536
537                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
538                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
539                 {
540                         if (errno != EINTR)
541                         {
542                                 perror ("nanosleep");
543                                 break;
544                         }
545                         else if (opt_count == 0)
546                         {
547                                 /* sigint */
548                                 break;
549                         }
550                 }
551
552                 if (opt_count > 0)
553                         opt_count--;
554         } /* while (opt_count != 0) */
555
556         for (iter = ping_iterator_get (ping);
557                         iter != NULL;
558                         iter = ping_iterator_next (iter))
559         {
560                 ping_context_t *context;
561
562                 context = ping_iterator_get_context (iter);
563
564                 printf ("\n--- %s ping statistics ---\n"
565                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
566                                 context->host, context->req_sent, context->req_rcvd,
567                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
568                                 context->latency_total);
569
570                 if (context->req_rcvd != 0)
571                 {
572                         double num_total;
573                         double average;
574                         double deviation;
575
576                         num_total = (double) context->req_rcvd;
577
578                         average = context->latency_total / num_total;
579                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
580                                         / (num_total * (num_total - 1.0)));
581
582                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
583                                         context->latency_min,
584                                         average,
585                                         context->latency_max,
586                                         deviation);
587                 }
588
589                 ping_iterator_set_context (iter, NULL);
590                 context_destroy (context);
591         }
592
593         ping_destroy (ping);
594
595         return (0);
596 }