Code

c64060c0ba2ad7ef27bd1e30a13c43e2ef88e616
[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         char                    *data;
117         void                    *context;
119         struct pinghost         *next;
120 };
122 struct pingobj
124         double                   timeout;
125         int                      ttl;
126         int                      addrfamily;
127         char                    *data;
129         struct sockaddr_storage *srcaddr;
130         socklen_t                srcaddrlen;
132         char                     errmsg[PING_ERRMSG_LEN];
134         pinghost_t              *head;
135 };
137 /*
138  * private (static) functions
139  */
140 /* Even though Posix requires "strerror_r" to return an "int",
141  * some systems (e.g. the GNU libc) return a "char *" _and_
142  * ignore the second argument ... -tokkee */
143 char *sstrerror (int errnum, char *buf, size_t buflen)
145         buf[0] = 0;
147 #if !HAVE_STRERROR_R
148         {
149                 snprintf (buf, buflen, "Error %i (%#x)", errnum, errnum);
150         }
151 /* #endif !HAVE_STRERROR_R */
153 #elif STRERROR_R_CHAR_P
154         {
155                 char *temp;
156                 temp = strerror_r (errnum, buf, buflen);
157                 if (buf[0] == 0)
158                 {
159                         if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
160                                 strncpy (buf, temp, buflen);
161                         else
162                                 strncpy (buf, "strerror_r did not return "
163                                                 "an error message", buflen);
164                 }
165         }
166 /* #endif STRERROR_R_CHAR_P */
168 #else
169         if (strerror_r (errnum, buf, buflen) != 0)
170         {
171                 snprintf (buf, buflen, "Error %i (%#x); "
172                                 "Additionally, strerror_r failed.",
173                                 errnum, errnum);
174         }
175 #endif /* STRERROR_R_CHAR_P */
177         buf[buflen - 1] = 0;
179         return (buf);
180 } /* char *sstrerror */
182 static void ping_set_error (pingobj_t *obj, const char *function,
183                 const char *message)
185         snprintf (obj->errmsg, sizeof (obj->errmsg),
186                         "%s: %s", function, message);
187         obj->errmsg[sizeof (obj->errmsg) - 1] = 0;
190 static void ping_set_errno (pingobj_t *obj, const char *function,
191                 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         char   buffer[4096];
427         ssize_t buffer_len;
429         struct timeval diff;
431         pinghost_t *host = NULL;
433         struct sockaddr_storage sa;
434         socklen_t               sa_len;
436         sa_len = sizeof (sa);
438         buffer_len = recvfrom (fd, buffer, sizeof (buffer), 0,
439                         (struct sockaddr *) &sa, &sa_len);
440         if (buffer_len < 0)
441         {
442 #if WITH_DEBUG
443                 char errbuf[PING_ERRMSG_LEN];
444                 dprintf ("recvfrom: %s\n",
445                                 sstrerror (errno, errbuf, sizeof (errbuf)));
446 #endif
447                 return (-1);
448         }
450         dprintf ("Read %zi bytes from fd = %i\n", buffer_len, fd);
452         if (sa.ss_family == AF_INET)
453         {
454                 if ((host = ping_receive_ipv4 (ph, buffer, buffer_len)) == NULL)
455                         return (-1);
456         }
457         else if (sa.ss_family == AF_INET6)
458         {
459                 if ((host = ping_receive_ipv6 (ph, buffer, buffer_len)) == NULL)
460                         return (-1);
461         }
463         dprintf ("rcvd: %12i.%06i\n",
464                         (int) now->tv_sec,
465                         (int) now->tv_usec);
466         dprintf ("sent: %12i.%06i\n",
467                         (int) host->timer->tv_sec,
468                         (int) host->timer->tv_usec);
470         if (ping_timeval_sub (now, host->timer, &diff) < 0)
471         {
472                 timerclear (host->timer);
473                 return (-1);
474         }
476         dprintf ("diff: %12i.%06i\n",
477                         (int) diff.tv_sec,
478                         (int) diff.tv_usec);
480         host->latency  = ((double) diff.tv_usec) / 1000.0;
481         host->latency += ((double) diff.tv_sec)  * 1000.0;
483         timerclear (host->timer);
485         return (0);
488 static int ping_receive_all (pingobj_t *obj)
490         fd_set readfds;
491         int num_readfds;
492         int max_readfds;
494         pinghost_t *ph;
495         pinghost_t *ptr;
497         struct timeval endtime;
498         struct timeval nowtime;
499         struct timeval timeout;
500         int status;
502         int ret;
504         ph = obj->head;
505         ret = 0;
507         for (ptr = ph; ptr != NULL; ptr = ptr->next)
508                 ptr->latency = -1.0;
510         if (gettimeofday (&nowtime, NULL) == -1)
511         {
512                 ping_set_errno (obj, "gettimeofday", errno);
513                 return (-1);
514         }
516         /* Set up timeout */
517         timeout.tv_sec = (time_t) obj->timeout;
518         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
520         dprintf ("Set timeout to %i.%06i seconds\n",
521                         (int) timeout.tv_sec,
522                         (int) timeout.tv_usec);
524         ping_timeval_add (&nowtime, &timeout, &endtime);
526         while (1)
527         {
528                 FD_ZERO (&readfds);
529                 num_readfds =  0;
530                 max_readfds = -1;
532                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
533                 {
534                         if (!timerisset (ptr->timer))
535                                 continue;
537                         FD_SET (ptr->fd, &readfds);
538                         num_readfds++;
540                         if (max_readfds < ptr->fd)
541                                 max_readfds = ptr->fd;
542                 }
544                 if (num_readfds == 0)
545                         break;
547                 if (gettimeofday (&nowtime, NULL) == -1)
548                 {
549                         ping_set_errno (obj, "gettimeofday", errno);
550                         return (-1);
551                 }
553                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
554                         break;
556                 dprintf ("Waiting on %i sockets for %i.%06i seconds\n", num_readfds,
557                                 (int) timeout.tv_sec,
558                                 (int) timeout.tv_usec);
560                 status = select (max_readfds + 1, &readfds, NULL, NULL, &timeout);
562                 if (gettimeofday (&nowtime, NULL) == -1)
563                 {
564                         ping_set_errno (obj, "gettimeofday", errno);
565                         return (-1);
566                 }
567                 
568                 if ((status == -1) && (errno == EINTR))
569                 {
570                         dprintf ("select was interrupted by signal..\n");
571                         continue;
572                 }
573                 else if (status < 0)
574                 {
575 #if WITH_DEBUG
576                         char errbuf[PING_ERRMSG_LEN];
577                         dprintf ("select: %s\n",
578                                         sstrerror (errno, errbuf, sizeof (errbuf)));
579 #endif
580                         break;
581                 }
582                 else if (status == 0)
583                 {
584                         dprintf ("select timed out\n");
585                         for (ptr = ph; ptr != NULL; ptr = ptr->next)
586                                 if (ptr->latency < 0.0)
587                                         ptr->dropped++;
588                         break;
589                 }
591                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
592                 {
593                         if (FD_ISSET (ptr->fd, &readfds))
594                                 if (ping_receive_one (ptr->fd, ph, &nowtime) == 0)
595                                         ret++;
596                 }
597         } /* while (1) */
598         
599         return (ret);
602 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
603  * Sending functions:                                                        *
604  *                                                                           *
605  * ping_send_all                                                             *
606  * +-> ping_send_one_ipv4                                                    *
607  * `-> ping_send_one_ipv6                                                    *
608  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
609 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
610                 const void *buf, size_t buflen)
612         ssize_t ret;
614         if (gettimeofday (ph->timer, NULL) == -1)
615         {
616                 timerclear (ph->timer);
617                 return (-1);
618         }
620         ret = sendto (ph->fd, buf, buflen, 0,
621                         (struct sockaddr *) ph->addr, ph->addrlen);
623         if (ret < 0)
624         {
625 #if defined(EHOSTUNREACH)
626                 if (errno == EHOSTUNREACH)
627                         return (0);
628 #endif
629 #if defined(ENETUNREACH)
630                 if (errno == ENETUNREACH)
631                         return (0);
632 #endif
633                 ping_set_errno (obj, "sendto", errno);
634         }
636         return (ret);
639 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
641         struct icmp *icmp4;
642         int status;
644         char buf[4096];
645         int  buflen;
647         char *data;
648         int   datalen;
650         dprintf ("ph->hostname = %s\n", ph->hostname);
652         memset (buf, '\0', sizeof (buf));
653         icmp4 = (struct icmp *) buf;
654         data  = (char *) (icmp4 + 1);
656         icmp4->icmp_type  = ICMP_ECHO;
657         icmp4->icmp_code  = 0;
658         icmp4->icmp_cksum = 0;
659         icmp4->icmp_id    = htons (ph->ident);
660         icmp4->icmp_seq   = htons (ph->sequence);
662         buflen = 4096 - sizeof (struct icmp);
663         strncpy (data, ph->data, buflen);
664         datalen = strlen (data);
666         buflen = datalen + sizeof (struct icmp);
668         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
670         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
672         status = ping_sendto (obj, ph, buf, buflen);
673         if (status < 0)
674         {
675                 perror ("ping_sendto");
676                 return (-1);
677         }
679         dprintf ("sendto: status = %i\n", status);
681         return (0);
684 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
686         struct icmp6_hdr *icmp6;
687         int status;
689         char buf[4096];
690         int  buflen;
692         char *data;
693         int   datalen;
695         dprintf ("ph->hostname = %s\n", ph->hostname);
697         memset (buf, '\0', sizeof (buf));
698         icmp6 = (struct icmp6_hdr *) buf;
699         data  = (char *) (icmp6 + 1);
701         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
702         icmp6->icmp6_code  = 0;
703         /* The checksum will be calculated by the TCP/IP stack.  */
704         /* FIXME */
705         icmp6->icmp6_cksum = 0;
706         icmp6->icmp6_id    = htons (ph->ident);
707         icmp6->icmp6_seq   = htons (ph->sequence);
709         buflen = 4096 - sizeof (struct icmp6_hdr);
710         strncpy (data, ph->data, buflen);
711         datalen = strlen (data);
713         buflen = datalen + sizeof (struct icmp6_hdr);
715         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
717         status = ping_sendto (obj, ph, buf, buflen);
718         if (status < 0)
719         {
720                 perror ("ping_sendto");
721                 return (-1);
722         }
724         dprintf ("sendto: status = %i\n", status);
726         return (0);
729 static int ping_send_all (pingobj_t *obj)
731         pinghost_t *ph;
732         pinghost_t *ptr;
734         int ret;
736         ret = 0;
737         ph = obj->head;
739         for (ptr = ph; ptr != NULL; ptr = ptr->next)
740         {
741                 /* start timer.. The GNU `ping6' starts the timer before
742                  * sending the packet, so I will do that too */
743                 if (gettimeofday (ptr->timer, NULL) == -1)
744                 {
745 #if WITH_DEBUG
746                         char errbuf[PING_ERRMSG_LEN];
747                         dprintf ("gettimeofday: %s\n",
748                                         sstrerror (errno, errbuf, sizeof (errbuf)));
749 #endif
750                         timerclear (ptr->timer);
751                         ret--;
752                         continue;
753                 }
754                 else
755                 {
756                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
757                 }
759                 if (ptr->addrfamily == AF_INET6)
760                 {       
761                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
762                         if (ping_send_one_ipv6 (obj, ptr) != 0)
763                         {
764                                 timerclear (ptr->timer);
765                                 ret--;
766                                 continue;
767                         }
768                 }
769                 else if (ptr->addrfamily == AF_INET)
770                 {
771                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
772                         if (ping_send_one_ipv4 (obj, ptr) != 0)
773                         {
774                                 timerclear (ptr->timer);
775                                 ret--;
776                                 continue;
777                         }
778                 }
779                 else /* this should not happen */
780                 {
781                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
782                         timerclear (ptr->timer);
783                         ret--;
784                         continue;
785                 }
787                 ptr->sequence++;
788         }
790         return (ret);
793 /*
794  * Set the TTL of a socket protocol independently.
795  */
796 static int ping_set_ttl (pinghost_t *ph, int ttl)
798         int ret = -2;
800         if (ph->addrfamily == AF_INET)
801         {
802                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL, &ttl, sizeof (ttl));
803         }
804         else if (ph->addrfamily == AF_INET6)
805         {
806                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof (ttl));
807         }
809         return (ret);
812 static int ping_get_ident (void)
814         int fd;
815         static int did_seed = 0;
817         int retval;
819         if (did_seed == 0)
820         {
821                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
822                 {
823                         unsigned int seed;
825                         if (read (fd, &seed, sizeof (seed)) != -1)
826                         {
827                                 did_seed = 1;
828                                 dprintf ("Random seed:   %#x\n", seed);
829                                 srandom (seed);
830                         }
832                         close (fd);
833                 }
834 #if WITH_DEBUG
835                 else
836                 {
837                         char errbuf[PING_ERRMSG_LEN];
838                         dprintf ("open (/dev/urandom): %s\n",
839                                         sstrerror (errno, errbuf, sizeof (errbuf)));
840                 }
841 #endif
842         }
844         retval = (int) random ();
846         dprintf ("Random number: %#x\n", retval);
847         
848         return (retval);
851 static pinghost_t *ping_alloc (void)
853         pinghost_t *ph;
854         size_t      ph_size;
856         ph_size = sizeof (pinghost_t)
857                 + sizeof (struct sockaddr_storage)
858                 + sizeof (struct timeval);
860         ph = (pinghost_t *) malloc (ph_size);
861         if (ph == NULL)
862                 return (NULL);
864         memset (ph, '\0', ph_size);
866         ph->timer   = (struct timeval *) (ph + 1);
867         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
869         ph->addrlen = sizeof (struct sockaddr_storage);
870         ph->fd      = -1;
871         ph->latency = -1.0;
872         ph->dropped = 0;
873         ph->ident   = ping_get_ident () & 0xFFFF;
875         return (ph);
878 static void ping_free (pinghost_t *ph)
880         if (ph->fd >= 0)
881                 close (ph->fd);
882         
883         if (ph->username != NULL)
884                 free (ph->username);
886         if (ph->hostname != NULL)
887                 free (ph->hostname);
889         if (ph->data != NULL)
890                 free (ph->data);
892         free (ph);
895 /*
896  * public methods
897  */
898 const char *ping_get_error (pingobj_t *obj)
900         return (obj->errmsg);
903 pingobj_t *ping_construct (void)
905         pingobj_t *obj;
907         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
908                 return (NULL);
909         memset (obj, '\0', sizeof (pingobj_t));
911         obj->timeout    = PING_DEF_TIMEOUT;
912         obj->ttl        = PING_DEF_TTL;
913         obj->addrfamily = PING_DEF_AF;
914         obj->data       = strdup (PING_DEF_DATA);
916         return (obj);
919 void ping_destroy (pingobj_t *obj)
921         pinghost_t *current;
922         pinghost_t *next;
924         current = obj->head;
925         next = NULL;
927         while (current != NULL)
928         {
929                 next = current->next;
930                 ping_free (current);
931                 current = next;
932         }
934         if (obj->data != NULL)
935                 free (obj->data);
937         if (obj->srcaddr != NULL)
938                 free (obj->srcaddr);
940         free (obj);
942         return;
945 int ping_setopt (pingobj_t *obj, int option, void *value)
947         int ret = 0;
949         switch (option)
950         {
951                 case PING_OPT_TIMEOUT:
952                         obj->timeout = *((double *) value);
953                         if (obj->timeout < 0.0)
954                         {
955                                 obj->timeout = PING_DEF_TIMEOUT;
956                                 ret = -1;
957                         }
958                         break;
960                 case PING_OPT_TTL:
961                         obj->ttl = *((int *) value);
962                         if ((obj->ttl < 1) || (obj->ttl > 255))
963                         {
964                                 obj->ttl = PING_DEF_TTL;
965                                 ret = -1;
966                         }
967                         break;
969                 case PING_OPT_AF:
970                         obj->addrfamily = *((int *) value);
971                         if ((obj->addrfamily != AF_UNSPEC)
972                                         && (obj->addrfamily != AF_INET)
973                                         && (obj->addrfamily != AF_INET6))
974                         {
975                                 obj->addrfamily = PING_DEF_AF;
976                                 ret = -1;
977                         }
978                         if (obj->srcaddr != NULL)
979                         {
980                                 free (obj->srcaddr);
981                                 obj->srcaddr = NULL;
982                         }
983                         break;
985                 case PING_OPT_DATA:
986                         if (obj->data != NULL)
987                         {
988                                 free (obj->data);
989                                 obj->data = NULL;
990                         }
991                         obj->data = strdup ((const char *) value);
992                         break;
994                 case PING_OPT_SOURCE:
995                 {
996                         char            *hostname = (char *) value;
997                         struct addrinfo  ai_hints;
998                         struct addrinfo *ai_list;
999                         int              status;
1000 #if WITH_DEBUG
1001                         if (obj->addrfamily != AF_UNSPEC)
1002                         {
1003                                 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
1004                         }
1005 #endif
1006                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
1007                         ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
1008 #if defined(AI_ADDRCONFIG)
1009                         ai_hints.ai_flags = AI_ADDRCONFIG;
1010 #endif
1011                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
1012                         if (status != 0)
1013                         {
1014 #if defined(EAI_SYSTEM)
1015                                 char errbuf[PING_ERRMSG_LEN];
1016 #endif
1017                                 ping_set_error (obj, "getaddrinfo",
1018 #if defined(EAI_SYSTEM)
1019                                                 (status == EAI_SYSTEM)
1020                                                 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1021 #endif
1022                                                 gai_strerror (status));
1023                                 ret = -1;
1024                                 break;
1025                         }
1026 #if WITH_DEBUG
1027                         if (ai_list->ai_next != NULL)
1028                         {
1029                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
1030                         }
1031 #endif
1032                         if (obj->srcaddr == NULL)
1033                         {
1034                                 obj->srcaddrlen = 0;
1035                                 obj->srcaddr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage));
1036                                 if (obj->srcaddr == NULL)
1037                                 {
1038                                         ping_set_errno (obj, "malloc", errno);
1039                                         ret = -1;
1040                                         freeaddrinfo (ai_list);
1041                                         break;
1042                                 }
1043                         }
1044                         memset ((void *) obj->srcaddr, '\0', sizeof (struct sockaddr_storage));
1045                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
1046                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
1047                                         ai_list->ai_addrlen);
1048                         obj->srcaddrlen = ai_list->ai_addrlen;
1049                         obj->addrfamily = ai_list->ai_family;
1051                         freeaddrinfo (ai_list);
1052                 } /* case PING_OPT_SOURCE */
1053                 break;
1055                 default:
1056                         ret = -2;
1057         } /* switch (option) */
1059         return (ret);
1060 } /* int ping_setopt */
1063 int ping_send (pingobj_t *obj)
1065         int ret;
1067         if (ping_send_all (obj) < 0)
1068                 return (-1);
1070         if ((ret = ping_receive_all (obj)) < 0)
1071                 return (-2);
1073         return (ret);
1076 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
1078         while (ph != NULL)
1079         {
1080                 if (strcasecmp (ph->username, host) == 0)
1081                         break;
1083                 ph = ph->next;
1084         }
1086         return (ph);
1089 int ping_host_add (pingobj_t *obj, const char *host)
1091         pinghost_t *ph;
1093         struct sockaddr_storage sockaddr;
1094         socklen_t               sockaddr_len;
1096         struct addrinfo  ai_hints;
1097         struct addrinfo *ai_list, *ai_ptr;
1098         int              ai_return;
1100         dprintf ("host = %s\n", host);
1102         if (ping_host_search (obj->head, host) != NULL)
1103                 return (0);
1105         memset (&ai_hints, '\0', sizeof (ai_hints));
1106         ai_hints.ai_flags     = 0;
1107 #ifdef AI_ADDRCONFIG
1108         ai_hints.ai_flags    |= AI_ADDRCONFIG;
1109 #endif
1110 #ifdef AI_CANONNAME
1111         ai_hints.ai_flags    |= AI_CANONNAME;
1112 #endif
1113         ai_hints.ai_family    = obj->addrfamily;
1114         ai_hints.ai_socktype  = SOCK_RAW;
1116         if ((ph = ping_alloc ()) == NULL)
1117         {
1118                 dprintf ("Out of memory!\n");
1119                 return (-1);
1120         }
1122         if ((ph->username = strdup (host)) == NULL)
1123         {
1124                 dprintf ("Out of memory!\n");
1125                 ping_set_errno (obj, "strdup", errno);
1126                 ping_free (ph);
1127                 return (-1);
1128         }
1130         if ((ph->hostname = strdup (host)) == NULL)
1131         {
1132                 dprintf ("Out of memory!\n");
1133                 ping_set_errno (obj, "strdup", errno);
1134                 ping_free (ph);
1135                 return (-1);
1136         }
1138         /* obj->data is not garuanteed to be != NULL */
1139         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1140         {
1141                 dprintf ("Out of memory!\n");
1142                 ping_set_errno (obj, "strdup", errno);
1143                 ping_free (ph);
1144                 return (-1);
1145         }
1147         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1148         {
1149 #if defined(EAI_SYSTEM)
1150                 char errbuf[PING_ERRMSG_LEN];
1151 #endif
1152                 dprintf ("getaddrinfo failed\n");
1153                 ping_set_error (obj, "getaddrinfo",
1154 #if defined(EAI_SYSTEM)
1155                                                 (ai_return == EAI_SYSTEM)
1156                                                 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1157 #endif
1158                                 gai_strerror (ai_return));
1159                 ping_free (ph);
1160                 return (-1);
1161         }
1163         if (ai_list == NULL)
1164                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1166         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1167         {
1168                 ph->fd = -1;
1170                 sockaddr_len = sizeof (sockaddr);
1171                 memset (&sockaddr, '\0', sockaddr_len);
1173                 if (ai_ptr->ai_family == AF_INET)
1174                 {
1175                         struct sockaddr_in *si;
1177                         si = (struct sockaddr_in *) &sockaddr;
1178                         si->sin_family = AF_INET;
1179                         si->sin_port   = htons (ph->ident);
1180                         si->sin_addr.s_addr = htonl (INADDR_ANY);
1182                         ai_ptr->ai_socktype = SOCK_RAW;
1183                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1184                 }
1185                 else if (ai_ptr->ai_family == AF_INET6)
1186                 {
1187                         struct sockaddr_in6 *si;
1189                         si = (struct sockaddr_in6 *) &sockaddr;
1190                         si->sin6_family = AF_INET6;
1191                         si->sin6_port   = htons (ph->ident);
1192                         si->sin6_addr   = in6addr_any;
1194                         ai_ptr->ai_socktype = SOCK_RAW;
1195                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1196                 }
1197                 else
1198                 {
1199                         char errmsg[PING_ERRMSG_LEN];
1201                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1202                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1204                         dprintf (errmsg);
1205                         ping_set_error (obj, "getaddrinfo", errmsg);
1206                         continue;
1207                 }
1209                 /* TODO: Move this to a static function `ping_open_socket' and
1210                  * call it whenever the socket dies. */
1211                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1212                 if (ph->fd == -1)
1213                 {
1214 #if WITH_DEBUG
1215                         char errbuf[PING_ERRMSG_LEN];
1216                         dprintf ("socket: %s\n",
1217                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1218 #endif
1219                         ping_set_errno (obj, "socket", errno);
1220                         continue;
1221                 }
1223                 if (obj->srcaddr != NULL)
1224                 {
1225                         assert (obj->srcaddrlen > 0);
1226                         assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1228                         if (bind (ph->fd, (struct sockaddr *) obj->srcaddr, obj->srcaddrlen) == -1)
1229                         {
1230 #if WITH_DEBUG
1231                                 char errbuf[PING_ERRMSG_LEN];
1232                                 dprintf ("bind: %s\n",
1233                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1234 #endif
1235                                 ping_set_errno (obj, "bind", errno);
1236                                 close (ph->fd);
1237                                 ph->fd = -1;
1238                                 continue;
1239                         }
1240                 }
1242                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1243                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1244                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1245                 ph->addrlen = ai_ptr->ai_addrlen;
1246                 ph->addrfamily = ai_ptr->ai_family;
1248 #ifdef AI_CANONNAME
1249                 if ((ai_ptr->ai_canonname != NULL)
1250                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1251                 {
1252                         char *old_hostname;
1254                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1255                                         ph->hostname, ai_ptr->ai_canonname);
1257                         old_hostname = ph->hostname;
1258                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1259                         {
1260                                 /* strdup failed, falling back to old hostname */
1261                                 ph->hostname = old_hostname;
1262                         }
1263                         else if (old_hostname != NULL)
1264                         {
1265                                 free (old_hostname);
1266                         }
1267                 }
1268 #endif /* AI_CANONNAME */
1270                 break;
1271         }
1273         freeaddrinfo (ai_list);
1275         if (ph->fd < 0)
1276         {
1277                 ping_free (ph);
1278                 return (-1);
1279         }
1281         /*
1282          * Adding in the front is much easier, but then the iterator will
1283          * return the host that was added last as first host. That's just not
1284          * nice. -octo
1285          */
1286         if (obj->head == NULL)
1287         {
1288                 obj->head = ph;
1289         }
1290         else
1291         {
1292                 pinghost_t *hptr;
1294                 hptr = obj->head;
1295                 while (hptr->next != NULL)
1296                         hptr = hptr->next;
1298                 assert ((hptr != NULL) && (hptr->next == NULL));
1299                 hptr->next = ph;
1300         }
1302         ping_set_ttl (ph, obj->ttl);
1304         return (0);
1307 int ping_host_remove (pingobj_t *obj, const char *host)
1309         pinghost_t *pre, *cur;
1311         pre = NULL;
1312         cur = obj->head;
1314         while (cur != NULL)
1315         {
1316                 if (strcasecmp (host, cur->username) == 0)
1317                         break;
1319                 pre = cur;
1320                 cur = cur->next;
1321         }
1323         if (cur == NULL)
1324         {
1325                 ping_set_error (obj, "ping_host_remove", "Host not found");
1326                 return (-1);
1327         }
1329         if (pre == NULL)
1330                 obj->head = cur->next;
1331         else
1332                 pre->next = cur->next;
1333         
1334         ping_free (cur);
1336         return (0);
1339 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1341         return ((pingobj_iter_t *) obj->head);
1344 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1346         return ((pingobj_iter_t *) iter->next);
1349 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1350                 void *buffer, size_t *buffer_len)
1352         int ret = EINVAL;
1354         size_t orig_buffer_len = *buffer_len;
1356         switch (info)
1357         {
1358                 case PING_INFO_USERNAME:
1359                         ret = ENOMEM;
1360                         *buffer_len = strlen (iter->username) + 1;
1361                         if (orig_buffer_len <= *buffer_len)
1362                                 break;
1363                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1364                          * will copy `*buffer_len' and pad the rest of
1365                          * `buffer' with null-bytes */
1366                         strncpy (buffer, iter->username, orig_buffer_len);
1367                         ret = 0;
1368                         break;
1370                 case PING_INFO_HOSTNAME:
1371                         ret = ENOMEM;
1372                         *buffer_len = strlen (iter->hostname) + 1;
1373                         if (orig_buffer_len < *buffer_len)
1374                                 break;
1375                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1376                          * will copy `*buffer_len' and pad the rest of
1377                          * `buffer' with null-bytes */
1378                         strncpy (buffer, iter->hostname, orig_buffer_len);
1379                         ret = 0;
1380                         break;
1382                 case PING_INFO_ADDRESS:
1383                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1384                                         iter->addrlen,
1385                                         (char *) buffer,
1386                                         *buffer_len,
1387                                         NULL, 0,
1388                                         NI_NUMERICHOST);
1389                         if (ret != 0)
1390                         {
1391                                 if ((ret == EAI_MEMORY)
1392 #ifdef EAI_OVERFLOW
1393                                                 || (ret == EAI_OVERFLOW)
1394 #endif
1395                                    )
1396                                         ret = ENOMEM;
1397 #if defined(EAI_SYSTEM)
1398                                 else if (ret == EAI_SYSTEM)
1399                                         ret = errno;
1400 #endif
1401                                 else
1402                                         ret = EINVAL;
1403                         }
1404                         break;
1406                 case PING_INFO_FAMILY:
1407                         ret = ENOMEM;
1408                         *buffer_len = sizeof (int);
1409                         if (orig_buffer_len < sizeof (int))
1410                                 break;
1411                         *((int *) buffer) = iter->addrfamily;
1412                         ret = 0;
1413                         break;
1415                 case PING_INFO_LATENCY:
1416                         ret = ENOMEM;
1417                         *buffer_len = sizeof (double);
1418                         if (orig_buffer_len < sizeof (double))
1419                                 break;
1420                         *((double *) buffer) = iter->latency;
1421                         ret = 0;
1422                         break;
1424                 case PING_INFO_DROPPED:
1425                         ret = ENOMEM;
1426                         *buffer_len = sizeof (uint32_t);
1427                         if (orig_buffer_len < sizeof (uint32_t))
1428                                 break;
1429                         *((uint32_t *) buffer) = iter->dropped;
1430                         ret = 0;
1431                         break;
1433                 case PING_INFO_SEQUENCE:
1434                         ret = ENOMEM;
1435                         *buffer_len = sizeof (unsigned int);
1436                         if (orig_buffer_len < sizeof (unsigned int))
1437                                 break;
1438                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1439                         ret = 0;
1440                         break;
1442                 case PING_INFO_IDENT:
1443                         ret = ENOMEM;
1444                         *buffer_len = sizeof (uint16_t);
1445                         if (orig_buffer_len < sizeof (uint16_t))
1446                                 break;
1447                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1448                         ret = 0;
1449                         break;
1451                 case PING_INFO_DATA:
1452                         ret = ENOMEM;
1453                         *buffer_len = strlen (iter->data);
1454                         if (orig_buffer_len < *buffer_len)
1455                                 break;
1456                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1457                         ret = 0;
1458                         break;
1459         }
1461         return (ret);
1462 } /* ping_iterator_get_info */
1464 void *ping_iterator_get_context (pingobj_iter_t *iter)
1466         return (iter->context);
1469 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1471         iter->context = context;