Code

5a39633b6eab1d4e4cef7f104d5ae7c045948e5b
[liboping.git] / src / liboping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2016  Florian octo Forster <ff at octo.it>
4  *
5  * This library is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU Lesser General Public License as published by the
7  * Free Software Foundation; either version 2.1 of the License, or (at your
8  * option) any later version.
9  * 
10  * This library is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
13  * for more details.
14  * 
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with this library; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18  */
20 #ifdef __APPLE__
21 #define __APPLE_USE_RFC_3542
22 #endif
24 #if HAVE_CONFIG_H
25 # include <config.h>
26 #endif
28 #if STDC_HEADERS
29 # include <stdlib.h>
30 # include <stdio.h>
31 # include <string.h>
32 # include <inttypes.h>
33 # include <errno.h>
34 # include <assert.h>
35 #else
36 # error "You don't have the standard C99 header files installed"
37 #endif /* STDC_HEADERS */
39 #ifdef HAVE_STDINT_H
40 # include <stdint.h>
41 #endif
43 #if HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif
47 #if HAVE_FCNTL_H
48 # include <fcntl.h>
49 #endif
50 #if HAVE_SYS_TYPES_H
51 # include <sys/types.h>
52 #endif
53 #if HAVE_SYS_STAT_H
54 # include <sys/stat.h>
55 #endif
57 #if TIME_WITH_SYS_TIME
58 # include <sys/time.h>
59 # include <time.h>
60 #else
61 # if HAVE_SYS_TIME_H
62 #  include <sys/time.h>
63 # else
64 #  include <time.h>
65 # endif
66 #endif
68 #if HAVE_SYS_SOCKET_H
69 # include <sys/socket.h>
70 #endif
72 #if HAVE_NETDB_H
73 # include <netdb.h>
74 #endif
76 #if HAVE_NETINET_IN_SYSTM_H
77 # include <netinet/in_systm.h>
78 #endif
79 #if HAVE_NETINET_IN_H
80 # include <netinet/in.h>
81 #endif
82 #if HAVE_NETINET_IP_H
83 # include <netinet/ip.h>
84 #endif
85 #if HAVE_NETINET_IP_ICMP_H
86 # include <netinet/ip_icmp.h>
87 #endif
88 #ifdef HAVE_NETINET_IP_VAR_H
89 # include <netinet/ip_var.h>
90 #endif
91 #if HAVE_NETINET_IP6_H
92 # include <netinet/ip6.h>
93 #endif
94 #if HAVE_NETINET_ICMP6_H
95 # include <netinet/icmp6.h>
96 #endif
98 #include "oping.h"
100 #if WITH_DEBUG
101 # define dprintf(...) printf ("%s[%4i]: %-20s: ", __FILE__, __LINE__, __FUNCTION__); printf (__VA_ARGS__)
102 #else
103 # define dprintf(...) /**/
104 #endif
106 #define PING_ERRMSG_LEN 256
107 #define PING_TABLE_LEN 5381
109 struct pinghost
111         /* username: name passed in by the user */
112         char                    *username;
113         /* hostname: name returned by the reverse lookup */
114         char                    *hostname;
115         struct sockaddr_storage *addr;
116         socklen_t                addrlen;
117         int                      addrfamily;
118         int                      ident;
119         int                      sequence;
120         struct timeval          *timer;
121         double                   latency;
122         uint32_t                 dropped;
123         int                      recv_ttl;
124         uint8_t                  recv_qos;
125         char                    *data;
127         void                    *context;
129         struct pinghost         *next;
130         struct pinghost         *table_next;
131 };
133 struct pingobj
135         double                   timeout;
136         int                      ttl;
137         int                      addrfamily;
138         uint8_t                  qos;
139         char                    *data;
141         int                      fd4;
142         int                      fd6;
144         struct sockaddr         *srcaddr;
145         socklen_t                srcaddrlen;
147         char                    *device;
149         char                    set_mark;
150         int                     mark;
152         char                     errmsg[PING_ERRMSG_LEN];
154         pinghost_t              *head;
155         pinghost_t              *table[PING_TABLE_LEN];
156 };
158 /*
159  * private (static) functions
160  */
161 /* Even though Posix requires "strerror_r" to return an "int",
162  * some systems (e.g. the GNU libc) return a "char *" _and_
163  * ignore the second argument ... -tokkee */
164 static char *sstrerror (int errnum, char *buf, size_t buflen)
166         buf[0] = 0;
168 #if !HAVE_STRERROR_R
169         {
170                 snprintf (buf, buflen, "Error %i (%#x)", errnum, errnum);
171         }
172 /* #endif !HAVE_STRERROR_R */
174 #elif STRERROR_R_CHAR_P
175         {
176                 char *temp;
177                 temp = strerror_r (errnum, buf, buflen);
178                 if (buf[0] == 0)
179                 {
180                         if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
181                                 strncpy (buf, temp, buflen);
182                         else
183                                 strncpy (buf, "strerror_r did not return "
184                                                 "an error message", buflen);
185                 }
186         }
187 /* #endif STRERROR_R_CHAR_P */
189 #else
190         if (strerror_r (errnum, buf, buflen) != 0)
191         {
192                 snprintf (buf, buflen, "Error %i (%#x); "
193                                 "Additionally, strerror_r failed.",
194                                 errnum, errnum);
195         }
196 #endif /* STRERROR_R_CHAR_P */
198         buf[buflen - 1] = 0;
200         return (buf);
201 } /* char *sstrerror */
203 static void ping_set_error (pingobj_t *obj, const char *function,
204                 const char *message)
206         snprintf (obj->errmsg, sizeof (obj->errmsg),
207                         "%s: %s", function, message);
208         obj->errmsg[sizeof (obj->errmsg) - 1] = 0;
211 static void ping_set_errno (pingobj_t *obj, int error_number)
213         sstrerror (error_number, obj->errmsg, sizeof (obj->errmsg));
216 static int ping_timeval_add (struct timeval *tv1, struct timeval *tv2,
217                 struct timeval *res)
219         res->tv_sec  = tv1->tv_sec  + tv2->tv_sec;
220         res->tv_usec = tv1->tv_usec + tv2->tv_usec;
222         while (res->tv_usec > 1000000)
223         {
224                 res->tv_usec -= 1000000;
225                 res->tv_sec++;
226         }
228         return (0);
231 static int ping_timeval_sub (struct timeval *tv1, struct timeval *tv2,
232                 struct timeval *res)
234         if ((tv1->tv_sec < tv2->tv_sec)
235                         || ((tv1->tv_sec == tv2->tv_sec)
236                                 && (tv1->tv_usec < tv2->tv_usec)))
237                 return (-1);
239         res->tv_sec  = tv1->tv_sec  - tv2->tv_sec;
240         res->tv_usec = tv1->tv_usec - tv2->tv_usec;
242         assert ((res->tv_sec > 0) || ((res->tv_sec == 0) && (res->tv_usec >= 0)));
244         while (res->tv_usec < 0)
245         {
246                 res->tv_usec += 1000000;
247                 res->tv_sec--;
248         }
250         return (0);
253 static uint16_t ping_icmp4_checksum (char *buf, size_t len)
255         uint32_t sum = 0;
256         uint16_t ret = 0;
258         uint16_t *ptr;
260         for (ptr = (uint16_t *) buf; len > 1; ptr++, len -= 2)
261                 sum += *ptr;
263         if (len == 1)
264         {
265                 *(char *) &ret = *(char *) ptr;
266                 sum += ret;
267         }
269         /* Do this twice to get all possible carries.. */
270         sum = (sum >> 16) + (sum & 0xFFFF);
271         sum = (sum >> 16) + (sum & 0xFFFF);
273         ret = ~sum;
275         return (ret);
278 static pinghost_t *ping_receive_ipv4 (pingobj_t *obj, char *buffer,
279                 size_t buffer_len)
281         struct ip *ip_hdr;
282         struct icmp *icmp_hdr;
284         size_t ip_hdr_len;
286         uint16_t recv_checksum;
287         uint16_t calc_checksum;
289         uint16_t ident;
290         uint16_t seq;
292         pinghost_t *ptr;
294         if (buffer_len < sizeof (struct ip))
295                 return (NULL);
297         ip_hdr     = (struct ip *) buffer;
298         ip_hdr_len = ip_hdr->ip_hl << 2;
300         if (buffer_len < ip_hdr_len)
301                 return (NULL);
303         buffer     += ip_hdr_len;
304         buffer_len -= ip_hdr_len;
306         if (buffer_len < ICMP_MINLEN)
307                 return (NULL);
309         icmp_hdr = (struct icmp *) buffer;
310         if (icmp_hdr->icmp_type != ICMP_ECHOREPLY)
311         {
312                 dprintf ("Unexpected ICMP type: %"PRIu8"\n", icmp_hdr->icmp_type);
313                 return (NULL);
314         }
316         recv_checksum = icmp_hdr->icmp_cksum;
317         /* This writes to buffer. */
318         icmp_hdr->icmp_cksum = 0;
319         calc_checksum = ping_icmp4_checksum (buffer, buffer_len);
321         if (recv_checksum != calc_checksum)
322         {
323                 dprintf ("Checksum missmatch: Got 0x%04"PRIx16", "
324                                 "calculated 0x%04"PRIx16"\n",
325                                 recv_checksum, calc_checksum);
326                 return (NULL);
327         }
329         ident = ntohs (icmp_hdr->icmp_id);
330         seq   = ntohs (icmp_hdr->icmp_seq);
332         for (ptr = obj->table[ident % PING_TABLE_LEN];
333                         ptr != NULL; ptr = ptr->table_next)
334         {
335                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
336                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
338                 if (ptr->addrfamily != AF_INET)
339                         continue;
341                 if (!timerisset (ptr->timer))
342                         continue;
344                 if (ptr->ident != ident)
345                         continue;
347                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
348                         continue;
350                 dprintf ("Match found: hostname = %s, ident = 0x%04"PRIx16", "
351                                 "seq = %"PRIu16"\n",
352                                 ptr->hostname, ident, seq);
354                 break;
355         }
357         if (ptr == NULL)
358         {
359                 dprintf ("No match found for ident = 0x%04"PRIx16", seq = %"PRIu16"\n",
360                                 ident, seq);
361         }
363         if (ptr != NULL){
364                 ptr->recv_ttl = (int)     ip_hdr->ip_ttl;
365                 ptr->recv_qos = (uint8_t) ip_hdr->ip_tos;
366         }
367         return (ptr);
370 #ifndef ICMP6_ECHO_REQUEST
371 # ifdef ICMP6_ECHO /* AIX netinet/ip6_icmp.h */
372 #  define ICMP6_ECHO_REQUEST ICMP6_ECHO
373 # else
374 #  define ICMP6_ECHO_REQUEST 128
375 # endif
376 #endif
378 #ifndef ICMP6_ECHO_REPLY
379 # ifdef ICMP6_ECHOREPLY /* AIX netinet/ip6_icmp.h */
380 #  define ICMP6_ECHO_REPLY ICMP6_ECHOREPLY
381 # else
382 #  define ICMP6_ECHO_REPLY 129
383 # endif
384 #endif
386 static pinghost_t *ping_receive_ipv6 (pingobj_t *obj, char *buffer,
387                 size_t buffer_len)
389         struct icmp6_hdr *icmp_hdr;
391         uint16_t ident;
392         uint16_t seq;
394         pinghost_t *ptr;
396         if (buffer_len < ICMP_MINLEN)
397                 return (NULL);
399         icmp_hdr = (struct icmp6_hdr *) buffer;
400         buffer     += ICMP_MINLEN;
401         buffer_len -= ICMP_MINLEN;
403         if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
404         {
405                 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
406                 return (NULL);
407         }
409         if (icmp_hdr->icmp6_code != 0)
410         {
411                 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
412                 return (NULL);
413         }
415         ident = ntohs (icmp_hdr->icmp6_id);
416         seq   = ntohs (icmp_hdr->icmp6_seq);
418         /* We have to iterate over all hosts, since ICMPv6 packets may
419          * be received on any raw v6 socket. */
420         for (ptr = obj->head; ptr != NULL; ptr = ptr->next)
421         {
422                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
423                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
425                 if (ptr->addrfamily != AF_INET6)
426                         continue;
428                 if (!timerisset (ptr->timer))
429                         continue;
431                 if (ptr->ident != ident)
432                         continue;
434                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
435                         continue;
437                 dprintf ("Match found: hostname = %s, ident = 0x%04"PRIx16", "
438                                 "seq = %"PRIu16"\n",
439                                 ptr->hostname, ident, seq);
441                 break;
442         }
444         if (ptr == NULL)
445         {
446                 dprintf ("No match found for ident = 0x%04"PRIx16", "
447                                 "seq = %"PRIu16"\n",
448                                 ident, seq);
449         }
451         return (ptr);
454 static int ping_receive_one (pingobj_t *obj, struct timeval *now, int addrfam)
456         int fd = addrfam == AF_INET6 ? obj->fd6 : obj->fd4;
457         struct timeval diff, pkt_now = *now;
458         pinghost_t *host = NULL;
459         int recv_ttl;
460         uint8_t recv_qos;
462         /*
463          * Set up the receive buffer..
464          */
465         struct msghdr msghdr;
466         struct cmsghdr *cmsg;
467         char payload_buffer[4096];
468         ssize_t payload_buffer_len;
469         char control_buffer[4096];
470         struct iovec payload_iovec;
472         memset (&payload_iovec, 0, sizeof (payload_iovec));
473         payload_iovec.iov_base = payload_buffer;
474         payload_iovec.iov_len = sizeof (payload_buffer);
476         memset (&msghdr, 0, sizeof (msghdr));
477         /* unspecified source address */
478         msghdr.msg_name = NULL;
479         msghdr.msg_namelen = 0;
480         /* output buffer vector, see readv(2) */
481         msghdr.msg_iov = &payload_iovec;
482         msghdr.msg_iovlen = 1;
483         /* output buffer for control messages */
484         msghdr.msg_control = control_buffer;
485         msghdr.msg_controllen = sizeof (control_buffer);
486         /* flags; this is an output only field.. */
487         msghdr.msg_flags = 0;
488 #ifdef MSG_XPG4_2
489         msghdr.msg_flags |= MSG_XPG4_2;
490 #endif
492         payload_buffer_len = recvmsg (fd, &msghdr, /* flags = */ 0);
493         if (payload_buffer_len < 0)
494         {
495 #if WITH_DEBUG
496                 char errbuf[PING_ERRMSG_LEN];
497                 dprintf ("recvfrom: %s\n",
498                                 sstrerror (errno, errbuf, sizeof (errbuf)));
499 #endif
500                 return (-1);
501         }
502         dprintf ("Read %zi bytes from fd = %i\n", payload_buffer_len, fd);
504         /* Iterate over all auxiliary data in msghdr */
505         recv_ttl = -1;
506         recv_qos = 0;
507         for (cmsg = CMSG_FIRSTHDR (&msghdr); /* {{{ */
508                         cmsg != NULL;
509                         cmsg = CMSG_NXTHDR (&msghdr, cmsg))
510         {
511                 if (cmsg->cmsg_level == SOL_SOCKET)
512                 {
513 #ifdef SO_TIMESTAMP
514                         if (cmsg->cmsg_type == SO_TIMESTAMP)
515                                 memcpy (&pkt_now, CMSG_DATA (cmsg), sizeof (pkt_now));
516 #endif /* SO_TIMESTAMP */
517                 }
518                 else if (addrfam == AF_INET) /* {{{ */
519                 {
520                         if (cmsg->cmsg_level != IPPROTO_IP)
521                                 continue;
523                         if (cmsg->cmsg_type == IP_TOS)
524                         {
525                                 memcpy (&recv_qos, CMSG_DATA (cmsg),
526                                                 sizeof (recv_qos));
527                                 dprintf ("TOSv4 = 0x%02"PRIx8";\n", recv_qos);
528                         } else
529                         if (cmsg->cmsg_type == IP_TTL)
530                         {
531                                 memcpy (&recv_ttl, CMSG_DATA (cmsg),
532                                                 sizeof (recv_ttl));
533                                 dprintf ("TTLv4 = %i;\n", recv_ttl);
534                         }
535                         else
536                         {
537                                 dprintf ("Not handling option %i.\n",
538                                                 cmsg->cmsg_type);
539                         }
540                 } /* }}} */
541                 else if (addrfam == AF_INET6) /* {{{ */
542                 {
543                         if (cmsg->cmsg_level != IPPROTO_IPV6)
544                                 continue;
546                         if (cmsg->cmsg_type == IPV6_TCLASS)
547                         {
548                                 memcpy (&recv_qos, CMSG_DATA (cmsg),
549                                                 sizeof (recv_qos));
550                                 dprintf ("TOSv6 = 0x%02"PRIx8";\n", recv_qos);
551                         } else
552 #ifdef IPV6_HOPLIMIT
553                         if (cmsg->cmsg_type == IPV6_HOPLIMIT)
554                         {
555                                 memcpy (&recv_ttl, CMSG_DATA (cmsg),
556                                                 sizeof (recv_ttl));
557                                 dprintf ("TTLv6 = %i;\n", recv_ttl);
558                         }
559                         else
560 #endif
561 #ifdef IPV6_UNICAST_HOPS
562                         if (cmsg->cmsg_type == IPV6_UNICAST_HOPS)
563                         {
564                                 memcpy (&recv_ttl, CMSG_DATA (cmsg),
565                                                 sizeof (recv_ttl));
566                                 dprintf ("TTLv6 = %i;\n", recv_ttl);
567                         }
568                         else
569 #endif
570 #ifdef IPV6_MULTICAST_HOPS
571                         if (cmsg->cmsg_type == IPV6_MULTICAST_HOPS)
572                         {
573                                 memcpy (&recv_ttl, CMSG_DATA (cmsg),
574                                                 sizeof (recv_ttl));
575                                 dprintf ("TTLv6 = %i;\n", recv_ttl);
576                         }
577                         else
578 #endif
579                         {
580                                 dprintf ("Not handling option %i.\n",
581                                                 cmsg->cmsg_type);
582                         }
583                 } /* }}} */
584                 else
585                 {
586                         dprintf ("Don't know how to handle "
587                                         "unknown protocol %i.\n",
588                                         cmsg->cmsg_level);
589                 }
590         } /* }}} for (cmsg) */
592         if (addrfam == AF_INET)
593         {
594                 host = ping_receive_ipv4 (obj, payload_buffer, payload_buffer_len);
595                 if (host == NULL)
596                         return (-1);
597         }
598         else if (addrfam == AF_INET6)
599         {
600                 host = ping_receive_ipv6 (obj, payload_buffer, payload_buffer_len);
601                 if (host == NULL)
602                         return (-1);
603         }
604         else
605         {
606                 dprintf ("ping_receive_one: Unknown address family %i.\n",
607                                 addrfam);
608                 return (-1);
609         }
611         dprintf ("rcvd: %12i.%06i\n",
612                         (int) pkt_now.tv_sec,
613                         (int) pkt_now.tv_usec);
614         dprintf ("sent: %12i.%06i\n",
615                         (int) host->timer->tv_sec,
616                         (int) host->timer->tv_usec);
618         if (ping_timeval_sub (&pkt_now, host->timer, &diff) < 0)
619         {
620                 timerclear (host->timer);
621                 return (-1);
622         }
624         dprintf ("diff: %12i.%06i\n",
625                         (int) diff.tv_sec,
626                         (int) diff.tv_usec);
628         if (recv_ttl >= 0)
629                 host->recv_ttl = recv_ttl;
630         host->recv_qos = recv_qos;
632         host->latency  = ((double) diff.tv_usec) / 1000.0;
633         host->latency += ((double) diff.tv_sec)  * 1000.0;
635         timerclear (host->timer);
637         return (0);
640 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
641  * Sending functions:                                                        *
642  *                                                                           *
643  * ping_send_all                                                             *
644  * +-> ping_send_one_ipv4                                                    *
645  * `-> ping_send_one_ipv6                                                    *
646  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
647 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
648                 const void *buf, size_t buflen, int fd)
650         ssize_t ret;
652         if (gettimeofday (ph->timer, NULL) == -1)
653         {
654                 timerclear (ph->timer);
655                 return (-1);
656         }
658         ret = sendto (fd, buf, buflen, 0,
659                         (struct sockaddr *) ph->addr, ph->addrlen);
661         if (ret < 0)
662         {
663 #if defined(EHOSTUNREACH)
664                 if (errno == EHOSTUNREACH)
665                         return (0);
666 #endif
667 #if defined(ENETUNREACH)
668                 if (errno == ENETUNREACH)
669                         return (0);
670 #endif
671                 ping_set_errno (obj, errno);
672         }
674         return (ret);
677 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph, int fd)
679         struct icmp *icmp4;
680         int status;
682         char   buf[4096] = {0};
683         size_t buflen;
685         char *data;
686         size_t datalen;
688         dprintf ("ph->hostname = %s\n", ph->hostname);
690         icmp4 = (struct icmp *) buf;
691         *icmp4 = (struct icmp) {
692                 .icmp_type = ICMP_ECHO,
693                 .icmp_id   = htons (ph->ident),
694                 .icmp_seq  = htons (ph->sequence),
695         };
697         datalen = strlen (ph->data);
698         buflen = ICMP_MINLEN + datalen;
699         if (sizeof (buf) < buflen)
700                 return (EINVAL);
702         data  = buf + ICMP_MINLEN;
703         memcpy (data, ph->data, datalen);
705         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
707         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
709         status = ping_sendto (obj, ph, buf, buflen, fd);
710         if (status < 0)
711         {
712                 perror ("ping_sendto");
713                 return (-1);
714         }
716         dprintf ("sendto: status = %i\n", status);
718         return (0);
721 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph, int fd)
723         struct icmp6_hdr *icmp6;
724         int status;
726         char buf[4096] = {0};
727         int  buflen;
729         char *data;
730         int   datalen;
732         dprintf ("ph->hostname = %s\n", ph->hostname);
734         icmp6 = (struct icmp6_hdr *) buf;
735         *icmp6 = (struct icmp6_hdr) {
736                 .icmp6_type  = ICMP6_ECHO_REQUEST,
737                 .icmp6_id    = htons (ph->ident),
738                 .icmp6_seq   = htons (ph->sequence),
739         };
741         datalen = strlen (ph->data);
742         buflen = sizeof (*icmp6) + datalen;
743         if (sizeof (buf) < buflen)
744                 return (EINVAL);
746         data  = buf + ICMP_MINLEN;
747         memcpy (data, ph->data, datalen);
749         /* The checksum will be calculated by the TCP/IP stack. */
751         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
753         status = ping_sendto (obj, ph, buf, buflen, fd);
754         if (status < 0)
755         {
756                 perror ("ping_sendto");
757                 return (-1);
758         }
760         dprintf ("sendto: status = %i\n", status);
762         return (0);
765 static int ping_send_one (pingobj_t *obj, pinghost_t *ptr, int fd)
767         if (gettimeofday (ptr->timer, NULL) == -1)
768         {
769                 /* start timer.. The GNU `ping6' starts the timer before
770                  * sending the packet, so I will do that too */
771 #if WITH_DEBUG
772                 char errbuf[PING_ERRMSG_LEN];
773                 dprintf ("gettimeofday: %s\n",
774                                 sstrerror (errno, errbuf, sizeof (errbuf)));
775 #endif
776                 timerclear (ptr->timer);
777                 return (-1);
778         }
779         else
780         {
781                 dprintf ("timer set for hostname = %s\n", ptr->hostname);
782         }
784         if (ptr->addrfamily == AF_INET6)
785         {
786                 dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
787                 if (ping_send_one_ipv6 (obj, ptr, fd) != 0)
788                 {
789                         timerclear (ptr->timer);
790                         return (-1);
791                 }
792         }
793         else if (ptr->addrfamily == AF_INET)
794         {
795                 dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
796                 if (ping_send_one_ipv4 (obj, ptr, fd) != 0)
797                 {
798                         timerclear (ptr->timer);
799                         return (-1);
800                 }
801         }
802         else /* this should not happen */
803         {
804                 dprintf ("Unknown address family: %i\n", ptr->addrfamily);
805                 timerclear (ptr->timer);
806                 return (-1);
807         }
809         ptr->sequence++;
811         return (0);
814 /*
815  * Set the TTL of a socket protocol independently.
816  */
817 static int ping_set_ttl (pingobj_t *obj, int ttl)
819         int ret = 0;
820         char errbuf[PING_ERRMSG_LEN];
822         if (obj->fd4 != -1)
823         {
824                 if (setsockopt (obj->fd4, IPPROTO_IP, IP_TTL,
825                                 &ttl, sizeof (ttl)))
826                 {
827                         ret = errno;
828                         ping_set_error (obj, "ping_set_ttl",
829                                         sstrerror (ret, errbuf, sizeof (errbuf)));
830                         dprintf ("Setting TTLv4 failed: %s\n", errbuf);
831                 }
832         }
834         if (obj->fd6 != -1)
835         {
836                 dprintf ("Setting TTLv6 to %i\n", ttl);
837                 if (setsockopt (obj->fd6, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
838                                 &ttl, sizeof (ttl)))
839                 {
840                         ret = errno;
841                         ping_set_error (obj, "ping_set_ttl",
842                                         sstrerror (ret, errbuf, sizeof (errbuf)));
843                         dprintf ("Setting TTLv6 failed: %s\n", errbuf);
844                 }
845         }
847         return (ret);
850 /*
851  * Set the TOS of a socket protocol independently.
852  *
853  * Using SOL_SOCKET / SO_PRIORITY might be a protocol independent way to
854  * set this. See socket(7) for details.
855  */
856 static int ping_set_qos (pingobj_t *obj, uint8_t qos)
858         int ret = 0;
859         char errbuf[PING_ERRMSG_LEN];
861         if (obj->fd4 != -1)
862         {
863                 dprintf ("Setting TP_TOS to %#04"PRIx8"\n", qos);
864                 if (setsockopt (obj->fd4, IPPROTO_IP, IP_TOS,
865                                 &qos, sizeof (qos)))
866                 {
867                         ret = errno;
868                         ping_set_error (obj, "ping_set_qos",
869                                         sstrerror (ret, errbuf, sizeof (errbuf)));
870                         dprintf ("Setting TP_TOS failed: %s\n", errbuf);
871                 }
872         }
874         if (obj->fd6 != -1)
875         {
876                 /* IPV6_TCLASS requires an "int". */
877                 int tmp = (int) qos;
879                 dprintf ("Setting IPV6_TCLASS to %#04"PRIx8" (%i)\n", qos, tmp);
880                 if (setsockopt (obj->fd6, IPPROTO_IPV6, IPV6_TCLASS,
881                         &tmp, sizeof (tmp)))
882                 {
883                         ret = errno;
884                         ping_set_error (obj, "ping_set_qos",
885                                         sstrerror (ret, errbuf, sizeof (errbuf)));
886                         dprintf ("Setting IPV6_TCLASS failed: %s\n", errbuf);
887                 }
888         }
890         return (ret);
893 static int ping_get_ident (void)
895         int fd;
896         static int did_seed = 0;
898         int retval;
900         if (did_seed == 0)
901         {
902                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
903                 {
904                         unsigned int seed;
906                         if (read (fd, &seed, sizeof (seed)) != -1)
907                         {
908                                 did_seed = 1;
909                                 dprintf ("Random seed:   %#x\n", seed);
910                                 srandom (seed);
911                         }
913                         close (fd);
914                 }
915 #if WITH_DEBUG
916                 else
917                 {
918                         char errbuf[PING_ERRMSG_LEN];
919                         dprintf ("open (/dev/urandom): %s\n",
920                                         sstrerror (errno, errbuf, sizeof (errbuf)));
921                 }
922 #endif
923         }
925         retval = (int) random ();
927         dprintf ("Random number: %#x\n", retval);
929         return (retval);
932 static pinghost_t *ping_alloc (void)
934         pinghost_t *ph;
935         size_t      ph_size;
937         ph_size = sizeof (pinghost_t)
938                 + sizeof (struct sockaddr_storage)
939                 + sizeof (struct timeval);
941         ph = (pinghost_t *) malloc (ph_size);
942         if (ph == NULL)
943                 return (NULL);
945         memset (ph, '\0', ph_size);
947         ph->timer   = (struct timeval *) (ph + 1);
948         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
950         ph->addrlen = sizeof (struct sockaddr_storage);
951         ph->latency = -1.0;
952         ph->dropped = 0;
953         ph->ident   = ping_get_ident () & 0xFFFF;
955         return (ph);
958 static void ping_free (pinghost_t *ph)
960         if (ph == NULL)
961                 return;
963         free (ph->username);
964         free (ph->hostname);
965         free (ph->data);
967         free (ph);
970 /* ping_open_socket opens, initializes and returns a new raw socket to use for
971  * ICMPv4 or ICMPv6 packets. addrfam must be either AF_INET or AF_INET6. On
972  * error, -1 is returned and obj->errmsg is set appropriately. */
973 static int ping_open_socket(pingobj_t *obj, int addrfam)
975         int fd;
976         if (addrfam == AF_INET6)
977         {
978                 fd = socket(addrfam, SOCK_RAW, IPPROTO_ICMPV6);
979         }
980         else if (addrfam == AF_INET)
981         {
982                 fd = socket(addrfam, SOCK_RAW, IPPROTO_ICMP);
983         }
984         else /* this should not happen */
985         {
986                 ping_set_error (obj, "ping_open_socket", "Unknown address family");
987                 dprintf ("Unknown address family: %i\n", addrfam);
988                 return -1;
989         }
991         if (fd == -1)
992         {
993                 ping_set_errno (obj, errno);
994 #if WITH_DEBUG
995                 char errbuf[PING_ERRMSG_LEN];
996                 dprintf ("socket: %s\n",
997                                 sstrerror (errno, errbuf, sizeof (errbuf)));
998 #endif
999                 return -1;
1000         }
1001         else if (fd >= FD_SETSIZE)
1002         {
1003                 ping_set_errno (obj, EMFILE);
1004                 dprintf ("socket(2) returned file descriptor %d, which is above the file "
1005                          "descriptor limit for select(2) (FD_SETSIZE = %d)\n",
1006                          fd, FD_SETSIZE);
1007                 close (fd);
1008                 return -1;
1009         }
1011         if (obj->srcaddr != NULL)
1012         {
1013                 assert (obj->srcaddrlen > 0);
1014                 assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1016                 if (bind (fd, obj->srcaddr, obj->srcaddrlen) == -1)
1017                 {
1018                         ping_set_errno (obj, errno);
1019 #if WITH_DEBUG
1020                         char errbuf[PING_ERRMSG_LEN];
1021                         dprintf ("bind: %s\n",
1022                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1023 #endif
1024                         close (fd);
1025                         return -1;
1026                 }
1027         }
1029 #ifdef SO_BINDTODEVICE
1030         if (obj->device != NULL)
1031         {
1032                 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1033                                 obj->device, strlen (obj->device) + 1) != 0)
1034                 {
1035                         ping_set_errno (obj, errno);
1036 #if WITH_DEBUG
1037                         char errbuf[PING_ERRMSG_LEN];
1038                         dprintf ("setsockopt (SO_BINDTODEVICE): %s\n",
1039                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1040 #endif
1041                         close (fd);
1042                         return -1;
1043                 }
1044         }
1045 #endif /* SO_BINDTODEVICE */
1046 #ifdef SO_MARK
1047         if (obj->set_mark)
1048         {
1049                 if (setsockopt(fd, SOL_SOCKET, SO_MARK,
1050                                 &obj->mark, sizeof(obj->mark)) != 0)
1051                 {
1052                         ping_set_errno (obj, errno);
1053 #if WITH_DEBUG
1054                         char errbuf[PING_ERRMSG_LEN];
1055                         dprintf ("setsockopt (SO_MARK): %s\n",
1056                                  sstrerror (errno, errbuf, sizeof (errbuf)));
1057 #endif
1058                         close (fd);
1059                         return -1;
1060                 }
1061         }
1062 #endif
1063 #ifdef SO_TIMESTAMP
1064         if (1) /* {{{ */
1065         {
1066                 int status = setsockopt (fd, SOL_SOCKET, SO_TIMESTAMP,
1067                                          &(int){1}, sizeof(int));
1068                 if (status != 0)
1069                 {
1070                         ping_set_errno (obj, errno);
1071 #if WITH_DEBUG
1072                         char errbuf[PING_ERRMSG_LEN];
1073                         dprintf ("setsockopt (SO_TIMESTAMP): %s\n",
1074                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1075 #endif
1076                         close (fd);
1077                         return -1;
1078                 }
1079         } /* }}} if (1) */
1080 #endif /* SO_TIMESTAMP */
1082         if (addrfam == AF_INET)
1083         {
1084 #ifdef IP_RECVTOS
1085                 /* Enable receiving the TOS field */
1086                 setsockopt (fd, IPPROTO_IP, IP_RECVTOS, &(int){1}, sizeof(int));
1087 #endif /* IP_RECVTOS */
1089                 /* Enable receiving the TTL field */
1090                 setsockopt (fd, IPPROTO_IP, IP_RECVTTL, &(int){1}, sizeof(int));
1091         }
1092 #if defined(IPV6_RECVHOPLIMIT) || defined(IPV6_RECVTCLASS)
1093         else if (addrfam == AF_INET6)
1094         {
1095 # if defined(IPV6_RECVHOPLIMIT)
1096                 /* For details see RFC 3542, section 6.3. */
1097                 setsockopt (fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
1098                             &(int){1}, sizeof(int));
1099 # endif /* IPV6_RECVHOPLIMIT */
1101 # if defined(IPV6_RECVTCLASS)
1102                 /* For details see RFC 3542, section 6.5. */
1103                 setsockopt (fd, IPPROTO_IPV6, IPV6_RECVTCLASS,
1104                             &(int){1}, sizeof(int));
1105 # endif /* IPV6_RECVTCLASS */
1106         }
1107 #endif /* IPV6_RECVHOPLIMIT || IPV6_RECVTCLASS */
1109         return fd;
1112 /*
1113  * public methods
1114  */
1115 const char *ping_get_error (pingobj_t *obj)
1117         if (obj == NULL)
1118                 return (NULL);
1119         return (obj->errmsg);
1122 pingobj_t *ping_construct (void)
1124         pingobj_t *obj;
1126         if ((obj = malloc (sizeof (*obj))) == NULL)
1127                 return (NULL);
1128         memset (obj, 0, sizeof (*obj));
1130         obj->timeout    = PING_DEF_TIMEOUT;
1131         obj->ttl        = PING_DEF_TTL;
1132         obj->addrfamily = PING_DEF_AF;
1133         obj->data       = strdup (PING_DEF_DATA);
1134         obj->qos        = 0;
1135         obj->fd4        = -1;
1136         obj->fd6        = -1;
1138         return (obj);
1141 void ping_destroy (pingobj_t *obj)
1143         pinghost_t *current;
1144         pinghost_t *next;
1146         if (obj == NULL)
1147                 return;
1149         current = obj->head;
1150         next = NULL;
1152         while (current != NULL)
1153         {
1154                 next = current->next;
1155                 ping_free (current);
1156                 current = next;
1157         }
1159         free (obj->data);
1160         free (obj->srcaddr);
1161         free (obj->device);
1163         if (obj->fd4 != -1)
1164                 close(obj->fd4);
1166         if (obj->fd6 != -1)
1167                 close(obj->fd6);
1169         free (obj);
1171         return;
1174 int ping_setopt (pingobj_t *obj, int option, void *value)
1176         int ret = 0;
1178         if ((obj == NULL) || (value == NULL))
1179                 return (-1);
1181         switch (option)
1182         {
1183                 case PING_OPT_QOS:
1184                 {
1185                         obj->qos = *((uint8_t *) value);
1186                         ret = ping_set_qos (obj, obj->qos);
1187                         break;
1188                 }
1190                 case PING_OPT_TIMEOUT:
1191                         obj->timeout = *((double *) value);
1192                         if (obj->timeout < 0.0)
1193                         {
1194                                 obj->timeout = PING_DEF_TIMEOUT;
1195                                 ret = -1;
1196                         }
1197                         break;
1199                 case PING_OPT_TTL:
1200                         ret = *((int *) value);
1201                         if ((ret < 1) || (ret > 255))
1202                         {
1203                                 obj->ttl = PING_DEF_TTL;
1204                                 ret = -1;
1205                         }
1206                         else
1207                         {
1208                                 obj->ttl = ret;
1209                                 ret = ping_set_ttl (obj, obj->ttl);
1210                         }
1211                         break;
1213                 case PING_OPT_AF:
1214                         obj->addrfamily = *((int *) value);
1215                         if ((obj->addrfamily != AF_UNSPEC)
1216                                         && (obj->addrfamily != AF_INET)
1217                                         && (obj->addrfamily != AF_INET6))
1218                         {
1219                                 obj->addrfamily = PING_DEF_AF;
1220                                 ret = -1;
1221                         }
1222                         if (obj->srcaddr != NULL)
1223                         {
1224                                 free (obj->srcaddr);
1225                                 obj->srcaddr = NULL;
1226                         }
1227                         break;
1229                 case PING_OPT_DATA:
1230                         if (obj->data != NULL)
1231                         {
1232                                 free (obj->data);
1233                                 obj->data = NULL;
1234                         }
1235                         obj->data = strdup ((const char *) value);
1236                         break;
1238                 case PING_OPT_SOURCE:
1239                 {
1240                         char            *hostname = (char *) value;
1241                         struct addrinfo  ai_hints;
1242                         struct addrinfo *ai_list;
1243                         int              status;
1244 #if WITH_DEBUG
1245                         if (obj->addrfamily != AF_UNSPEC)
1246                         {
1247                                 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
1248                         }
1249 #endif
1250                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
1251                         ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
1252 #if defined(AI_ADDRCONFIG)
1253                         ai_hints.ai_flags = AI_ADDRCONFIG;
1254 #endif
1255                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
1256                         if (status != 0)
1257                         {
1258 #if defined(EAI_SYSTEM)
1259                                 char errbuf[PING_ERRMSG_LEN];
1260 #endif
1261                                 ping_set_error (obj, "getaddrinfo",
1262 #if defined(EAI_SYSTEM)
1263                                                 (status == EAI_SYSTEM)
1264                                                 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1265 #endif
1266                                                 gai_strerror (status));
1267                                 ret = -1;
1268                                 break;
1269                         }
1270 #if WITH_DEBUG
1271                         if (ai_list->ai_next != NULL)
1272                         {
1273                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
1274                         }
1275 #endif
1276                         if (obj->srcaddr == NULL)
1277                         {
1278                                 obj->srcaddrlen = 0;
1279                                 obj->srcaddr = malloc (sizeof (struct sockaddr_storage));
1280                                 if (obj->srcaddr == NULL)
1281                                 {
1282                                         ping_set_errno (obj, errno);
1283                                         ret = -1;
1284                                         freeaddrinfo (ai_list);
1285                                         break;
1286                                 }
1287                         }
1288                         memset ((void *) obj->srcaddr, 0, sizeof (struct sockaddr_storage));
1289                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
1290                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
1291                                         ai_list->ai_addrlen);
1292                         obj->srcaddrlen = ai_list->ai_addrlen;
1293                         obj->addrfamily = ai_list->ai_family;
1295                         freeaddrinfo (ai_list);
1296                 } /* case PING_OPT_SOURCE */
1297                 break;
1299                 case PING_OPT_DEVICE:
1300                 {
1301 #ifdef SO_BINDTODEVICE
1302                         char *device = strdup ((char *) value);
1304                         if (device == NULL)
1305                         {
1306                                 ping_set_errno (obj, errno);
1307                                 ret = -1;
1308                                 break;
1309                         }
1311                         if (obj->device != NULL)
1312                                 free (obj->device);
1313                         obj->device = device;
1314 #else /* ! SO_BINDTODEVICE */
1315                         ping_set_errno (obj, ENOTSUP);
1316                         ret = -1;
1317 #endif /* ! SO_BINDTODEVICE */
1318                 } /* case PING_OPT_DEVICE */
1319                 break;
1321                 case PING_OPT_MARK:
1322                 {
1323 #ifdef SO_MARK
1324                         obj->mark     = *(int*)(value);
1325                         obj->set_mark = 1;
1326 #else /* SO_MARK */
1327                         ping_set_errno (obj, ENOTSUP);
1328                         ret = -1;
1329 #endif /* !SO_MARK */
1331                 } /* case PING_OPT_MARK */
1332                 break;
1334                 default:
1335                         ret = -2;
1336         } /* switch (option) */
1338         return (ret);
1339 } /* int ping_setopt */
1341 int ping_send (pingobj_t *obj)
1343         pinghost_t *ptr;
1345         struct timeval endtime;
1346         struct timeval nowtime;
1347         struct timeval timeout;
1349         _Bool need_ipv4_socket = 0;
1350         _Bool need_ipv6_socket = 0;
1352         for (ptr = obj->head; ptr != NULL; ptr = ptr->next)
1353         {
1354                 ptr->latency  = -1.0;
1355                 ptr->recv_ttl = -1;
1357                 if (ptr->addrfamily == AF_INET)
1358                         need_ipv4_socket = 1;
1359                 else if (ptr->addrfamily == AF_INET6)
1360                         need_ipv6_socket = 1;
1361         }
1363         if (!need_ipv4_socket && !need_ipv6_socket)
1364         {
1365                 ping_set_error (obj, "ping_send", "No hosts to ping");
1366                 return (-1);
1367         }
1369         if (need_ipv4_socket && obj->fd4 == -1)
1370         {
1371                 obj->fd4 = ping_open_socket(obj, AF_INET);
1372                 if (obj->fd4 == -1)
1373                         return (-1);
1374                 ping_set_ttl (obj, obj->ttl);
1375                 ping_set_qos (obj, obj->qos);
1376         }
1377         if (need_ipv6_socket && obj->fd6 == -1)
1378         {
1379                 obj->fd6 = ping_open_socket(obj, AF_INET6);
1380                 if (obj->fd6 == -1)
1381                         return (-1);
1382                 ping_set_ttl (obj, obj->ttl);
1383                 ping_set_qos (obj, obj->qos);
1384         }
1386         if (gettimeofday (&nowtime, NULL) == -1)
1387         {
1388                 ping_set_errno (obj, errno);
1389                 return (-1);
1390         }
1392         /* Set up timeout */
1393         timeout.tv_sec = (time_t) obj->timeout;
1394         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
1396         dprintf ("Set timeout to %i.%06i seconds\n",
1397                         (int) timeout.tv_sec,
1398                         (int) timeout.tv_usec);
1400         ping_timeval_add (&nowtime, &timeout, &endtime);
1402         /* host_to_ping points to the host to which to send the next ping. The
1403          * pointer is advanced to the next host in the linked list after the
1404          * ping has been sent. If host_to_ping is NULL, no more pings need to be
1405          * send out. */
1406         pinghost_t *host_to_ping = obj->head;
1408         /* pings_in_flight is the number of hosts we sent a "ping" to but didn't
1409          * receive a "pong" yet. */
1410         int pings_in_flight = 0;
1412         /* pongs_received is the number of echo replies received. Unless there
1413          * is an error, this is used as the return value of ping_send(). */
1414         int pongs_received = 0;
1416         int error_count = 0;
1418         while (pings_in_flight > 0 || host_to_ping != NULL)
1419         {
1420                 fd_set read_fds;
1421                 fd_set write_fds;
1423                 int write_fd = -1;
1424                 int max_fd = -1;
1426                 FD_ZERO (&read_fds);
1427                 FD_ZERO (&write_fds);
1429                 if (obj->fd4 != -1)
1430                 {
1431                         FD_SET(obj->fd4, &read_fds);
1432                         if (host_to_ping != NULL && host_to_ping->addrfamily == AF_INET)
1433                                 write_fd = obj->fd4;
1435                         if (max_fd < obj->fd4)
1436                                 max_fd = obj->fd4;
1437                 }
1439                 if (obj->fd6 != -1)
1440                 {
1441                         FD_SET(obj->fd6, &read_fds);
1442                         if (host_to_ping != NULL && host_to_ping->addrfamily == AF_INET6)
1443                                 write_fd = obj->fd6;
1445                         if (max_fd < obj->fd6)
1446                                 max_fd = obj->fd6;
1447                 }
1449                 if (write_fd != -1)
1450                         FD_SET(write_fd, &write_fds);
1452                 assert (max_fd != -1);
1453                 assert (max_fd < FD_SETSIZE);
1455                 if (gettimeofday (&nowtime, NULL) == -1)
1456                 {
1457                         ping_set_errno (obj, errno);
1458                         return (-1);
1459                 }
1461                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
1462                         break;
1464                 dprintf ("Waiting on %i sockets for %u.%06u seconds\n",
1465                                 ((obj->fd4 != -1) ? 1 : 0) + ((obj->fd6 != -1) ? 1 : 0),
1466                                 (unsigned) timeout.tv_sec,
1467                                 (unsigned) timeout.tv_usec);
1469                 int status = select (max_fd + 1, &read_fds, &write_fds, NULL, &timeout);
1471                 if (gettimeofday (&nowtime, NULL) == -1)
1472                 {
1473                         ping_set_errno (obj, errno);
1474                         return (-1);
1475                 }
1477                 if (status == -1)
1478                 {
1479                         ping_set_errno (obj, errno);
1480                         dprintf ("select: %s\n", obj->errmsg);
1481                         return (-1);
1482                 }
1483                 else if (status == 0)
1484                 {
1485                         dprintf ("select timed out\n");
1487                         pinghost_t *ph;
1488                         for (ph = obj->head; ph != NULL; ph = ph->next)
1489                                 if (ph->latency < 0.0)
1490                                         ph->dropped++;
1491                         break;
1492                 }
1494                 /* first, check if we can receive a reply ... */
1495                 if (obj->fd6  != -1 && FD_ISSET (obj->fd6, &read_fds))
1496                 {
1497                         if (ping_receive_one (obj, &nowtime, AF_INET6) == 0)
1498                         {
1499                                 pings_in_flight--;
1500                                 pongs_received++;
1501                         }
1502                         continue;
1503                 }
1504                 if (obj->fd4 != -1 && FD_ISSET (obj->fd4, &read_fds))
1505                 {
1506                         if (ping_receive_one (obj, &nowtime, AF_INET) == 0)
1507                         {
1508                                 pings_in_flight--;
1509                                 pongs_received++;
1510                         }
1511                         continue;
1512                 }
1514                 /* ... and if no reply is available to read, continue sending
1515                  * out pings. */
1517                 /* this condition should always be true. We keep it for
1518                  * consistency with the read blocks above and just to be on the
1519                  * safe side. */
1520                 if (write_fd != -1 && FD_ISSET (write_fd, &write_fds))
1521                 {
1522                         if (ping_send_one (obj, host_to_ping, write_fd) == 0)
1523                                 pings_in_flight++;
1524                         else
1525                                 error_count++;
1526                         host_to_ping = host_to_ping->next;
1527                         continue;
1528                 }
1529         } /* while (1) */
1531         if (error_count)
1532                 return (-1 * error_count);
1533         return (pongs_received);
1534 } /* int ping_send */
1536 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
1538         while (ph != NULL)
1539         {
1540                 if (strcasecmp (ph->username, host) == 0)
1541                         break;
1543                 ph = ph->next;
1544         }
1546         return (ph);
1549 int ping_host_add (pingobj_t *obj, const char *host)
1551         pinghost_t *ph;
1553         struct addrinfo  ai_hints;
1554         struct addrinfo *ai_list, *ai_ptr;
1555         int              ai_return;
1557         if ((obj == NULL) || (host == NULL))
1558                 return (-1);
1560         dprintf ("host = %s\n", host);
1562         if (ping_host_search (obj->head, host) != NULL)
1563                 return (0);
1565         memset (&ai_hints, '\0', sizeof (ai_hints));
1566         ai_hints.ai_flags     = 0;
1567 #ifdef AI_ADDRCONFIG
1568         ai_hints.ai_flags    |= AI_ADDRCONFIG;
1569 #endif
1570 #ifdef AI_CANONNAME
1571         ai_hints.ai_flags    |= AI_CANONNAME;
1572 #endif
1573         ai_hints.ai_family    = obj->addrfamily;
1574         ai_hints.ai_socktype  = SOCK_RAW;
1576         if ((ph = ping_alloc ()) == NULL)
1577         {
1578                 dprintf ("Out of memory!\n");
1579                 return (-1);
1580         }
1582         if ((ph->username = strdup (host)) == NULL)
1583         {
1584                 dprintf ("Out of memory!\n");
1585                 ping_set_errno (obj, errno);
1586                 ping_free (ph);
1587                 return (-1);
1588         }
1590         if ((ph->hostname = strdup (host)) == NULL)
1591         {
1592                 dprintf ("Out of memory!\n");
1593                 ping_set_errno (obj, errno);
1594                 ping_free (ph);
1595                 return (-1);
1596         }
1598         /* obj->data is not garuanteed to be != NULL */
1599         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1600         {
1601                 dprintf ("Out of memory!\n");
1602                 ping_set_errno (obj, errno);
1603                 ping_free (ph);
1604                 return (-1);
1605         }
1607         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1608         {
1609 #if defined(EAI_SYSTEM)
1610                 char errbuf[PING_ERRMSG_LEN];
1611 #endif
1612                 dprintf ("getaddrinfo failed\n");
1613                 ping_set_error (obj, "getaddrinfo",
1614 #if defined(EAI_SYSTEM)
1615                                                 (ai_return == EAI_SYSTEM)
1616                                                 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1617 #endif
1618                                 gai_strerror (ai_return));
1619                 ping_free (ph);
1620                 return (-1);
1621         }
1623         if (ai_list == NULL)
1624                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1626         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1627         {
1628                 if (ai_ptr->ai_family == AF_INET)
1629                 {
1630                         ai_ptr->ai_socktype = SOCK_RAW;
1631                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1632                 }
1633                 else if (ai_ptr->ai_family == AF_INET6)
1634                 {
1635                         ai_ptr->ai_socktype = SOCK_RAW;
1636                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1637                 }
1638                 else
1639                 {
1640                         char errmsg[PING_ERRMSG_LEN];
1642                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1643                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1645                         dprintf ("%s", errmsg);
1646                         ping_set_error (obj, "getaddrinfo", errmsg);
1647                         continue;
1648                 }
1650                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1651                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1652                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1653                 ph->addrlen = ai_ptr->ai_addrlen;
1654                 ph->addrfamily = ai_ptr->ai_family;
1656 #ifdef AI_CANONNAME
1657                 if ((ai_ptr->ai_canonname != NULL)
1658                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1659                 {
1660                         char *old_hostname;
1662                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1663                                         ph->hostname, ai_ptr->ai_canonname);
1665                         old_hostname = ph->hostname;
1666                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1667                         {
1668                                 /* strdup failed, falling back to old hostname */
1669                                 ph->hostname = old_hostname;
1670                         }
1671                         else if (old_hostname != NULL)
1672                         {
1673                                 free (old_hostname);
1674                         }
1675                 }
1676 #endif /* AI_CANONNAME */
1677         } /* for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) */
1679         freeaddrinfo (ai_list);
1681         /*
1682          * Adding in the front is much easier, but then the iterator will
1683          * return the host that was added last as first host. That's just not
1684          * nice. -octo
1685          */
1686         if (obj->head == NULL)
1687         {
1688                 obj->head = ph;
1689         }
1690         else
1691         {
1692                 pinghost_t *hptr;
1694                 hptr = obj->head;
1695                 while (hptr->next != NULL)
1696                         hptr = hptr->next;
1698                 assert ((hptr != NULL) && (hptr->next == NULL));
1699                 hptr->next = ph;
1700         }
1702         ph->table_next = obj->table[ph->ident % PING_TABLE_LEN];
1703         obj->table[ph->ident % PING_TABLE_LEN] = ph;
1705         return (0);
1706 } /* int ping_host_add */
1708 int ping_host_remove (pingobj_t *obj, const char *host)
1710         pinghost_t *pre, *cur, *target;
1712         if ((obj == NULL) || (host == NULL))
1713                 return (-1);
1715         pre = NULL;
1716         cur = obj->head;
1718         while (cur != NULL)
1719         {
1720                 if (strcasecmp (host, cur->username) == 0)
1721                         break;
1723                 pre = cur;
1724                 cur = cur->next;
1725         }
1727         if (cur == NULL)
1728         {
1729                 ping_set_error (obj, "ping_host_remove", "Host not found");
1730                 return (-1);
1731         }
1733         if (pre == NULL)
1734                 obj->head = cur->next;
1735         else
1736                 pre->next = cur->next;
1738         target = cur;
1739         pre = NULL;
1741         cur = obj->table[target->ident % PING_TABLE_LEN];
1743         while (cur != NULL)
1744         {
1745                 if (cur == target)
1746                         break;
1748                 pre = cur;
1749                 cur = cur->table_next;
1750         }
1752         if (cur == NULL)
1753         {
1754                 ping_set_error(obj, "ping_host_remove", "Host not found (T)");
1755                 ping_free(target);
1756                 return (-1);
1757         }
1759         if (pre == NULL)
1760                 obj->table[target->ident % PING_TABLE_LEN] = cur->table_next;
1761         else
1762                 pre->table_next = cur->table_next;
1764         ping_free (cur);
1766         return (0);
1769 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1771         if (obj == NULL)
1772                 return (NULL);
1773         return ((pingobj_iter_t *) obj->head);
1776 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1778         if (iter == NULL)
1779                 return (NULL);
1780         return ((pingobj_iter_t *) iter->next);
1783 int ping_iterator_count (pingobj_t *obj)
1785         if (obj == NULL)
1786                 return 0;
1788         int count = 0;
1789         pingobj_iter_t *iter = obj->head;
1790         while (iter) {
1791                 count++;
1792                 iter = iter->next;
1793         }
1794         return count;
1797 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1798                 void *buffer, size_t *buffer_len)
1800         int ret = EINVAL;
1802         size_t orig_buffer_len = *buffer_len;
1804         if ((iter == NULL) || (buffer_len == NULL))
1805                 return (-1);
1807         if ((buffer == NULL) && (*buffer_len != 0 ))
1808                 return (-1);
1810         switch (info)
1811         {
1812                 case PING_INFO_USERNAME:
1813                         ret = ENOMEM;
1814                         *buffer_len = strlen (iter->username) + 1;
1815                         if (orig_buffer_len <= *buffer_len)
1816                                 break;
1817                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1818                          * will copy `*buffer_len' and pad the rest of
1819                          * `buffer' with null-bytes */
1820                         strncpy (buffer, iter->username, orig_buffer_len);
1821                         ret = 0;
1822                         break;
1824                 case PING_INFO_HOSTNAME:
1825                         ret = ENOMEM;
1826                         *buffer_len = strlen (iter->hostname) + 1;
1827                         if (orig_buffer_len < *buffer_len)
1828                                 break;
1829                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1830                          * will copy `*buffer_len' and pad the rest of
1831                          * `buffer' with null-bytes */
1832                         strncpy (buffer, iter->hostname, orig_buffer_len);
1833                         ret = 0;
1834                         break;
1836                 case PING_INFO_ADDRESS:
1837                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1838                                         iter->addrlen,
1839                                         (char *) buffer,
1840                                         *buffer_len,
1841                                         NULL, 0,
1842                                         NI_NUMERICHOST);
1843                         if (ret != 0)
1844                         {
1845                                 if ((ret == EAI_MEMORY)
1846 #ifdef EAI_OVERFLOW
1847                                                 || (ret == EAI_OVERFLOW)
1848 #endif
1849                                    )
1850                                         ret = ENOMEM;
1851 #if defined(EAI_SYSTEM)
1852                                 else if (ret == EAI_SYSTEM)
1853                                         ret = errno;
1854 #endif
1855                                 else
1856                                         ret = EINVAL;
1857                         }
1858                         break;
1860                 case PING_INFO_FAMILY:
1861                         ret = ENOMEM;
1862                         *buffer_len = sizeof (int);
1863                         if (orig_buffer_len < sizeof (int))
1864                                 break;
1865                         *((int *) buffer) = iter->addrfamily;
1866                         ret = 0;
1867                         break;
1869                 case PING_INFO_LATENCY:
1870                         ret = ENOMEM;
1871                         *buffer_len = sizeof (double);
1872                         if (orig_buffer_len < sizeof (double))
1873                                 break;
1874                         *((double *) buffer) = iter->latency;
1875                         ret = 0;
1876                         break;
1878                 case PING_INFO_DROPPED:
1879                         ret = ENOMEM;
1880                         *buffer_len = sizeof (uint32_t);
1881                         if (orig_buffer_len < sizeof (uint32_t))
1882                                 break;
1883                         *((uint32_t *) buffer) = iter->dropped;
1884                         ret = 0;
1885                         break;
1887                 case PING_INFO_SEQUENCE:
1888                         ret = ENOMEM;
1889                         *buffer_len = sizeof (unsigned int);
1890                         if (orig_buffer_len < sizeof (unsigned int))
1891                                 break;
1892                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1893                         ret = 0;
1894                         break;
1896                 case PING_INFO_IDENT:
1897                         ret = ENOMEM;
1898                         *buffer_len = sizeof (uint16_t);
1899                         if (orig_buffer_len < sizeof (uint16_t))
1900                                 break;
1901                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1902                         ret = 0;
1903                         break;
1905                 case PING_INFO_DATA:
1906                         ret = ENOMEM;
1907                         *buffer_len = strlen (iter->data);
1908                         if (orig_buffer_len < *buffer_len)
1909                                 break;
1910                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1911                         ret = 0;
1912                         break;
1914                 case PING_INFO_RECV_TTL:
1915                         ret = ENOMEM;
1916                         *buffer_len = sizeof (int);
1917                         if (orig_buffer_len < sizeof (int))
1918                                 break;
1919                         *((int *) buffer) = iter->recv_ttl;
1920                         ret = 0;
1921                         break;
1923                 case PING_INFO_RECV_QOS:
1924                         ret = ENOMEM;
1925                         if (*buffer_len>sizeof(unsigned)) *buffer_len=sizeof(unsigned);
1926                         if (!*buffer_len) *buffer_len=1;
1927                         if (orig_buffer_len < *buffer_len)
1928                                 break;
1929                         memcpy(buffer,&iter->recv_qos,*buffer_len);
1930                         ret = 0;
1931                         break;
1932         }
1934         return (ret);
1935 } /* ping_iterator_get_info */
1937 void *ping_iterator_get_context (pingobj_iter_t *iter)
1939         if (iter == NULL)
1940                 return (NULL);
1941         return (iter->context);
1944 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1946         if (iter == NULL)
1947                 return;
1948         iter->context = context;