Provide a fallback if `ICMP6_ECHO_REQUEST' or `ICMP6_ECHO_REPLY' is not defined.
[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 #ifndef ICMP6_ECHO_REQUEST
292 # ifdef ICMP6_ECHO /* AIX netinet/ip6_icmp.h */
293 #  define ICMP6_ECHO_REQUEST ICMP6_ECHO
294 # else
295 #  define ICMP6_ECHO_REQUEST 128
296 # endif
297 #endif
298
299 #ifndef ICMP6_ECHO_REPLY
300 # ifdef ICMP6_ECHOREPLY /* AIX netinet/ip6_icmp.h */
301 #  define ICMP6_ECHO_REPLY ICMP6_ECHOREPLY
302 # else
303 #  define ICMP6_ECHO_REPLY 129
304 # endif
305 #endif
306
307 static pinghost_t *ping_receive_ipv6 (pinghost_t *ph, char *buffer, size_t buffer_len)
308 {
309         struct icmp6_hdr *icmp_hdr;
310
311         uint16_t ident;
312         uint16_t seq;
313
314         pinghost_t *ptr;
315
316         if (buffer_len < sizeof (struct icmp6_hdr))
317                 return (NULL);
318
319         icmp_hdr = (struct icmp6_hdr *) buffer;
320         buffer     += sizeof (struct icmp);
321         buffer_len -= sizeof (struct icmp);
322
323         if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
324         {
325                 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
326                 return (NULL);
327         }
328
329         if (icmp_hdr->icmp6_code != 0)
330         {
331                 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
332                 return (NULL);
333         }
334
335         ident = ntohs (icmp_hdr->icmp6_id);
336         seq   = ntohs (icmp_hdr->icmp6_seq);
337
338         for (ptr = ph; ptr != NULL; ptr = ptr->next)
339         {
340                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
341                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
342
343                 if (ptr->addrfamily != AF_INET6)
344                         continue;
345
346                 if (!timerisset (ptr->timer))
347                         continue;
348
349                 if (ptr->ident != ident)
350                         continue;
351
352                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
353                         continue;
354
355                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
356                                 ptr->hostname, ident, seq);
357
358                 break;
359         }
360
361         if (ptr == NULL)
362         {
363                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
364                                 ident, seq);
365         }
366
367         return (ptr);
368 }
369
370 static int ping_receive_one (int fd, pinghost_t *ph, struct timeval *now)
371 {
372         char   buffer[4096];
373         size_t buffer_len;
374
375         struct timeval diff;
376
377         pinghost_t *host = NULL;
378
379         struct sockaddr_storage sa;
380         socklen_t               sa_len;
381
382         sa_len = sizeof (sa);
383
384         buffer_len = recvfrom (fd, buffer, sizeof (buffer), 0,
385                         (struct sockaddr *) &sa, &sa_len);
386         if (buffer_len == -1)
387         {
388                 dprintf ("recvfrom: %s\n", strerror (errno));
389                 return (-1);
390         }
391
392         dprintf ("Read %u bytes from fd = %i\n", (unsigned int) buffer_len, fd);
393
394         if (sa.ss_family == AF_INET)
395         {
396                 if ((host = ping_receive_ipv4 (ph, buffer, buffer_len)) == NULL)
397                         return (-1);
398         }
399         else if (sa.ss_family == AF_INET6)
400         {
401                 if ((host = ping_receive_ipv6 (ph, buffer, buffer_len)) == NULL)
402                         return (-1);
403         }
404
405         dprintf ("rcvd: %12i.%06i\n",
406                         (int) now->tv_sec,
407                         (int) now->tv_usec);
408         dprintf ("sent: %12i.%06i\n",
409                         (int) host->timer->tv_sec,
410                         (int) host->timer->tv_usec);
411
412         if (ping_timeval_sub (now, host->timer, &diff) < 0)
413         {
414                 timerclear (host->timer);
415                 return (-1);
416         }
417
418         dprintf ("diff: %12i.%06i\n",
419                         (int) diff.tv_sec,
420                         (int) diff.tv_usec);
421
422         host->latency  = ((double) diff.tv_usec) / 1000.0;
423         host->latency += ((double) diff.tv_sec)  * 1000.0;
424
425         timerclear (host->timer);
426
427         return (0);
428 }
429
430 static int ping_receive_all (pingobj_t *obj)
431 {
432         fd_set readfds;
433         int num_readfds;
434         int max_readfds;
435
436         pinghost_t *ph;
437         pinghost_t *ptr;
438
439         struct timeval endtime;
440         struct timeval nowtime;
441         struct timeval timeout;
442         int status;
443
444         int ret;
445
446         ph = obj->head;
447         ret = 0;
448
449         for (ptr = ph; ptr != NULL; ptr = ptr->next)
450                 ptr->latency = -1.0;
451
452         if (gettimeofday (&nowtime, NULL) == -1)
453         {
454                 ping_set_error (obj, "gettimeofday", strerror (errno));
455                 return (-1);
456         }
457
458         /* Set up timeout */
459         timeout.tv_sec = (time_t) obj->timeout;
460         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
461
462         dprintf ("Set timeout to %i.%06i seconds\n",
463                         (int) timeout.tv_sec,
464                         (int) timeout.tv_usec);
465
466         ping_timeval_add (&nowtime, &timeout, &endtime);
467
468         while (1)
469         {
470                 FD_ZERO (&readfds);
471                 num_readfds =  0;
472                 max_readfds = -1;
473
474                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
475                 {
476                         if (!timerisset (ptr->timer))
477                                 continue;
478
479                         FD_SET (ptr->fd, &readfds);
480                         num_readfds++;
481
482                         if (max_readfds < ptr->fd)
483                                 max_readfds = ptr->fd;
484                 }
485
486                 if (num_readfds == 0)
487                         break;
488
489                 if (gettimeofday (&nowtime, NULL) == -1)
490                 {
491                         ping_set_error (obj, "gettimeofday", strerror (errno));
492                         return (-1);
493                 }
494
495                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
496                         break;
497
498                 dprintf ("Waiting on %i sockets for %i.%06i seconds\n", num_readfds,
499                                 (int) timeout.tv_sec,
500                                 (int) timeout.tv_usec);
501
502                 status = select (max_readfds + 1, &readfds, NULL, NULL, &timeout);
503
504                 if (gettimeofday (&nowtime, NULL) == -1)
505                 {
506                         ping_set_error (obj, "gettimeofday", strerror (errno));
507                         return (-1);
508                 }
509                 
510                 if ((status == -1) && (errno == EINTR))
511                 {
512                         dprintf ("select was interrupted by signal..\n");
513                         continue;
514                 }
515                 else if (status < 0)
516                 {
517                         dprintf ("select: %s\n", strerror (errno));
518                         break;
519                 }
520                 else if (status == 0)
521                 {
522                         dprintf ("select timed out\n");
523                         break;
524                 }
525
526                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
527                 {
528                         if (FD_ISSET (ptr->fd, &readfds))
529                                 if (ping_receive_one (ptr->fd, ph, &nowtime) == 0)
530                                         ret++;
531                 }
532         } /* while (1) */
533         
534         return (ret);
535 }
536
537 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
538  * Sending functions:                                                        *
539  *                                                                           *
540  * ping_send_all                                                             *
541  * +-> ping_send_one_ipv4                                                    *
542  * `-> ping_send_one_ipv6                                                    *
543  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
544 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
545                 const void *buf, size_t buflen)
546 {
547         ssize_t ret;
548
549         if (gettimeofday (ph->timer, NULL) == -1)
550         {
551                 timerclear (ph->timer);
552                 return (-1);
553         }
554
555         ret = sendto (ph->fd, buf, buflen, 0,
556                         (struct sockaddr *) ph->addr, ph->addrlen);
557
558         if (ret < 0)
559         {
560 #if defined(EHOSTUNREACH)
561                 if (errno == EHOSTUNREACH)
562                         return (0);
563 #endif
564 #if defined(ENETUNREACH)
565                 if (errno == ENETUNREACH)
566                         return (0);
567 #endif
568                 ping_set_error (obj, "sendto", strerror (errno));
569         }
570
571         return (ret);
572 }
573
574 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
575 {
576         struct icmp *icmp4;
577         int status;
578
579         char buf[4096];
580         int  buflen;
581
582         char *data;
583         int   datalen;
584
585         dprintf ("ph->hostname = %s\n", ph->hostname);
586
587         memset (buf, '\0', sizeof (buf));
588         icmp4 = (struct icmp *) buf;
589         data  = (char *) (icmp4 + 1);
590
591         icmp4->icmp_type  = ICMP_ECHO;
592         icmp4->icmp_code  = 0;
593         icmp4->icmp_cksum = 0;
594         icmp4->icmp_id    = htons (ph->ident);
595         icmp4->icmp_seq   = htons (ph->sequence);
596
597         buflen = 4096 - sizeof (struct icmp);
598         strncpy (data, ph->data, buflen);
599         datalen = strlen (data);
600
601         buflen = datalen + sizeof (struct icmp);
602
603         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
604
605         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
606
607         status = ping_sendto (obj, ph, buf, buflen);
608         if (status < 0)
609         {
610                 perror ("ping_sendto");
611                 return (-1);
612         }
613
614         dprintf ("sendto: status = %i\n", status);
615
616         return (0);
617 }
618
619 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
620 {
621         struct icmp6_hdr *icmp6;
622         int status;
623
624         char buf[4096];
625         int  buflen;
626
627         char *data;
628         int   datalen;
629
630         dprintf ("ph->hostname = %s\n", ph->hostname);
631
632         memset (buf, '\0', sizeof (buf));
633         icmp6 = (struct icmp6_hdr *) buf;
634         data  = (char *) (icmp6 + 1);
635
636         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
637         icmp6->icmp6_code  = 0;
638         /* The checksum will be calculated by the TCP/IP stack.  */
639         /* FIXME */
640         icmp6->icmp6_cksum = 0;
641         icmp6->icmp6_id    = htons (ph->ident);
642         icmp6->icmp6_seq   = htons (ph->sequence);
643
644         buflen = 4096 - sizeof (struct icmp6_hdr);
645         strncpy (data, ph->data, buflen);
646         datalen = strlen (data);
647
648         buflen = datalen + sizeof (struct icmp6_hdr);
649
650         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
651
652         status = ping_sendto (obj, ph, buf, buflen);
653         if (status < 0)
654         {
655                 perror ("ping_sendto");
656                 return (-1);
657         }
658
659         dprintf ("sendto: status = %i\n", status);
660
661         return (0);
662 }
663
664 static int ping_send_all (pingobj_t *obj)
665 {
666         pinghost_t *ph;
667         pinghost_t *ptr;
668
669         int ret;
670
671         ret = 0;
672         ph = obj->head;
673
674         for (ptr = ph; ptr != NULL; ptr = ptr->next)
675         {
676                 /* start timer.. The GNU `ping6' starts the timer before
677                  * sending the packet, so I will do that too */
678                 if (gettimeofday (ptr->timer, NULL) == -1)
679                 {
680                         dprintf ("gettimeofday: %s\n", strerror (errno));
681                         timerclear (ptr->timer);
682                         ret--;
683                         continue;
684                 }
685                 else
686                 {
687                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
688                 }
689
690                 if (ptr->addrfamily == AF_INET6)
691                 {       
692                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
693                         if (ping_send_one_ipv6 (obj, ptr) != 0)
694                         {
695                                 timerclear (ptr->timer);
696                                 ret--;
697                                 continue;
698                         }
699                 }
700                 else if (ptr->addrfamily == AF_INET)
701                 {
702                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
703                         if (ping_send_one_ipv4 (obj, ptr) != 0)
704                         {
705                                 timerclear (ptr->timer);
706                                 ret--;
707                                 continue;
708                         }
709                 }
710                 else /* this should not happen */
711                 {
712                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
713                         timerclear (ptr->timer);
714                         ret--;
715                         continue;
716                 }
717
718                 ptr->sequence++;
719         }
720
721         return (ret);
722 }
723
724 /*
725  * Set the TTL of a socket protocol independently.
726  */
727 static int ping_set_ttl (pinghost_t *ph, int ttl)
728 {
729         int ret = -2;
730
731         if (ph->addrfamily == AF_INET)
732         {
733                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL, &ttl, sizeof (ttl));
734         }
735         else if (ph->addrfamily == AF_INET6)
736         {
737                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof (ttl));
738         }
739
740         return (ret);
741 }
742
743 static int ping_get_ident (void)
744 {
745         int fd;
746         static int did_seed = 0;
747
748         int retval;
749
750         if (did_seed == 0)
751         {
752                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
753                 {
754                         unsigned int seed;
755
756                         if (read (fd, &seed, sizeof (seed)) != -1)
757                         {
758                                 did_seed = 1;
759                                 dprintf ("Random seed: %i\n", seed);
760                                 srandom (seed);
761                         }
762
763                         close (fd);
764                 }
765                 else
766                 {
767                         dprintf ("open (/dev/urandom): %s\n", strerror (errno));
768                 }
769         }
770
771         retval = (int) random ();
772
773         dprintf ("Random number: %i\n", retval);
774         
775         return (retval);
776 }
777
778 static pinghost_t *ping_alloc (void)
779 {
780         pinghost_t *ph;
781         size_t      ph_size;
782
783         ph_size = sizeof (pinghost_t)
784                 + sizeof (struct sockaddr_storage)
785                 + sizeof (struct timeval);
786
787         ph = (pinghost_t *) malloc (ph_size);
788         if (ph == NULL)
789                 return (NULL);
790
791         memset (ph, '\0', ph_size);
792
793         ph->timer   = (struct timeval *) (ph + 1);
794         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
795
796         ph->addrlen = sizeof (struct sockaddr_storage);
797         ph->fd      = -1;
798         ph->latency = -1.0;
799         ph->ident   = ping_get_ident () & 0xFFFF;
800
801         return (ph);
802 }
803
804 static void ping_free (pinghost_t *ph)
805 {
806         if (ph->fd >= 0)
807                 close (ph->fd);
808         
809         if (ph->hostname != NULL)
810                 free (ph->hostname);
811
812         if (ph->data != NULL)
813                 free (ph->data);
814
815         free (ph);
816 }
817
818 /*
819  * public methods
820  */
821 const char *ping_get_error (pingobj_t *obj)
822 {
823         return (obj->errmsg);
824 }
825
826 pingobj_t *ping_construct (void)
827 {
828         pingobj_t *obj;
829
830         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
831                 return (NULL);
832         memset (obj, '\0', sizeof (pingobj_t));
833
834         obj->timeout    = PING_DEF_TIMEOUT;
835         obj->ttl        = PING_DEF_TTL;
836         obj->addrfamily = PING_DEF_AF;
837         obj->data       = strdup (PING_DEF_DATA);
838
839         return (obj);
840 }
841
842 void ping_destroy (pingobj_t *obj)
843 {
844         pinghost_t *current;
845         pinghost_t *next;
846
847         current = obj->head;
848         next = NULL;
849
850         while (current != NULL)
851         {
852                 next = current->next;
853                 ping_free (current);
854                 current = next;
855         }
856
857         if (obj->data != NULL)
858                 free (obj->data);
859
860         if (obj->srcaddr != NULL)
861                 free (obj->srcaddr);
862
863         free (obj);
864
865         return;
866 }
867
868 int ping_setopt (pingobj_t *obj, int option, void *value)
869 {
870         int ret = 0;
871
872         switch (option)
873         {
874                 case PING_OPT_TIMEOUT:
875                         obj->timeout = *((double *) value);
876                         if (obj->timeout < 0.0)
877                         {
878                                 obj->timeout = PING_DEF_TIMEOUT;
879                                 ret = -1;
880                         }
881                         break;
882
883                 case PING_OPT_TTL:
884                         obj->ttl = *((int *) value);
885                         if ((obj->ttl < 1) || (obj->ttl > 255))
886                         {
887                                 obj->ttl = PING_DEF_TTL;
888                                 ret = -1;
889                         }
890                         break;
891
892                 case PING_OPT_AF:
893                         obj->addrfamily = *((int *) value);
894                         if ((obj->addrfamily != AF_UNSPEC)
895                                         && (obj->addrfamily != AF_INET)
896                                         && (obj->addrfamily != AF_INET6))
897                         {
898                                 obj->addrfamily = PING_DEF_AF;
899                                 ret = -1;
900                         }
901                         if (obj->srcaddr != NULL)
902                         {
903                                 free (obj->srcaddr);
904                                 obj->srcaddr = NULL;
905                         }
906                         break;
907
908                 case PING_OPT_DATA:
909                         if (obj->data != NULL)
910                         {
911                                 free (obj->data);
912                                 obj->data = NULL;
913                         }
914                         obj->data = strdup ((const char *) value);
915                         break;
916
917                 case PING_OPT_SOURCE:
918                 {
919                         char            *hostname = (char *) value;
920                         struct addrinfo  ai_hints;
921                         struct addrinfo *ai_list;
922                         int              status;
923 #if WITH_DEBUG
924                         if (obj->addrfamily != AF_UNSPEC)
925                         {
926                                 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
927                         }
928 #endif
929                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
930                         ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
931 #if defined(AI_ADDRCONFIG)
932                         ai_hints.ai_flags = AI_ADDRCONFIG;
933 #endif
934                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
935                         if (status != 0)
936                         {
937                                 ping_set_error (obj, "getaddrinfo",
938                                                 status == EAI_SYSTEM
939                                                 ? strerror (errno)
940                                                 : gai_strerror (status));
941                                 ret = -1;
942                                 break;
943                         }
944 #if WITH_DEBUG
945                         if (ai_list->ai_next != NULL)
946                         {
947                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
948                         }
949 #endif
950                         if (obj->srcaddr == NULL)
951                         {
952                                 obj->srcaddrlen = 0;
953                                 obj->srcaddr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage));
954                                 if (obj->srcaddr == NULL)
955                                 {
956                                         ping_set_error (obj, "malloc",
957                                                         strerror (errno));
958                                         ret = -1;
959                                         freeaddrinfo (ai_list);
960                                         break;
961                                 }
962                         }
963                         memset ((void *) obj->srcaddr, '\0', sizeof (struct sockaddr_storage));
964                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
965                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
966                                         ai_list->ai_addrlen);
967                         obj->srcaddrlen = ai_list->ai_addrlen;
968                         obj->addrfamily = ai_list->ai_family;
969
970                         freeaddrinfo (ai_list);
971                 } /* case PING_OPT_SOURCE */
972                 break;
973
974                 default:
975                         ret = -2;
976         } /* switch (option) */
977
978         return (ret);
979 } /* int ping_setopt */
980
981
982 int ping_send (pingobj_t *obj)
983 {
984         int ret;
985
986         if (ping_send_all (obj) < 0)
987                 return (-1);
988
989         if ((ret = ping_receive_all (obj)) < 0)
990                 return (-2);
991
992         return (ret);
993 }
994
995 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
996 {
997         while (ph != NULL)
998         {
999                 if (strcasecmp (ph->hostname, host) == 0)
1000                         break;
1001
1002                 ph = ph->next;
1003         }
1004
1005         return (ph);
1006 }
1007
1008 int ping_host_add (pingobj_t *obj, const char *host)
1009 {
1010         pinghost_t *ph;
1011
1012         struct sockaddr_storage sockaddr;
1013         socklen_t               sockaddr_len;
1014
1015         struct addrinfo  ai_hints;
1016         struct addrinfo *ai_list, *ai_ptr;
1017         int              ai_return;
1018
1019         dprintf ("host = %s\n", host);
1020
1021         if (ping_host_search (obj->head, host) != NULL)
1022                 return (0);
1023
1024         memset (&ai_hints, '\0', sizeof (ai_hints));
1025         ai_hints.ai_flags     = 0;
1026 #ifdef AI_ADDRCONFIG
1027         ai_hints.ai_flags    |= AI_ADDRCONFIG;
1028 #endif
1029 #ifdef AI_CANONNAME
1030         ai_hints.ai_flags    |= AI_CANONNAME;
1031 #endif
1032         ai_hints.ai_family    = obj->addrfamily;
1033         ai_hints.ai_socktype  = SOCK_RAW;
1034
1035         if ((ph = ping_alloc ()) == NULL)
1036         {
1037                 dprintf ("Out of memory!\n");
1038                 return (-1);
1039         }
1040
1041         if ((ph->hostname = strdup (host)) == NULL)
1042         {
1043                 dprintf ("Out of memory!\n");
1044                 ping_set_error (obj, "strdup", strerror (errno));
1045                 ping_free (ph);
1046                 return (-1);
1047         }
1048
1049         /* obj->data is not garuanteed to be != NULL */
1050         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1051         {
1052                 dprintf ("Out of memory!\n");
1053                 ping_set_error (obj, "strdup", strerror (errno));
1054                 ping_free (ph);
1055                 return (-1);
1056         }
1057
1058         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1059         {
1060                 dprintf ("getaddrinfo failed\n");
1061                 ping_set_error (obj, "getaddrinfo",
1062                                 (ai_return == EAI_SYSTEM)
1063                                 ? strerror (errno)
1064                                 : gai_strerror (ai_return));
1065                 ping_free (ph);
1066                 return (-1);
1067         }
1068
1069         if (ai_list == NULL)
1070                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1071
1072         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1073         {
1074                 ph->fd = -1;
1075
1076                 sockaddr_len = sizeof (sockaddr);
1077                 memset (&sockaddr, '\0', sockaddr_len);
1078
1079                 if (ai_ptr->ai_family == AF_INET)
1080                 {
1081                         struct sockaddr_in *si;
1082
1083                         si = (struct sockaddr_in *) &sockaddr;
1084                         si->sin_family = AF_INET;
1085                         si->sin_port   = htons (ph->ident);
1086                         si->sin_addr.s_addr = htonl (INADDR_ANY);
1087
1088                         ai_ptr->ai_socktype = SOCK_RAW;
1089                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1090                 }
1091                 else if (ai_ptr->ai_family == AF_INET6)
1092                 {
1093                         struct sockaddr_in6 *si;
1094
1095                         si = (struct sockaddr_in6 *) &sockaddr;
1096                         si->sin6_family = AF_INET6;
1097                         si->sin6_port   = htons (ph->ident);
1098                         si->sin6_addr   = in6addr_any;
1099
1100                         ai_ptr->ai_socktype = SOCK_RAW;
1101                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1102                 }
1103                 else
1104                 {
1105                         char errmsg[PING_ERRMSG_LEN];
1106
1107                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1108                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1109
1110                         dprintf (errmsg);
1111                         ping_set_error (obj, "getaddrinfo", errmsg);
1112                         continue;
1113                 }
1114
1115                 /* TODO: Move this to a static function `ping_open_socket' and
1116                  * call it whenever the socket dies. */
1117                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1118                 if (ph->fd == -1)
1119                 {
1120                         dprintf ("socket: %s\n", strerror (errno));
1121                         ping_set_error (obj, "socket", strerror (errno));
1122                         continue;
1123                 }
1124
1125                 if (obj->srcaddr != NULL)
1126                 {
1127                         assert (obj->srcaddrlen > 0);
1128                         assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1129
1130                         if (bind (ph->fd, (struct sockaddr *) obj->srcaddr, obj->srcaddrlen) == -1)
1131                         {
1132                                 dprintf ("bind: %s\n", strerror (errno));
1133                                 ping_set_error (obj, "bind", strerror (errno));
1134                                 close (ph->fd);
1135                                 ph->fd = -1;
1136                                 continue;
1137                         }
1138                 }
1139
1140                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1141                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1142                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1143                 ph->addrlen = ai_ptr->ai_addrlen;
1144                 ph->addrfamily = ai_ptr->ai_family;
1145
1146 #ifdef AI_CANONNAME
1147                 if ((ai_ptr->ai_canonname != NULL)
1148                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1149                 {
1150                         char *old_hostname;
1151
1152                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1153                                         ph->hostname, ai_ptr->ai_canonname);
1154
1155                         old_hostname = ph->hostname;
1156                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1157                         {
1158                                 /* strdup failed, falling back to old hostname */
1159                                 ph->hostname = old_hostname;
1160                         }
1161                         else if (old_hostname != NULL)
1162                         {
1163                                 free (old_hostname);
1164                         }
1165                 }
1166 #endif /* AI_CANONNAME */
1167
1168                 break;
1169         }
1170
1171         freeaddrinfo (ai_list);
1172
1173         if (ph->fd < 0)
1174         {
1175                 ping_free (ph);
1176                 return (-1);
1177         }
1178
1179         /*
1180          * Adding in the front is much easier, but then the iterator will
1181          * return the host that was added last as first host. That's just not
1182          * nice. -octo
1183          */
1184         if (obj->head == NULL)
1185         {
1186                 obj->head = ph;
1187         }
1188         else
1189         {
1190                 pinghost_t *hptr;
1191
1192                 hptr = obj->head;
1193                 while (hptr->next != NULL)
1194                         hptr = hptr->next;
1195
1196                 assert ((hptr != NULL) && (hptr->next == NULL));
1197                 hptr->next = ph;
1198         }
1199
1200         ping_set_ttl (ph, obj->ttl);
1201
1202         return (0);
1203 }
1204
1205 int ping_host_remove (pingobj_t *obj, const char *host)
1206 {
1207         pinghost_t *pre, *cur;
1208
1209         pre = NULL;
1210         cur = obj->head;
1211
1212         while (cur != NULL)
1213         {
1214                 if (strcasecmp (host, cur->hostname) == 0)
1215                         break;
1216
1217                 pre = cur;
1218                 cur = cur->next;
1219         }
1220
1221         if (cur == NULL)
1222         {
1223                 ping_set_error (obj, "ping_host_remove", "Host not found");
1224                 return (-1);
1225         }
1226
1227         if (pre == NULL)
1228                 obj->head = cur->next;
1229         else
1230                 pre->next = cur->next;
1231         
1232         ping_free (cur);
1233
1234         return (0);
1235 }
1236
1237 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1238 {
1239         return ((pingobj_iter_t *) obj->head);
1240 }
1241
1242 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1243 {
1244         return ((pingobj_iter_t *) iter->next);
1245 }
1246
1247 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1248                 void *buffer, size_t *buffer_len)
1249 {
1250         int ret = EINVAL;
1251
1252         size_t orig_buffer_len = *buffer_len;
1253
1254         switch (info)
1255         {
1256                 case PING_INFO_HOSTNAME:
1257                         ret = ENOMEM;
1258                         *buffer_len = strlen (iter->hostname);
1259                         if (orig_buffer_len <= *buffer_len)
1260                                 break;
1261                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1262                          * will copy `*buffer_len' and pad the rest of
1263                          * `buffer' with null-bytes */
1264                         strncpy (buffer, iter->hostname, orig_buffer_len);
1265                         ret = 0;
1266                         break;
1267
1268                 case PING_INFO_ADDRESS:
1269                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1270                                         iter->addrlen,
1271                                         (char *) buffer,
1272                                         *buffer_len,
1273                                         NULL, 0,
1274                                         NI_NUMERICHOST);
1275                         if (ret != 0)
1276                         {
1277                                 if ((ret == EAI_MEMORY)
1278 #ifdef EAI_OVERFLOW
1279                                                 || (ret == EAI_OVERFLOW)
1280 #endif
1281                                    )
1282                                         ret = ENOMEM;
1283                                 else if (ret == EAI_SYSTEM)
1284                                         /* XXX: Not thread-safe! */
1285                                         ret = errno;
1286                                 else
1287                                         ret = EINVAL;
1288                         }
1289                         break;
1290
1291                 case PING_INFO_FAMILY:
1292                         ret = ENOMEM;
1293                         *buffer_len = sizeof (int);
1294                         if (orig_buffer_len < sizeof (int))
1295                                 break;
1296                         *((int *) buffer) = iter->addrfamily;
1297                         ret = 0;
1298                         break;
1299
1300                 case PING_INFO_LATENCY:
1301                         ret = ENOMEM;
1302                         *buffer_len = sizeof (double);
1303                         if (orig_buffer_len < sizeof (double))
1304                                 break;
1305                         *((double *) buffer) = iter->latency;
1306                         ret = 0;
1307                         break;
1308
1309                 case PING_INFO_SEQUENCE:
1310                         ret = ENOMEM;
1311                         *buffer_len = sizeof (unsigned int);
1312                         if (orig_buffer_len < sizeof (unsigned int))
1313                                 break;
1314                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1315                         ret = 0;
1316                         break;
1317
1318                 case PING_INFO_IDENT:
1319                         ret = ENOMEM;
1320                         *buffer_len = sizeof (uint16_t);
1321                         if (orig_buffer_len < sizeof (uint16_t))
1322                                 break;
1323                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1324                         ret = 0;
1325                         break;
1326
1327                 case PING_INFO_DATA:
1328                         ret = ENOMEM;
1329                         *buffer_len = strlen (iter->data);
1330                         if (orig_buffer_len < *buffer_len)
1331                                 break;
1332                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1333                         ret = 0;
1334                         break;
1335         }
1336
1337         return (ret);
1338 }
1339
1340 void *ping_iterator_get_context (pingobj_iter_t *iter)
1341 {
1342         return (iter->context);
1343 }
1344
1345 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1346 {
1347         iter->context = context;
1348 }