Reset the address-family to `AF_UNSPEC' before setting the source address.
[liboping.git] / src / liboping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006  Florian octo Forster <octo at verplant.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  */
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 <errno.h>
29 # include <assert.h>
30 #else
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
33
34 #if HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #if HAVE_FCNTL_H
39 # include <fcntl.h>
40 #endif
41 #if HAVE_SYS_TYPES_H
42 # include <sys/types.h>
43 #endif
44 #if HAVE_SYS_STAT_H
45 # include <sys/stat.h>
46 #endif
47
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
50 # include <time.h>
51 #else
52 # if HAVE_SYS_TIME_H
53 #  include <sys/time.h>
54 # else
55 #  include <time.h>
56 # endif
57 #endif
58
59 #if HAVE_SYS_SOCKET_H
60 # include <sys/socket.h>
61 #endif
62 #if HAVE_NETDB_H
63 # include <netdb.h>
64 #endif
65
66 #if HAVE_NETINET_IN_SYSTM_H
67 # include <netinet/in_systm.h>
68 #endif
69 #if HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #if HAVE_NETINET_IP_H
73 # include <netinet/ip.h>
74 #endif
75 #if HAVE_NETINET_IP_ICMP_H
76 # include <netinet/ip_icmp.h>
77 #endif
78 #ifdef HAVE_NETINET_IP_VAR_H
79 # include <netinet/ip_var.h>
80 #endif
81 #if HAVE_NETINET_IP6_H
82 # include <netinet/ip6.h>
83 #endif
84 #if HAVE_NETINET_ICMP6_H
85 # include <netinet/icmp6.h>
86 #endif
87
88 #include "oping.h"
89
90 #if WITH_DEBUG
91 # define dprintf(...) printf ("%s[%4i]: %-20s: ", __FILE__, __LINE__, __FUNCTION__); printf (__VA_ARGS__)
92 #else
93 # define dprintf(...) /**/
94 #endif
95
96 #define PING_ERRMSG_LEN 256
97
98 struct pinghost
99 {
100         char                    *hostname;
101         struct sockaddr_storage *addr;
102         socklen_t                addrlen;
103         int                      addrfamily;
104         int                      fd;
105         int                      ident;
106         int                      sequence;
107         struct timeval          *timer;
108         double                   latency;
109         char                    *data;
110
111         void                    *context;
112
113         struct pinghost         *next;
114 };
115
116 struct pingobj
117 {
118         double                   timeout;
119         int                      ttl;
120         int                      addrfamily;
121         char                    *data;
122
123         struct sockaddr_storage *srcaddr;
124         socklen_t                srcaddrlen;
125
126         char                     errmsg[PING_ERRMSG_LEN];
127
128         pinghost_t              *head;
129 };
130
131 /*
132  * private (static) functions
133  */
134 static void ping_set_error (pingobj_t *obj, const char *function,
135                 const char *message)
136 {
137         snprintf (obj->errmsg, PING_ERRMSG_LEN, "%s: %s", function, message);
138         obj->errmsg[PING_ERRMSG_LEN - 1] = '\0';
139 }
140
141 static int ping_timeval_add (struct timeval *tv1, struct timeval *tv2,
142                 struct timeval *res)
143 {
144         res->tv_sec  = tv1->tv_sec  + tv2->tv_sec;
145         res->tv_usec = tv1->tv_usec + tv2->tv_usec;
146
147         while (res->tv_usec > 1000000)
148         {
149                 res->tv_usec -= 1000000;
150                 res->tv_sec++;
151         }
152
153         return (0);
154 }
155
156 static int ping_timeval_sub (struct timeval *tv1, struct timeval *tv2,
157                 struct timeval *res)
158 {
159
160         if ((tv1->tv_sec < tv2->tv_sec)
161                         || ((tv1->tv_sec == tv2->tv_sec)
162                                 && (tv1->tv_usec < tv2->tv_usec)))
163                 return (-1);
164
165         res->tv_sec  = tv1->tv_sec  - tv2->tv_sec;
166         res->tv_usec = tv1->tv_usec - tv2->tv_usec;
167
168         assert ((res->tv_sec > 0) || ((res->tv_sec == 0) && (res->tv_usec > 0)));
169
170         while (res->tv_usec < 0)
171         {
172                 res->tv_usec += 1000000;
173                 res->tv_sec--;
174         }
175
176         return (0);
177 }
178
179 static uint16_t ping_icmp4_checksum (char *buf, size_t len)
180 {
181         uint32_t sum = 0;
182         uint16_t ret = 0;
183
184         uint16_t *ptr;
185
186         for (ptr = (uint16_t *) buf; len > 1; ptr++, len -= 2)
187                 sum += *ptr;
188
189         if (len == 1)
190         {
191                 *(char *) &ret = *(char *) ptr;
192                 sum += ret;
193         }
194
195         /* Do this twice to get all possible carries.. */
196         sum = (sum >> 16) + (sum & 0xFFFF);
197         sum = (sum >> 16) + (sum & 0xFFFF);
198
199         ret = ~sum;
200
201         return (ret);
202 }
203
204 static pinghost_t *ping_receive_ipv4 (pinghost_t *ph, char *buffer, size_t buffer_len)
205 {
206         struct ip *ip_hdr;
207         struct icmp *icmp_hdr;
208
209         size_t ip_hdr_len;
210
211         uint16_t recv_checksum;
212         uint16_t calc_checksum;
213
214         uint16_t ident;
215         uint16_t seq;
216
217         pinghost_t *ptr;
218
219         if (buffer_len < sizeof (struct ip))
220                 return (NULL);
221
222         ip_hdr     = (struct ip *) buffer;
223         ip_hdr_len = ip_hdr->ip_hl << 2;
224
225         if (buffer_len < ip_hdr_len)
226                 return (NULL);
227
228         buffer     += ip_hdr_len;
229         buffer_len -= ip_hdr_len;
230
231         if (buffer_len < sizeof (struct icmp))
232                 return (NULL);
233
234         icmp_hdr = (struct icmp *) buffer;
235         buffer     += sizeof (struct icmp);
236         buffer_len -= sizeof (struct icmp);
237
238         if (icmp_hdr->icmp_type != ICMP_ECHOREPLY)
239         {
240                 dprintf ("Unexpected ICMP type: %i\n", icmp_hdr->icmp_type);
241                 return (NULL);
242         }
243
244         recv_checksum = icmp_hdr->icmp_cksum;
245         icmp_hdr->icmp_cksum = 0;
246         calc_checksum = ping_icmp4_checksum ((char *) icmp_hdr,
247                         sizeof (struct icmp) + buffer_len);
248
249         if (recv_checksum != calc_checksum)
250         {
251                 dprintf ("Checksum missmatch: Got 0x%04x, calculated 0x%04x\n",
252                                 recv_checksum, calc_checksum);
253                 return (NULL);
254         }
255
256         ident = ntohs (icmp_hdr->icmp_id);
257         seq   = ntohs (icmp_hdr->icmp_seq);
258
259         for (ptr = ph; ptr != NULL; ptr = ptr->next)
260         {
261                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
262                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
263
264                 if (ptr->addrfamily != AF_INET)
265                         continue;
266
267                 if (!timerisset (ptr->timer))
268                         continue;
269
270                 if (ptr->ident != ident)
271                         continue;
272
273                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
274                         continue;
275
276                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
277                                 ptr->hostname, ident, seq);
278
279                 break;
280         }
281
282         if (ptr == NULL)
283         {
284                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
285                                 ident, seq);
286         }
287
288         return (ptr);
289 }
290
291 static pinghost_t *ping_receive_ipv6 (pinghost_t *ph, char *buffer, size_t buffer_len)
292 {
293         struct icmp6_hdr *icmp_hdr;
294
295         uint16_t ident;
296         uint16_t seq;
297
298         pinghost_t *ptr;
299
300         if (buffer_len < sizeof (struct icmp6_hdr))
301                 return (NULL);
302
303         icmp_hdr = (struct icmp6_hdr *) buffer;
304         buffer     += sizeof (struct icmp);
305         buffer_len -= sizeof (struct icmp);
306
307         if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
308         {
309                 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
310                 return (NULL);
311         }
312
313         if (icmp_hdr->icmp6_code != 0)
314         {
315                 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
316                 return (NULL);
317         }
318
319         ident = ntohs (icmp_hdr->icmp6_id);
320         seq   = ntohs (icmp_hdr->icmp6_seq);
321
322         for (ptr = ph; ptr != NULL; ptr = ptr->next)
323         {
324                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
325                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
326
327                 if (ptr->addrfamily != AF_INET6)
328                         continue;
329
330                 if (!timerisset (ptr->timer))
331                         continue;
332
333                 if (ptr->ident != ident)
334                         continue;
335
336                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
337                         continue;
338
339                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
340                                 ptr->hostname, ident, seq);
341
342                 break;
343         }
344
345         if (ptr == NULL)
346         {
347                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
348                                 ident, seq);
349         }
350
351         return (ptr);
352 }
353
354 static int ping_receive_one (int fd, pinghost_t *ph, struct timeval *now)
355 {
356         char   buffer[4096];
357         size_t buffer_len;
358
359         struct timeval diff;
360
361         pinghost_t *host = NULL;
362
363         struct sockaddr_storage sa;
364         socklen_t               sa_len;
365
366         sa_len = sizeof (sa);
367
368         buffer_len = recvfrom (fd, buffer, sizeof (buffer), 0,
369                         (struct sockaddr *) &sa, &sa_len);
370         if (buffer_len == -1)
371         {
372                 dprintf ("recvfrom: %s\n", strerror (errno));
373                 return (-1);
374         }
375
376         dprintf ("Read %u bytes from fd = %i\n", (unsigned int) buffer_len, fd);
377
378         if (sa.ss_family == AF_INET)
379         {
380                 if ((host = ping_receive_ipv4 (ph, buffer, buffer_len)) == NULL)
381                         return (-1);
382         }
383         else if (sa.ss_family == AF_INET6)
384         {
385                 if ((host = ping_receive_ipv6 (ph, buffer, buffer_len)) == NULL)
386                         return (-1);
387         }
388
389         dprintf ("rcvd: %12i.%06i\n",
390                         (int) now->tv_sec,
391                         (int) now->tv_usec);
392         dprintf ("sent: %12i.%06i\n",
393                         (int) host->timer->tv_sec,
394                         (int) host->timer->tv_usec);
395
396         if (ping_timeval_sub (now, host->timer, &diff) < 0)
397         {
398                 timerclear (host->timer);
399                 return (-1);
400         }
401
402         dprintf ("diff: %12i.%06i\n",
403                         (int) diff.tv_sec,
404                         (int) diff.tv_usec);
405
406         host->latency  = ((double) diff.tv_usec) / 1000.0;
407         host->latency += ((double) diff.tv_sec)  * 1000.0;
408
409         timerclear (host->timer);
410
411         return (0);
412 }
413
414 static int ping_receive_all (pingobj_t *obj)
415 {
416         fd_set readfds;
417         int num_readfds;
418         int max_readfds;
419
420         pinghost_t *ph;
421         pinghost_t *ptr;
422
423         struct timeval endtime;
424         struct timeval nowtime;
425         struct timeval timeout;
426         int status;
427
428         int ret;
429
430         ph = obj->head;
431         ret = 0;
432
433         for (ptr = ph; ptr != NULL; ptr = ptr->next)
434                 ptr->latency = -1.0;
435
436         if (gettimeofday (&nowtime, NULL) == -1)
437         {
438                 ping_set_error (obj, "gettimeofday", strerror (errno));
439                 return (-1);
440         }
441
442         /* Set up timeout */
443         timeout.tv_sec = (time_t) obj->timeout;
444         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
445
446         dprintf ("Set timeout to %i.%06i seconds\n",
447                         (int) timeout.tv_sec,
448                         (int) timeout.tv_usec);
449
450         ping_timeval_add (&nowtime, &timeout, &endtime);
451
452         while (1)
453         {
454                 FD_ZERO (&readfds);
455                 num_readfds =  0;
456                 max_readfds = -1;
457
458                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
459                 {
460                         if (!timerisset (ptr->timer))
461                                 continue;
462
463                         FD_SET (ptr->fd, &readfds);
464                         num_readfds++;
465
466                         if (max_readfds < ptr->fd)
467                                 max_readfds = ptr->fd;
468                 }
469
470                 if (num_readfds == 0)
471                         break;
472
473                 if (gettimeofday (&nowtime, NULL) == -1)
474                 {
475                         ping_set_error (obj, "gettimeofday", strerror (errno));
476                         return (-1);
477                 }
478
479                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
480                         break;
481
482                 dprintf ("Waiting on %i sockets for %i.%06i seconds\n", num_readfds,
483                                 (int) timeout.tv_sec,
484                                 (int) timeout.tv_usec);
485
486                 status = select (max_readfds + 1, &readfds, NULL, NULL, &timeout);
487
488                 if (gettimeofday (&nowtime, NULL) == -1)
489                 {
490                         ping_set_error (obj, "gettimeofday", strerror (errno));
491                         return (-1);
492                 }
493                 
494                 if ((status == -1) && (errno == EINTR))
495                 {
496                         dprintf ("select was interrupted by signal..\n");
497                         continue;
498                 }
499                 else if (status < 0)
500                 {
501                         dprintf ("select: %s\n", strerror (errno));
502                         break;
503                 }
504                 else if (status == 0)
505                 {
506                         dprintf ("select timed out\n");
507                         break;
508                 }
509
510                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
511                 {
512                         if (FD_ISSET (ptr->fd, &readfds))
513                                 if (ping_receive_one (ptr->fd, ph, &nowtime) == 0)
514                                         ret++;
515                 }
516         } /* while (1) */
517         
518         return (ret);
519 }
520
521 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
522  * Sending functions:                                                        *
523  *                                                                           *
524  * ping_send_all                                                             *
525  * +-> ping_send_one_ipv4                                                    *
526  * `-> ping_send_one_ipv6                                                    *
527  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
528 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
529                 const void *buf, size_t buflen)
530 {
531         ssize_t ret;
532
533         if (gettimeofday (ph->timer, NULL) == -1)
534         {
535                 timerclear (ph->timer);
536                 return (-1);
537         }
538
539         ret = sendto (ph->fd, buf, buflen, 0,
540                         (struct sockaddr *) ph->addr, ph->addrlen);
541
542         if (ret < 0)
543                 ping_set_error (obj, "sendto", strerror (errno));
544
545         return (ret);
546 }
547
548 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
549 {
550         struct icmp *icmp4;
551         int status;
552
553         char buf[4096];
554         int  buflen;
555
556         char *data;
557         int   datalen;
558
559         dprintf ("ph->hostname = %s\n", ph->hostname);
560
561         memset (buf, '\0', sizeof (buf));
562         icmp4 = (struct icmp *) buf;
563         data  = (char *) (icmp4 + 1);
564
565         icmp4->icmp_type  = ICMP_ECHO;
566         icmp4->icmp_code  = 0;
567         icmp4->icmp_cksum = 0;
568         icmp4->icmp_id    = htons (ph->ident);
569         icmp4->icmp_seq   = htons (ph->sequence);
570
571         buflen = 4096 - sizeof (struct icmp);
572         strncpy (data, ph->data, buflen);
573         datalen = strlen (data);
574
575         buflen = datalen + sizeof (struct icmp);
576
577         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
578
579         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
580
581         status = ping_sendto (obj, ph, buf, buflen);
582         if (status < 0)
583         {
584                 perror ("ping_sendto");
585                 return (-1);
586         }
587
588         dprintf ("sendto: status = %i\n", status);
589
590         return (0);
591 }
592
593 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
594 {
595         struct icmp6_hdr *icmp6;
596         int status;
597
598         char buf[4096];
599         int  buflen;
600
601         char *data;
602         int   datalen;
603
604         dprintf ("ph->hostname = %s\n", ph->hostname);
605
606         memset (buf, '\0', sizeof (buf));
607         icmp6 = (struct icmp6_hdr *) buf;
608         data  = (char *) (icmp6 + 1);
609
610         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
611         icmp6->icmp6_code  = 0;
612         /* The checksum will be calculated by the TCP/IP stack.  */
613         /* FIXME */
614         icmp6->icmp6_cksum = 0;
615         icmp6->icmp6_id    = htons (ph->ident);
616         icmp6->icmp6_seq   = htons (ph->sequence);
617
618         buflen = 4096 - sizeof (struct icmp6_hdr);
619         strncpy (data, ph->data, buflen);
620         datalen = strlen (data);
621
622         buflen = datalen + sizeof (struct icmp6_hdr);
623
624         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
625
626         status = ping_sendto (obj, ph, buf, buflen);
627         if (status < 0)
628         {
629                 perror ("ping_sendto");
630                 return (-1);
631         }
632
633         dprintf ("sendto: status = %i\n", status);
634
635         return (0);
636 }
637
638 static int ping_send_all (pingobj_t *obj)
639 {
640         pinghost_t *ph;
641         pinghost_t *ptr;
642
643         int ret;
644
645         ret = 0;
646         ph = obj->head;
647
648         for (ptr = ph; ptr != NULL; ptr = ptr->next)
649         {
650                 /* start timer.. The GNU `ping6' starts the timer before
651                  * sending the packet, so I will do that too */
652                 if (gettimeofday (ptr->timer, NULL) == -1)
653                 {
654                         dprintf ("gettimeofday: %s\n", strerror (errno));
655                         timerclear (ptr->timer);
656                         ret--;
657                         continue;
658                 }
659                 else
660                 {
661                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
662                 }
663
664                 if (ptr->addrfamily == AF_INET6)
665                 {       
666                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
667                         if (ping_send_one_ipv6 (obj, ptr) != 0)
668                         {
669                                 timerclear (ptr->timer);
670                                 ret--;
671                                 continue;
672                         }
673                 }
674                 else if (ptr->addrfamily == AF_INET)
675                 {
676                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
677                         if (ping_send_one_ipv4 (obj, ptr) != 0)
678                         {
679                                 timerclear (ptr->timer);
680                                 ret--;
681                                 continue;
682                         }
683                 }
684                 else /* this should not happen */
685                 {
686                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
687                         timerclear (ptr->timer);
688                         ret--;
689                         continue;
690                 }
691
692                 ptr->sequence++;
693         }
694
695         return (ret);
696 }
697
698 /*
699  * Set the TTL of a socket protocol independently.
700  */
701 static int ping_set_ttl (pinghost_t *ph, int ttl)
702 {
703         int ret = -2;
704
705         if (ph->addrfamily == AF_INET)
706         {
707                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL, &ttl, sizeof (ttl));
708         }
709         else if (ph->addrfamily == AF_INET6)
710         {
711                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof (ttl));
712         }
713
714         return (ret);
715 }
716
717 static int ping_get_ident (void)
718 {
719         int fd;
720         static int did_seed = 0;
721
722         int retval;
723
724         if (did_seed == 0)
725         {
726                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
727                 {
728                         unsigned int seed;
729
730                         if (read (fd, &seed, sizeof (seed)) != -1)
731                         {
732                                 did_seed = 1;
733                                 dprintf ("Random seed: %i\n", seed);
734                                 srandom (seed);
735                         }
736
737                         close (fd);
738                 }
739                 else
740                 {
741                         dprintf ("open (/dev/urandom): %s\n", strerror (errno));
742                 }
743         }
744
745         retval = (int) random ();
746
747         dprintf ("Random number: %i\n", retval);
748         
749         return (retval);
750 }
751
752 static pinghost_t *ping_alloc (void)
753 {
754         pinghost_t *ph;
755         size_t      ph_size;
756
757         ph_size = sizeof (pinghost_t)
758                 + sizeof (struct sockaddr_storage)
759                 + sizeof (struct timeval);
760
761         ph = (pinghost_t *) malloc (ph_size);
762         if (ph == NULL)
763                 return (NULL);
764
765         memset (ph, '\0', ph_size);
766
767         ph->timer   = (struct timeval *) (ph + 1);
768         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
769
770         ph->addrlen = sizeof (struct sockaddr_storage);
771         ph->latency = -1.0;
772         ph->ident   = ping_get_ident () & 0xFFFF;
773
774         return (ph);
775 }
776
777 static void ping_free (pinghost_t *ph)
778 {
779         if (ph->hostname != NULL)
780                 free (ph->hostname);
781
782         if (ph->data != NULL)
783                 free (ph->data);
784
785         free (ph);
786 }
787
788 /*
789  * public methods
790  */
791 const char *ping_get_error (pingobj_t *obj)
792 {
793         return (obj->errmsg);
794 }
795
796 pingobj_t *ping_construct (void)
797 {
798         pingobj_t *obj;
799
800         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
801                 return (NULL);
802         memset (obj, '\0', sizeof (pingobj_t));
803
804         obj->timeout    = PING_DEF_TIMEOUT;
805         obj->ttl        = PING_DEF_TTL;
806         obj->addrfamily = PING_DEF_AF;
807         obj->data       = strdup (PING_DEF_DATA);
808
809         return (obj);
810 }
811
812 void ping_destroy (pingobj_t *obj)
813 {
814         pinghost_t *current;
815         pinghost_t *next;
816
817         current = obj->head;
818         next = NULL;
819
820         while (current != NULL)
821         {
822                 next = current->next;
823                 ping_free (current);
824                 current = next;
825         }
826
827         if (obj->data != NULL)
828                 free (obj->data);
829
830         if (obj->srcaddr != NULL)
831                 free (obj->srcaddr);
832
833         free (obj);
834
835         return;
836 }
837
838 int ping_setopt (pingobj_t *obj, int option, void *value)
839 {
840         int ret = 0;
841
842         switch (option)
843         {
844                 case PING_OPT_TIMEOUT:
845                         obj->timeout = *((double *) value);
846                         if (obj->timeout < 0.0)
847                         {
848                                 obj->timeout = PING_DEF_TIMEOUT;
849                                 ret = -1;
850                         }
851                         break;
852
853                 case PING_OPT_TTL:
854                         obj->ttl = *((int *) value);
855                         if ((obj->ttl < 1) || (obj->ttl > 255))
856                         {
857                                 obj->ttl = PING_DEF_TTL;
858                                 ret = -1;
859                         }
860                         break;
861
862                 case PING_OPT_AF:
863                         obj->addrfamily = *((int *) value);
864                         if ((obj->addrfamily != AF_UNSPEC)
865                                         && (obj->addrfamily != AF_INET)
866                                         && (obj->addrfamily != AF_INET6))
867                         {
868                                 obj->addrfamily = PING_DEF_AF;
869                                 ret = -1;
870                         }
871                         if (obj->srcaddr != NULL)
872                         {
873                                 free (obj->srcaddr);
874                                 obj->srcaddr = NULL;
875                         }
876                         break;
877
878                 case PING_OPT_DATA:
879                         if (obj->data != NULL)
880                         {
881                                 free (obj->data);
882                                 obj->data = NULL;
883                         }
884                         obj->data = strdup ((const char *) value);
885                         break;
886
887                 case PING_OPT_SOURCE:
888                 {
889                         char            *hostname = (char *) value;
890                         struct addrinfo  ai_hints;
891                         struct addrinfo *ai_list;
892                         int              status;
893 #if WITH_DEBUG
894                         if (obj->addrfamily != AF_UNSPEC)
895                         {
896                                 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
897                         }
898 #endif
899                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
900                         ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
901 #if defined(AI_ADDRCONFIG)
902                         ai_hints.ai_flags = AI_ADDRCONFIG;
903 #endif
904                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
905                         if (status != 0)
906                         {
907                                 ping_set_error (obj, "getaddrinfo",
908                                                 status == EAI_SYSTEM
909                                                 ? strerror (errno)
910                                                 : gai_strerror (status));
911                                 ret = -1;
912                                 break;
913                         }
914 #if WITH_DEBUG
915                         if (ai_list->ai_next != NULL)
916                         {
917                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
918                         }
919 #endif
920                         if (obj->srcaddr == NULL)
921                         {
922                                 obj->srcaddrlen = 0;
923                                 obj->srcaddr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage));
924                                 if (obj->srcaddr == NULL)
925                                 {
926                                         ping_set_error (obj, "malloc",
927                                                         strerror (errno));
928                                         ret = -1;
929                                         freeaddrinfo (ai_list);
930                                         break;
931                                 }
932                         }
933                         memset ((void *) obj->srcaddr, '\0', sizeof (struct sockaddr_storage));
934                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
935                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
936                                         ai_list->ai_addrlen);
937                         obj->srcaddrlen = ai_list->ai_addrlen;
938                         obj->addrfamily = ai_list->ai_family;
939
940                         freeaddrinfo (ai_list);
941                 } /* case PING_OPT_SOURCE */
942                 break;
943
944                 default:
945                         ret = -2;
946         } /* switch (option) */
947
948         return (ret);
949 } /* int ping_setopt */
950
951
952 int ping_send (pingobj_t *obj)
953 {
954         int ret;
955
956         if (ping_send_all (obj) < 0)
957                 return (-1);
958
959         if ((ret = ping_receive_all (obj)) < 0)
960                 return (-2);
961
962         return (ret);
963 }
964
965 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
966 {
967         while (ph != NULL)
968         {
969                 if (strcasecmp (ph->hostname, host) == 0)
970                         break;
971
972                 ph = ph->next;
973         }
974
975         return (ph);
976 }
977
978 int ping_host_add (pingobj_t *obj, const char *host)
979 {
980         pinghost_t *ph;
981
982         struct sockaddr_storage sockaddr;
983         socklen_t               sockaddr_len;
984
985         struct addrinfo  ai_hints;
986         struct addrinfo *ai_list, *ai_ptr;
987         int              ai_return;
988
989         dprintf ("host = %s\n", host);
990
991         if (ping_host_search (obj->head, host) != NULL)
992                 return (0);
993
994         memset (&ai_hints, '\0', sizeof (ai_hints));
995         ai_hints.ai_flags     = 0;
996 #ifdef AI_ADDRCONFIG
997         ai_hints.ai_flags    |= AI_ADDRCONFIG;
998 #endif
999 #ifdef AI_CANONNAME
1000         ai_hints.ai_flags    |= AI_CANONNAME;
1001 #endif
1002         ai_hints.ai_family    = obj->addrfamily;
1003         ai_hints.ai_socktype  = SOCK_RAW;
1004
1005         if ((ph = ping_alloc ()) == NULL)
1006         {
1007                 dprintf ("Out of memory!\n");
1008                 return (-1);
1009         }
1010
1011         if ((ph->hostname = strdup (host)) == NULL)
1012         {
1013                 dprintf ("Out of memory!\n");
1014                 ping_set_error (obj, "strdup", strerror (errno));
1015                 ping_free (ph);
1016                 return (-1);
1017         }
1018
1019         /* obj->data is not garuanteed to be != NULL */
1020         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1021         {
1022                 dprintf ("Out of memory!\n");
1023                 ping_set_error (obj, "strdup", strerror (errno));
1024                 ping_free (ph);
1025                 return (-1);
1026         }
1027
1028         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1029         {
1030                 dprintf ("getaddrinfo failed\n");
1031                 ping_set_error (obj, "getaddrinfo",
1032                                 (ai_return == EAI_SYSTEM)
1033                                 ? strerror (errno)
1034                                 : gai_strerror (ai_return));
1035                 ping_free (ph);
1036                 return (-1);
1037         }
1038
1039         if (ai_list == NULL)
1040                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1041
1042         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1043         {
1044                 ph->fd = -1;
1045
1046                 sockaddr_len = sizeof (sockaddr);
1047                 memset (&sockaddr, '\0', sockaddr_len);
1048
1049                 if (ai_ptr->ai_family == AF_INET)
1050                 {
1051                         struct sockaddr_in *si;
1052
1053                         si = (struct sockaddr_in *) &sockaddr;
1054                         si->sin_family = AF_INET;
1055                         si->sin_port   = htons (ph->ident);
1056                         si->sin_addr.s_addr = htonl (INADDR_ANY);
1057
1058                         ai_ptr->ai_socktype = SOCK_RAW;
1059                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1060                 }
1061                 else if (ai_ptr->ai_family == AF_INET6)
1062                 {
1063                         struct sockaddr_in6 *si;
1064
1065                         si = (struct sockaddr_in6 *) &sockaddr;
1066                         si->sin6_family = AF_INET6;
1067                         si->sin6_port   = htons (ph->ident);
1068                         si->sin6_addr   = in6addr_any;
1069
1070                         ai_ptr->ai_socktype = SOCK_RAW;
1071                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1072                 }
1073                 else
1074                 {
1075                         char errmsg[PING_ERRMSG_LEN];
1076
1077                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1078                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1079
1080                         dprintf (errmsg);
1081                         ping_set_error (obj, "getaddrinfo", errmsg);
1082                         continue;
1083                 }
1084
1085                 /* TODO: Move this to a static function `ping_open_socket' and
1086                  * call it whenever the socket dies. */
1087                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1088                 if (ph->fd == -1)
1089                 {
1090                         dprintf ("socket: %s\n", strerror (errno));
1091                         ping_set_error (obj, "socket", strerror (errno));
1092                         continue;
1093                 }
1094
1095 /*
1096  * The majority vote of operating systems has decided that you don't need to
1097  * bind here. This code should be reactivated to bind to a specific address,
1098  * though. See the `-I' option of `ping(1)' (GNU).  -octo
1099  */
1100 #if 0
1101                 if (bind (ph->fd, (struct sockaddr *) &sockaddr, sockaddr_len) == -1)
1102                 {
1103                         dprintf ("bind: %s\n", strerror (errno));
1104                         ping_set_error (obj, "bind", strerror (errno));
1105                         close (ph->fd);
1106                         ph->fd = -1;
1107                         continue;
1108                 }
1109 #endif
1110
1111                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1112                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1113                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1114                 ph->addrlen = ai_ptr->ai_addrlen;
1115                 ph->addrfamily = ai_ptr->ai_family;
1116
1117 #ifdef AI_CANONNAME
1118                 if ((ai_ptr->ai_canonname != NULL)
1119                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1120                 {
1121                         char *old_hostname;
1122
1123                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1124                                         ph->hostname, ai_ptr->ai_canonname);
1125
1126                         old_hostname = ph->hostname;
1127                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1128                         {
1129                                 /* strdup failed, falling back to old hostname */
1130                                 ph->hostname = old_hostname;
1131                         }
1132                         else if (old_hostname != NULL)
1133                         {
1134                                 free (old_hostname);
1135                         }
1136                 }
1137 #endif /* AI_CANONNAME */
1138
1139                 break;
1140         }
1141
1142         freeaddrinfo (ai_list);
1143
1144         if (ph->fd < 0)
1145         {
1146                 free (ph->hostname);
1147                 free (ph);
1148                 return (-1);
1149         }
1150
1151         /*
1152          * Adding in the front is much easier, but then the iterator will
1153          * return the host that was added last as first host. That's just not
1154          * nice. -octo
1155          */
1156         if (obj->head == NULL)
1157         {
1158                 obj->head = ph;
1159         }
1160         else
1161         {
1162                 pinghost_t *hptr;
1163
1164                 hptr = obj->head;
1165                 while (hptr->next != NULL)
1166                         hptr = hptr->next;
1167
1168                 assert ((hptr != NULL) && (hptr->next == NULL));
1169                 hptr->next = ph;
1170         }
1171
1172         ping_set_ttl (ph, obj->ttl);
1173
1174         return (0);
1175 }
1176
1177 int ping_host_remove (pingobj_t *obj, const char *host)
1178 {
1179         pinghost_t *pre, *cur;
1180
1181         pre = NULL;
1182         cur = obj->head;
1183
1184         while (cur != NULL)
1185         {
1186                 if (strcasecmp (host, cur->hostname))
1187                         break;
1188
1189                 pre = cur;
1190                 cur = cur->next;
1191         }
1192
1193         if (cur == NULL)
1194         {
1195                 ping_set_error (obj, "ping_host_remove", "Host not found");
1196                 return (-1);
1197         }
1198
1199         if (pre == NULL)
1200                 obj->head = cur->next;
1201         else
1202                 pre->next = cur->next;
1203         
1204         if (cur->fd >= 0)
1205                 close (cur->fd);
1206
1207         ping_free (cur);
1208
1209         return (0);
1210 }
1211
1212 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1213 {
1214         return ((pingobj_iter_t *) obj->head);
1215 }
1216
1217 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1218 {
1219         return ((pingobj_iter_t *) iter->next);
1220 }
1221
1222 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1223                 void *buffer, size_t *buffer_len)
1224 {
1225         int ret = EINVAL;
1226
1227         size_t orig_buffer_len = *buffer_len;
1228
1229         switch (info)
1230         {
1231                 case PING_INFO_HOSTNAME:
1232                         ret = ENOMEM;
1233                         *buffer_len = strlen (iter->hostname);
1234                         if (orig_buffer_len <= *buffer_len)
1235                                 break;
1236                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1237                          * will copy `*buffer_len' and pad the rest of
1238                          * `buffer' with null-bytes */
1239                         strncpy (buffer, iter->hostname, orig_buffer_len);
1240                         ret = 0;
1241                         break;
1242
1243                 case PING_INFO_ADDRESS:
1244                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1245                                         iter->addrlen,
1246                                         (char *) buffer,
1247                                         *buffer_len,
1248                                         NULL, 0,
1249                                         NI_NUMERICHOST);
1250                         if (ret != 0)
1251                         {
1252                                 if ((ret == EAI_MEMORY)
1253 #ifdef EAI_OVERFLOW
1254                                                 || (ret == EAI_OVERFLOW)
1255 #endif
1256                                    )
1257                                         ret = ENOMEM;
1258                                 else if (ret == EAI_SYSTEM)
1259                                         /* XXX: Not thread-safe! */
1260                                         ret = errno;
1261                                 else
1262                                         ret = EINVAL;
1263                         }
1264                         break;
1265
1266                 case PING_INFO_FAMILY:
1267                         ret = ENOMEM;
1268                         *buffer_len = sizeof (int);
1269                         if (orig_buffer_len < sizeof (int))
1270                                 break;
1271                         *((int *) buffer) = iter->addrfamily;
1272                         ret = 0;
1273                         break;
1274
1275                 case PING_INFO_LATENCY:
1276                         ret = ENOMEM;
1277                         *buffer_len = sizeof (double);
1278                         if (orig_buffer_len < sizeof (double))
1279                                 break;
1280                         *((double *) buffer) = iter->latency;
1281                         ret = 0;
1282                         break;
1283
1284                 case PING_INFO_SEQUENCE:
1285                         ret = ENOMEM;
1286                         *buffer_len = sizeof (unsigned int);
1287                         if (orig_buffer_len < sizeof (unsigned int))
1288                                 break;
1289                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1290                         ret = 0;
1291                         break;
1292
1293                 case PING_INFO_IDENT:
1294                         ret = ENOMEM;
1295                         *buffer_len = sizeof (uint16_t);
1296                         if (orig_buffer_len < sizeof (uint16_t))
1297                                 break;
1298                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1299                         ret = 0;
1300                         break;
1301
1302                 case PING_INFO_DATA:
1303                         ret = ENOMEM;
1304                         *buffer_len = strlen (iter->data);
1305                         if (orig_buffer_len < *buffer_len)
1306                                 break;
1307                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1308                         ret = 0;
1309                         break;
1310         }
1311
1312         return (ret);
1313 }
1314
1315 void *ping_iterator_get_context (pingobj_iter_t *iter)
1316 {
1317         return (iter->context);
1318 }
1319
1320 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1321 {
1322         iter->context = context;
1323 }