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