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