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