Code

65b2ef529dd81cff07b7948f2d8f47eeb76e76c1
[liboping.git] / src / liboping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2009  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 <stdint.h>
29 # include <inttypes.h>
30 # include <errno.h>
31 # include <assert.h>
32 #else
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
40 #if HAVE_FCNTL_H
41 # include <fcntl.h>
42 #endif
43 #if HAVE_SYS_TYPES_H
44 # include <sys/types.h>
45 #endif
46 #if HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
50 #if TIME_WITH_SYS_TIME
51 # include <sys/time.h>
52 # include <time.h>
53 #else
54 # if HAVE_SYS_TIME_H
55 #  include <sys/time.h>
56 # else
57 #  include <time.h>
58 # endif
59 #endif
61 #if HAVE_SYS_SOCKET_H
62 # include <sys/socket.h>
63 #endif
64 #if HAVE_NETDB_H
65 # include <netdb.h>
66 #endif
68 #if HAVE_NETINET_IN_SYSTM_H
69 # include <netinet/in_systm.h>
70 #endif
71 #if HAVE_NETINET_IN_H
72 # include <netinet/in.h>
73 #endif
74 #if HAVE_NETINET_IP_H
75 # include <netinet/ip.h>
76 #endif
77 #if HAVE_NETINET_IP_ICMP_H
78 # include <netinet/ip_icmp.h>
79 #endif
80 #ifdef HAVE_NETINET_IP_VAR_H
81 # include <netinet/ip_var.h>
82 #endif
83 #if HAVE_NETINET_IP6_H
84 # include <netinet/ip6.h>
85 #endif
86 #if HAVE_NETINET_ICMP6_H
87 # include <netinet/icmp6.h>
88 #endif
90 #include "oping.h"
92 #if WITH_DEBUG
93 # define dprintf(...) printf ("%s[%4i]: %-20s: ", __FILE__, __LINE__, __FUNCTION__); printf (__VA_ARGS__)
94 #else
95 # define dprintf(...) /**/
96 #endif
98 #define PING_ERRMSG_LEN 256
100 struct pinghost
102         /* username: name passed in by the user */
103         char                    *username;
104         /* hostname: name returned by the reverse lookup */
105         char                    *hostname;
106         struct sockaddr_storage *addr;
107         socklen_t                addrlen;
108         int                      addrfamily;
109         int                      fd;
110         int                      ident;
111         int                      sequence;
112         struct timeval          *timer;
113         double                   latency;
114         uint32_t                 dropped;
115         int                      recv_ttl;
116         char                    *data;
118         void                    *context;
120         struct pinghost         *next;
121 };
123 struct pingobj
125         double                   timeout;
126         int                      ttl;
127         int                      addrfamily;
128         char                    *data;
130         struct sockaddr         *srcaddr;
131         socklen_t                srcaddrlen;
133         char                     errmsg[PING_ERRMSG_LEN];
135         pinghost_t              *head;
136 };
138 /*
139  * private (static) functions
140  */
141 /* Even though Posix requires "strerror_r" to return an "int",
142  * some systems (e.g. the GNU libc) return a "char *" _and_
143  * ignore the second argument ... -tokkee */
144 char *sstrerror (int errnum, char *buf, size_t buflen)
146         buf[0] = 0;
148 #if !HAVE_STRERROR_R
149         {
150                 snprintf (buf, buflen, "Error %i (%#x)", errnum, errnum);
151         }
152 /* #endif !HAVE_STRERROR_R */
154 #elif STRERROR_R_CHAR_P
155         {
156                 char *temp;
157                 temp = strerror_r (errnum, buf, buflen);
158                 if (buf[0] == 0)
159                 {
160                         if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
161                                 strncpy (buf, temp, buflen);
162                         else
163                                 strncpy (buf, "strerror_r did not return "
164                                                 "an error message", buflen);
165                 }
166         }
167 /* #endif STRERROR_R_CHAR_P */
169 #else
170         if (strerror_r (errnum, buf, buflen) != 0)
171         {
172                 snprintf (buf, buflen, "Error %i (%#x); "
173                                 "Additionally, strerror_r failed.",
174                                 errnum, errnum);
175         }
176 #endif /* STRERROR_R_CHAR_P */
178         buf[buflen - 1] = 0;
180         return (buf);
181 } /* char *sstrerror */
183 static void ping_set_error (pingobj_t *obj, const char *function,
184                 const char *message)
186         snprintf (obj->errmsg, sizeof (obj->errmsg),
187                         "%s: %s", function, message);
188         obj->errmsg[sizeof (obj->errmsg) - 1] = 0;
191 static void ping_set_errno (pingobj_t *obj, int error_number)
193         sstrerror (error_number, obj->errmsg, sizeof (obj->errmsg));
196 static int ping_timeval_add (struct timeval *tv1, struct timeval *tv2,
197                 struct timeval *res)
199         res->tv_sec  = tv1->tv_sec  + tv2->tv_sec;
200         res->tv_usec = tv1->tv_usec + tv2->tv_usec;
202         while (res->tv_usec > 1000000)
203         {
204                 res->tv_usec -= 1000000;
205                 res->tv_sec++;
206         }
208         return (0);
211 static int ping_timeval_sub (struct timeval *tv1, struct timeval *tv2,
212                 struct timeval *res)
214         if ((tv1->tv_sec < tv2->tv_sec)
215                         || ((tv1->tv_sec == tv2->tv_sec)
216                                 && (tv1->tv_usec < tv2->tv_usec)))
217                 return (-1);
219         res->tv_sec  = tv1->tv_sec  - tv2->tv_sec;
220         res->tv_usec = tv1->tv_usec - tv2->tv_usec;
222         assert ((res->tv_sec > 0) || ((res->tv_sec == 0) && (res->tv_usec >= 0)));
224         while (res->tv_usec < 0)
225         {
226                 res->tv_usec += 1000000;
227                 res->tv_sec--;
228         }
230         return (0);
233 static uint16_t ping_icmp4_checksum (char *buf, size_t len)
235         uint32_t sum = 0;
236         uint16_t ret = 0;
238         uint16_t *ptr;
240         for (ptr = (uint16_t *) buf; len > 1; ptr++, len -= 2)
241                 sum += *ptr;
243         if (len == 1)
244         {
245                 *(char *) &ret = *(char *) ptr;
246                 sum += ret;
247         }
249         /* Do this twice to get all possible carries.. */
250         sum = (sum >> 16) + (sum & 0xFFFF);
251         sum = (sum >> 16) + (sum & 0xFFFF);
253         ret = ~sum;
255         return (ret);
258 static pinghost_t *ping_receive_ipv4 (pinghost_t *ph, char *buffer, size_t buffer_len)
260         struct ip *ip_hdr;
261         struct icmp *icmp_hdr;
263         size_t ip_hdr_len;
265         uint16_t recv_checksum;
266         uint16_t calc_checksum;
268         uint16_t ident;
269         uint16_t seq;
271         pinghost_t *ptr;
273         if (buffer_len < sizeof (struct ip))
274                 return (NULL);
276         ip_hdr     = (struct ip *) buffer;
277         ip_hdr_len = ip_hdr->ip_hl << 2;
279         if (buffer_len < ip_hdr_len)
280                 return (NULL);
282         buffer     += ip_hdr_len;
283         buffer_len -= ip_hdr_len;
285         if (buffer_len < sizeof (struct icmp))
286                 return (NULL);
288         icmp_hdr = (struct icmp *) buffer;
289         buffer     += sizeof (struct icmp);
290         buffer_len -= sizeof (struct icmp);
292         if (icmp_hdr->icmp_type != ICMP_ECHOREPLY)
293         {
294                 dprintf ("Unexpected ICMP type: %i\n", icmp_hdr->icmp_type);
295                 return (NULL);
296         }
298         recv_checksum = icmp_hdr->icmp_cksum;
299         icmp_hdr->icmp_cksum = 0;
300         calc_checksum = ping_icmp4_checksum ((char *) icmp_hdr,
301                         sizeof (struct icmp) + buffer_len);
303         if (recv_checksum != calc_checksum)
304         {
305                 dprintf ("Checksum missmatch: Got 0x%04x, calculated 0x%04x\n",
306                                 recv_checksum, calc_checksum);
307                 return (NULL);
308         }
310         ident = ntohs (icmp_hdr->icmp_id);
311         seq   = ntohs (icmp_hdr->icmp_seq);
313         for (ptr = ph; ptr != NULL; ptr = ptr->next)
314         {
315                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
316                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
318                 if (ptr->addrfamily != AF_INET)
319                         continue;
321                 if (!timerisset (ptr->timer))
322                         continue;
324                 if (ptr->ident != ident)
325                         continue;
327                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
328                         continue;
330                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
331                                 ptr->hostname, ident, seq);
333                 break;
334         }
336         if (ptr == NULL)
337         {
338                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
339                                 ident, seq);
340         }
342         return (ptr);
345 #ifndef ICMP6_ECHO_REQUEST
346 # ifdef ICMP6_ECHO /* AIX netinet/ip6_icmp.h */
347 #  define ICMP6_ECHO_REQUEST ICMP6_ECHO
348 # else
349 #  define ICMP6_ECHO_REQUEST 128
350 # endif
351 #endif
353 #ifndef ICMP6_ECHO_REPLY
354 # ifdef ICMP6_ECHOREPLY /* AIX netinet/ip6_icmp.h */
355 #  define ICMP6_ECHO_REPLY ICMP6_ECHOREPLY
356 # else
357 #  define ICMP6_ECHO_REPLY 129
358 # endif
359 #endif
361 static pinghost_t *ping_receive_ipv6 (pinghost_t *ph, char *buffer, size_t buffer_len)
363         struct icmp6_hdr *icmp_hdr;
365         uint16_t ident;
366         uint16_t seq;
368         pinghost_t *ptr;
370         if (buffer_len < sizeof (struct icmp6_hdr))
371                 return (NULL);
373         icmp_hdr = (struct icmp6_hdr *) buffer;
374         buffer     += sizeof (struct icmp);
375         buffer_len -= sizeof (struct icmp);
377         if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
378         {
379                 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
380                 return (NULL);
381         }
383         if (icmp_hdr->icmp6_code != 0)
384         {
385                 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
386                 return (NULL);
387         }
389         ident = ntohs (icmp_hdr->icmp6_id);
390         seq   = ntohs (icmp_hdr->icmp6_seq);
392         for (ptr = ph; ptr != NULL; ptr = ptr->next)
393         {
394                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
395                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
397                 if (ptr->addrfamily != AF_INET6)
398                         continue;
400                 if (!timerisset (ptr->timer))
401                         continue;
403                 if (ptr->ident != ident)
404                         continue;
406                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
407                         continue;
409                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
410                                 ptr->hostname, ident, seq);
412                 break;
413         }
415         if (ptr == NULL)
416         {
417                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
418                                 ident, seq);
419         }
421         return (ptr);
424 static int ping_receive_one (int fd, pinghost_t *ph, struct timeval *now)
426         struct timeval diff;
427         pinghost_t *host = NULL;
428         int family;
429         int recv_ttl;
430         
431         /*
432          * Set up the receive buffer..
433          */
434         struct msghdr msghdr;
435         struct cmsghdr *cmsg;
436         char payload_buffer[4096];
437         ssize_t payload_buffer_len;
438         char control_buffer[4096];
439         struct iovec payload_iovec;
441         memset (&payload_iovec, 0, sizeof (payload_iovec));
442         payload_iovec.iov_base = payload_buffer;
443         payload_iovec.iov_len = sizeof (payload_buffer);
445         memset (&msghdr, 0, sizeof (msghdr));
446         /* unspecified source address */
447         msghdr.msg_name = NULL;
448         msghdr.msg_namelen = 0;
449         /* output buffer vector, see readv(2) */
450         msghdr.msg_iov = &payload_iovec;
451         msghdr.msg_iovlen = 1;
452         /* output buffer for control messages */
453         msghdr.msg_control = control_buffer;
454         msghdr.msg_controllen = sizeof (control_buffer);
455         /* flags; this is an output only field.. */
456         msghdr.msg_flags = 0;
458         payload_buffer_len = recvmsg (fd, &msghdr, /* flags = */ 0);
459         if (payload_buffer_len < 0)
460         {
461 #if WITH_DEBUG
462                 char errbuf[PING_ERRMSG_LEN];
463                 dprintf ("recvfrom: %s\n",
464                                 sstrerror (errno, errbuf, sizeof (errbuf)));
465 #endif
466                 return (-1);
467         }
468         dprintf ("Read %zi bytes from fd = %i\n", payload_buffer_len, fd);
470         /* Iterate over all auxiliary data in msghdr */
471         family = -1;
472         recv_ttl = -1;
473         for (cmsg = CMSG_FIRSTHDR (&msghdr); /* {{{ */
474                         cmsg != NULL;
475                         cmsg = CMSG_NXTHDR (&msghdr, cmsg))
476         {
477                 if (cmsg->cmsg_level == IPPROTO_IP) /* {{{ */
478                 {
479                         family = AF_INET;
480                         if (cmsg->cmsg_type == IP_TTL)
481                         {
482                                 memcpy (&recv_ttl, CMSG_DATA (cmsg),
483                                                 sizeof (recv_ttl));
484                                 dprintf ("TTLv4 = %i;\n", recv_ttl);
485                         }
486                         else
487                         {
488                                 dprintf ("Not handling option %i.\n",
489                                                 cmsg->cmsg_type);
490                         }
491                 } /* }}} */
492                 else if (cmsg->cmsg_level == IPPROTO_IPV6) /* {{{ */
493                 {
494                         family = AF_INET6;
495                         if (cmsg->cmsg_type == IPV6_HOPLIMIT)
496                         {
497                                 memcpy (&recv_ttl, CMSG_DATA (cmsg),
498                                                 sizeof (recv_ttl));
499                                 dprintf ("TTLv6 = %i;\n", recv_ttl);
500                         }
501                         else
502                         {
503                                 dprintf ("Not handling option %i.\n",
504                                                 cmsg->cmsg_type);
505                         }
506                 } /* }}} */
507                 else
508                 {
509                         dprintf ("Don't know how to handle "
510                                         "unknown protocol %i.\n",
511                                         cmsg->cmsg_level);
512                 }
513         } /* }}} for (cmsg) */
515         if (family == AF_INET)
516         {
517                 host = ping_receive_ipv4 (ph, payload_buffer, payload_buffer_len);
518                 if (host == NULL)
519                         return (-1);
520         }
521         else if (family == AF_INET6)
522         {
523                 host = ping_receive_ipv6 (ph, payload_buffer, payload_buffer_len);
524                 if (host == NULL)
525                         return (-1);
526         }
527         else
528         {
529                 dprintf ("ping_receive_one: Unknown address family %i.\n",
530                                 family);
531                 return (-1);
532         }
534         dprintf ("rcvd: %12i.%06i\n",
535                         (int) now->tv_sec,
536                         (int) now->tv_usec);
537         dprintf ("sent: %12i.%06i\n",
538                         (int) host->timer->tv_sec,
539                         (int) host->timer->tv_usec);
541         if (ping_timeval_sub (now, host->timer, &diff) < 0)
542         {
543                 timerclear (host->timer);
544                 return (-1);
545         }
547         dprintf ("diff: %12i.%06i\n",
548                         (int) diff.tv_sec,
549                         (int) diff.tv_usec);
551         host->latency  = ((double) diff.tv_usec) / 1000.0;
552         host->latency += ((double) diff.tv_sec)  * 1000.0;
554         host->recv_ttl = recv_ttl;
556         timerclear (host->timer);
558         return (0);
561 static int ping_receive_all (pingobj_t *obj)
563         fd_set readfds;
564         int num_readfds;
565         int max_readfds;
567         pinghost_t *ph;
568         pinghost_t *ptr;
570         struct timeval endtime;
571         struct timeval nowtime;
572         struct timeval timeout;
573         int status;
575         int ret;
577         ph = obj->head;
578         ret = 0;
580         for (ptr = ph; ptr != NULL; ptr = ptr->next)
581                 ptr->latency = -1.0;
583         if (gettimeofday (&nowtime, NULL) == -1)
584         {
585                 ping_set_errno (obj, errno);
586                 return (-1);
587         }
589         /* Set up timeout */
590         timeout.tv_sec = (time_t) obj->timeout;
591         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
593         dprintf ("Set timeout to %i.%06i seconds\n",
594                         (int) timeout.tv_sec,
595                         (int) timeout.tv_usec);
597         ping_timeval_add (&nowtime, &timeout, &endtime);
599         while (1)
600         {
601                 FD_ZERO (&readfds);
602                 num_readfds =  0;
603                 max_readfds = -1;
605                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
606                 {
607                         if (!timerisset (ptr->timer))
608                                 continue;
610                         FD_SET (ptr->fd, &readfds);
611                         num_readfds++;
613                         if (max_readfds < ptr->fd)
614                                 max_readfds = ptr->fd;
615                 }
617                 if (num_readfds == 0)
618                         break;
620                 if (gettimeofday (&nowtime, NULL) == -1)
621                 {
622                         ping_set_errno (obj, errno);
623                         return (-1);
624                 }
626                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
627                         break;
629                 dprintf ("Waiting on %i sockets for %i.%06i seconds\n", num_readfds,
630                                 (int) timeout.tv_sec,
631                                 (int) timeout.tv_usec);
633                 status = select (max_readfds + 1, &readfds, NULL, NULL, &timeout);
635                 if (gettimeofday (&nowtime, NULL) == -1)
636                 {
637                         ping_set_errno (obj, errno);
638                         return (-1);
639                 }
640                 
641                 if ((status == -1) && (errno == EINTR))
642                 {
643                         dprintf ("select was interrupted by signal..\n");
644                         continue;
645                 }
646                 else if (status < 0)
647                 {
648 #if WITH_DEBUG
649                         char errbuf[PING_ERRMSG_LEN];
650                         dprintf ("select: %s\n",
651                                         sstrerror (errno, errbuf, sizeof (errbuf)));
652 #endif
653                         break;
654                 }
655                 else if (status == 0)
656                 {
657                         dprintf ("select timed out\n");
658                         for (ptr = ph; ptr != NULL; ptr = ptr->next)
659                                 if (ptr->latency < 0.0)
660                                         ptr->dropped++;
661                         break;
662                 }
664                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
665                 {
666                         if (FD_ISSET (ptr->fd, &readfds))
667                                 if (ping_receive_one (ptr->fd, ph, &nowtime) == 0)
668                                         ret++;
669                 }
670         } /* while (1) */
671         
672         return (ret);
675 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
676  * Sending functions:                                                        *
677  *                                                                           *
678  * ping_send_all                                                             *
679  * +-> ping_send_one_ipv4                                                    *
680  * `-> ping_send_one_ipv6                                                    *
681  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
682 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
683                 const void *buf, size_t buflen)
685         ssize_t ret;
687         if (gettimeofday (ph->timer, NULL) == -1)
688         {
689                 timerclear (ph->timer);
690                 return (-1);
691         }
693         ret = sendto (ph->fd, buf, buflen, 0,
694                         (struct sockaddr *) ph->addr, ph->addrlen);
696         if (ret < 0)
697         {
698 #if defined(EHOSTUNREACH)
699                 if (errno == EHOSTUNREACH)
700                         return (0);
701 #endif
702 #if defined(ENETUNREACH)
703                 if (errno == ENETUNREACH)
704                         return (0);
705 #endif
706                 ping_set_errno (obj, errno);
707         }
709         return (ret);
712 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
714         struct icmp *icmp4;
715         int status;
717         char buf[4096];
718         int  buflen;
720         char *data;
721         int   datalen;
723         dprintf ("ph->hostname = %s\n", ph->hostname);
725         memset (buf, '\0', sizeof (buf));
726         icmp4 = (struct icmp *) buf;
727         data  = (char *) (icmp4 + 1);
729         icmp4->icmp_type  = ICMP_ECHO;
730         icmp4->icmp_code  = 0;
731         icmp4->icmp_cksum = 0;
732         icmp4->icmp_id    = htons (ph->ident);
733         icmp4->icmp_seq   = htons (ph->sequence);
735         buflen = 4096 - sizeof (struct icmp);
736         strncpy (data, ph->data, buflen);
737         datalen = strlen (data);
739         buflen = datalen + sizeof (struct icmp);
741         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
743         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
745         status = ping_sendto (obj, ph, buf, buflen);
746         if (status < 0)
747         {
748                 perror ("ping_sendto");
749                 return (-1);
750         }
752         dprintf ("sendto: status = %i\n", status);
754         return (0);
757 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
759         struct icmp6_hdr *icmp6;
760         int status;
762         char buf[4096];
763         int  buflen;
765         char *data;
766         int   datalen;
768         dprintf ("ph->hostname = %s\n", ph->hostname);
770         memset (buf, '\0', sizeof (buf));
771         icmp6 = (struct icmp6_hdr *) buf;
772         data  = (char *) (icmp6 + 1);
774         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
775         icmp6->icmp6_code  = 0;
776         /* The checksum will be calculated by the TCP/IP stack.  */
777         /* FIXME */
778         icmp6->icmp6_cksum = 0;
779         icmp6->icmp6_id    = htons (ph->ident);
780         icmp6->icmp6_seq   = htons (ph->sequence);
782         buflen = 4096 - sizeof (struct icmp6_hdr);
783         strncpy (data, ph->data, buflen);
784         datalen = strlen (data);
786         buflen = datalen + sizeof (struct icmp6_hdr);
788         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
790         status = ping_sendto (obj, ph, buf, buflen);
791         if (status < 0)
792         {
793                 perror ("ping_sendto");
794                 return (-1);
795         }
797         dprintf ("sendto: status = %i\n", status);
799         return (0);
802 static int ping_send_all (pingobj_t *obj)
804         pinghost_t *ph;
805         pinghost_t *ptr;
807         int ret;
809         ret = 0;
810         ph = obj->head;
812         for (ptr = ph; ptr != NULL; ptr = ptr->next)
813         {
814                 /* start timer.. The GNU `ping6' starts the timer before
815                  * sending the packet, so I will do that too */
816                 if (gettimeofday (ptr->timer, NULL) == -1)
817                 {
818 #if WITH_DEBUG
819                         char errbuf[PING_ERRMSG_LEN];
820                         dprintf ("gettimeofday: %s\n",
821                                         sstrerror (errno, errbuf, sizeof (errbuf)));
822 #endif
823                         timerclear (ptr->timer);
824                         ret--;
825                         continue;
826                 }
827                 else
828                 {
829                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
830                 }
832                 if (ptr->addrfamily == AF_INET6)
833                 {       
834                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
835                         if (ping_send_one_ipv6 (obj, ptr) != 0)
836                         {
837                                 timerclear (ptr->timer);
838                                 ret--;
839                                 continue;
840                         }
841                 }
842                 else if (ptr->addrfamily == AF_INET)
843                 {
844                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
845                         if (ping_send_one_ipv4 (obj, ptr) != 0)
846                         {
847                                 timerclear (ptr->timer);
848                                 ret--;
849                                 continue;
850                         }
851                 }
852                 else /* this should not happen */
853                 {
854                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
855                         timerclear (ptr->timer);
856                         ret--;
857                         continue;
858                 }
860                 ptr->sequence++;
861         }
863         return (ret);
866 /*
867  * Set the TTL of a socket protocol independently.
868  */
869 static int ping_set_ttl (pinghost_t *ph, int ttl)
871         int ret = -2;
873         if (ph->addrfamily == AF_INET)
874         {
875                 dprintf ("Setting TTLv4 to %i\n", ttl);
876                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL,
877                                 &ttl, sizeof (ttl));
878         }
879         else if (ph->addrfamily == AF_INET6)
880         {
881                 dprintf ("Setting TTLv6 to %i\n", ttl);
882                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
883                                 &ttl, sizeof (ttl));
884         }
886         return (ret);
889 static int ping_get_ident (void)
891         int fd;
892         static int did_seed = 0;
894         int retval;
896         if (did_seed == 0)
897         {
898                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
899                 {
900                         unsigned int seed;
902                         if (read (fd, &seed, sizeof (seed)) != -1)
903                         {
904                                 did_seed = 1;
905                                 dprintf ("Random seed:   %#x\n", seed);
906                                 srandom (seed);
907                         }
909                         close (fd);
910                 }
911 #if WITH_DEBUG
912                 else
913                 {
914                         char errbuf[PING_ERRMSG_LEN];
915                         dprintf ("open (/dev/urandom): %s\n",
916                                         sstrerror (errno, errbuf, sizeof (errbuf)));
917                 }
918 #endif
919         }
921         retval = (int) random ();
923         dprintf ("Random number: %#x\n", retval);
924         
925         return (retval);
928 static pinghost_t *ping_alloc (void)
930         pinghost_t *ph;
931         size_t      ph_size;
933         ph_size = sizeof (pinghost_t)
934                 + sizeof (struct sockaddr_storage)
935                 + sizeof (struct timeval);
937         ph = (pinghost_t *) malloc (ph_size);
938         if (ph == NULL)
939                 return (NULL);
941         memset (ph, '\0', ph_size);
943         ph->timer   = (struct timeval *) (ph + 1);
944         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
946         ph->addrlen = sizeof (struct sockaddr_storage);
947         ph->fd      = -1;
948         ph->latency = -1.0;
949         ph->dropped = 0;
950         ph->ident   = ping_get_ident () & 0xFFFF;
952         return (ph);
955 static void ping_free (pinghost_t *ph)
957         if (ph->fd >= 0)
958                 close (ph->fd);
959         
960         if (ph->username != NULL)
961                 free (ph->username);
963         if (ph->hostname != NULL)
964                 free (ph->hostname);
966         if (ph->data != NULL)
967                 free (ph->data);
969         free (ph);
972 /*
973  * public methods
974  */
975 const char *ping_get_error (pingobj_t *obj)
977         return (obj->errmsg);
980 pingobj_t *ping_construct (void)
982         pingobj_t *obj;
984         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
985                 return (NULL);
986         memset (obj, '\0', sizeof (pingobj_t));
988         obj->timeout    = PING_DEF_TIMEOUT;
989         obj->ttl        = PING_DEF_TTL;
990         obj->addrfamily = PING_DEF_AF;
991         obj->data       = strdup (PING_DEF_DATA);
993         return (obj);
996 void ping_destroy (pingobj_t *obj)
998         pinghost_t *current;
999         pinghost_t *next;
1001         current = obj->head;
1002         next = NULL;
1004         while (current != NULL)
1005         {
1006                 next = current->next;
1007                 ping_free (current);
1008                 current = next;
1009         }
1011         if (obj->data != NULL)
1012                 free (obj->data);
1014         if (obj->srcaddr != NULL)
1015                 free (obj->srcaddr);
1017         free (obj);
1019         return;
1022 int ping_setopt (pingobj_t *obj, int option, void *value)
1024         int ret = 0;
1026         switch (option)
1027         {
1028                 case PING_OPT_TIMEOUT:
1029                         obj->timeout = *((double *) value);
1030                         if (obj->timeout < 0.0)
1031                         {
1032                                 obj->timeout = PING_DEF_TIMEOUT;
1033                                 ret = -1;
1034                         }
1035                         break;
1037                 case PING_OPT_TTL:
1038                         obj->ttl = *((int *) value);
1039                         if ((obj->ttl < 1) || (obj->ttl > 255))
1040                         {
1041                                 obj->ttl = PING_DEF_TTL;
1042                                 ret = -1;
1043                         }
1044                         break;
1046                 case PING_OPT_AF:
1047                         obj->addrfamily = *((int *) value);
1048                         if ((obj->addrfamily != AF_UNSPEC)
1049                                         && (obj->addrfamily != AF_INET)
1050                                         && (obj->addrfamily != AF_INET6))
1051                         {
1052                                 obj->addrfamily = PING_DEF_AF;
1053                                 ret = -1;
1054                         }
1055                         if (obj->srcaddr != NULL)
1056                         {
1057                                 free (obj->srcaddr);
1058                                 obj->srcaddr = NULL;
1059                         }
1060                         break;
1062                 case PING_OPT_DATA:
1063                         if (obj->data != NULL)
1064                         {
1065                                 free (obj->data);
1066                                 obj->data = NULL;
1067                         }
1068                         obj->data = strdup ((const char *) value);
1069                         break;
1071                 case PING_OPT_SOURCE:
1072                 {
1073                         char            *hostname = (char *) value;
1074                         struct addrinfo  ai_hints;
1075                         struct addrinfo *ai_list;
1076                         int              status;
1077 #if WITH_DEBUG
1078                         if (obj->addrfamily != AF_UNSPEC)
1079                         {
1080                                 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
1081                         }
1082 #endif
1083                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
1084                         ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
1085 #if defined(AI_ADDRCONFIG)
1086                         ai_hints.ai_flags = AI_ADDRCONFIG;
1087 #endif
1088                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
1089                         if (status != 0)
1090                         {
1091 #if defined(EAI_SYSTEM)
1092                                 char errbuf[PING_ERRMSG_LEN];
1093 #endif
1094                                 ping_set_error (obj, "getaddrinfo",
1095 #if defined(EAI_SYSTEM)
1096                                                 (status == EAI_SYSTEM)
1097                                                 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1098 #endif
1099                                                 gai_strerror (status));
1100                                 ret = -1;
1101                                 break;
1102                         }
1103 #if WITH_DEBUG
1104                         if (ai_list->ai_next != NULL)
1105                         {
1106                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
1107                         }
1108 #endif
1109                         if (obj->srcaddr == NULL)
1110                         {
1111                                 obj->srcaddrlen = 0;
1112                                 obj->srcaddr = malloc (sizeof (struct sockaddr_storage));
1113                                 if (obj->srcaddr == NULL)
1114                                 {
1115                                         ping_set_errno (obj, errno);
1116                                         ret = -1;
1117                                         freeaddrinfo (ai_list);
1118                                         break;
1119                                 }
1120                         }
1121                         memset ((void *) obj->srcaddr, 0, sizeof (struct sockaddr_storage));
1122                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
1123                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
1124                                         ai_list->ai_addrlen);
1125                         obj->srcaddrlen = ai_list->ai_addrlen;
1126                         obj->addrfamily = ai_list->ai_family;
1128                         freeaddrinfo (ai_list);
1129                 } /* case PING_OPT_SOURCE */
1130                 break;
1132                 default:
1133                         ret = -2;
1134         } /* switch (option) */
1136         return (ret);
1137 } /* int ping_setopt */
1140 int ping_send (pingobj_t *obj)
1142         int ret;
1144         if (ping_send_all (obj) < 0)
1145                 return (-1);
1147         if ((ret = ping_receive_all (obj)) < 0)
1148                 return (-2);
1150         return (ret);
1153 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
1155         while (ph != NULL)
1156         {
1157                 if (strcasecmp (ph->username, host) == 0)
1158                         break;
1160                 ph = ph->next;
1161         }
1163         return (ph);
1166 int ping_host_add (pingobj_t *obj, const char *host)
1168         pinghost_t *ph;
1170         struct addrinfo  ai_hints;
1171         struct addrinfo *ai_list, *ai_ptr;
1172         int              ai_return;
1174         dprintf ("host = %s\n", host);
1176         if (ping_host_search (obj->head, host) != NULL)
1177                 return (0);
1179         memset (&ai_hints, '\0', sizeof (ai_hints));
1180         ai_hints.ai_flags     = 0;
1181 #ifdef AI_ADDRCONFIG
1182         ai_hints.ai_flags    |= AI_ADDRCONFIG;
1183 #endif
1184 #ifdef AI_CANONNAME
1185         ai_hints.ai_flags    |= AI_CANONNAME;
1186 #endif
1187         ai_hints.ai_family    = obj->addrfamily;
1188         ai_hints.ai_socktype  = SOCK_RAW;
1190         if ((ph = ping_alloc ()) == NULL)
1191         {
1192                 dprintf ("Out of memory!\n");
1193                 return (-1);
1194         }
1196         if ((ph->username = strdup (host)) == NULL)
1197         {
1198                 dprintf ("Out of memory!\n");
1199                 ping_set_errno (obj, errno);
1200                 ping_free (ph);
1201                 return (-1);
1202         }
1204         if ((ph->hostname = strdup (host)) == NULL)
1205         {
1206                 dprintf ("Out of memory!\n");
1207                 ping_set_errno (obj, errno);
1208                 ping_free (ph);
1209                 return (-1);
1210         }
1212         /* obj->data is not garuanteed to be != NULL */
1213         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1214         {
1215                 dprintf ("Out of memory!\n");
1216                 ping_set_errno (obj, errno);
1217                 ping_free (ph);
1218                 return (-1);
1219         }
1221         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1222         {
1223 #if defined(EAI_SYSTEM)
1224                 char errbuf[PING_ERRMSG_LEN];
1225 #endif
1226                 dprintf ("getaddrinfo failed\n");
1227                 ping_set_error (obj, "getaddrinfo",
1228 #if defined(EAI_SYSTEM)
1229                                                 (ai_return == EAI_SYSTEM)
1230                                                 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1231 #endif
1232                                 gai_strerror (ai_return));
1233                 ping_free (ph);
1234                 return (-1);
1235         }
1237         if (ai_list == NULL)
1238                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1240         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1241         {
1242                 ph->fd = -1;
1244                 if (ai_ptr->ai_family == AF_INET)
1245                 {
1246                         ai_ptr->ai_socktype = SOCK_RAW;
1247                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1248                 }
1249                 else if (ai_ptr->ai_family == AF_INET6)
1250                 {
1251                         ai_ptr->ai_socktype = SOCK_RAW;
1252                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1253                 }
1254                 else
1255                 {
1256                         char errmsg[PING_ERRMSG_LEN];
1258                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1259                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1261                         dprintf (errmsg);
1262                         ping_set_error (obj, "getaddrinfo", errmsg);
1263                         continue;
1264                 }
1266                 /* TODO: Move this to a static function `ping_open_socket' and
1267                  * call it whenever the socket dies. */
1268                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1269                 if (ph->fd == -1)
1270                 {
1271 #if WITH_DEBUG
1272                         char errbuf[PING_ERRMSG_LEN];
1273                         dprintf ("socket: %s\n",
1274                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1275 #endif
1276                         ping_set_errno (obj, errno);
1277                         continue;
1278                 }
1280                 if (obj->srcaddr != NULL)
1281                 {
1282                         assert (obj->srcaddrlen > 0);
1283                         assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1285                         if (bind (ph->fd, obj->srcaddr, obj->srcaddrlen) == -1)
1286                         {
1287 #if WITH_DEBUG
1288                                 char errbuf[PING_ERRMSG_LEN];
1289                                 dprintf ("bind: %s\n",
1290                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1291 #endif
1292                                 ping_set_errno (obj, errno);
1293                                 close (ph->fd);
1294                                 ph->fd = -1;
1295                                 continue;
1296                         }
1297                 }
1299                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1300                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1301                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1302                 ph->addrlen = ai_ptr->ai_addrlen;
1303                 ph->addrfamily = ai_ptr->ai_family;
1305 #ifdef AI_CANONNAME
1306                 if ((ai_ptr->ai_canonname != NULL)
1307                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1308                 {
1309                         char *old_hostname;
1311                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1312                                         ph->hostname, ai_ptr->ai_canonname);
1314                         old_hostname = ph->hostname;
1315                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1316                         {
1317                                 /* strdup failed, falling back to old hostname */
1318                                 ph->hostname = old_hostname;
1319                         }
1320                         else if (old_hostname != NULL)
1321                         {
1322                                 free (old_hostname);
1323                         }
1324                 }
1325 #endif /* AI_CANONNAME */
1327                 if (ph->addrfamily == AF_INET)
1328                 {
1329                         int opt = 1;
1331                         setsockopt (ph->fd, IPPROTO_IP, IP_RECVTTL,
1332                                         &opt, sizeof (opt));
1333                 }
1334                 else if (ph->addrfamily == AF_INET6)
1335                 {
1336                         int opt = 1;
1338                         setsockopt (ph->fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
1339                                         &opt, sizeof (opt));
1340                 }
1342                 break;
1343         }
1345         freeaddrinfo (ai_list);
1347         if (ph->fd < 0)
1348         {
1349                 ping_free (ph);
1350                 return (-1);
1351         }
1353         /*
1354          * Adding in the front is much easier, but then the iterator will
1355          * return the host that was added last as first host. That's just not
1356          * nice. -octo
1357          */
1358         if (obj->head == NULL)
1359         {
1360                 obj->head = ph;
1361         }
1362         else
1363         {
1364                 pinghost_t *hptr;
1366                 hptr = obj->head;
1367                 while (hptr->next != NULL)
1368                         hptr = hptr->next;
1370                 assert ((hptr != NULL) && (hptr->next == NULL));
1371                 hptr->next = ph;
1372         }
1374         ping_set_ttl (ph, obj->ttl);
1376         return (0);
1377 } /* int ping_host_add */
1379 int ping_host_remove (pingobj_t *obj, const char *host)
1381         pinghost_t *pre, *cur;
1383         pre = NULL;
1384         cur = obj->head;
1386         while (cur != NULL)
1387         {
1388                 if (strcasecmp (host, cur->username) == 0)
1389                         break;
1391                 pre = cur;
1392                 cur = cur->next;
1393         }
1395         if (cur == NULL)
1396         {
1397                 ping_set_error (obj, "ping_host_remove", "Host not found");
1398                 return (-1);
1399         }
1401         if (pre == NULL)
1402                 obj->head = cur->next;
1403         else
1404                 pre->next = cur->next;
1405         
1406         ping_free (cur);
1408         return (0);
1411 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1413         return ((pingobj_iter_t *) obj->head);
1416 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1418         return ((pingobj_iter_t *) iter->next);
1421 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1422                 void *buffer, size_t *buffer_len)
1424         int ret = EINVAL;
1426         size_t orig_buffer_len = *buffer_len;
1428         switch (info)
1429         {
1430                 case PING_INFO_USERNAME:
1431                         ret = ENOMEM;
1432                         *buffer_len = strlen (iter->username) + 1;
1433                         if (orig_buffer_len <= *buffer_len)
1434                                 break;
1435                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1436                          * will copy `*buffer_len' and pad the rest of
1437                          * `buffer' with null-bytes */
1438                         strncpy (buffer, iter->username, orig_buffer_len);
1439                         ret = 0;
1440                         break;
1442                 case PING_INFO_HOSTNAME:
1443                         ret = ENOMEM;
1444                         *buffer_len = strlen (iter->hostname) + 1;
1445                         if (orig_buffer_len < *buffer_len)
1446                                 break;
1447                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1448                          * will copy `*buffer_len' and pad the rest of
1449                          * `buffer' with null-bytes */
1450                         strncpy (buffer, iter->hostname, orig_buffer_len);
1451                         ret = 0;
1452                         break;
1454                 case PING_INFO_ADDRESS:
1455                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1456                                         iter->addrlen,
1457                                         (char *) buffer,
1458                                         *buffer_len,
1459                                         NULL, 0,
1460                                         NI_NUMERICHOST);
1461                         if (ret != 0)
1462                         {
1463                                 if ((ret == EAI_MEMORY)
1464 #ifdef EAI_OVERFLOW
1465                                                 || (ret == EAI_OVERFLOW)
1466 #endif
1467                                    )
1468                                         ret = ENOMEM;
1469 #if defined(EAI_SYSTEM)
1470                                 else if (ret == EAI_SYSTEM)
1471                                         ret = errno;
1472 #endif
1473                                 else
1474                                         ret = EINVAL;
1475                         }
1476                         break;
1478                 case PING_INFO_FAMILY:
1479                         ret = ENOMEM;
1480                         *buffer_len = sizeof (int);
1481                         if (orig_buffer_len < sizeof (int))
1482                                 break;
1483                         *((int *) buffer) = iter->addrfamily;
1484                         ret = 0;
1485                         break;
1487                 case PING_INFO_LATENCY:
1488                         ret = ENOMEM;
1489                         *buffer_len = sizeof (double);
1490                         if (orig_buffer_len < sizeof (double))
1491                                 break;
1492                         *((double *) buffer) = iter->latency;
1493                         ret = 0;
1494                         break;
1496                 case PING_INFO_DROPPED:
1497                         ret = ENOMEM;
1498                         *buffer_len = sizeof (uint32_t);
1499                         if (orig_buffer_len < sizeof (uint32_t))
1500                                 break;
1501                         *((uint32_t *) buffer) = iter->dropped;
1502                         ret = 0;
1503                         break;
1505                 case PING_INFO_SEQUENCE:
1506                         ret = ENOMEM;
1507                         *buffer_len = sizeof (unsigned int);
1508                         if (orig_buffer_len < sizeof (unsigned int))
1509                                 break;
1510                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1511                         ret = 0;
1512                         break;
1514                 case PING_INFO_IDENT:
1515                         ret = ENOMEM;
1516                         *buffer_len = sizeof (uint16_t);
1517                         if (orig_buffer_len < sizeof (uint16_t))
1518                                 break;
1519                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1520                         ret = 0;
1521                         break;
1523                 case PING_INFO_DATA:
1524                         ret = ENOMEM;
1525                         *buffer_len = strlen (iter->data);
1526                         if (orig_buffer_len < *buffer_len)
1527                                 break;
1528                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1529                         ret = 0;
1530                         break;
1532                 case PING_INFO_RECV_TTL:
1533                         ret = ENOMEM;
1534                         *buffer_len = sizeof (int);
1535                         if (orig_buffer_len < sizeof (int))
1536                                 break;
1537                         *((int *) buffer) = iter->recv_ttl;
1538                         ret = 0;
1539                         break;
1540         }
1542         return (ret);
1543 } /* ping_iterator_get_info */
1545 void *ping_iterator_get_context (pingobj_iter_t *iter)
1547         return (iter->context);
1550 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1552         iter->context = context;