Added the ability to set the source address in the library.
[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
894                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
895                         ai_hints.ai_family = obj->addrfamily;
896 #if defined(AI_ADDRCONFIG)
897                         ai_hints.ai_flags = AI_ADDRCONFIG;
898 #endif
899                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
900                         if (status != 0)
901                         {
902                                 ping_set_error (obj, "getaddrinfo",
903                                                 status == EAI_SYSTEM
904                                                 ? strerror (errno)
905                                                 : gai_strerror (status));
906                                 ret = -1;
907                                 break;
908                         }
909 #if WITH_DEBUG
910                         if (ai_list->ai_next != NULL)
911                         {
912                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
913                         }
914 #endif
915                         if (obj->srcaddr == NULL)
916                         {
917                                 obj->srcaddrlen = 0;
918                                 obj->srcaddr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage));
919                                 if (obj->srcaddr == NULL)
920                                 {
921                                         ping_set_error (obj, "malloc",
922                                                         strerror (errno));
923                                         ret = -1;
924                                         freeaddrinfo (ai_list);
925                                         break;
926                                 }
927                         }
928                         memset ((void *) obj->srcaddr, '\0', sizeof (struct sockaddr_storage));
929                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
930                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
931                                         ai_list->ai_addrlen);
932                         obj->srcaddrlen = ai_list->ai_addrlen;
933
934                         freeaddrinfo (ai_list);
935                 } /* case PING_OPT_SOURCE */
936                 break;
937
938                 default:
939                         ret = -2;
940         } /* switch (option) */
941
942         return (ret);
943 } /* int ping_setopt */
944
945
946 int ping_send (pingobj_t *obj)
947 {
948         int ret;
949
950         if (ping_send_all (obj) < 0)
951                 return (-1);
952
953         if ((ret = ping_receive_all (obj)) < 0)
954                 return (-2);
955
956         return (ret);
957 }
958
959 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
960 {
961         while (ph != NULL)
962         {
963                 if (strcasecmp (ph->hostname, host) == 0)
964                         break;
965
966                 ph = ph->next;
967         }
968
969         return (ph);
970 }
971
972 int ping_host_add (pingobj_t *obj, const char *host)
973 {
974         pinghost_t *ph;
975
976         struct sockaddr_storage sockaddr;
977         socklen_t               sockaddr_len;
978
979         struct addrinfo  ai_hints;
980         struct addrinfo *ai_list, *ai_ptr;
981         int              ai_return;
982
983         dprintf ("host = %s\n", host);
984
985         if (ping_host_search (obj->head, host) != NULL)
986                 return (0);
987
988         memset (&ai_hints, '\0', sizeof (ai_hints));
989         ai_hints.ai_flags     = 0;
990 #ifdef AI_ADDRCONFIG
991         ai_hints.ai_flags    |= AI_ADDRCONFIG;
992 #endif
993 #ifdef AI_CANONNAME
994         ai_hints.ai_flags    |= AI_CANONNAME;
995 #endif
996         ai_hints.ai_family    = obj->addrfamily;
997         ai_hints.ai_socktype  = SOCK_RAW;
998
999         if ((ph = ping_alloc ()) == NULL)
1000         {
1001                 dprintf ("Out of memory!\n");
1002                 return (-1);
1003         }
1004
1005         if ((ph->hostname = strdup (host)) == NULL)
1006         {
1007                 dprintf ("Out of memory!\n");
1008                 ping_set_error (obj, "strdup", strerror (errno));
1009                 ping_free (ph);
1010                 return (-1);
1011         }
1012
1013         /* obj->data is not garuanteed to be != NULL */
1014         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1015         {
1016                 dprintf ("Out of memory!\n");
1017                 ping_set_error (obj, "strdup", strerror (errno));
1018                 ping_free (ph);
1019                 return (-1);
1020         }
1021
1022         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1023         {
1024                 dprintf ("getaddrinfo failed\n");
1025                 ping_set_error (obj, "getaddrinfo",
1026                                 (ai_return == EAI_SYSTEM)
1027                                 ? strerror (errno)
1028                                 : gai_strerror (ai_return));
1029                 ping_free (ph);
1030                 return (-1);
1031         }
1032
1033         if (ai_list == NULL)
1034                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1035
1036         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1037         {
1038                 ph->fd = -1;
1039
1040                 sockaddr_len = sizeof (sockaddr);
1041                 memset (&sockaddr, '\0', sockaddr_len);
1042
1043                 if (ai_ptr->ai_family == AF_INET)
1044                 {
1045                         struct sockaddr_in *si;
1046
1047                         si = (struct sockaddr_in *) &sockaddr;
1048                         si->sin_family = AF_INET;
1049                         si->sin_port   = htons (ph->ident);
1050                         si->sin_addr.s_addr = htonl (INADDR_ANY);
1051
1052                         ai_ptr->ai_socktype = SOCK_RAW;
1053                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1054                 }
1055                 else if (ai_ptr->ai_family == AF_INET6)
1056                 {
1057                         struct sockaddr_in6 *si;
1058
1059                         si = (struct sockaddr_in6 *) &sockaddr;
1060                         si->sin6_family = AF_INET6;
1061                         si->sin6_port   = htons (ph->ident);
1062                         si->sin6_addr   = in6addr_any;
1063
1064                         ai_ptr->ai_socktype = SOCK_RAW;
1065                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1066                 }
1067                 else
1068                 {
1069                         char errmsg[PING_ERRMSG_LEN];
1070
1071                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1072                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1073
1074                         dprintf (errmsg);
1075                         ping_set_error (obj, "getaddrinfo", errmsg);
1076                         continue;
1077                 }
1078
1079                 /* TODO: Move this to a static function `ping_open_socket' and
1080                  * call it whenever the socket dies. */
1081                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1082                 if (ph->fd == -1)
1083                 {
1084                         dprintf ("socket: %s\n", strerror (errno));
1085                         ping_set_error (obj, "socket", strerror (errno));
1086                         continue;
1087                 }
1088
1089 /*
1090  * The majority vote of operating systems has decided that you don't need to
1091  * bind here. This code should be reactivated to bind to a specific address,
1092  * though. See the `-I' option of `ping(1)' (GNU).  -octo
1093  */
1094 #if 0
1095                 if (bind (ph->fd, (struct sockaddr *) &sockaddr, sockaddr_len) == -1)
1096                 {
1097                         dprintf ("bind: %s\n", strerror (errno));
1098                         ping_set_error (obj, "bind", strerror (errno));
1099                         close (ph->fd);
1100                         ph->fd = -1;
1101                         continue;
1102                 }
1103 #endif
1104
1105                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1106                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1107                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1108                 ph->addrlen = ai_ptr->ai_addrlen;
1109                 ph->addrfamily = ai_ptr->ai_family;
1110
1111 #ifdef AI_CANONNAME
1112                 if ((ai_ptr->ai_canonname != NULL)
1113                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1114                 {
1115                         char *old_hostname;
1116
1117                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1118                                         ph->hostname, ai_ptr->ai_canonname);
1119
1120                         old_hostname = ph->hostname;
1121                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1122                         {
1123                                 /* strdup failed, falling back to old hostname */
1124                                 ph->hostname = old_hostname;
1125                         }
1126                         else if (old_hostname != NULL)
1127                         {
1128                                 free (old_hostname);
1129                         }
1130                 }
1131 #endif /* AI_CANONNAME */
1132
1133                 break;
1134         }
1135
1136         freeaddrinfo (ai_list);
1137
1138         if (ph->fd < 0)
1139         {
1140                 free (ph->hostname);
1141                 free (ph);
1142                 return (-1);
1143         }
1144
1145         /*
1146          * Adding in the front is much easier, but then the iterator will
1147          * return the host that was added last as first host. That's just not
1148          * nice. -octo
1149          */
1150         if (obj->head == NULL)
1151         {
1152                 obj->head = ph;
1153         }
1154         else
1155         {
1156                 pinghost_t *hptr;
1157
1158                 hptr = obj->head;
1159                 while (hptr->next != NULL)
1160                         hptr = hptr->next;
1161
1162                 assert ((hptr != NULL) && (hptr->next == NULL));
1163                 hptr->next = ph;
1164         }
1165
1166         ping_set_ttl (ph, obj->ttl);
1167
1168         return (0);
1169 }
1170
1171 int ping_host_remove (pingobj_t *obj, const char *host)
1172 {
1173         pinghost_t *pre, *cur;
1174
1175         pre = NULL;
1176         cur = obj->head;
1177
1178         while (cur != NULL)
1179         {
1180                 if (strcasecmp (host, cur->hostname))
1181                         break;
1182
1183                 pre = cur;
1184                 cur = cur->next;
1185         }
1186
1187         if (cur == NULL)
1188         {
1189                 ping_set_error (obj, "ping_host_remove", "Host not found");
1190                 return (-1);
1191         }
1192
1193         if (pre == NULL)
1194                 obj->head = cur->next;
1195         else
1196                 pre->next = cur->next;
1197         
1198         if (cur->fd >= 0)
1199                 close (cur->fd);
1200
1201         ping_free (cur);
1202
1203         return (0);
1204 }
1205
1206 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1207 {
1208         return ((pingobj_iter_t *) obj->head);
1209 }
1210
1211 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1212 {
1213         return ((pingobj_iter_t *) iter->next);
1214 }
1215
1216 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1217                 void *buffer, size_t *buffer_len)
1218 {
1219         int ret = EINVAL;
1220
1221         size_t orig_buffer_len = *buffer_len;
1222
1223         switch (info)
1224         {
1225                 case PING_INFO_HOSTNAME:
1226                         ret = ENOMEM;
1227                         *buffer_len = strlen (iter->hostname);
1228                         if (orig_buffer_len <= *buffer_len)
1229                                 break;
1230                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1231                          * will copy `*buffer_len' and pad the rest of
1232                          * `buffer' with null-bytes */
1233                         strncpy (buffer, iter->hostname, orig_buffer_len);
1234                         ret = 0;
1235                         break;
1236
1237                 case PING_INFO_ADDRESS:
1238                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1239                                         iter->addrlen,
1240                                         (char *) buffer,
1241                                         *buffer_len,
1242                                         NULL, 0,
1243                                         NI_NUMERICHOST);
1244                         if (ret != 0)
1245                         {
1246                                 if ((ret == EAI_MEMORY)
1247 #ifdef EAI_OVERFLOW
1248                                                 || (ret == EAI_OVERFLOW)
1249 #endif
1250                                    )
1251                                         ret = ENOMEM;
1252                                 else if (ret == EAI_SYSTEM)
1253                                         /* XXX: Not thread-safe! */
1254                                         ret = errno;
1255                                 else
1256                                         ret = EINVAL;
1257                         }
1258                         break;
1259
1260                 case PING_INFO_FAMILY:
1261                         ret = ENOMEM;
1262                         *buffer_len = sizeof (int);
1263                         if (orig_buffer_len < sizeof (int))
1264                                 break;
1265                         *((int *) buffer) = iter->addrfamily;
1266                         ret = 0;
1267                         break;
1268
1269                 case PING_INFO_LATENCY:
1270                         ret = ENOMEM;
1271                         *buffer_len = sizeof (double);
1272                         if (orig_buffer_len < sizeof (double))
1273                                 break;
1274                         *((double *) buffer) = iter->latency;
1275                         ret = 0;
1276                         break;
1277
1278                 case PING_INFO_SEQUENCE:
1279                         ret = ENOMEM;
1280                         *buffer_len = sizeof (unsigned int);
1281                         if (orig_buffer_len < sizeof (unsigned int))
1282                                 break;
1283                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1284                         ret = 0;
1285                         break;
1286
1287                 case PING_INFO_IDENT:
1288                         ret = ENOMEM;
1289                         *buffer_len = sizeof (uint16_t);
1290                         if (orig_buffer_len < sizeof (uint16_t))
1291                                 break;
1292                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1293                         ret = 0;
1294                         break;
1295
1296                 case PING_INFO_DATA:
1297                         ret = ENOMEM;
1298                         *buffer_len = strlen (iter->data);
1299                         if (orig_buffer_len < *buffer_len)
1300                                 break;
1301                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1302                         ret = 0;
1303                         break;
1304         }
1305
1306         return (ret);
1307 }
1308
1309 void *ping_iterator_get_context (pingobj_iter_t *iter)
1310 {
1311         return (iter->context);
1312 }
1313
1314 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1315 {
1316         iter->context = context;
1317 }