Code

src/oping.c: Change some codig style.
[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                                 }
150                                 break;
152                         case 'f':
153                                 {
154                                         if (opt_filename != NULL)
155                                                 free (opt_filename);
156                                         opt_filename = strdup (optarg);
157                                 }
158                                 break;
160                         case 'i':
161                                 {
162                                         double new_interval;
163                                         new_interval = atof (optarg);
164                                         if (new_interval < 0.001)
165                                                 fprintf (stderr, "Ignoring invalid interval %g.\n",
166                                                                 new_interval);
167                                         else
168                                                 opt_interval = new_interval;
169                                 }
170                                 break;
171                         case 'I':
172                                 {
173                                         if (opt_srcaddr != NULL)
174                                                 free (opt_srcaddr);
175                                         opt_srcaddr = strdup (optarg);
176                                 }
177                                 break;
179                         case 't':
180                         {
181                                 int new_send_ttl;
182                                 new_send_ttl = atoi (optarg);
183                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
184                                         opt_send_ttl = new_send_ttl;
185                                 else
186                                         fprintf (stderr, "Invalid TTL argument: %s\n",
187                                                         optarg);
188                                 break;
189                         }
191                         case 'h':
192                         default:
193                                 usage_exit (argv[0]);
194                 }
195         }
197         return (optind);
200 static void print_host (pingobj_iter_t *iter)
202         double          latency;
203         unsigned int    sequence;
204         int             recv_ttl;
205         size_t          buffer_len;
206         size_t          data_len;
207         ping_context_t *context;
209         latency = -1.0;
210         buffer_len = sizeof (latency);
211         ping_iterator_get_info (iter, PING_INFO_LATENCY,
212                         &latency, &buffer_len);
214         sequence = 0;
215         buffer_len = sizeof (sequence);
216         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
217                         &sequence, &buffer_len);
219         recv_ttl = -1;
220         buffer_len = sizeof (recv_ttl);
221         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
222                         &recv_ttl, &buffer_len);
224         data_len = 0;
225         ping_iterator_get_info (iter, PING_INFO_DATA,
226                         NULL, &data_len);
228         context = (ping_context_t *) ping_iterator_get_context (iter);
230         context->req_sent++;
231         if (latency > 0.0)
232         {
233                 context->req_rcvd++;
234                 context->latency_total += latency;
235                 context->latency_total_square += (latency * latency);
237                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
238                         context->latency_max = latency;
239                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
240                         context->latency_min = latency;
242                 printf ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i time=%.2f ms\n",
243                                 data_len,
244                                 context->host, context->addr,
245                                 sequence, recv_ttl, latency);
246         }
247         else
248         {
249                 printf ("echo reply from %s (%s): icmp_seq=%u timeout\n",
250                                 context->host, context->addr,
251                                 sequence);
252         }
255 static void time_normalize (struct timespec *ts)
257         while (ts->tv_nsec < 0)
258         {
259                 if (ts->tv_sec == 0)
260                 {
261                         ts->tv_nsec = 0;
262                         return;
263                 }
265                 ts->tv_sec  -= 1;
266                 ts->tv_nsec += 1000000000;
267         }
269         while (ts->tv_nsec >= 1000000000)
270         {
271                 ts->tv_sec  += 1;
272                 ts->tv_nsec -= 1000000000;
273         }
276 static void time_calc (struct timespec *ts_dest,
277                 const struct timespec *ts_int,
278                 const struct timeval  *tv_begin,
279                 const struct timeval  *tv_end)
281         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
282         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
283         time_normalize (ts_dest);
285         /* Assure that `(begin + interval) > end'.
286          * This may seem overly complicated, but `tv_sec' is of type `time_t'
287          * which may be `unsigned. *sigh* */
288         if ((tv_end->tv_sec > ts_dest->tv_sec)
289                         || ((tv_end->tv_sec == ts_dest->tv_sec)
290                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
291         {
292                 ts_dest->tv_sec  = 0;
293                 ts_dest->tv_nsec = 0;
294                 return;
295         }
297         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
298         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
299         time_normalize (ts_dest);
302 int main (int argc, char **argv)
304         pingobj_t      *ping;
305         pingobj_iter_t *iter;
307         struct sigaction sigint_action;
309         struct timeval  tv_begin;
310         struct timeval  tv_end;
311         struct timespec ts_wait;
312         struct timespec ts_int;
314         int optind;
315         int i;
317         optind = read_options (argc, argv);
319         if ((optind >= argc) && (opt_filename == NULL)) {
320                 usage_exit (argv[0]);
321         }
323         if (geteuid () != 0)
324         {
325                 fprintf (stderr, "Need superuser privileges to open a RAW socket. Sorry.\n");
326                 return (1);
327         }
329         if ((ping = ping_construct ()) == NULL)
330         {
331                 fprintf (stderr, "ping_construct failed\n");
332                 return (1);
333         }
335         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
336         {
337                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
338                                 opt_send_ttl, ping_get_error (ping));
339         }
341         {
342                 double temp_sec;
343                 double temp_nsec;
345                 temp_nsec = modf (opt_interval, &temp_sec);
346                 ts_int.tv_sec  = (time_t) temp_sec;
347                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
349                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
350         }
352         if (opt_addrfamily != PING_DEF_AF)
353                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
355         if (opt_srcaddr != NULL)
356         {
357                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
358                 {
359                         fprintf (stderr, "Setting source address failed: %s\n",
360                                         ping_get_error (ping));
361                 }
362         }
364         if (opt_filename != NULL)
365         {
366                 FILE *infile;
367                 char line[256];
368                 char host[256];
370                 if (strcmp (opt_filename, "-") == 0)
371                         /* Open STDIN */
372                         infile = fdopen(0, "r");
373                 else
374                         infile = fopen(opt_filename, "r");
376                 if (infile == NULL)
377                 {
378                         fprintf (stderr, "Opening %s failed: %s\n",
379                                         (strcmp (opt_filename, "-") == 0)
380                                         ? "STDIN" : opt_filename,
381                                         strerror(errno));
382                         return (1);
383                 }
385                 while (fgets(line, sizeof(line), infile))
386                 {
387                         /* Strip whitespace */
388                         if (sscanf(line, "%s", host) != 1)
389                                 continue;
391                         if ((host[0] == 0) || (host[0] == '#'))
392                                 continue;
394                         if (ping_host_add(ping, host) < 0)
395                         {
396                                 const char *errmsg = ping_get_error (ping);
398                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
399                                 continue;
400                         }
401                 }
403                 fclose(infile);
404         }
406         for (i = optind; i < argc; i++)
407         {
408                 if (ping_host_add (ping, argv[i]) < 0)
409                 {
410                         const char *errmsg = ping_get_error (ping);
412                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
413                         continue;
414                 }
415         }
417         /* Drop root privileges if we're setuid-root. */
418         setuid (getuid ());
420         i = 0;
421         for (iter = ping_iterator_get (ping);
422                         iter != NULL;
423                         iter = ping_iterator_next (iter))
424         {
425                 ping_context_t *context;
426                 size_t buffer_size;
428                 context = context_create ();
430                 buffer_size = sizeof (context->host);
431                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
433                 buffer_size = sizeof (context->addr);
434                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
436                 buffer_size = 0;
437                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
439                 printf ("PING %s (%s) %zu bytes of data.\n",
440                                 context->host, context->addr, buffer_size);
442                 ping_iterator_set_context (iter, (void *) context);
444                 i++;
445         }
447         if (i == 0)
448                 return (1);
450         memset (&sigint_action, '\0', sizeof (sigint_action));
451         sigint_action.sa_handler = sigint_handler;
452         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
453         {
454                 perror ("sigaction");
455                 return (1);
456         }
458         while (opt_count != 0)
459         {
460                 int status;
462                 if (gettimeofday (&tv_begin, NULL) < 0)
463                 {
464                         perror ("gettimeofday");
465                         return (1);
466                 }
468                 if (ping_send (ping) < 0)
469                 {
470                         fprintf (stderr, "ping_send failed: %s\n",
471                                         ping_get_error (ping));
472                         return (1);
473                 }
475                 for (iter = ping_iterator_get (ping);
476                                 iter != NULL;
477                                 iter = ping_iterator_next (iter))
478                 {
479                         print_host (iter);
480                 }
481                 fflush (stdout);
483                 /* Don't sleep in the last iteration */
484                 if (opt_count == 1)
485                         break;
487                 if (gettimeofday (&tv_end, NULL) < 0)
488                 {
489                         perror ("gettimeofday");
490                         return (1);
491                 }
493                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
495                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
496                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
497                 {
498                         if (errno != EINTR)
499                         {
500                                 perror ("nanosleep");
501                                 break;
502                         }
503                         else if (opt_count == 0)
504                         {
505                                 /* sigint */
506                                 break;
507                         }
508                 }
510                 if (opt_count > 0)
511                         opt_count--;
512         } /* while (opt_count != 0) */
514         for (iter = ping_iterator_get (ping);
515                         iter != NULL;
516                         iter = ping_iterator_next (iter))
517         {
518                 ping_context_t *context;
520                 context = ping_iterator_get_context (iter);
522                 printf ("\n--- %s ping statistics ---\n"
523                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
524                                 context->host, context->req_sent, context->req_rcvd,
525                                 100.0 * (context->req_sent - context->req_rcvd) / ((double) context->req_sent),
526                                 context->latency_total);
528                 if (context->req_rcvd != 0)
529                 {
530                         double num_total;
531                         double average;
532                         double deviation;
534                         num_total = (double) context->req_rcvd;
536                         average = context->latency_total / num_total;
537                         deviation = sqrt (((num_total * context->latency_total_square) - (context->latency_total * context->latency_total))
538                                         / (num_total * (num_total - 1.0)));
540                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
541                                         context->latency_min,
542                                         average,
543                                         context->latency_max,
544                                         deviation);
545                 }
547                 ping_iterator_set_context (iter, NULL);
548                 context_destroy (context);
549         }
551         ping_destroy (ping);
553         return (0);