Merge branch 'v022/net-unreach'
[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; only version 2 of the License is
8  * applicable.
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         {
544 #if defined(EHOSTUNREACH)
545                 if (errno == EHOSTUNREACH)
546                         return (0);
547 #endif
548 #if defined(ENETUNREACH)
549                 if (errno == ENETUNREACH)
550                         return (0);
551 #endif
552                 ping_set_error (obj, "sendto", strerror (errno));
553         }
554
555         return (ret);
556 }
557
558 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
559 {
560         struct icmp *icmp4;
561         int status;
562
563         char buf[4096];
564         int  buflen;
565
566         char *data;
567         int   datalen;
568
569         dprintf ("ph->hostname = %s\n", ph->hostname);
570
571         memset (buf, '\0', sizeof (buf));
572         icmp4 = (struct icmp *) buf;
573         data  = (char *) (icmp4 + 1);
574
575         icmp4->icmp_type  = ICMP_ECHO;
576         icmp4->icmp_code  = 0;
577         icmp4->icmp_cksum = 0;
578         icmp4->icmp_id    = htons (ph->ident);
579         icmp4->icmp_seq   = htons (ph->sequence);
580
581         buflen = 4096 - sizeof (struct icmp);
582         strncpy (data, ph->data, buflen);
583         datalen = strlen (data);
584
585         buflen = datalen + sizeof (struct icmp);
586
587         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
588
589         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
590
591         status = ping_sendto (obj, ph, buf, buflen);
592         if (status < 0)
593         {
594                 perror ("ping_sendto");
595                 return (-1);
596         }
597
598         dprintf ("sendto: status = %i\n", status);
599
600         return (0);
601 }
602
603 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
604 {
605         struct icmp6_hdr *icmp6;
606         int status;
607
608         char buf[4096];
609         int  buflen;
610
611         char *data;
612         int   datalen;
613
614         dprintf ("ph->hostname = %s\n", ph->hostname);
615
616         memset (buf, '\0', sizeof (buf));
617         icmp6 = (struct icmp6_hdr *) buf;
618         data  = (char *) (icmp6 + 1);
619
620         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
621         icmp6->icmp6_code  = 0;
622         /* The checksum will be calculated by the TCP/IP stack.  */
623         /* FIXME */
624         icmp6->icmp6_cksum = 0;
625         icmp6->icmp6_id    = htons (ph->ident);
626         icmp6->icmp6_seq   = htons (ph->sequence);
627
628         buflen = 4096 - sizeof (struct icmp6_hdr);
629         strncpy (data, ph->data, buflen);
630         datalen = strlen (data);
631
632         buflen = datalen + sizeof (struct icmp6_hdr);
633
634         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
635
636         status = ping_sendto (obj, ph, buf, buflen);
637         if (status < 0)
638         {
639                 perror ("ping_sendto");
640                 return (-1);
641         }
642
643         dprintf ("sendto: status = %i\n", status);
644
645         return (0);
646 }
647
648 static int ping_send_all (pingobj_t *obj)
649 {
650         pinghost_t *ph;
651         pinghost_t *ptr;
652
653         int ret;
654
655         ret = 0;
656         ph = obj->head;
657
658         for (ptr = ph; ptr != NULL; ptr = ptr->next)
659         {
660                 /* start timer.. The GNU `ping6' starts the timer before
661                  * sending the packet, so I will do that too */
662                 if (gettimeofday (ptr->timer, NULL) == -1)
663                 {
664                         dprintf ("gettimeofday: %s\n", strerror (errno));
665                         timerclear (ptr->timer);
666                         ret--;
667                         continue;
668                 }
669                 else
670                 {
671                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
672                 }
673
674                 if (ptr->addrfamily == AF_INET6)
675                 {       
676                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
677                         if (ping_send_one_ipv6 (obj, ptr) != 0)
678                         {
679                                 timerclear (ptr->timer);
680                                 ret--;
681                                 continue;
682                         }
683                 }
684                 else if (ptr->addrfamily == AF_INET)
685                 {
686                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
687                         if (ping_send_one_ipv4 (obj, ptr) != 0)
688                         {
689                                 timerclear (ptr->timer);
690                                 ret--;
691                                 continue;
692                         }
693                 }
694                 else /* this should not happen */
695                 {
696                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
697                         timerclear (ptr->timer);
698                         ret--;
699                         continue;
700                 }
701
702                 ptr->sequence++;
703         }
704
705         return (ret);
706 }
707
708 /*
709  * Set the TTL of a socket protocol independently.
710  */
711 static int ping_set_ttl (pinghost_t *ph, int ttl)
712 {
713         int ret = -2;
714
715         if (ph->addrfamily == AF_INET)
716         {
717                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL, &ttl, sizeof (ttl));
718         }
719         else if (ph->addrfamily == AF_INET6)
720         {
721                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof (ttl));
722         }
723
724         return (ret);
725 }
726
727 static int ping_get_ident (void)
728 {
729         int fd;
730         static int did_seed = 0;
731
732         int retval;
733
734         if (did_seed == 0)
735         {
736                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
737                 {
738                         unsigned int seed;
739
740                         if (read (fd, &seed, sizeof (seed)) != -1)
741                         {
742                                 did_seed = 1;
743                                 dprintf ("Random seed: %i\n", seed);
744                                 srandom (seed);
745                         }
746
747                         close (fd);
748                 }
749                 else
750                 {
751                         dprintf ("open (/dev/urandom): %s\n", strerror (errno));
752                 }
753         }
754
755         retval = (int) random ();
756
757         dprintf ("Random number: %i\n", retval);
758         
759         return (retval);
760 }
761
762 static pinghost_t *ping_alloc (void)
763 {
764         pinghost_t *ph;
765         size_t      ph_size;
766
767         ph_size = sizeof (pinghost_t)
768                 + sizeof (struct sockaddr_storage)
769                 + sizeof (struct timeval);
770
771         ph = (pinghost_t *) malloc (ph_size);
772         if (ph == NULL)
773                 return (NULL);
774
775         memset (ph, '\0', ph_size);
776
777         ph->timer   = (struct timeval *) (ph + 1);
778         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
779
780         ph->addrlen = sizeof (struct sockaddr_storage);
781         ph->latency = -1.0;
782         ph->ident   = ping_get_ident () & 0xFFFF;
783
784         return (ph);
785 }
786
787 static void ping_free (pinghost_t *ph)
788 {
789         if (ph->hostname != NULL)
790                 free (ph->hostname);
791
792         if (ph->data != NULL)
793                 free (ph->data);
794
795         free (ph);
796 }
797
798 /*
799  * public methods
800  */
801 const char *ping_get_error (pingobj_t *obj)
802 {
803         return (obj->errmsg);
804 }
805
806 pingobj_t *ping_construct (void)
807 {
808         pingobj_t *obj;
809
810         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
811                 return (NULL);
812         memset (obj, '\0', sizeof (pingobj_t));
813
814         obj->timeout    = PING_DEF_TIMEOUT;
815         obj->ttl        = PING_DEF_TTL;
816         obj->addrfamily = PING_DEF_AF;
817         obj->data       = strdup (PING_DEF_DATA);
818
819         return (obj);
820 }
821
822 void ping_destroy (pingobj_t *obj)
823 {
824         pinghost_t *current;
825         pinghost_t *next;
826
827         current = obj->head;
828         next = NULL;
829
830         while (current != NULL)
831         {
832                 next = current->next;
833                 ping_free (current);
834                 current = next;
835         }
836
837         if (obj->data != NULL)
838                 free (obj->data);
839
840         if (obj->srcaddr != NULL)
841                 free (obj->srcaddr);
842
843         free (obj);
844
845         return;
846 }
847
848 int ping_setopt (pingobj_t *obj, int option, void *value)
849 {
850         int ret = 0;
851
852         switch (option)
853         {
854                 case PING_OPT_TIMEOUT:
855                         obj->timeout = *((double *) value);
856                         if (obj->timeout < 0.0)
857                         {
858                                 obj->timeout = PING_DEF_TIMEOUT;
859                                 ret = -1;
860                         }
861                         break;
862
863                 case PING_OPT_TTL:
864                         obj->ttl = *((int *) value);
865                         if ((obj->ttl < 1) || (obj->ttl > 255))
866                         {
867                                 obj->ttl = PING_DEF_TTL;
868                                 ret = -1;
869                         }
870                         break;
871
872                 case PING_OPT_AF:
873                         obj->addrfamily = *((int *) value);
874                         if ((obj->addrfamily != AF_UNSPEC)
875                                         && (obj->addrfamily != AF_INET)
876                                         && (obj->addrfamily != AF_INET6))
877                         {
878                                 obj->addrfamily = PING_DEF_AF;
879                                 ret = -1;
880                         }
881                         if (obj->srcaddr != NULL)
882                         {
883                                 free (obj->srcaddr);
884                                 obj->srcaddr = NULL;
885                         }
886                         break;
887
888                 case PING_OPT_DATA:
889                         if (obj->data != NULL)
890                         {
891                                 free (obj->data);
892                                 obj->data = NULL;
893                         }
894                         obj->data = strdup ((const char *) value);
895                         break;
896
897                 case PING_OPT_SOURCE:
898                 {
899                         char            *hostname = (char *) value;
900                         struct addrinfo  ai_hints;
901                         struct addrinfo *ai_list;
902                         int              status;
903 #if WITH_DEBUG
904                         if (obj->addrfamily != AF_UNSPEC)
905                         {
906                                 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
907                         }
908 #endif
909                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
910                         ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
911 #if defined(AI_ADDRCONFIG)
912                         ai_hints.ai_flags = AI_ADDRCONFIG;
913 #endif
914                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
915                         if (status != 0)
916                         {
917                                 ping_set_error (obj, "getaddrinfo",
918                                                 status == EAI_SYSTEM
919                                                 ? strerror (errno)
920                                                 : gai_strerror (status));
921                                 ret = -1;
922                                 break;
923                         }
924 #if WITH_DEBUG
925                         if (ai_list->ai_next != NULL)
926                         {
927                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
928                         }
929 #endif
930                         if (obj->srcaddr == NULL)
931                         {
932                                 obj->srcaddrlen = 0;
933                                 obj->srcaddr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage));
934                                 if (obj->srcaddr == NULL)
935                                 {
936                                         ping_set_error (obj, "malloc",
937                                                         strerror (errno));
938                                         ret = -1;
939                                         freeaddrinfo (ai_list);
940                                         break;
941                                 }
942                         }
943                         memset ((void *) obj->srcaddr, '\0', sizeof (struct sockaddr_storage));
944                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
945                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
946                                         ai_list->ai_addrlen);
947                         obj->srcaddrlen = ai_list->ai_addrlen;
948                         obj->addrfamily = ai_list->ai_family;
949
950                         freeaddrinfo (ai_list);
951                 } /* case PING_OPT_SOURCE */
952                 break;
953
954                 default:
955                         ret = -2;
956         } /* switch (option) */
957
958         return (ret);
959 } /* int ping_setopt */
960
961
962 int ping_send (pingobj_t *obj)
963 {
964         int ret;
965
966         if (ping_send_all (obj) < 0)
967                 return (-1);
968
969         if ((ret = ping_receive_all (obj)) < 0)
970                 return (-2);
971
972         return (ret);
973 }
974
975 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
976 {
977         while (ph != NULL)
978         {
979                 if (strcasecmp (ph->hostname, host) == 0)
980                         break;
981
982                 ph = ph->next;
983         }
984
985         return (ph);
986 }
987
988 int ping_host_add (pingobj_t *obj, const char *host)
989 {
990         pinghost_t *ph;
991
992         struct sockaddr_storage sockaddr;
993         socklen_t               sockaddr_len;
994
995         struct addrinfo  ai_hints;
996         struct addrinfo *ai_list, *ai_ptr;
997         int              ai_return;
998
999         dprintf ("host = %s\n", host);
1000
1001         if (ping_host_search (obj->head, host) != NULL)
1002                 return (0);
1003
1004         memset (&ai_hints, '\0', sizeof (ai_hints));
1005         ai_hints.ai_flags     = 0;
1006 #ifdef AI_ADDRCONFIG
1007         ai_hints.ai_flags    |= AI_ADDRCONFIG;
1008 #endif
1009 #ifdef AI_CANONNAME
1010         ai_hints.ai_flags    |= AI_CANONNAME;
1011 #endif
1012         ai_hints.ai_family    = obj->addrfamily;
1013         ai_hints.ai_socktype  = SOCK_RAW;
1014
1015         if ((ph = ping_alloc ()) == NULL)
1016         {
1017                 dprintf ("Out of memory!\n");
1018                 return (-1);
1019         }
1020
1021         if ((ph->hostname = strdup (host)) == NULL)
1022         {
1023                 dprintf ("Out of memory!\n");
1024                 ping_set_error (obj, "strdup", strerror (errno));
1025                 ping_free (ph);
1026                 return (-1);
1027         }
1028
1029         /* obj->data is not garuanteed to be != NULL */
1030         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1031         {
1032                 dprintf ("Out of memory!\n");
1033                 ping_set_error (obj, "strdup", strerror (errno));
1034                 ping_free (ph);
1035                 return (-1);
1036         }
1037
1038         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1039         {
1040                 dprintf ("getaddrinfo failed\n");
1041                 ping_set_error (obj, "getaddrinfo",
1042                                 (ai_return == EAI_SYSTEM)
1043                                 ? strerror (errno)
1044                                 : gai_strerror (ai_return));
1045                 ping_free (ph);
1046                 return (-1);
1047         }
1048
1049         if (ai_list == NULL)
1050                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1051
1052         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1053         {
1054                 ph->fd = -1;
1055
1056                 sockaddr_len = sizeof (sockaddr);
1057                 memset (&sockaddr, '\0', sockaddr_len);
1058
1059                 if (ai_ptr->ai_family == AF_INET)
1060                 {
1061                         struct sockaddr_in *si;
1062
1063                         si = (struct sockaddr_in *) &sockaddr;
1064                         si->sin_family = AF_INET;
1065                         si->sin_port   = htons (ph->ident);
1066                         si->sin_addr.s_addr = htonl (INADDR_ANY);
1067
1068                         ai_ptr->ai_socktype = SOCK_RAW;
1069                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1070                 }
1071                 else if (ai_ptr->ai_family == AF_INET6)
1072                 {
1073                         struct sockaddr_in6 *si;
1074
1075                         si = (struct sockaddr_in6 *) &sockaddr;
1076                         si->sin6_family = AF_INET6;
1077                         si->sin6_port   = htons (ph->ident);
1078                         si->sin6_addr   = in6addr_any;
1079
1080                         ai_ptr->ai_socktype = SOCK_RAW;
1081                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1082                 }
1083                 else
1084                 {
1085                         char errmsg[PING_ERRMSG_LEN];
1086
1087                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1088                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1089
1090                         dprintf (errmsg);
1091                         ping_set_error (obj, "getaddrinfo", errmsg);
1092                         continue;
1093                 }
1094
1095                 /* TODO: Move this to a static function `ping_open_socket' and
1096                  * call it whenever the socket dies. */
1097                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1098                 if (ph->fd == -1)
1099                 {
1100                         dprintf ("socket: %s\n", strerror (errno));
1101                         ping_set_error (obj, "socket", strerror (errno));
1102                         continue;
1103                 }
1104
1105                 if (obj->srcaddr != NULL)
1106                 {
1107                         assert (obj->srcaddrlen > 0);
1108                         assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1109
1110                         if (bind (ph->fd, (struct sockaddr *) obj->srcaddr, obj->srcaddrlen) == -1)
1111                         {
1112                                 dprintf ("bind: %s\n", strerror (errno));
1113                                 ping_set_error (obj, "bind", strerror (errno));
1114                                 close (ph->fd);
1115                                 ph->fd = -1;
1116                                 continue;
1117                         }
1118                 }
1119
1120                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1121                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1122                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1123                 ph->addrlen = ai_ptr->ai_addrlen;
1124                 ph->addrfamily = ai_ptr->ai_family;
1125
1126 #ifdef AI_CANONNAME
1127                 if ((ai_ptr->ai_canonname != NULL)
1128                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1129                 {
1130                         char *old_hostname;
1131
1132                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1133                                         ph->hostname, ai_ptr->ai_canonname);
1134
1135                         old_hostname = ph->hostname;
1136                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1137                         {
1138                                 /* strdup failed, falling back to old hostname */
1139                                 ph->hostname = old_hostname;
1140                         }
1141                         else if (old_hostname != NULL)
1142                         {
1143                                 free (old_hostname);
1144                         }
1145                 }
1146 #endif /* AI_CANONNAME */
1147
1148                 break;
1149         }
1150
1151         freeaddrinfo (ai_list);
1152
1153         if (ph->fd < 0)
1154         {
1155                 free (ph->hostname);
1156                 free (ph);
1157                 return (-1);
1158         }
1159
1160         /*
1161          * Adding in the front is much easier, but then the iterator will
1162          * return the host that was added last as first host. That's just not
1163          * nice. -octo
1164          */
1165         if (obj->head == NULL)
1166         {
1167                 obj->head = ph;
1168         }
1169         else
1170         {
1171                 pinghost_t *hptr;
1172
1173                 hptr = obj->head;
1174                 while (hptr->next != NULL)
1175                         hptr = hptr->next;
1176
1177                 assert ((hptr != NULL) && (hptr->next == NULL));
1178                 hptr->next = ph;
1179         }
1180
1181         ping_set_ttl (ph, obj->ttl);
1182
1183         return (0);
1184 }
1185
1186 int ping_host_remove (pingobj_t *obj, const char *host)
1187 {
1188         pinghost_t *pre, *cur;
1189
1190         pre = NULL;
1191         cur = obj->head;
1192
1193         while (cur != NULL)
1194         {
1195                 if (strcasecmp (host, cur->hostname))
1196                         break;
1197
1198                 pre = cur;
1199                 cur = cur->next;
1200         }
1201
1202         if (cur == NULL)
1203         {
1204                 ping_set_error (obj, "ping_host_remove", "Host not found");
1205                 return (-1);
1206         }
1207
1208         if (pre == NULL)
1209                 obj->head = cur->next;
1210         else
1211                 pre->next = cur->next;
1212         
1213         if (cur->fd >= 0)
1214                 close (cur->fd);
1215
1216         ping_free (cur);
1217
1218         return (0);
1219 }
1220
1221 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1222 {
1223         return ((pingobj_iter_t *) obj->head);
1224 }
1225
1226 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1227 {
1228         return ((pingobj_iter_t *) iter->next);
1229 }
1230
1231 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1232                 void *buffer, size_t *buffer_len)
1233 {
1234         int ret = EINVAL;
1235
1236         size_t orig_buffer_len = *buffer_len;
1237
1238         switch (info)
1239         {
1240                 case PING_INFO_HOSTNAME:
1241                         ret = ENOMEM;
1242                         *buffer_len = strlen (iter->hostname);
1243                         if (orig_buffer_len <= *buffer_len)
1244                                 break;
1245                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1246                          * will copy `*buffer_len' and pad the rest of
1247                          * `buffer' with null-bytes */
1248                         strncpy (buffer, iter->hostname, orig_buffer_len);
1249                         ret = 0;
1250                         break;
1251
1252                 case PING_INFO_ADDRESS:
1253                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1254                                         iter->addrlen,
1255                                         (char *) buffer,
1256                                         *buffer_len,
1257                                         NULL, 0,
1258                                         NI_NUMERICHOST);
1259                         if (ret != 0)
1260                         {
1261                                 if ((ret == EAI_MEMORY)
1262 #ifdef EAI_OVERFLOW
1263                                                 || (ret == EAI_OVERFLOW)
1264 #endif
1265                                    )
1266                                         ret = ENOMEM;
1267                                 else if (ret == EAI_SYSTEM)
1268                                         /* XXX: Not thread-safe! */
1269                                         ret = errno;
1270                                 else
1271                                         ret = EINVAL;
1272                         }
1273                         break;
1274
1275                 case PING_INFO_FAMILY:
1276                         ret = ENOMEM;
1277                         *buffer_len = sizeof (int);
1278                         if (orig_buffer_len < sizeof (int))
1279                                 break;
1280                         *((int *) buffer) = iter->addrfamily;
1281                         ret = 0;
1282                         break;
1283
1284                 case PING_INFO_LATENCY:
1285                         ret = ENOMEM;
1286                         *buffer_len = sizeof (double);
1287                         if (orig_buffer_len < sizeof (double))
1288                                 break;
1289                         *((double *) buffer) = iter->latency;
1290                         ret = 0;
1291                         break;
1292
1293                 case PING_INFO_SEQUENCE:
1294                         ret = ENOMEM;
1295                         *buffer_len = sizeof (unsigned int);
1296                         if (orig_buffer_len < sizeof (unsigned int))
1297                                 break;
1298                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1299                         ret = 0;
1300                         break;
1301
1302                 case PING_INFO_IDENT:
1303                         ret = ENOMEM;
1304                         *buffer_len = sizeof (uint16_t);
1305                         if (orig_buffer_len < sizeof (uint16_t))
1306                                 break;
1307                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1308                         ret = 0;
1309                         break;
1310
1311                 case PING_INFO_DATA:
1312                         ret = ENOMEM;
1313                         *buffer_len = strlen (iter->data);
1314                         if (orig_buffer_len < *buffer_len)
1315                                 break;
1316                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1317                         ret = 0;
1318                         break;
1319         }
1320
1321         return (ret);
1322 }
1323
1324 void *ping_iterator_get_context (pingobj_iter_t *iter)
1325 {
1326         return (iter->context);
1327 }
1328
1329 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1330 {
1331         iter->context = context;
1332 }