74122a80f63706c4c9166f30bba50f6c6e3a3073
[liboping.git] / src / liboping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2011  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  */
19
20 #ifdef __APPLE__
21 #define __APPLE_USE_RFC_3542
22 #endif
23
24 #if HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27
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 */
38
39 #ifdef HAVE_STDINT_H
40 # include <stdint.h>
41 #endif
42
43 #if HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif
46
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
56
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
67
68 #if HAVE_SYS_SOCKET_H
69 # include <sys/socket.h>
70 #endif
71
72 #if HAVE_NETDB_H
73 # include <netdb.h>
74 #endif
75
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
97
98 #include "oping.h"
99
100 #if WITH_DEBUG
101 # define dprintf(...) printf ("%s[%4i]: %-20s: ", __FILE__, __LINE__, __FUNCTION__); printf (__VA_ARGS__)
102 #else
103 # define dprintf(...) /**/
104 #endif
105
106 #define PING_ERRMSG_LEN 256
107
108 struct pinghost
109 {
110         /* username: name passed in by the user */
111         char                    *username;
112         /* hostname: name returned by the reverse lookup */
113         char                    *hostname;
114         struct sockaddr_storage *addr;
115         socklen_t                addrlen;
116         int                      addrfamily;
117         int                      fd;
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;
126
127         void                    *context;
128
129         struct pinghost         *next;
130 };
131
132 struct pingobj
133 {
134         double                   timeout;
135         int                      ttl;
136         int                      addrfamily;
137         uint8_t                  qos;
138         char                    *data;
139
140         struct sockaddr         *srcaddr;
141         socklen_t                srcaddrlen;
142
143         char                    *device;
144
145         char                     errmsg[PING_ERRMSG_LEN];
146
147         pinghost_t              *head;
148 };
149
150 /*
151  * private (static) functions
152  */
153 /* Even though Posix requires "strerror_r" to return an "int",
154  * some systems (e.g. the GNU libc) return a "char *" _and_
155  * ignore the second argument ... -tokkee */
156 static char *sstrerror (int errnum, char *buf, size_t buflen)
157 {
158         buf[0] = 0;
159
160 #if !HAVE_STRERROR_R
161         {
162                 snprintf (buf, buflen, "Error %i (%#x)", errnum, errnum);
163         }
164 /* #endif !HAVE_STRERROR_R */
165
166 #elif STRERROR_R_CHAR_P
167         {
168                 char *temp;
169                 temp = strerror_r (errnum, buf, buflen);
170                 if (buf[0] == 0)
171                 {
172                         if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
173                                 strncpy (buf, temp, buflen);
174                         else
175                                 strncpy (buf, "strerror_r did not return "
176                                                 "an error message", buflen);
177                 }
178         }
179 /* #endif STRERROR_R_CHAR_P */
180
181 #else
182         if (strerror_r (errnum, buf, buflen) != 0)
183         {
184                 snprintf (buf, buflen, "Error %i (%#x); "
185                                 "Additionally, strerror_r failed.",
186                                 errnum, errnum);
187         }
188 #endif /* STRERROR_R_CHAR_P */
189
190         buf[buflen - 1] = 0;
191
192         return (buf);
193 } /* char *sstrerror */
194
195 static void ping_set_error (pingobj_t *obj, const char *function,
196                 const char *message)
197 {
198         snprintf (obj->errmsg, sizeof (obj->errmsg),
199                         "%s: %s", function, message);
200         obj->errmsg[sizeof (obj->errmsg) - 1] = 0;
201 }
202
203 static void ping_set_errno (pingobj_t *obj, int error_number)
204 {
205         sstrerror (error_number, obj->errmsg, sizeof (obj->errmsg));
206 }
207
208 static int ping_timeval_add (struct timeval *tv1, struct timeval *tv2,
209                 struct timeval *res)
210 {
211         res->tv_sec  = tv1->tv_sec  + tv2->tv_sec;
212         res->tv_usec = tv1->tv_usec + tv2->tv_usec;
213
214         while (res->tv_usec > 1000000)
215         {
216                 res->tv_usec -= 1000000;
217                 res->tv_sec++;
218         }
219
220         return (0);
221 }
222
223 static int ping_timeval_sub (struct timeval *tv1, struct timeval *tv2,
224                 struct timeval *res)
225 {
226         if ((tv1->tv_sec < tv2->tv_sec)
227                         || ((tv1->tv_sec == tv2->tv_sec)
228                                 && (tv1->tv_usec < tv2->tv_usec)))
229                 return (-1);
230
231         res->tv_sec  = tv1->tv_sec  - tv2->tv_sec;
232         res->tv_usec = tv1->tv_usec - tv2->tv_usec;
233
234         assert ((res->tv_sec > 0) || ((res->tv_sec == 0) && (res->tv_usec >= 0)));
235
236         while (res->tv_usec < 0)
237         {
238                 res->tv_usec += 1000000;
239                 res->tv_sec--;
240         }
241
242         return (0);
243 }
244
245 static uint16_t ping_icmp4_checksum (char *buf, size_t len)
246 {
247         uint32_t sum = 0;
248         uint16_t ret = 0;
249
250         uint16_t *ptr;
251
252         for (ptr = (uint16_t *) buf; len > 1; ptr++, len -= 2)
253                 sum += *ptr;
254
255         if (len == 1)
256         {
257                 *(char *) &ret = *(char *) ptr;
258                 sum += ret;
259         }
260
261         /* Do this twice to get all possible carries.. */
262         sum = (sum >> 16) + (sum & 0xFFFF);
263         sum = (sum >> 16) + (sum & 0xFFFF);
264
265         ret = ~sum;
266
267         return (ret);
268 }
269
270 static pinghost_t *ping_receive_ipv4 (pingobj_t *obj, char *buffer,
271                 size_t buffer_len)
272 {
273         struct ip *ip_hdr;
274         struct icmp *icmp_hdr;
275
276         size_t ip_hdr_len;
277
278         uint16_t recv_checksum;
279         uint16_t calc_checksum;
280
281         uint16_t ident;
282         uint16_t seq;
283
284         pinghost_t *ptr;
285
286         if (buffer_len < sizeof (struct ip))
287                 return (NULL);
288
289         ip_hdr     = (struct ip *) buffer;
290         ip_hdr_len = ip_hdr->ip_hl << 2;
291
292         if (buffer_len < ip_hdr_len)
293                 return (NULL);
294
295         buffer     += ip_hdr_len;
296         buffer_len -= ip_hdr_len;
297
298         if (buffer_len < sizeof (struct icmp))
299                 return (NULL);
300
301         icmp_hdr = (struct icmp *) buffer;
302         buffer     += sizeof (struct icmp);
303         buffer_len -= sizeof (struct icmp);
304
305         if (icmp_hdr->icmp_type != ICMP_ECHOREPLY)
306         {
307                 dprintf ("Unexpected ICMP type: %i\n", icmp_hdr->icmp_type);
308                 return (NULL);
309         }
310
311         recv_checksum = icmp_hdr->icmp_cksum;
312         icmp_hdr->icmp_cksum = 0;
313         calc_checksum = ping_icmp4_checksum ((char *) icmp_hdr,
314                         sizeof (struct icmp) + buffer_len);
315
316         if (recv_checksum != calc_checksum)
317         {
318                 dprintf ("Checksum missmatch: Got 0x%04"PRIx16", "
319                                 "calculated 0x%04"PRIx16"\n",
320                                 recv_checksum, calc_checksum);
321                 return (NULL);
322         }
323
324         ident = ntohs (icmp_hdr->icmp_id);
325         seq   = ntohs (icmp_hdr->icmp_seq);
326
327         /* We have to iterate over all hosts, since ICMPv4 packets may
328          * be received on any raw v4 socket. */
329         for (ptr = obj->head; ptr != NULL; ptr = ptr->next)
330         {
331                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
332                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
333
334                 if (ptr->addrfamily != AF_INET)
335                         continue;
336
337                 if (!timerisset (ptr->timer))
338                         continue;
339
340                 if (ptr->ident != ident)
341                         continue;
342
343                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
344                         continue;
345
346                 dprintf ("Match found: hostname = %s, ident = 0x%04"PRIx16", "
347                                 "seq = %"PRIu16"\n",
348                                 ptr->hostname, ident, seq);
349
350                 break;
351         }
352
353         if (ptr == NULL)
354         {
355                 dprintf ("No match found for ident = 0x%04"PRIx16", seq = %"PRIu16"\n",
356                                 ident, seq);
357         }
358
359         if (ptr != NULL){
360                 ptr->recv_ttl = (int)     ip_hdr->ip_ttl;
361                 ptr->recv_qos = (uint8_t) ip_hdr->ip_tos;
362         }
363         return (ptr);
364 }
365
366 #ifndef ICMP6_ECHO_REQUEST
367 # ifdef ICMP6_ECHO /* AIX netinet/ip6_icmp.h */
368 #  define ICMP6_ECHO_REQUEST ICMP6_ECHO
369 # else
370 #  define ICMP6_ECHO_REQUEST 128
371 # endif
372 #endif
373
374 #ifndef ICMP6_ECHO_REPLY
375 # ifdef ICMP6_ECHOREPLY /* AIX netinet/ip6_icmp.h */
376 #  define ICMP6_ECHO_REPLY ICMP6_ECHOREPLY
377 # else
378 #  define ICMP6_ECHO_REPLY 129
379 # endif
380 #endif
381
382 static pinghost_t *ping_receive_ipv6 (pingobj_t *obj, char *buffer,
383                 size_t buffer_len)
384 {
385         struct icmp6_hdr *icmp_hdr;
386
387         uint16_t ident;
388         uint16_t seq;
389
390         pinghost_t *ptr;
391
392         if (buffer_len < sizeof (struct icmp6_hdr))
393                 return (NULL);
394
395         icmp_hdr = (struct icmp6_hdr *) buffer;
396         buffer     += sizeof (struct icmp);
397         buffer_len -= sizeof (struct icmp);
398
399         if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
400         {
401                 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
402                 return (NULL);
403         }
404
405         if (icmp_hdr->icmp6_code != 0)
406         {
407                 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
408                 return (NULL);
409         }
410
411         ident = ntohs (icmp_hdr->icmp6_id);
412         seq   = ntohs (icmp_hdr->icmp6_seq);
413
414         /* We have to iterate over all hosts, since ICMPv6 packets may
415          * be received on any raw v6 socket. */
416         for (ptr = obj->head; ptr != NULL; ptr = ptr->next)
417         {
418                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
419                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
420
421                 if (ptr->addrfamily != AF_INET6)
422                         continue;
423
424                 if (!timerisset (ptr->timer))
425                         continue;
426
427                 if (ptr->ident != ident)
428                         continue;
429
430                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
431                         continue;
432
433                 dprintf ("Match found: hostname = %s, ident = 0x%04"PRIx16", "
434                                 "seq = %"PRIu16"\n",
435                                 ptr->hostname, ident, seq);
436
437                 break;
438         }
439
440         if (ptr == NULL)
441         {
442                 dprintf ("No match found for ident = 0x%04"PRIx16", "
443                                 "seq = %"PRIu16"\n",
444                                 ident, seq);
445         }
446
447         return (ptr);
448 }
449
450 static int ping_receive_one (pingobj_t *obj, const pinghost_t *ph,
451                 struct timeval *now)
452 {
453         /* Note: 'ph' is not necessarily the host object for which we receive a
454          * reply. The right object will be returned by ping_receive_ipv*(). For
455          * now, we can only rely on ph->fd and ph->addrfamily. */
456
457         struct timeval diff, pkt_now = *now;
458         pinghost_t *host = NULL;
459         int recv_ttl;
460         uint8_t recv_qos;
461         
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;
471
472         memset (&payload_iovec, 0, sizeof (payload_iovec));
473         payload_iovec.iov_base = payload_buffer;
474         payload_iovec.iov_len = sizeof (payload_buffer);
475
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
491
492         payload_buffer_len = recvmsg (ph->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, ph->fd);
503
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 (ph->addrfamily == AF_INET) /* {{{ */
519                 {
520                         if (cmsg->cmsg_level != IPPROTO_IP)
521                                 continue;
522
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 (ph->addrfamily == AF_INET6) /* {{{ */
542                 {
543                         if (cmsg->cmsg_level != IPPROTO_IPV6)
544                                 continue;
545
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) */
591
592         if (ph->addrfamily == 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 (ph->addrfamily == 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                                 ph->addrfamily);
608                 return (-1);
609         }
610
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);
617
618         if (ping_timeval_sub (&pkt_now, host->timer, &diff) < 0)
619         {
620                 timerclear (host->timer);
621                 return (-1);
622         }
623
624         dprintf ("diff: %12i.%06i\n",
625                         (int) diff.tv_sec,
626                         (int) diff.tv_usec);
627
628         if (recv_ttl >= 0)
629                 host->recv_ttl = recv_ttl;
630         host->recv_qos = recv_qos;
631
632         host->latency  = ((double) diff.tv_usec) / 1000.0;
633         host->latency += ((double) diff.tv_sec)  * 1000.0;
634
635         timerclear (host->timer);
636
637         return (0);
638 }
639
640 static int ping_receive_all (pingobj_t *obj)
641 {
642         fd_set read_fds;
643         fd_set err_fds;
644         int num_fds;
645         int max_fd;
646
647         pinghost_t *ph;
648         pinghost_t *ptr;
649
650         struct timeval endtime;
651         struct timeval nowtime;
652         struct timeval timeout;
653         int status;
654
655         int ret;
656
657         ph = obj->head;
658         ret = 0;
659
660         for (ptr = ph; ptr != NULL; ptr = ptr->next)
661         {
662                 ptr->latency  = -1.0;
663                 ptr->recv_ttl = -1;
664         }
665
666         if (gettimeofday (&nowtime, NULL) == -1)
667         {
668                 ping_set_errno (obj, errno);
669                 return (-1);
670         }
671
672         /* Set up timeout */
673         timeout.tv_sec = (time_t) obj->timeout;
674         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
675
676         dprintf ("Set timeout to %i.%06i seconds\n",
677                         (int) timeout.tv_sec,
678                         (int) timeout.tv_usec);
679
680         ping_timeval_add (&nowtime, &timeout, &endtime);
681
682         while (1)
683         {
684                 FD_ZERO (&read_fds);
685                 FD_ZERO (&err_fds);
686                 num_fds =  0;
687                 max_fd = -1;
688
689                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
690                 {
691                         if (!timerisset (ptr->timer))
692                                 continue;
693
694                         FD_SET (ptr->fd, &read_fds);
695                         FD_SET (ptr->fd, &err_fds);
696                         num_fds++;
697
698                         if (max_fd < ptr->fd)
699                                 max_fd = ptr->fd;
700                 }
701
702                 if (num_fds == 0)
703                         break;
704
705                 if (gettimeofday (&nowtime, NULL) == -1)
706                 {
707                         ping_set_errno (obj, errno);
708                         return (-1);
709                 }
710
711                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
712                         break;
713
714                 dprintf ("Waiting on %i sockets for %i.%06i seconds\n", num_fds,
715                                 (int) timeout.tv_sec,
716                                 (int) timeout.tv_usec);
717
718                 status = select (max_fd + 1, &read_fds, NULL, &err_fds, &timeout);
719
720                 if (gettimeofday (&nowtime, NULL) == -1)
721                 {
722                         ping_set_errno (obj, errno);
723                         return (-1);
724                 }
725                 
726                 if ((status == -1) && (errno == EINTR))
727                 {
728                         dprintf ("select was interrupted by signal..\n");
729                         continue;
730                 }
731                 else if (status < 0)
732                 {
733 #if WITH_DEBUG
734                         char errbuf[PING_ERRMSG_LEN];
735                         dprintf ("select: %s\n",
736                                         sstrerror (errno, errbuf, sizeof (errbuf)));
737 #endif
738                         break;
739                 }
740                 else if (status == 0)
741                 {
742                         dprintf ("select timed out\n");
743                         for (ptr = ph; ptr != NULL; ptr = ptr->next)
744                                 if (ptr->latency < 0.0)
745                                         ptr->dropped++;
746                         break;
747                 }
748
749                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
750                 {
751                         if (FD_ISSET (ptr->fd, &read_fds))
752                         {
753                                 if (ping_receive_one (obj, ptr, &nowtime) == 0)
754                                         ret++;
755                         }
756                         else if (FD_ISSET (ptr->fd, &err_fds))
757                         {
758                                 /* clear the timer in this case so that we
759                                  * don't run into an endless loop. */
760                                 /* TODO: Set an error flag in this case. */
761                                 timerclear (ptr->timer);
762                         }
763                 }
764         } /* while (1) */
765         
766         return (ret);
767 }
768
769 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
770  * Sending functions:                                                        *
771  *                                                                           *
772  * ping_send_all                                                             *
773  * +-> ping_send_one_ipv4                                                    *
774  * `-> ping_send_one_ipv6                                                    *
775  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
776 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
777                 const void *buf, size_t buflen)
778 {
779         ssize_t ret;
780
781         if (gettimeofday (ph->timer, NULL) == -1)
782         {
783                 timerclear (ph->timer);
784                 return (-1);
785         }
786
787         ret = sendto (ph->fd, buf, buflen, 0,
788                         (struct sockaddr *) ph->addr, ph->addrlen);
789
790         if (ret < 0)
791         {
792 #if defined(EHOSTUNREACH)
793                 if (errno == EHOSTUNREACH)
794                         return (0);
795 #endif
796 #if defined(ENETUNREACH)
797                 if (errno == ENETUNREACH)
798                         return (0);
799 #endif
800                 ping_set_errno (obj, errno);
801         }
802
803         return (ret);
804 }
805
806 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
807 {
808         struct icmp *icmp4;
809         int status;
810
811         char buf[4096];
812         int  buflen;
813
814         char *data;
815         int   datalen;
816
817         dprintf ("ph->hostname = %s\n", ph->hostname);
818
819         memset (buf, '\0', sizeof (buf));
820         icmp4 = (struct icmp *) buf;
821         data  = (char *) (icmp4 + 1);
822
823         icmp4->icmp_type  = ICMP_ECHO;
824         icmp4->icmp_code  = 0;
825         icmp4->icmp_cksum = 0;
826         icmp4->icmp_id    = htons (ph->ident);
827         icmp4->icmp_seq   = htons (ph->sequence);
828
829         buflen = 4096 - sizeof (struct icmp);
830         strncpy (data, ph->data, buflen);
831         datalen = strlen (data);
832
833         buflen = datalen + sizeof (struct icmp);
834
835         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
836
837         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
838
839         status = ping_sendto (obj, ph, buf, buflen);
840         if (status < 0)
841         {
842                 perror ("ping_sendto");
843                 return (-1);
844         }
845
846         dprintf ("sendto: status = %i\n", status);
847
848         return (0);
849 }
850
851 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
852 {
853         struct icmp6_hdr *icmp6;
854         int status;
855
856         char buf[4096];
857         int  buflen;
858
859         char *data;
860         int   datalen;
861
862         dprintf ("ph->hostname = %s\n", ph->hostname);
863
864         memset (buf, '\0', sizeof (buf));
865         icmp6 = (struct icmp6_hdr *) buf;
866         data  = (char *) (icmp6 + 1);
867
868         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
869         icmp6->icmp6_code  = 0;
870         /* The checksum will be calculated by the TCP/IP stack.  */
871         /* FIXME */
872         icmp6->icmp6_cksum = 0;
873         icmp6->icmp6_id    = htons (ph->ident);
874         icmp6->icmp6_seq   = htons (ph->sequence);
875
876         buflen = 4096 - sizeof (struct icmp6_hdr);
877         strncpy (data, ph->data, buflen);
878         datalen = strlen (data);
879
880         buflen = datalen + sizeof (struct icmp6_hdr);
881
882         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
883
884         status = ping_sendto (obj, ph, buf, buflen);
885         if (status < 0)
886         {
887                 perror ("ping_sendto");
888                 return (-1);
889         }
890
891         dprintf ("sendto: status = %i\n", status);
892
893         return (0);
894 }
895
896 static int ping_send_all (pingobj_t *obj)
897 {
898         pinghost_t *ph;
899         pinghost_t *ptr;
900
901         int ret;
902
903         ret = 0;
904         ph = obj->head;
905
906         for (ptr = ph; ptr != NULL; ptr = ptr->next)
907         {
908                 /* start timer.. The GNU `ping6' starts the timer before
909                  * sending the packet, so I will do that too */
910                 if (gettimeofday (ptr->timer, NULL) == -1)
911                 {
912 #if WITH_DEBUG
913                         char errbuf[PING_ERRMSG_LEN];
914                         dprintf ("gettimeofday: %s\n",
915                                         sstrerror (errno, errbuf, sizeof (errbuf)));
916 #endif
917                         timerclear (ptr->timer);
918                         ret--;
919                         continue;
920                 }
921                 else
922                 {
923                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
924                 }
925
926                 if (ptr->addrfamily == AF_INET6)
927                 {       
928                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
929                         if (ping_send_one_ipv6 (obj, ptr) != 0)
930                         {
931                                 timerclear (ptr->timer);
932                                 ret--;
933                                 continue;
934                         }
935                 }
936                 else if (ptr->addrfamily == AF_INET)
937                 {
938                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
939                         if (ping_send_one_ipv4 (obj, ptr) != 0)
940                         {
941                                 timerclear (ptr->timer);
942                                 ret--;
943                                 continue;
944                         }
945                 }
946                 else /* this should not happen */
947                 {
948                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
949                         timerclear (ptr->timer);
950                         ret--;
951                         continue;
952                 }
953
954                 ptr->sequence++;
955         }
956
957         return (ret);
958 }
959
960 /*
961  * Set the TTL of a socket protocol independently.
962  */
963 static int ping_set_ttl (pinghost_t *ph, int ttl)
964 {
965         int ret = -2;
966
967         if (ph->addrfamily == AF_INET)
968         {
969                 dprintf ("Setting TTLv4 to %i\n", ttl);
970                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL,
971                                 &ttl, sizeof (ttl));
972         }
973         else if (ph->addrfamily == AF_INET6)
974         {
975                 dprintf ("Setting TTLv6 to %i\n", ttl);
976                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
977                                 &ttl, sizeof (ttl));
978         }
979
980         return (ret);
981 }
982
983 /*
984  * Set the TOS of a socket protocol independently.
985  *
986  * Using SOL_SOCKET / SO_PRIORITY might be a protocol independent way to
987  * set this. See socket(7) for details.
988  */
989 static int ping_set_qos (pingobj_t *obj, pinghost_t *ph, uint8_t qos)
990 {
991         int ret = EINVAL;
992         char errbuf[PING_ERRMSG_LEN];
993
994         if (ph->addrfamily == AF_INET)
995         {
996                 dprintf ("Setting TP_TOS to %#04"PRIx8"\n", qos);
997                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TOS,
998                                 &qos, sizeof (qos));
999                 if (ret != 0)
1000                 {
1001                         ret = errno;
1002                         ping_set_error (obj, "ping_set_qos",
1003                                         sstrerror (ret, errbuf, sizeof (errbuf)));
1004                         dprintf ("Setting TP_TOS failed: %s\n", errbuf);
1005                 }
1006         }
1007         else if (ph->addrfamily == AF_INET6)
1008         {
1009                 /* IPV6_TCLASS requires an "int". */
1010                 int tmp = (int) qos;
1011
1012                 dprintf ("Setting IPV6_TCLASS to %#04"PRIx8" (%i)\n", qos, tmp);
1013                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_TCLASS,
1014                                 &tmp, sizeof (tmp));
1015                 if (ret != 0)
1016                 {
1017                         ret = errno;
1018                         ping_set_error (obj, "ping_set_qos",
1019                                         sstrerror (ret, errbuf, sizeof (errbuf)));
1020                         dprintf ("Setting IPV6_TCLASS failed: %s\n", errbuf);
1021                 }
1022         }
1023
1024         return (ret);
1025 }
1026
1027 static int ping_get_ident (void)
1028 {
1029         int fd;
1030         static int did_seed = 0;
1031
1032         int retval;
1033
1034         if (did_seed == 0)
1035         {
1036                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
1037                 {
1038                         unsigned int seed;
1039
1040                         if (read (fd, &seed, sizeof (seed)) != -1)
1041                         {
1042                                 did_seed = 1;
1043                                 dprintf ("Random seed:   %#x\n", seed);
1044                                 srandom (seed);
1045                         }
1046
1047                         close (fd);
1048                 }
1049 #if WITH_DEBUG
1050                 else
1051                 {
1052                         char errbuf[PING_ERRMSG_LEN];
1053                         dprintf ("open (/dev/urandom): %s\n",
1054                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1055                 }
1056 #endif
1057         }
1058
1059         retval = (int) random ();
1060
1061         dprintf ("Random number: %#x\n", retval);
1062         
1063         return (retval);
1064 }
1065
1066 static pinghost_t *ping_alloc (void)
1067 {
1068         pinghost_t *ph;
1069         size_t      ph_size;
1070
1071         ph_size = sizeof (pinghost_t)
1072                 + sizeof (struct sockaddr_storage)
1073                 + sizeof (struct timeval);
1074
1075         ph = (pinghost_t *) malloc (ph_size);
1076         if (ph == NULL)
1077                 return (NULL);
1078
1079         memset (ph, '\0', ph_size);
1080
1081         ph->timer   = (struct timeval *) (ph + 1);
1082         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
1083
1084         ph->addrlen = sizeof (struct sockaddr_storage);
1085         ph->fd      = -1;
1086         ph->latency = -1.0;
1087         ph->dropped = 0;
1088         ph->ident   = ping_get_ident () & 0xFFFF;
1089
1090         return (ph);
1091 }
1092
1093 static void ping_free (pinghost_t *ph)
1094 {
1095         if (ph->fd >= 0)
1096                 close (ph->fd);
1097         
1098         if (ph->username != NULL)
1099                 free (ph->username);
1100
1101         if (ph->hostname != NULL)
1102                 free (ph->hostname);
1103
1104         if (ph->data != NULL)
1105                 free (ph->data);
1106
1107         free (ph);
1108 }
1109
1110 /*
1111  * public methods
1112  */
1113 const char *ping_get_error (pingobj_t *obj)
1114 {
1115         if (obj == NULL)
1116                 return (NULL);
1117         return (obj->errmsg);
1118 }
1119
1120 pingobj_t *ping_construct (void)
1121 {
1122         pingobj_t *obj;
1123
1124         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
1125                 return (NULL);
1126         memset (obj, 0, sizeof (pingobj_t));
1127
1128         obj->timeout    = PING_DEF_TIMEOUT;
1129         obj->ttl        = PING_DEF_TTL;
1130         obj->addrfamily = PING_DEF_AF;
1131         obj->data       = strdup (PING_DEF_DATA);
1132         obj->qos        = 0;
1133
1134         return (obj);
1135 }
1136
1137 void ping_destroy (pingobj_t *obj)
1138 {
1139         pinghost_t *current;
1140         pinghost_t *next;
1141
1142         if (obj == NULL)
1143                 return;
1144
1145         current = obj->head;
1146         next = NULL;
1147
1148         while (current != NULL)
1149         {
1150                 next = current->next;
1151                 ping_free (current);
1152                 current = next;
1153         }
1154
1155         if (obj->data != NULL)
1156                 free (obj->data);
1157
1158         if (obj->srcaddr != NULL)
1159                 free (obj->srcaddr);
1160
1161         if (obj->device != NULL)
1162                 free (obj->device);
1163
1164         free (obj);
1165
1166         return;
1167 }
1168
1169 int ping_setopt (pingobj_t *obj, int option, void *value)
1170 {
1171         int ret = 0;
1172
1173         if ((obj == NULL) || (value == NULL))
1174                 return (-1);
1175
1176         switch (option)
1177         {
1178                 case PING_OPT_QOS:
1179                 {
1180                         pinghost_t *ph;
1181
1182                         obj->qos = *((uint8_t *) value);
1183                         for (ph = obj->head; ph != NULL; ph = ph->next)
1184                                 ping_set_qos (obj, ph, obj->qos);
1185                         break;
1186                 }
1187
1188                 case PING_OPT_TIMEOUT:
1189                         obj->timeout = *((double *) value);
1190                         if (obj->timeout < 0.0)
1191                         {
1192                                 obj->timeout = PING_DEF_TIMEOUT;
1193                                 ret = -1;
1194                         }
1195                         break;
1196
1197                 case PING_OPT_TTL:
1198                         obj->ttl = *((int *) value);
1199                         if ((obj->ttl < 1) || (obj->ttl > 255))
1200                         {
1201                                 obj->ttl = PING_DEF_TTL;
1202                                 ret = -1;
1203                         }
1204                         else
1205                         {
1206                                 pinghost_t *ph;
1207
1208                                 for (ph = obj->head; ph != NULL; ph = ph->next)
1209                                         ping_set_ttl (ph, obj->ttl);
1210                         }
1211                         break;
1212
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;
1228
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;
1237
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;
1294
1295                         freeaddrinfo (ai_list);
1296                 } /* case PING_OPT_SOURCE */
1297                 break;
1298
1299                 case PING_OPT_DEVICE:
1300                 {
1301 #ifdef SO_BINDTODEVICE
1302                         char *device = strdup ((char *) value);
1303
1304                         if (device == NULL)
1305                         {
1306                                 ping_set_errno (obj, errno);
1307                                 ret = -1;
1308                                 break;
1309                         }
1310
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;
1320
1321                 default:
1322                         ret = -2;
1323         } /* switch (option) */
1324
1325         return (ret);
1326 } /* int ping_setopt */
1327
1328
1329 int ping_send (pingobj_t *obj)
1330 {
1331         int ret;
1332
1333         if (obj == NULL)
1334                 return (-1);
1335
1336         if (ping_send_all (obj) < 0)
1337                 return (-1);
1338
1339         if ((ret = ping_receive_all (obj)) < 0)
1340                 return (-2);
1341
1342         return (ret);
1343 }
1344
1345 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
1346 {
1347         while (ph != NULL)
1348         {
1349                 if (strcasecmp (ph->username, host) == 0)
1350                         break;
1351
1352                 ph = ph->next;
1353         }
1354
1355         return (ph);
1356 }
1357
1358 int ping_host_add (pingobj_t *obj, const char *host)
1359 {
1360         pinghost_t *ph;
1361
1362         struct addrinfo  ai_hints;
1363         struct addrinfo *ai_list, *ai_ptr;
1364         int              ai_return;
1365
1366         if ((obj == NULL) || (host == NULL))
1367                 return (-1);
1368
1369         dprintf ("host = %s\n", host);
1370
1371         if (ping_host_search (obj->head, host) != NULL)
1372                 return (0);
1373
1374         memset (&ai_hints, '\0', sizeof (ai_hints));
1375         ai_hints.ai_flags     = 0;
1376 #ifdef AI_ADDRCONFIG
1377         ai_hints.ai_flags    |= AI_ADDRCONFIG;
1378 #endif
1379 #ifdef AI_CANONNAME
1380         ai_hints.ai_flags    |= AI_CANONNAME;
1381 #endif
1382         ai_hints.ai_family    = obj->addrfamily;
1383         ai_hints.ai_socktype  = SOCK_RAW;
1384
1385         if ((ph = ping_alloc ()) == NULL)
1386         {
1387                 dprintf ("Out of memory!\n");
1388                 return (-1);
1389         }
1390
1391         if ((ph->username = strdup (host)) == NULL)
1392         {
1393                 dprintf ("Out of memory!\n");
1394                 ping_set_errno (obj, errno);
1395                 ping_free (ph);
1396                 return (-1);
1397         }
1398
1399         if ((ph->hostname = strdup (host)) == NULL)
1400         {
1401                 dprintf ("Out of memory!\n");
1402                 ping_set_errno (obj, errno);
1403                 ping_free (ph);
1404                 return (-1);
1405         }
1406
1407         /* obj->data is not garuanteed to be != NULL */
1408         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1409         {
1410                 dprintf ("Out of memory!\n");
1411                 ping_set_errno (obj, errno);
1412                 ping_free (ph);
1413                 return (-1);
1414         }
1415
1416         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1417         {
1418 #if defined(EAI_SYSTEM)
1419                 char errbuf[PING_ERRMSG_LEN];
1420 #endif
1421                 dprintf ("getaddrinfo failed\n");
1422                 ping_set_error (obj, "getaddrinfo",
1423 #if defined(EAI_SYSTEM)
1424                                                 (ai_return == EAI_SYSTEM)
1425                                                 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1426 #endif
1427                                 gai_strerror (ai_return));
1428                 ping_free (ph);
1429                 return (-1);
1430         }
1431
1432         if (ai_list == NULL)
1433                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1434
1435         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1436         {
1437                 ph->fd = -1;
1438
1439                 if (ai_ptr->ai_family == AF_INET)
1440                 {
1441                         ai_ptr->ai_socktype = SOCK_RAW;
1442                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1443                 }
1444                 else if (ai_ptr->ai_family == AF_INET6)
1445                 {
1446                         ai_ptr->ai_socktype = SOCK_RAW;
1447                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1448                 }
1449                 else
1450                 {
1451                         char errmsg[PING_ERRMSG_LEN];
1452
1453                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1454                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1455
1456                         dprintf ("%s", errmsg);
1457                         ping_set_error (obj, "getaddrinfo", errmsg);
1458                         continue;
1459                 }
1460
1461                 /* TODO: Move this to a static function `ping_open_socket' and
1462                  * call it whenever the socket dies. */
1463                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1464                 if (ph->fd == -1)
1465                 {
1466 #if WITH_DEBUG
1467                         char errbuf[PING_ERRMSG_LEN];
1468                         dprintf ("socket: %s\n",
1469                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1470 #endif
1471                         ping_set_errno (obj, errno);
1472                         continue;
1473                 }
1474
1475                 if (obj->srcaddr != NULL)
1476                 {
1477                         assert (obj->srcaddrlen > 0);
1478                         assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1479
1480                         if (bind (ph->fd, obj->srcaddr, obj->srcaddrlen) == -1)
1481                         {
1482 #if WITH_DEBUG
1483                                 char errbuf[PING_ERRMSG_LEN];
1484                                 dprintf ("bind: %s\n",
1485                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1486 #endif
1487                                 ping_set_errno (obj, errno);
1488                                 close (ph->fd);
1489                                 ph->fd = -1;
1490                                 continue;
1491                         }
1492                 }
1493
1494 #ifdef SO_BINDTODEVICE
1495                 if (obj->device != NULL)
1496                 {
1497                         if (setsockopt (ph->fd, SOL_SOCKET, SO_BINDTODEVICE,
1498                                         obj->device, strlen (obj->device) + 1) != 0)
1499                         {
1500 #if WITH_DEBUG
1501                                 char errbuf[PING_ERRMSG_LEN];
1502                                 dprintf ("setsockopt (SO_BINDTODEVICE): %s\n",
1503                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1504 #endif
1505                                 ping_set_errno (obj, errno);
1506                                 close (ph->fd);
1507                                 ph->fd = -1;
1508                                 continue;
1509                         }
1510                 }
1511 #endif /* SO_BINDTODEVICE */
1512 #ifdef SO_TIMESTAMP
1513                 if (1) /* {{{ */
1514                 {
1515                         int status;
1516                         int opt = 1;
1517
1518                         status = setsockopt (ph->fd,
1519                                         SOL_SOCKET, SO_TIMESTAMP,
1520                                         &opt, sizeof (opt));
1521                         if (status != 0)
1522                         {
1523 #if WITH_DEBUG
1524                                 char errbuf[PING_ERRMSG_LEN];
1525                                 dprintf ("setsockopt (SO_TIMESTAMP): %s\n",
1526                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1527 #endif
1528                                 ping_set_errno (obj, errno);
1529                                 close (ph->fd);
1530                                 ph->fd = -1;
1531                                 continue;
1532                         }
1533                 } /* }}} if (1) */
1534 #endif /* SO_TIMESTAMP */
1535                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1536                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1537                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1538                 ph->addrlen = ai_ptr->ai_addrlen;
1539                 ph->addrfamily = ai_ptr->ai_family;
1540
1541 #ifdef AI_CANONNAME
1542                 if ((ai_ptr->ai_canonname != NULL)
1543                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1544                 {
1545                         char *old_hostname;
1546
1547                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1548                                         ph->hostname, ai_ptr->ai_canonname);
1549
1550                         old_hostname = ph->hostname;
1551                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1552                         {
1553                                 /* strdup failed, falling back to old hostname */
1554                                 ph->hostname = old_hostname;
1555                         }
1556                         else if (old_hostname != NULL)
1557                         {
1558                                 free (old_hostname);
1559                         }
1560                 }
1561 #endif /* AI_CANONNAME */
1562
1563                 if (ph->addrfamily == AF_INET)
1564                 {
1565                         int opt;
1566
1567 #ifdef IP_RECVTOS
1568                         /* Enable receiving the TOS field */
1569                         opt = 1;
1570                         setsockopt (ph->fd, IPPROTO_IP, IP_RECVTOS,
1571                                         &opt, sizeof (opt));
1572 #endif  /* IP_RECVTOS */
1573
1574                         /* Enable receiving the TTL field */
1575                         opt = 1;
1576                         setsockopt (ph->fd, IPPROTO_IP, IP_RECVTTL,
1577                                         &opt, sizeof (opt));
1578                 }
1579 #if defined(IPV6_RECVHOPLIMIT) || defined(IPV6_RECVTCLASS)
1580                 else if (ph->addrfamily == AF_INET6)
1581                 {
1582                         int opt;
1583
1584 # if defined(IPV6_RECVHOPLIMIT)
1585                         /* For details see RFC 3542, section 6.3. */
1586                         opt = 1;
1587                         setsockopt (ph->fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
1588                                         &opt, sizeof (opt));
1589 # endif /* IPV6_RECVHOPLIMIT */
1590
1591 # if defined(IPV6_RECVTCLASS)
1592                         /* For details see RFC 3542, section 6.5. */
1593                         opt = 1;
1594                         setsockopt (ph->fd, IPPROTO_IPV6, IPV6_RECVTCLASS,
1595                                         &opt, sizeof (opt));
1596 # endif /* IPV6_RECVTCLASS */
1597                 }
1598 #endif /* IPV6_RECVHOPLIMIT || IPV6_RECVTCLASS */
1599
1600                 break;
1601         } /* for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) */
1602
1603         freeaddrinfo (ai_list);
1604
1605         if (ph->fd < 0)
1606         {
1607                 ping_free (ph);
1608                 return (-1);
1609         }
1610
1611         /*
1612          * Adding in the front is much easier, but then the iterator will
1613          * return the host that was added last as first host. That's just not
1614          * nice. -octo
1615          */
1616         if (obj->head == NULL)
1617         {
1618                 obj->head = ph;
1619         }
1620         else
1621         {
1622                 pinghost_t *hptr;
1623
1624                 hptr = obj->head;
1625                 while (hptr->next != NULL)
1626                         hptr = hptr->next;
1627
1628                 assert ((hptr != NULL) && (hptr->next == NULL));
1629                 hptr->next = ph;
1630         }
1631
1632         ping_set_ttl (ph, obj->ttl);
1633         ping_set_qos (obj, ph, obj->qos);
1634
1635         return (0);
1636 } /* int ping_host_add */
1637
1638 int ping_host_remove (pingobj_t *obj, const char *host)
1639 {
1640         pinghost_t *pre, *cur;
1641
1642         if ((obj == NULL) || (host == NULL))
1643                 return (-1);
1644
1645         pre = NULL;
1646         cur = obj->head;
1647
1648         while (cur != NULL)
1649         {
1650                 if (strcasecmp (host, cur->username) == 0)
1651                         break;
1652
1653                 pre = cur;
1654                 cur = cur->next;
1655         }
1656
1657         if (cur == NULL)
1658         {
1659                 ping_set_error (obj, "ping_host_remove", "Host not found");
1660                 return (-1);
1661         }
1662
1663         if (pre == NULL)
1664                 obj->head = cur->next;
1665         else
1666                 pre->next = cur->next;
1667         
1668         ping_free (cur);
1669
1670         return (0);
1671 }
1672
1673 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1674 {
1675         if (obj == NULL)
1676                 return (NULL);
1677         return ((pingobj_iter_t *) obj->head);
1678 }
1679
1680 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1681 {
1682         if (iter == NULL)
1683                 return (NULL);
1684         return ((pingobj_iter_t *) iter->next);
1685 }
1686
1687 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1688                 void *buffer, size_t *buffer_len)
1689 {
1690         int ret = EINVAL;
1691
1692         size_t orig_buffer_len = *buffer_len;
1693
1694         if ((iter == NULL) || (buffer_len == NULL))
1695                 return (-1);
1696
1697         if ((buffer == NULL) && (*buffer_len != 0 ))
1698                 return (-1);
1699
1700         switch (info)
1701         {
1702                 case PING_INFO_USERNAME:
1703                         ret = ENOMEM;
1704                         *buffer_len = strlen (iter->username) + 1;
1705                         if (orig_buffer_len <= *buffer_len)
1706                                 break;
1707                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1708                          * will copy `*buffer_len' and pad the rest of
1709                          * `buffer' with null-bytes */
1710                         strncpy (buffer, iter->username, orig_buffer_len);
1711                         ret = 0;
1712                         break;
1713
1714                 case PING_INFO_HOSTNAME:
1715                         ret = ENOMEM;
1716                         *buffer_len = strlen (iter->hostname) + 1;
1717                         if (orig_buffer_len < *buffer_len)
1718                                 break;
1719                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1720                          * will copy `*buffer_len' and pad the rest of
1721                          * `buffer' with null-bytes */
1722                         strncpy (buffer, iter->hostname, orig_buffer_len);
1723                         ret = 0;
1724                         break;
1725
1726                 case PING_INFO_ADDRESS:
1727                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1728                                         iter->addrlen,
1729                                         (char *) buffer,
1730                                         *buffer_len,
1731                                         NULL, 0,
1732                                         NI_NUMERICHOST);
1733                         if (ret != 0)
1734                         {
1735                                 if ((ret == EAI_MEMORY)
1736 #ifdef EAI_OVERFLOW
1737                                                 || (ret == EAI_OVERFLOW)
1738 #endif
1739                                    )
1740                                         ret = ENOMEM;
1741 #if defined(EAI_SYSTEM)
1742                                 else if (ret == EAI_SYSTEM)
1743                                         ret = errno;
1744 #endif
1745                                 else
1746                                         ret = EINVAL;
1747                         }
1748                         break;
1749
1750                 case PING_INFO_FAMILY:
1751                         ret = ENOMEM;
1752                         *buffer_len = sizeof (int);
1753                         if (orig_buffer_len < sizeof (int))
1754                                 break;
1755                         *((int *) buffer) = iter->addrfamily;
1756                         ret = 0;
1757                         break;
1758
1759                 case PING_INFO_LATENCY:
1760                         ret = ENOMEM;
1761                         *buffer_len = sizeof (double);
1762                         if (orig_buffer_len < sizeof (double))
1763                                 break;
1764                         *((double *) buffer) = iter->latency;
1765                         ret = 0;
1766                         break;
1767
1768                 case PING_INFO_DROPPED:
1769                         ret = ENOMEM;
1770                         *buffer_len = sizeof (uint32_t);
1771                         if (orig_buffer_len < sizeof (uint32_t))
1772                                 break;
1773                         *((uint32_t *) buffer) = iter->dropped;
1774                         ret = 0;
1775                         break;
1776
1777                 case PING_INFO_SEQUENCE:
1778                         ret = ENOMEM;
1779                         *buffer_len = sizeof (unsigned int);
1780                         if (orig_buffer_len < sizeof (unsigned int))
1781                                 break;
1782                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1783                         ret = 0;
1784                         break;
1785
1786                 case PING_INFO_IDENT:
1787                         ret = ENOMEM;
1788                         *buffer_len = sizeof (uint16_t);
1789                         if (orig_buffer_len < sizeof (uint16_t))
1790                                 break;
1791                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1792                         ret = 0;
1793                         break;
1794
1795                 case PING_INFO_DATA:
1796                         ret = ENOMEM;
1797                         *buffer_len = strlen (iter->data);
1798                         if (orig_buffer_len < *buffer_len)
1799                                 break;
1800                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1801                         ret = 0;
1802                         break;
1803
1804                 case PING_INFO_RECV_TTL:
1805                         ret = ENOMEM;
1806                         *buffer_len = sizeof (int);
1807                         if (orig_buffer_len < sizeof (int))
1808                                 break;
1809                         *((int *) buffer) = iter->recv_ttl;
1810                         ret = 0;
1811                         break;
1812
1813                 case PING_INFO_RECV_QOS:
1814                         ret = ENOMEM;
1815                         if (*buffer_len>sizeof(unsigned)) *buffer_len=sizeof(unsigned);
1816                         if (!*buffer_len) *buffer_len=1;
1817                         if (orig_buffer_len < *buffer_len)
1818                                 break;
1819                         memcpy(buffer,&iter->recv_qos,*buffer_len);
1820                         ret = 0;
1821                         break;
1822         }
1823
1824         return (ret);
1825 } /* ping_iterator_get_info */
1826
1827 void *ping_iterator_get_context (pingobj_iter_t *iter)
1828 {
1829         if (iter == NULL)
1830                 return (NULL);
1831         return (iter->context);
1832 }
1833
1834 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1835 {
1836         if (iter == NULL)
1837                 return;
1838         iter->context = context;
1839 }