Copied trunk/ to tags/liboping-0.1.0
[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 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 #define PING_DATA "Florian Forster <octo@verplant.org> http://verplant.org/"
99
100 struct pinghost
101 {
102         char                    *hostname;
103         struct sockaddr_storage *addr;
104         socklen_t                addrlen;
105         int                      addrfamily;
106         int                      fd;
107         int                      ident;
108         int                      sequence;
109         struct timeval          *timer;
110         double                   latency;
111
112         void                    *context;
113
114         struct pinghost         *next;
115 };
116
117 struct pingobj
118 {
119         double      timeout;
120         int         ttl;
121         int         addrfamily;
122
123         char        errmsg[PING_ERRMSG_LEN];
124
125         pinghost_t *head;
126 };
127
128 /*
129  * private (static) functions
130  */
131 static void ping_set_error (pingobj_t *obj, const char *function,
132                 const char *message)
133 {
134         snprintf (obj->errmsg, PING_ERRMSG_LEN, "%s: %s", function, message);
135         obj->errmsg[PING_ERRMSG_LEN - 1] = '\0';
136 }
137
138 static int ping_timeval_add (struct timeval *tv1, struct timeval *tv2,
139                 struct timeval *res)
140 {
141         res->tv_sec  = tv1->tv_sec  + tv2->tv_sec;
142         res->tv_usec = tv1->tv_usec + tv2->tv_usec;
143
144         while (res->tv_usec > 1000000)
145         {
146                 res->tv_usec -= 1000000;
147                 res->tv_sec++;
148         }
149
150         return (0);
151 }
152
153 static int ping_timeval_sub (struct timeval *tv1, struct timeval *tv2,
154                 struct timeval *res)
155 {
156
157         if ((tv1->tv_sec < tv2->tv_sec)
158                         || ((tv1->tv_sec == tv2->tv_sec)
159                                 && (tv1->tv_usec < tv2->tv_usec)))
160                 return (-1);
161
162         res->tv_sec  = tv1->tv_sec  - tv2->tv_sec;
163         res->tv_usec = tv1->tv_usec - tv2->tv_usec;
164
165         assert ((res->tv_sec > 0) || ((res->tv_sec == 0) && (res->tv_usec > 0)));
166
167         while (res->tv_usec < 0)
168         {
169                 res->tv_usec += 1000000;
170                 res->tv_sec--;
171         }
172
173         return (0);
174 }
175
176 static uint16_t ping_icmp4_checksum (char *buf, size_t len)
177 {
178         uint32_t sum = 0;
179         uint16_t ret = 0;
180
181         uint16_t *ptr;
182
183         for (ptr = (uint16_t *) buf; len > 1; ptr++, len -= 2)
184                 sum += *ptr;
185
186         if (len == 1)
187         {
188                 *(char *) &ret = *(char *) ptr;
189                 sum += ret;
190         }
191
192         /* Do this twice to get all possible carries.. */
193         sum = (sum >> 16) + (sum & 0xFFFF);
194         sum = (sum >> 16) + (sum & 0xFFFF);
195
196         ret = ~sum;
197
198         return (ret);
199 }
200
201 static pinghost_t *ping_receive_ipv4 (pinghost_t *ph, char *buffer, size_t buffer_len)
202 {
203         struct ip *ip_hdr;
204         struct icmp *icmp_hdr;
205
206         size_t ip_hdr_len;
207
208         uint16_t recv_checksum;
209         uint16_t calc_checksum;
210
211         uint16_t ident;
212         uint16_t seq;
213
214         pinghost_t *ptr;
215
216         if (buffer_len < sizeof (struct ip))
217                 return (NULL);
218
219         ip_hdr     = (struct ip *) buffer;
220         ip_hdr_len = ip_hdr->ip_hl << 2;
221
222         if (buffer_len < ip_hdr_len)
223                 return (NULL);
224
225         buffer     += ip_hdr_len;
226         buffer_len -= ip_hdr_len;
227
228         if (buffer_len < sizeof (struct icmp))
229                 return (NULL);
230
231         icmp_hdr = (struct icmp *) buffer;
232         buffer     += sizeof (struct icmp);
233         buffer_len -= sizeof (struct icmp);
234
235         if (icmp_hdr->icmp_type != ICMP_ECHOREPLY)
236         {
237                 dprintf ("Unexpected ICMP type: %i\n", icmp_hdr->icmp_type);
238                 return (NULL);
239         }
240
241         recv_checksum = icmp_hdr->icmp_cksum;
242         icmp_hdr->icmp_cksum = 0;
243         calc_checksum = ping_icmp4_checksum ((char *) icmp_hdr,
244                         sizeof (struct icmp) + buffer_len);
245
246         if (recv_checksum != calc_checksum)
247         {
248                 dprintf ("Checksum missmatch: Got 0x%04x, calculated 0x%04x\n",
249                                 recv_checksum, calc_checksum);
250                 return (NULL);
251         }
252
253         ident = ntohs (icmp_hdr->icmp_id);
254         seq   = ntohs (icmp_hdr->icmp_seq);
255
256         for (ptr = ph; ptr != NULL; ptr = ptr->next)
257         {
258                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
259                                 ptr->hostname, ptr->ident, ptr->sequence - 1);
260
261                 if (ptr->addrfamily != AF_INET)
262                         continue;
263
264                 if (!timerisset (ptr->timer))
265                         continue;
266
267                 if (ptr->ident != ident)
268                         continue;
269
270                 if ((ptr->sequence - 1) != seq)
271                         continue;
272
273                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
274                                 ptr->hostname, ident, seq);
275
276                 break;
277         }
278
279         if (ptr == NULL)
280         {
281                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
282                                 ident, seq);
283         }
284
285         return (ptr);
286 }
287
288 static pinghost_t *ping_receive_ipv6 (pinghost_t *ph, char *buffer, size_t buffer_len)
289 {
290         struct icmp6_hdr *icmp_hdr;
291
292         uint16_t ident;
293         uint16_t seq;
294
295         pinghost_t *ptr;
296
297         if (buffer_len < sizeof (struct icmp6_hdr))
298                 return (NULL);
299
300         icmp_hdr = (struct icmp6_hdr *) buffer;
301         buffer     += sizeof (struct icmp);
302         buffer_len -= sizeof (struct icmp);
303
304         if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
305         {
306                 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
307                 return (NULL);
308         }
309
310         if (icmp_hdr->icmp6_code != 0)
311         {
312                 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
313                 return (NULL);
314         }
315
316         ident = ntohs (icmp_hdr->icmp6_id);
317         seq   = ntohs (icmp_hdr->icmp6_seq);
318
319         for (ptr = ph; ptr != NULL; ptr = ptr->next)
320         {
321                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
322                                 ptr->hostname, ptr->ident, ptr->sequence - 1);
323
324                 if (ptr->addrfamily != AF_INET6)
325                         continue;
326
327                 if (!timerisset (ptr->timer))
328                         continue;
329
330                 if (ptr->ident != ident)
331                         continue;
332
333                 if ((ptr->sequence - 1) != seq)
334                         continue;
335
336                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
337                                 ptr->hostname, ident, seq);
338
339                 break;
340         }
341
342         if (ptr == NULL)
343         {
344                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
345                                 ident, seq);
346         }
347
348         return (ptr);
349 }
350
351 static int ping_receive_one (int fd, pinghost_t *ph, struct timeval *now)
352 {
353         char   buffer[4096];
354         size_t buffer_len;
355
356         struct timeval diff;
357
358         pinghost_t *host = NULL;
359
360         struct sockaddr_storage sa;
361         socklen_t               sa_len;
362
363         sa_len = sizeof (sa);
364
365         buffer_len = recvfrom (fd, buffer, sizeof (buffer), 0,
366                         (struct sockaddr *) &sa, &sa_len);
367         if (buffer_len == -1)
368         {
369                 dprintf ("recvfrom: %s\n", strerror (errno));
370                 return (-1);
371         }
372
373         dprintf ("Read %i bytes from fd = %i\n", buffer_len, fd);
374
375         if (sa.ss_family == AF_INET)
376         {
377                 if ((host = ping_receive_ipv4 (ph, buffer, buffer_len)) == NULL)
378                         return (-1);
379         }
380         else if (sa.ss_family == AF_INET6)
381         {
382                 if ((host = ping_receive_ipv6 (ph, buffer, buffer_len)) == NULL)
383                         return (-1);
384         }
385
386         dprintf ("rcvd: %12i.%06i\n",
387                         (int) now->tv_sec,
388                         (int) now->tv_usec);
389         dprintf ("sent: %12i.%06i\n",
390                         (int) host->timer->tv_sec,
391                         (int) host->timer->tv_usec);
392
393         if (ping_timeval_sub (now, host->timer, &diff) < 0)
394         {
395                 timerclear (host->timer);
396                 return (-1);
397         }
398
399         dprintf ("diff: %12i.%06i\n",
400                         (int) diff.tv_sec,
401                         (int) diff.tv_usec);
402
403         host->latency  = ((double) diff.tv_usec) / 1000.0;
404         host->latency += ((double) diff.tv_sec)  * 1000.0;
405
406         timerclear (host->timer);
407
408         return (0);
409 }
410
411 static int ping_receive_all (pingobj_t *obj)
412 {
413         fd_set readfds;
414         int num_readfds;
415         int max_readfds;
416
417         pinghost_t *ph;
418         pinghost_t *ptr;
419
420         struct timeval endtime;
421         struct timeval nowtime;
422         struct timeval timeout;
423         int status;
424
425         int ret;
426
427         ph = obj->head;
428         ret = 0;
429
430         for (ptr = ph; ptr != NULL; ptr = ptr->next)
431                 ptr->latency = -1.0;
432
433         if (gettimeofday (&nowtime, NULL) == -1)
434         {
435                 ping_set_error (obj, "gettimeofday", strerror (errno));
436                 return (-1);
437         }
438
439         /* Set up timeout */
440         timeout.tv_sec = (time_t) obj->timeout;
441         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
442
443         dprintf ("Set timeout to %i.%06i seconds\n",
444                         (int) timeout.tv_sec,
445                         (int) timeout.tv_usec);
446
447         ping_timeval_add (&nowtime, &timeout, &endtime);
448
449         while (1)
450         {
451                 FD_ZERO (&readfds);
452                 num_readfds =  0;
453                 max_readfds = -1;
454
455                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
456                 {
457                         if (!timerisset (ptr->timer))
458                                 continue;
459
460                         FD_SET (ptr->fd, &readfds);
461                         num_readfds++;
462
463                         if (max_readfds < ptr->fd)
464                                 max_readfds = ptr->fd;
465                 }
466
467                 if (num_readfds == 0)
468                         break;
469
470                 if (gettimeofday (&nowtime, NULL) == -1)
471                 {
472                         ping_set_error (obj, "gettimeofday", strerror (errno));
473                         return (-1);
474                 }
475
476                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
477                         break;
478
479                 dprintf ("Waiting on %i sockets for %i.%06i seconds\n", num_readfds,
480                                 (int) timeout.tv_sec,
481                                 (int) timeout.tv_usec);
482
483                 status = select (max_readfds + 1, &readfds, NULL, NULL, &timeout);
484
485                 if (gettimeofday (&nowtime, NULL) == -1)
486                 {
487                         ping_set_error (obj, "gettimeofday", strerror (errno));
488                         return (-1);
489                 }
490                 
491                 if ((status == -1) && (errno == EINTR))
492                 {
493                         dprintf ("select was interrupted by signal..\n");
494                         continue;
495                 }
496                 else if (status < 0)
497                 {
498                         dprintf ("select: %s\n", strerror (errno));
499                         break;
500                 }
501                 else if (status == 0)
502                 {
503                         dprintf ("select timed out\n");
504                         break;
505                 }
506
507                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
508                 {
509                         if (FD_ISSET (ptr->fd, &readfds))
510                                 if (ping_receive_one (ptr->fd, ph, &nowtime) == 0)
511                                         ret++;
512                 }
513         } /* while (1) */
514         
515         return (ret);
516 }
517
518 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
519  * Sending functions:                                                        *
520  *                                                                           *
521  * ping_send_all                                                             *
522  * +-> ping_send_one_ipv4                                                    *
523  * `-> ping_send_one_ipv6                                                    *
524  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
525 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
526                 const void *buf, size_t buflen)
527 {
528         ssize_t ret;
529
530         if (gettimeofday (ph->timer, NULL) == -1)
531         {
532                 timerclear (ph->timer);
533                 return (-1);
534         }
535
536         ret = sendto (ph->fd, buf, buflen, 0,
537                         (struct sockaddr *) ph->addr, ph->addrlen);
538
539         if (ret < 0)
540                 ping_set_error (obj, "sendto", strerror (errno));
541
542         return (ret);
543 }
544
545 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
546 {
547         struct icmp *icmp4;
548         int status;
549
550         char buf[4096];
551         int  buflen;
552
553         char *data;
554         int   datalen;
555
556         dprintf ("ph->hostname = %s\n", ph->hostname);
557
558         memset (buf, '\0', sizeof (buf));
559         icmp4 = (struct icmp *) buf;
560         data  = (char *) (icmp4 + 1);
561
562         icmp4->icmp_type  = ICMP_ECHO;
563         icmp4->icmp_code  = 0;
564         icmp4->icmp_cksum = 0;
565         icmp4->icmp_id    = htons (ph->ident);
566         icmp4->icmp_seq   = htons (ph->sequence);
567
568         strcpy (data, PING_DATA);
569         datalen = strlen (data);
570
571         buflen = datalen + sizeof (struct icmp);
572
573         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
574
575         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
576
577         status = ping_sendto (obj, ph, buf, buflen);
578         if (status < 0)
579         {
580                 perror ("ping_sendto");
581                 return (-1);
582         }
583
584         dprintf ("sendto: status = %i\n", status);
585
586         return (0);
587 }
588
589 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
590 {
591         struct icmp6_hdr *icmp6;
592         int status;
593
594         char buf[4096];
595         int  buflen;
596
597         char *data;
598         int   datalen;
599
600         dprintf ("ph->hostname = %s\n", ph->hostname);
601
602         memset (buf, '\0', sizeof (buf));
603         icmp6 = (struct icmp6_hdr *) buf;
604         data  = (char *) (icmp6 + 1);
605
606         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
607         icmp6->icmp6_code  = 0;
608         /* The checksum will be calculated by the TCP/IP stack.  */
609         icmp6->icmp6_cksum = 0;
610         icmp6->icmp6_id    = htons (ph->ident);
611         icmp6->icmp6_seq   = htons (ph->sequence);
612
613         strcpy (data, PING_DATA);
614         datalen = strlen (data);
615
616         buflen = datalen + sizeof (struct icmp6_hdr);
617
618         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
619
620         status = ping_sendto (obj, ph, buf, buflen);
621         if (status < 0)
622         {
623                 perror ("ping_sendto");
624                 return (-1);
625         }
626
627         dprintf ("sendto: status = %i\n", status);
628
629         return (0);
630 }
631
632 static int ping_send_all (pingobj_t *obj)
633 {
634         pinghost_t *ph;
635         pinghost_t *ptr;
636
637         int ret;
638
639         ret = 0;
640         ph = obj->head;
641
642         for (ptr = ph; ptr != NULL; ptr = ptr->next)
643         {
644                 /* start timer.. The GNU `ping6' starts the timer before
645                  * sending the packet, so I will do that too */
646                 if (gettimeofday (ptr->timer, NULL) == -1)
647                 {
648                         dprintf ("gettimeofday: %s\n", strerror (errno));
649                         timerclear (ptr->timer);
650                         ret--;
651                         continue;
652                 }
653                 else
654                 {
655                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
656                 }
657
658                 if (ptr->addrfamily == AF_INET6)
659                 {       
660                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
661                         if (ping_send_one_ipv6 (obj, ptr) != 0)
662                         {
663                                 timerclear (ptr->timer);
664                                 ret--;
665                                 continue;
666                         }
667                 }
668                 else if (ptr->addrfamily == AF_INET)
669                 {
670                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
671                         if (ping_send_one_ipv4 (obj, ptr) != 0)
672                         {
673                                 timerclear (ptr->timer);
674                                 ret--;
675                                 continue;
676                         }
677                 }
678                 else /* this should not happen */
679                 {
680                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
681                         timerclear (ptr->timer);
682                         ret--;
683                         continue;
684                 }
685
686                 ptr->sequence++;
687         }
688
689         return (ret);
690 }
691
692 /*
693  * Set the TTL of a socket protocol independently.
694  */
695 static int ping_set_ttl (pinghost_t *ph, int ttl)
696 {
697         int ret = -2;
698
699         if (ph->addrfamily == AF_INET)
700         {
701                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL, &ttl, sizeof (ttl));
702         }
703         else if (ph->addrfamily == AF_INET6)
704         {
705                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof (ttl));
706         }
707
708         return (ret);
709 }
710
711 static int ping_get_ident (void)
712 {
713         int fd;
714         static int did_seed = 0;
715
716         int retval;
717
718         if (did_seed == 0)
719         {
720                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
721                 {
722                         unsigned int seed;
723
724                         if (read (fd, &seed, sizeof (seed)) != -1)
725                         {
726                                 did_seed = 1;
727                                 dprintf ("Random seed: %i\n", seed);
728                                 srandom (seed);
729                         }
730
731                         close (fd);
732                 }
733                 else
734                 {
735                         dprintf ("open (/dev/urandom): %s\n", strerror (errno));
736                 }
737         }
738
739         retval = (int) random ();
740
741         dprintf ("Random number: %i\n", retval);
742         
743         return (retval);
744 }
745
746 static pinghost_t *ping_alloc (void)
747 {
748         pinghost_t *ph;
749         size_t      ph_size;
750
751         ph_size = sizeof (pinghost_t)
752                 + sizeof (struct sockaddr_storage)
753                 + sizeof (struct timeval);
754
755         ph = (pinghost_t *) malloc (ph_size);
756         if (ph == NULL)
757                 return (NULL);
758
759         memset (ph, '\0', ph_size);
760
761         ph->timer   = (struct timeval *) (ph + 1);
762         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
763
764         ph->addrlen = sizeof (struct sockaddr_storage);
765         ph->latency = -1.0;
766         ph->ident   = ping_get_ident () & 0xFFFF;
767
768         return (ph);
769 }
770
771 static void ping_free (pinghost_t *ph)
772 {
773         if (ph->hostname != NULL)
774                 free (ph->hostname);
775
776         free (ph);
777 }
778
779 /*
780  * public methods
781  */
782 const char *ping_get_error (pingobj_t *obj)
783 {
784         return (obj->errmsg);
785 }
786
787 pingobj_t *ping_construct (void)
788 {
789         pingobj_t *obj;
790
791         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
792                 return (NULL);
793         memset (obj, '\0', sizeof (pingobj_t));
794
795         obj->timeout    = PING_DEF_TIMEOUT;
796         obj->ttl        = PING_DEF_TTL;
797         obj->addrfamily = PING_DEF_AF;
798
799         return (obj);
800 }
801
802 void ping_destroy (pingobj_t *obj)
803 {
804         pinghost_t *current;
805         pinghost_t *next;
806
807         current = obj->head;
808         next = NULL;
809
810         while (current != NULL)
811         {
812                 next = current->next;
813                 ping_free (current);
814                 current = next;
815         }
816
817         free (obj);
818
819         return;
820 }
821
822 int ping_setopt (pingobj_t *obj, int option, void *value)
823 {
824         int ret = 0;
825
826         switch (option)
827         {
828                 case PING_OPT_TIMEOUT:
829                         obj->timeout = *((double *) value);
830                         if (obj->timeout < 0.0)
831                         {
832                                 obj->timeout = PING_DEF_TIMEOUT;
833                                 ret = -1;
834                         }
835                         break;
836
837                 case PING_OPT_TTL:
838                         obj->ttl = *((int *) value);
839                         if ((obj->ttl < 1) || (obj->ttl > 255))
840                         {
841                                 obj->ttl = PING_DEF_TTL;
842                                 ret = -1;
843                         }
844                         break;
845
846                 case PING_OPT_AF:
847                         obj->addrfamily = *((int *) value);
848                         if ((obj->addrfamily != AF_UNSPEC)
849                                         && (obj->addrfamily != AF_INET)
850                                         && (obj->addrfamily != AF_INET6))
851                         {
852                                 obj->addrfamily = PING_DEF_AF;
853                                 ret = -1;
854                         }
855                         break;
856
857                 default:
858                         ret = -2;
859         } /* switch (option) */
860
861         return (ret);
862 } /* int ping_setopt */
863
864
865 int ping_send (pingobj_t *obj)
866 {
867         int ret;
868
869         if (ping_send_all (obj) < 0)
870                 return (-1);
871
872         if ((ret = ping_receive_all (obj)) < 0)
873                 return (-2);
874
875         return (ret);
876 }
877
878 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
879 {
880         while (ph != NULL)
881         {
882                 if (strcasecmp (ph->hostname, host) == 0)
883                         break;
884
885                 ph = ph->next;
886         }
887
888         return (ph);
889 }
890
891 int ping_host_add (pingobj_t *obj, const char *host)
892 {
893         pinghost_t *ph;
894
895         struct sockaddr_storage sockaddr;
896         socklen_t               sockaddr_len;
897
898         struct addrinfo  ai_hints;
899         struct addrinfo *ai_list, *ai_ptr;
900         int              ai_return;
901
902         dprintf ("host = %s\n", host);
903
904         if (ping_host_search (obj->head, host) != NULL)
905                 return (0);
906
907         memset (&ai_hints, '\0', sizeof (ai_hints));
908         ai_hints.ai_flags     = 0;
909 #ifdef AI_ADDRCONFIG
910         ai_hints.ai_flags    |= AI_ADDRCONFIG;
911 #endif
912         ai_hints.ai_family    = obj->addrfamily;
913         ai_hints.ai_socktype  = SOCK_RAW;
914
915         if ((ph = ping_alloc ()) == NULL)
916         {
917                 dprintf ("Out of memory!\n");
918                 return (-1);
919         }
920
921         if ((ph->hostname = strdup (host)) == NULL)
922         {
923                 dprintf ("Out of memory!\n");
924                 ping_set_error (obj, "strdup", strerror (errno));
925                 ping_free (ph);
926                 return (-1);
927         }
928
929         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
930         {
931                 dprintf ("getaddrinfo failed\n");
932                 ping_set_error (obj, "getaddrinfo",
933                                 (ai_return == EAI_SYSTEM)
934                                 ? strerror (errno)
935                                 : gai_strerror (ai_return));
936                 ping_free (ph);
937                 return (-1);
938         }
939
940         if (ai_list == NULL)
941                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
942
943         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
944         {
945                 ph->fd = -1;
946
947                 sockaddr_len = sizeof (sockaddr);
948                 memset (&sockaddr, '\0', sockaddr_len);
949
950                 if (ai_ptr->ai_family == AF_INET)
951                 {
952                         struct sockaddr_in *si;
953
954                         si = (struct sockaddr_in *) &sockaddr;
955                         si->sin_family = AF_INET;
956                         si->sin_port   = htons (ph->ident);
957                         si->sin_addr.s_addr = htonl (INADDR_ANY);
958
959                         ai_ptr->ai_socktype = SOCK_RAW;
960                         ai_ptr->ai_protocol = IPPROTO_ICMP;
961                 }
962                 else if (ai_ptr->ai_family == AF_INET6)
963                 {
964                         struct sockaddr_in6 *si;
965
966                         si = (struct sockaddr_in6 *) &sockaddr;
967                         si->sin6_family = AF_INET6;
968                         si->sin6_port   = htons (ph->ident);
969                         si->sin6_addr   = in6addr_any;
970
971                         ai_ptr->ai_socktype = SOCK_RAW;
972                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
973                 }
974                 else
975                 {
976                         char errmsg[PING_ERRMSG_LEN];
977
978                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
979                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
980
981                         dprintf (errmsg);
982                         ping_set_error (obj, "getaddrinfo", errmsg);
983                         continue;
984                 }
985
986                 /* TODO: Move this to a static function `ping_open_socket' and
987                  * call it whenever the socket dies. */
988                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
989                 if (ph->fd == -1)
990                 {
991                         dprintf ("socket: %s\n", strerror (errno));
992                         ping_set_error (obj, "socket", strerror (errno));
993                         continue;
994                 }
995
996                 if (bind (ph->fd, (struct sockaddr *) &sockaddr, sockaddr_len) == -1)
997                 {
998                         dprintf ("bind: %s\n", strerror (errno));
999                         ping_set_error (obj, "bind", strerror (errno));
1000                         close (ph->fd);
1001                         ph->fd = -1;
1002                         continue;
1003                 }
1004
1005                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1006                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1007                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1008                 ph->addrlen = ai_ptr->ai_addrlen;
1009                 ph->addrfamily = ai_ptr->ai_family;
1010
1011                 break;
1012         }
1013
1014         freeaddrinfo (ai_list);
1015
1016         if (ph->fd < 0)
1017         {
1018                 free (ph->hostname);
1019                 free (ph);
1020                 return (-1);
1021         }
1022
1023         ph->next  = obj->head;
1024         obj->head = ph;
1025
1026         ping_set_ttl (ph, obj->ttl);
1027
1028         return (0);
1029 }
1030
1031 int ping_host_remove (pingobj_t *obj, const char *host)
1032 {
1033         pinghost_t *pre, *cur;
1034
1035         pre = NULL;
1036         cur = obj->head;
1037
1038         while (cur != NULL)
1039         {
1040                 if (strcasecmp (host, cur->hostname))
1041                         break;
1042
1043                 pre = cur;
1044                 cur = cur->next;
1045         }
1046
1047         if (cur == NULL)
1048         {
1049                 ping_set_error (obj, "ping_host_remove", "Host not found");
1050                 return (-1);
1051         }
1052
1053         if (pre == NULL)
1054                 obj->head = cur->next;
1055         else
1056                 pre->next = cur->next;
1057         
1058         if (cur->fd >= 0)
1059                 close (cur->fd);
1060
1061         ping_free (cur);
1062
1063         return (0);
1064 }
1065
1066 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1067 {
1068         return ((pingobj_iter_t *) obj->head);
1069 }
1070
1071 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1072 {
1073         return ((pingobj_iter_t *) iter->next);
1074 }
1075
1076 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1077                 void *buffer, size_t *buffer_len)
1078 {
1079         int ret = EINVAL;
1080
1081         size_t orig_buffer_len = *buffer_len;
1082
1083         switch (info)
1084         {
1085                 case PING_INFO_HOSTNAME:
1086                         ret = ENOMEM;
1087                         *buffer_len = strlen (iter->hostname);
1088                         if (orig_buffer_len <= *buffer_len)
1089                                 break;
1090                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1091                          * will copy `*buffer_len' and pad the rest of
1092                          * `buffer' with null-bytes */
1093                         strncpy (buffer, iter->hostname, orig_buffer_len);
1094                         ret = 0;
1095                         break;
1096
1097                 case PING_INFO_ADDRESS:
1098                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1099                                         iter->addrlen,
1100                                         (char *) buffer,
1101                                         *buffer_len,
1102                                         NULL, 0,
1103                                         NI_NUMERICHOST);
1104                         if (ret != 0)
1105                         {
1106                                 if ((ret == EAI_MEMORY)
1107 #ifdef EAI_OVERFLOW
1108                                                 || (ret == EAI_OVERFLOW)
1109 #endif
1110                                    )
1111                                         ret = ENOMEM;
1112                                 else if (ret == EAI_SYSTEM)
1113                                         /* XXX: Not thread-safe! */
1114                                         ret = errno;
1115                                 else
1116                                         ret = EINVAL;
1117                         }
1118                         break;
1119
1120                 case PING_INFO_FAMILY:
1121                         ret = ENOMEM;
1122                         *buffer_len = sizeof (int);
1123                         if (orig_buffer_len < sizeof (int))
1124                                 break;
1125                         *((int *) buffer) = iter->addrfamily;
1126                         ret = 0;
1127                         break;
1128
1129                 case PING_INFO_LATENCY:
1130                         ret = ENOMEM;
1131                         *buffer_len = sizeof (double);
1132                         if (orig_buffer_len < sizeof (double))
1133                                 break;
1134                         *((double *) buffer) = iter->latency;
1135                         ret = 0;
1136                         break;
1137
1138                 case PING_INFO_SEQUENCE:
1139                         ret = ENOMEM;
1140                         *buffer_len = sizeof (uint16_t);
1141                         if (orig_buffer_len < sizeof (uint16_t))
1142                                 break;
1143                         *((uint16_t *) buffer) = (uint16_t) iter->sequence;
1144                         ret = 0;
1145                         break;
1146
1147                 case PING_INFO_IDENT:
1148                         ret = ENOMEM;
1149                         *buffer_len = sizeof (uint16_t);
1150                         if (orig_buffer_len < sizeof (uint16_t))
1151                                 break;
1152                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1153                         ret = 0;
1154                         break;
1155         }
1156
1157         return (ret);
1158 }
1159
1160 void *ping_iterator_get_context (pingobj_iter_t *iter)
1161 {
1162         return (iter->context);
1163 }
1164
1165 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1166 {
1167         iter->context = context;
1168 }