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