Code

src/oping.c: Improved and unified error messages when parsing CL options.
[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  */
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_MATH_H
35 # include <math.h>
36 #endif
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
40 # include <time.h>
41 #else
42 # if HAVE_SYS_TIME_H
43 #  include <sys/time.h>
44 # else
45 #  include <time.h>
46 # endif
47 #endif
49 #if HAVE_NETDB_H
50 # include <netdb.h> /* NI_MAXHOST */
51 #endif
53 #if HAVE_SIGNAL_H
54 # include <signal.h>
55 #endif
57 #include "oping.h"
59 typedef struct ping_context
60 {
61         char host[NI_MAXHOST];
62         char addr[NI_MAXHOST];
64         int req_sent;
65         int req_rcvd;
67         double latency_min;
68         double latency_max;
69         double latency_total;
70         double latency_total_square;
71 } ping_context_t;
73 static double  opt_interval   = 1.0;
74 static int     opt_addrfamily = PING_DEF_AF;
75 static char   *opt_srcaddr    = NULL;
76 static char   *opt_filename   = NULL;
77 static int     opt_count      = -1;
78 static int     opt_send_ttl   = 64;
80 static void sigint_handler (int signal)
81 {
82         /* Make compiler happy */
83         signal = 0;
84         /* Exit the loop */
85         opt_count = 0;
86 }
88 static ping_context_t *context_create (void)
89 {
90         ping_context_t *ret;
92         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
93                 return (NULL);
95         memset (ret, '\0', sizeof (ping_context_t));
97         ret->latency_min   = -1.0;
98         ret->latency_max   = -1.0;
99         ret->latency_total = 0.0;
100         ret->latency_total_square = 0.0;
102         return (ret);
105 static void context_destroy (ping_context_t *context)
107         free (context);
110 static void usage_exit (const char *name)
112         int name_length;
114         name_length = (int) strlen (name);
116         fprintf (stderr, "Usage: %s [-46] [-c count] [-i interval]\n"
117                         "%*s[-t ttl] [-I srcaddr]\n"
118                         "%*s-f filename | host [host [host ...]]\n",
119                         name,
120                         8 + name_length, "",
121                         8 + name_length, "");
122         exit (1);
125 static int read_options (int argc, char **argv)
127         int optchar;
129         while (1)
130         {
131                 optchar = getopt (argc, argv, "46c:hi:I:t:f:");
133                 if (optchar == -1)
134                         break;
136                 switch (optchar)
137                 {
138                         case '4':
139                         case '6':
140                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
141                                 break;
143                         case 'c':
144                                 {
145                                         int new_count;
146                                         new_count = atoi (optarg);
147                                         if (new_count > 0)
148                                                 opt_count = new_count;
149                                         else
150                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
151                                                                 optarg);
152                                 }
153                                 break;
155                         case 'f':
156                                 {
157                                         if (opt_filename != NULL)
158                                                 free (opt_filename);
159                                         opt_filename = strdup (optarg);
160                                 }
161                                 break;
163                         case 'i':
164                                 {
165                                         double new_interval;
166                                         new_interval = atof (optarg);
167                                         if (new_interval < 0.001)
168                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
169                                                                 optarg);
170                                         else
171                                                 opt_interval = new_interval;
172                                 }
173                                 break;
174                         case 'I':
175                                 {
176                                         if (opt_srcaddr != NULL)
177                                                 free (opt_srcaddr);
178                                         opt_srcaddr = strdup (optarg);
179                                 }
180                                 break;
182                         case 't':
183                         {
184                                 int new_send_ttl;
185                                 new_send_ttl = atoi (optarg);
186                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
187                                         opt_send_ttl = new_send_ttl;
188                                 else
189                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
190                                                         optarg);
191                                 break;
192                         }
194                         case 'h':
195                         default:
196                                 usage_exit (argv[0]);
197                 }
198         }
200         return (optind);
203 static void print_host (pingobj_iter_t *iter)
205         double          latency;
206         unsigned int    sequence;
207         int             recv_ttl;
208         size_t          buffer_len;
209         size_t          data_len;
210         ping_context_t *context;
212         latency = -1.0;
213         buffer_len = sizeof (latency);
214         ping_iterator_get_info (iter, PING_INFO_LATENCY,
215                         &latency, &buffer_len);
217         sequence = 0;
218         buffer_len = sizeof (sequence);
219         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
220                         &sequence, &buffer_len);
222         recv_ttl = -1;
223         buffer_len = sizeof (recv_ttl);
224         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
225                         &recv_ttl, &buffer_len);
227         data_len = 0;
228         ping_iterator_get_info (iter, PING_INFO_DATA,
229                         NULL, &data_len);
231         context = (ping_context_t *) ping_iterator_get_context (iter);
233         context->req_sent++;
234         if (latency > 0.0)
235         {
236                 context->req_rcvd++;
237                 context->latency_total += latency;
238                 context->latency_total_square += (latency * latency);
240                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
241                         context->latency_max = latency;
242                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
243                         context->latency_min = latency;
245                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
246                                 data_len,
247                                 context->host, context->addr,
248                                 sequence, recv_ttl, latency);
249         }
250         else
251         {
252                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
253                                 context->host, context->addr,
254                                 sequence);
255         }
258 static void time_normalize (struct timespec *ts)
260         while (ts->tv_nsec < 0)
261         {
262                 if (ts->tv_sec == 0)
263                 {
264                         ts->tv_nsec = 0;
265                         return;
266                 }
268                 ts->tv_sec  -= 1;
269                 ts->tv_nsec += 1000000000;
270         }
272         while (ts->tv_nsec >= 1000000000)
273         {
274                 ts->tv_sec  += 1;
275                 ts->tv_nsec -= 1000000000;
276         }
279 static void time_calc (struct timespec *ts_dest,
280                 const struct timespec *ts_int,
281                 const struct timeval  *tv_begin,
282                 const struct timeval  *tv_end)
284         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
285         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
286         time_normalize (ts_dest);
288         /* Assure that `(begin + interval) > end'.
289          * This may seem overly complicated, but `tv_sec' is of type `time_t'
290          * which may be `unsigned. *sigh* */
291         if ((tv_end->tv_sec > ts_dest->tv_sec)
292                         || ((tv_end->tv_sec == ts_dest->tv_sec)
293                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
294         {
295                 ts_dest->tv_sec  = 0;
296                 ts_dest->tv_nsec = 0;
297                 return;
298         }
300         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
301         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
302         time_normalize (ts_dest);
305 int main (int argc, char **argv)
307         pingobj_t      *ping;
308         pingobj_iter_t *iter;
310         struct sigaction sigint_action;
312         struct timeval  tv_begin;
313         struct timeval  tv_end;
314         struct timespec ts_wait;
315         struct timespec ts_int;
317         int optind;
318         int i;
320         optind = read_options (argc, argv);
322         if ((optind >= argc) && (opt_filename == NULL)) {
323                 usage_exit (argv[0]);
324         }
326         if (geteuid () != 0)
327         {
328                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
329                 return (1);
330         }
332         if ((ping = ping_construct ()) == NULL)
333         {
334                 fprintf (stderr, "ping_construct failed\n");
335                 return (1);
336         }
338         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
339         {
340                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
341                                 opt_send_ttl, ping_get_error (ping));
342         }
344         {
345                 double temp_sec;
346                 double temp_nsec;
348                 temp_nsec = modf (opt_interval, &temp_sec);
349                 ts_int.tv_sec  = (time_t) temp_sec;
350                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
352                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
353         }
355         if (opt_addrfamily != PING_DEF_AF)
356                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
358         if (opt_srcaddr != NULL)
359         {
360                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
361                 {
362                         fprintf (stderr, "Setting source address failed: %s\n",
363                                         ping_get_error (ping));
364                 }
365         }
367         if (opt_filename != NULL)
368         {
369                 FILE *infile;
370                 char line[256];
371                 char host[256];
373                 if (strcmp (opt_filename, "-") == 0)
374                         /* Open STDIN */
375                         infile = fdopen(0, "r");
376                 else
377                         infile = fopen(opt_filename, "r");
379                 if (infile == NULL)
380                 {
381                         fprintf (stderr, "Opening %s failed: %s\n",
382                                         (strcmp (opt_filename, "-") == 0)
383                                         ? "STDIN" : opt_filename,
384                                         strerror(errno));
385                         return (1);
386                 }
388                 while (fgets(line, sizeof(line), infile))
389                 {
390                         /* Strip whitespace */
391                         if (sscanf(line, "%s", host) != 1)
392                                 continue;
394                         if ((host[0] == 0) || (host[0] == '#'))
395                                 continue;
397                         if (ping_host_add(ping, host) < 0)
398                         {
399                                 const char *errmsg = ping_get_error (ping);
401                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
402                                 continue;
403                         }
404                 }
406                 fclose(infile);
407         }
409         for (i = optind; i < argc; i++)
410         {
411                 if (ping_host_add (ping, argv[i]) < 0)
412                 {
413                         const char *errmsg = ping_get_error (ping);
415                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
416                         continue;
417                 }
418         }
420         /* Drop root privileges if we're setuid-root. */
421         setuid (getuid ());
423         i = 0;
424         for (iter = ping_iterator_get (ping);
425                         iter != NULL;
426                         iter = ping_iterator_next (iter))
427         {
428                 ping_context_t *context;
429                 size_t buffer_size;
431                 context = context_create ();
433                 buffer_size = sizeof (context->host);
434                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
436                 buffer_size = sizeof (context->addr);
437                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
439                 buffer_size = 0;
440                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
442                 printf ("PING %s (%s) %zu bytes of data.\n",
443                                 context->host, context->addr, buffer_size);
445                 ping_iterator_set_context (iter, (void *) context);
447                 i++;
448         }
450         if (i == 0)
451                 return (1);
453         memset (&sigint_action, '\0', sizeof (sigint_action));
454         sigint_action.sa_handler = sigint_handler;
455         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
456         {
457                 perror ("sigaction");
458                 return (1);
459         }
461         while (opt_count != 0)
462         {
463                 int status;
465                 if (gettimeofday (&tv_begin, NULL) < 0)
466                 {
467                         perror ("gettimeofday");
468                         return (1);
469                 }
471                 if (ping_send (ping) < 0)
472                 {
473                         fprintf (stderr, "ping_send failed: %s\n",
474                                         ping_get_error (ping));
475                         return (1);
476                 }
478                 for (iter = ping_iterator_get (ping);
479                                 iter != NULL;
480                                 iter = ping_iterator_next (iter))
481                 {
482                         print_host (iter);
483                 }
484                 fflush (stdout);
486                 /* Don't sleep in the last iteration */
487                 if (opt_count == 1)
488                         break;
490                 if (gettimeofday (&tv_end, NULL) < 0)
491                 {
492                         perror ("gettimeofday");
493                         return (1);
494                 }
496                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
498                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
499                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
500                 {
501                         if (errno != EINTR)
502                         {
503                                 perror ("nanosleep");
504                                 break;
505                         }
506                         else if (opt_count == 0)
507                         {
508                                 /* sigint */
509                                 break;
510                         }
511                 }
513                 if (opt_count > 0)
514                         opt_count--;
515         } /* while (opt_count != 0) */
517         for (iter = ping_iterator_get (ping);
518                         iter != NULL;
519                         iter = ping_iterator_next (iter))
520         {
521                 ping_context_t *context;
523                 context = ping_iterator_get_context (iter);
525                 printf ("\n--- %s ping statistics ---\n"
526                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
527                                 context->host, context->req_sent, context->req_rcvd,
528                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
529                                 context->latency_total);
531                 if (context->req_rcvd != 0)
532                 {
533                         double num_total;
534                         double average;
535                         double deviation;
537                         num_total = (double) context->req_rcvd;
539                         average = context->latency_total / num_total;
540                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
541                                         / (num_total * (num_total - 1.0)));
543                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
544                                         context->latency_min,
545                                         average,
546                                         context->latency_max,
547                                         deviation);
548                 }
550                 ping_iterator_set_context (iter, NULL);
551                 context_destroy (context);
552         }
554         ping_destroy (ping);
556         return (0);