Close the filedescriptor in `ping_free', not `ping_host_remove'.
[liboping.git] / src / liboping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006  Florian octo Forster <octo at verplant.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; only version 2 of the License is
8  * applicable.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #if STDC_HEADERS
25 # include <stdlib.h>
26 # include <stdio.h>
27 # include <string.h>
28 # include <errno.h>
29 # include <assert.h>
30 #else
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
33
34 #if HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #if HAVE_FCNTL_H
39 # include <fcntl.h>
40 #endif
41 #if HAVE_SYS_TYPES_H
42 # include <sys/types.h>
43 #endif
44 #if HAVE_SYS_STAT_H
45 # include <sys/stat.h>
46 #endif
47
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
50 # include <time.h>
51 #else
52 # if HAVE_SYS_TIME_H
53 #  include <sys/time.h>
54 # else
55 #  include <time.h>
56 # endif
57 #endif
58
59 #if HAVE_SYS_SOCKET_H
60 # include <sys/socket.h>
61 #endif
62 #if HAVE_NETDB_H
63 # include <netdb.h>
64 #endif
65
66 #if HAVE_NETINET_IN_SYSTM_H
67 # include <netinet/in_systm.h>
68 #endif
69 #if HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #if HAVE_NETINET_IP_H
73 # include <netinet/ip.h>
74 #endif
75 #if HAVE_NETINET_IP_ICMP_H
76 # include <netinet/ip_icmp.h>
77 #endif
78 #ifdef HAVE_NETINET_IP_VAR_H
79 # include <netinet/ip_var.h>
80 #endif
81 #if HAVE_NETINET_IP6_H
82 # include <netinet/ip6.h>
83 #endif
84 #if HAVE_NETINET_ICMP6_H
85 # include <netinet/icmp6.h>
86 #endif
87
88 #include "oping.h"
89
90 #if WITH_DEBUG
91 # define dprintf(...) printf ("%s[%4i]: %-20s: ", __FILE__, __LINE__, __FUNCTION__); printf (__VA_ARGS__)
92 #else
93 # define dprintf(...) /**/
94 #endif
95
96 #define PING_ERRMSG_LEN 256
97
98 struct pinghost
99 {
100         char                    *hostname;
101         struct sockaddr_storage *addr;
102         socklen_t                addrlen;
103         int                      addrfamily;
104         int                      fd;
105         int                      ident;
106         int                      sequence;
107         struct timeval          *timer;
108         double                   latency;
109         char                    *data;
110
111         void                    *context;
112
113         struct pinghost         *next;
114 };
115
116 struct pingobj
117 {
118         double                   timeout;
119         int                      ttl;
120         int                      addrfamily;
121         char                    *data;
122
123         struct sockaddr_storage *srcaddr;
124         socklen_t                srcaddrlen;
125
126         char                     errmsg[PING_ERRMSG_LEN];
127
128         pinghost_t              *head;
129 };
130
131 /*
132  * private (static) functions
133  */
134 static void ping_set_error (pingobj_t *obj, const char *function,
135                 const char *message)
136 {
137         snprintf (obj->errmsg, PING_ERRMSG_LEN, "%s: %s", function, message);
138         obj->errmsg[PING_ERRMSG_LEN - 1] = '\0';
139 }
140
141 static int ping_timeval_add (struct timeval *tv1, struct timeval *tv2,
142                 struct timeval *res)
143 {
144         res->tv_sec  = tv1->tv_sec  + tv2->tv_sec;
145         res->tv_usec = tv1->tv_usec + tv2->tv_usec;
146
147         while (res->tv_usec > 1000000)
148         {
149                 res->tv_usec -= 1000000;
150                 res->tv_sec++;
151         }
152
153         return (0);
154 }
155
156 static int ping_timeval_sub (struct timeval *tv1, struct timeval *tv2,
157                 struct timeval *res)
158 {
159
160         if ((tv1->tv_sec < tv2->tv_sec)
161                         || ((tv1->tv_sec == tv2->tv_sec)
162                                 && (tv1->tv_usec < tv2->tv_usec)))
163                 return (-1);
164
165         res->tv_sec  = tv1->tv_sec  - tv2->tv_sec;
166         res->tv_usec = tv1->tv_usec - tv2->tv_usec;
167
168         assert ((res->tv_sec > 0) || ((res->tv_sec == 0) && (res->tv_usec > 0)));
169
170         while (res->tv_usec < 0)
171         {
172                 res->tv_usec += 1000000;
173                 res->tv_sec--;
174         }
175
176         return (0);
177 }
178
179 static uint16_t ping_icmp4_checksum (char *buf, size_t len)
180 {
181         uint32_t sum = 0;
182         uint16_t ret = 0;
183
184         uint16_t *ptr;
185
186         for (ptr = (uint16_t *) buf; len > 1; ptr++, len -= 2)
187                 sum += *ptr;
188
189         if (len == 1)
190         {
191                 *(char *) &ret = *(char *) ptr;
192                 sum += ret;
193         }
194
195         /* Do this twice to get all possible carries.. */
196         sum = (sum >> 16) + (sum & 0xFFFF);
197         sum = (sum >> 16) + (sum & 0xFFFF);
198
199         ret = ~sum;
200
201         return (ret);
202 }
203
204 static pinghost_t *ping_receive_ipv4 (pinghost_t *ph, char *buffer, size_t buffer_len)
205 {
206         struct ip *ip_hdr;
207         struct icmp *icmp_hdr;
208
209         size_t ip_hdr_len;
210
211         uint16_t recv_checksum;
212         uint16_t calc_checksum;
213
214         uint16_t ident;
215         uint16_t seq;
216
217         pinghost_t *ptr;
218
219         if (buffer_len < sizeof (struct ip))
220                 return (NULL);
221
222         ip_hdr     = (struct ip *) buffer;
223         ip_hdr_len = ip_hdr->ip_hl << 2;
224
225         if (buffer_len < ip_hdr_len)
226                 return (NULL);
227
228         buffer     += ip_hdr_len;
229         buffer_len -= ip_hdr_len;
230
231         if (buffer_len < sizeof (struct icmp))
232                 return (NULL);
233
234         icmp_hdr = (struct icmp *) buffer;
235         buffer     += sizeof (struct icmp);
236         buffer_len -= sizeof (struct icmp);
237
238         if (icmp_hdr->icmp_type != ICMP_ECHOREPLY)
239         {
240                 dprintf ("Unexpected ICMP type: %i\n", icmp_hdr->icmp_type);
241                 return (NULL);
242         }
243
244         recv_checksum = icmp_hdr->icmp_cksum;
245         icmp_hdr->icmp_cksum = 0;
246         calc_checksum = ping_icmp4_checksum ((char *) icmp_hdr,
247                         sizeof (struct icmp) + buffer_len);
248
249         if (recv_checksum != calc_checksum)
250         {
251                 dprintf ("Checksum missmatch: Got 0x%04x, calculated 0x%04x\n",
252                                 recv_checksum, calc_checksum);
253                 return (NULL);
254         }
255
256         ident = ntohs (icmp_hdr->icmp_id);
257         seq   = ntohs (icmp_hdr->icmp_seq);
258
259         for (ptr = ph; ptr != NULL; ptr = ptr->next)
260         {
261                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
262                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
263
264                 if (ptr->addrfamily != AF_INET)
265                         continue;
266
267                 if (!timerisset (ptr->timer))
268                         continue;
269
270                 if (ptr->ident != ident)
271                         continue;
272
273                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
274                         continue;
275
276                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
277                                 ptr->hostname, ident, seq);
278
279                 break;
280         }
281
282         if (ptr == NULL)
283         {
284                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
285                                 ident, seq);
286         }
287
288         return (ptr);
289 }
290
291 static pinghost_t *ping_receive_ipv6 (pinghost_t *ph, char *buffer, size_t buffer_len)
292 {
293         struct icmp6_hdr *icmp_hdr;
294
295         uint16_t ident;
296         uint16_t seq;
297
298         pinghost_t *ptr;
299
300         if (buffer_len < sizeof (struct icmp6_hdr))
301                 return (NULL);
302
303         icmp_hdr = (struct icmp6_hdr *) buffer;
304         buffer     += sizeof (struct icmp);
305         buffer_len -= sizeof (struct icmp);
306
307         if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
308         {
309                 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
310                 return (NULL);
311         }
312
313         if (icmp_hdr->icmp6_code != 0)
314         {
315                 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
316                 return (NULL);
317         }
318
319         ident = ntohs (icmp_hdr->icmp6_id);
320         seq   = ntohs (icmp_hdr->icmp6_seq);
321
322         for (ptr = ph; ptr != NULL; ptr = ptr->next)
323         {
324                 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
325                                 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
326
327                 if (ptr->addrfamily != AF_INET6)
328                         continue;
329
330                 if (!timerisset (ptr->timer))
331                         continue;
332
333                 if (ptr->ident != ident)
334                         continue;
335
336                 if (((ptr->sequence - 1) & 0xFFFF) != seq)
337                         continue;
338
339                 dprintf ("Match found: hostname = %s, ident = 0x%04x, seq = %i\n",
340                                 ptr->hostname, ident, seq);
341
342                 break;
343         }
344
345         if (ptr == NULL)
346         {
347                 dprintf ("No match found for ident = 0x%04x, seq = %i\n",
348                                 ident, seq);
349         }
350
351         return (ptr);
352 }
353
354 static int ping_receive_one (int fd, pinghost_t *ph, struct timeval *now)
355 {
356         char   buffer[4096];
357         size_t buffer_len;
358
359         struct timeval diff;
360
361         pinghost_t *host = NULL;
362
363         struct sockaddr_storage sa;
364         socklen_t               sa_len;
365
366         sa_len = sizeof (sa);
367
368         buffer_len = recvfrom (fd, buffer, sizeof (buffer), 0,
369                         (struct sockaddr *) &sa, &sa_len);
370         if (buffer_len == -1)
371         {
372                 dprintf ("recvfrom: %s\n", strerror (errno));
373                 return (-1);
374         }
375
376         dprintf ("Read %u bytes from fd = %i\n", (unsigned int) buffer_len, fd);
377
378         if (sa.ss_family == AF_INET)
379         {
380                 if ((host = ping_receive_ipv4 (ph, buffer, buffer_len)) == NULL)
381                         return (-1);
382         }
383         else if (sa.ss_family == AF_INET6)
384         {
385                 if ((host = ping_receive_ipv6 (ph, buffer, buffer_len)) == NULL)
386                         return (-1);
387         }
388
389         dprintf ("rcvd: %12i.%06i\n",
390                         (int) now->tv_sec,
391                         (int) now->tv_usec);
392         dprintf ("sent: %12i.%06i\n",
393                         (int) host->timer->tv_sec,
394                         (int) host->timer->tv_usec);
395
396         if (ping_timeval_sub (now, host->timer, &diff) < 0)
397         {
398                 timerclear (host->timer);
399                 return (-1);
400         }
401
402         dprintf ("diff: %12i.%06i\n",
403                         (int) diff.tv_sec,
404                         (int) diff.tv_usec);
405
406         host->latency  = ((double) diff.tv_usec) / 1000.0;
407         host->latency += ((double) diff.tv_sec)  * 1000.0;
408
409         timerclear (host->timer);
410
411         return (0);
412 }
413
414 static int ping_receive_all (pingobj_t *obj)
415 {
416         fd_set readfds;
417         int num_readfds;
418         int max_readfds;
419
420         pinghost_t *ph;
421         pinghost_t *ptr;
422
423         struct timeval endtime;
424         struct timeval nowtime;
425         struct timeval timeout;
426         int status;
427
428         int ret;
429
430         ph = obj->head;
431         ret = 0;
432
433         for (ptr = ph; ptr != NULL; ptr = ptr->next)
434                 ptr->latency = -1.0;
435
436         if (gettimeofday (&nowtime, NULL) == -1)
437         {
438                 ping_set_error (obj, "gettimeofday", strerror (errno));
439                 return (-1);
440         }
441
442         /* Set up timeout */
443         timeout.tv_sec = (time_t) obj->timeout;
444         timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
445
446         dprintf ("Set timeout to %i.%06i seconds\n",
447                         (int) timeout.tv_sec,
448                         (int) timeout.tv_usec);
449
450         ping_timeval_add (&nowtime, &timeout, &endtime);
451
452         while (1)
453         {
454                 FD_ZERO (&readfds);
455                 num_readfds =  0;
456                 max_readfds = -1;
457
458                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
459                 {
460                         if (!timerisset (ptr->timer))
461                                 continue;
462
463                         FD_SET (ptr->fd, &readfds);
464                         num_readfds++;
465
466                         if (max_readfds < ptr->fd)
467                                 max_readfds = ptr->fd;
468                 }
469
470                 if (num_readfds == 0)
471                         break;
472
473                 if (gettimeofday (&nowtime, NULL) == -1)
474                 {
475                         ping_set_error (obj, "gettimeofday", strerror (errno));
476                         return (-1);
477                 }
478
479                 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
480                         break;
481
482                 dprintf ("Waiting on %i sockets for %i.%06i seconds\n", num_readfds,
483                                 (int) timeout.tv_sec,
484                                 (int) timeout.tv_usec);
485
486                 status = select (max_readfds + 1, &readfds, NULL, NULL, &timeout);
487
488                 if (gettimeofday (&nowtime, NULL) == -1)
489                 {
490                         ping_set_error (obj, "gettimeofday", strerror (errno));
491                         return (-1);
492                 }
493                 
494                 if ((status == -1) && (errno == EINTR))
495                 {
496                         dprintf ("select was interrupted by signal..\n");
497                         continue;
498                 }
499                 else if (status < 0)
500                 {
501                         dprintf ("select: %s\n", strerror (errno));
502                         break;
503                 }
504                 else if (status == 0)
505                 {
506                         dprintf ("select timed out\n");
507                         break;
508                 }
509
510                 for (ptr = ph; ptr != NULL; ptr = ptr->next)
511                 {
512                         if (FD_ISSET (ptr->fd, &readfds))
513                                 if (ping_receive_one (ptr->fd, ph, &nowtime) == 0)
514                                         ret++;
515                 }
516         } /* while (1) */
517         
518         return (ret);
519 }
520
521 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
522  * Sending functions:                                                        *
523  *                                                                           *
524  * ping_send_all                                                             *
525  * +-> ping_send_one_ipv4                                                    *
526  * `-> ping_send_one_ipv6                                                    *
527  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
528 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
529                 const void *buf, size_t buflen)
530 {
531         ssize_t ret;
532
533         if (gettimeofday (ph->timer, NULL) == -1)
534         {
535                 timerclear (ph->timer);
536                 return (-1);
537         }
538
539         ret = sendto (ph->fd, buf, buflen, 0,
540                         (struct sockaddr *) ph->addr, ph->addrlen);
541
542         if (ret < 0)
543         {
544 #if defined(EHOSTUNREACH)
545                 if (errno == EHOSTUNREACH)
546                         return (0);
547 #endif
548 #if defined(ENETUNREACH)
549                 if (errno == ENETUNREACH)
550                         return (0);
551 #endif
552                 ping_set_error (obj, "sendto", strerror (errno));
553         }
554
555         return (ret);
556 }
557
558 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph)
559 {
560         struct icmp *icmp4;
561         int status;
562
563         char buf[4096];
564         int  buflen;
565
566         char *data;
567         int   datalen;
568
569         dprintf ("ph->hostname = %s\n", ph->hostname);
570
571         memset (buf, '\0', sizeof (buf));
572         icmp4 = (struct icmp *) buf;
573         data  = (char *) (icmp4 + 1);
574
575         icmp4->icmp_type  = ICMP_ECHO;
576         icmp4->icmp_code  = 0;
577         icmp4->icmp_cksum = 0;
578         icmp4->icmp_id    = htons (ph->ident);
579         icmp4->icmp_seq   = htons (ph->sequence);
580
581         buflen = 4096 - sizeof (struct icmp);
582         strncpy (data, ph->data, buflen);
583         datalen = strlen (data);
584
585         buflen = datalen + sizeof (struct icmp);
586
587         icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
588
589         dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
590
591         status = ping_sendto (obj, ph, buf, buflen);
592         if (status < 0)
593         {
594                 perror ("ping_sendto");
595                 return (-1);
596         }
597
598         dprintf ("sendto: status = %i\n", status);
599
600         return (0);
601 }
602
603 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph)
604 {
605         struct icmp6_hdr *icmp6;
606         int status;
607
608         char buf[4096];
609         int  buflen;
610
611         char *data;
612         int   datalen;
613
614         dprintf ("ph->hostname = %s\n", ph->hostname);
615
616         memset (buf, '\0', sizeof (buf));
617         icmp6 = (struct icmp6_hdr *) buf;
618         data  = (char *) (icmp6 + 1);
619
620         icmp6->icmp6_type  = ICMP6_ECHO_REQUEST;
621         icmp6->icmp6_code  = 0;
622         /* The checksum will be calculated by the TCP/IP stack.  */
623         /* FIXME */
624         icmp6->icmp6_cksum = 0;
625         icmp6->icmp6_id    = htons (ph->ident);
626         icmp6->icmp6_seq   = htons (ph->sequence);
627
628         buflen = 4096 - sizeof (struct icmp6_hdr);
629         strncpy (data, ph->data, buflen);
630         datalen = strlen (data);
631
632         buflen = datalen + sizeof (struct icmp6_hdr);
633
634         dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
635
636         status = ping_sendto (obj, ph, buf, buflen);
637         if (status < 0)
638         {
639                 perror ("ping_sendto");
640                 return (-1);
641         }
642
643         dprintf ("sendto: status = %i\n", status);
644
645         return (0);
646 }
647
648 static int ping_send_all (pingobj_t *obj)
649 {
650         pinghost_t *ph;
651         pinghost_t *ptr;
652
653         int ret;
654
655         ret = 0;
656         ph = obj->head;
657
658         for (ptr = ph; ptr != NULL; ptr = ptr->next)
659         {
660                 /* start timer.. The GNU `ping6' starts the timer before
661                  * sending the packet, so I will do that too */
662                 if (gettimeofday (ptr->timer, NULL) == -1)
663                 {
664                         dprintf ("gettimeofday: %s\n", strerror (errno));
665                         timerclear (ptr->timer);
666                         ret--;
667                         continue;
668                 }
669                 else
670                 {
671                         dprintf ("timer set for hostname = %s\n", ptr->hostname);
672                 }
673
674                 if (ptr->addrfamily == AF_INET6)
675                 {       
676                         dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
677                         if (ping_send_one_ipv6 (obj, ptr) != 0)
678                         {
679                                 timerclear (ptr->timer);
680                                 ret--;
681                                 continue;
682                         }
683                 }
684                 else if (ptr->addrfamily == AF_INET)
685                 {
686                         dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
687                         if (ping_send_one_ipv4 (obj, ptr) != 0)
688                         {
689                                 timerclear (ptr->timer);
690                                 ret--;
691                                 continue;
692                         }
693                 }
694                 else /* this should not happen */
695                 {
696                         dprintf ("Unknown address family: %i\n", ptr->addrfamily);
697                         timerclear (ptr->timer);
698                         ret--;
699                         continue;
700                 }
701
702                 ptr->sequence++;
703         }
704
705         return (ret);
706 }
707
708 /*
709  * Set the TTL of a socket protocol independently.
710  */
711 static int ping_set_ttl (pinghost_t *ph, int ttl)
712 {
713         int ret = -2;
714
715         if (ph->addrfamily == AF_INET)
716         {
717                 ret = setsockopt (ph->fd, IPPROTO_IP, IP_TTL, &ttl, sizeof (ttl));
718         }
719         else if (ph->addrfamily == AF_INET6)
720         {
721                 ret = setsockopt (ph->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof (ttl));
722         }
723
724         return (ret);
725 }
726
727 static int ping_get_ident (void)
728 {
729         int fd;
730         static int did_seed = 0;
731
732         int retval;
733
734         if (did_seed == 0)
735         {
736                 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
737                 {
738                         unsigned int seed;
739
740                         if (read (fd, &seed, sizeof (seed)) != -1)
741                         {
742                                 did_seed = 1;
743                                 dprintf ("Random seed: %i\n", seed);
744                                 srandom (seed);
745                         }
746
747                         close (fd);
748                 }
749                 else
750                 {
751                         dprintf ("open (/dev/urandom): %s\n", strerror (errno));
752                 }
753         }
754
755         retval = (int) random ();
756
757         dprintf ("Random number: %i\n", retval);
758         
759         return (retval);
760 }
761
762 static pinghost_t *ping_alloc (void)
763 {
764         pinghost_t *ph;
765         size_t      ph_size;
766
767         ph_size = sizeof (pinghost_t)
768                 + sizeof (struct sockaddr_storage)
769                 + sizeof (struct timeval);
770
771         ph = (pinghost_t *) malloc (ph_size);
772         if (ph == NULL)
773                 return (NULL);
774
775         memset (ph, '\0', ph_size);
776
777         ph->timer   = (struct timeval *) (ph + 1);
778         ph->addr    = (struct sockaddr_storage *) (ph->timer + 1);
779
780         ph->addrlen = sizeof (struct sockaddr_storage);
781         ph->fd      = -1;
782         ph->latency = -1.0;
783         ph->ident   = ping_get_ident () & 0xFFFF;
784
785         return (ph);
786 }
787
788 static void ping_free (pinghost_t *ph)
789 {
790         if (ph->fd >= 0)
791                 close (ph->fd);
792         
793         if (ph->hostname != NULL)
794                 free (ph->hostname);
795
796         if (ph->data != NULL)
797                 free (ph->data);
798
799         free (ph);
800 }
801
802 /*
803  * public methods
804  */
805 const char *ping_get_error (pingobj_t *obj)
806 {
807         return (obj->errmsg);
808 }
809
810 pingobj_t *ping_construct (void)
811 {
812         pingobj_t *obj;
813
814         if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
815                 return (NULL);
816         memset (obj, '\0', sizeof (pingobj_t));
817
818         obj->timeout    = PING_DEF_TIMEOUT;
819         obj->ttl        = PING_DEF_TTL;
820         obj->addrfamily = PING_DEF_AF;
821         obj->data       = strdup (PING_DEF_DATA);
822
823         return (obj);
824 }
825
826 void ping_destroy (pingobj_t *obj)
827 {
828         pinghost_t *current;
829         pinghost_t *next;
830
831         current = obj->head;
832         next = NULL;
833
834         while (current != NULL)
835         {
836                 next = current->next;
837                 ping_free (current);
838                 current = next;
839         }
840
841         if (obj->data != NULL)
842                 free (obj->data);
843
844         if (obj->srcaddr != NULL)
845                 free (obj->srcaddr);
846
847         free (obj);
848
849         return;
850 }
851
852 int ping_setopt (pingobj_t *obj, int option, void *value)
853 {
854         int ret = 0;
855
856         switch (option)
857         {
858                 case PING_OPT_TIMEOUT:
859                         obj->timeout = *((double *) value);
860                         if (obj->timeout < 0.0)
861                         {
862                                 obj->timeout = PING_DEF_TIMEOUT;
863                                 ret = -1;
864                         }
865                         break;
866
867                 case PING_OPT_TTL:
868                         obj->ttl = *((int *) value);
869                         if ((obj->ttl < 1) || (obj->ttl > 255))
870                         {
871                                 obj->ttl = PING_DEF_TTL;
872                                 ret = -1;
873                         }
874                         break;
875
876                 case PING_OPT_AF:
877                         obj->addrfamily = *((int *) value);
878                         if ((obj->addrfamily != AF_UNSPEC)
879                                         && (obj->addrfamily != AF_INET)
880                                         && (obj->addrfamily != AF_INET6))
881                         {
882                                 obj->addrfamily = PING_DEF_AF;
883                                 ret = -1;
884                         }
885                         if (obj->srcaddr != NULL)
886                         {
887                                 free (obj->srcaddr);
888                                 obj->srcaddr = NULL;
889                         }
890                         break;
891
892                 case PING_OPT_DATA:
893                         if (obj->data != NULL)
894                         {
895                                 free (obj->data);
896                                 obj->data = NULL;
897                         }
898                         obj->data = strdup ((const char *) value);
899                         break;
900
901                 case PING_OPT_SOURCE:
902                 {
903                         char            *hostname = (char *) value;
904                         struct addrinfo  ai_hints;
905                         struct addrinfo *ai_list;
906                         int              status;
907 #if WITH_DEBUG
908                         if (obj->addrfamily != AF_UNSPEC)
909                         {
910                                 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
911                         }
912 #endif
913                         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
914                         ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
915 #if defined(AI_ADDRCONFIG)
916                         ai_hints.ai_flags = AI_ADDRCONFIG;
917 #endif
918                         status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
919                         if (status != 0)
920                         {
921                                 ping_set_error (obj, "getaddrinfo",
922                                                 status == EAI_SYSTEM
923                                                 ? strerror (errno)
924                                                 : gai_strerror (status));
925                                 ret = -1;
926                                 break;
927                         }
928 #if WITH_DEBUG
929                         if (ai_list->ai_next != NULL)
930                         {
931                                 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
932                         }
933 #endif
934                         if (obj->srcaddr == NULL)
935                         {
936                                 obj->srcaddrlen = 0;
937                                 obj->srcaddr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage));
938                                 if (obj->srcaddr == NULL)
939                                 {
940                                         ping_set_error (obj, "malloc",
941                                                         strerror (errno));
942                                         ret = -1;
943                                         freeaddrinfo (ai_list);
944                                         break;
945                                 }
946                         }
947                         memset ((void *) obj->srcaddr, '\0', sizeof (struct sockaddr_storage));
948                         assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
949                         memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
950                                         ai_list->ai_addrlen);
951                         obj->srcaddrlen = ai_list->ai_addrlen;
952                         obj->addrfamily = ai_list->ai_family;
953
954                         freeaddrinfo (ai_list);
955                 } /* case PING_OPT_SOURCE */
956                 break;
957
958                 default:
959                         ret = -2;
960         } /* switch (option) */
961
962         return (ret);
963 } /* int ping_setopt */
964
965
966 int ping_send (pingobj_t *obj)
967 {
968         int ret;
969
970         if (ping_send_all (obj) < 0)
971                 return (-1);
972
973         if ((ret = ping_receive_all (obj)) < 0)
974                 return (-2);
975
976         return (ret);
977 }
978
979 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
980 {
981         while (ph != NULL)
982         {
983                 if (strcasecmp (ph->hostname, host) == 0)
984                         break;
985
986                 ph = ph->next;
987         }
988
989         return (ph);
990 }
991
992 int ping_host_add (pingobj_t *obj, const char *host)
993 {
994         pinghost_t *ph;
995
996         struct sockaddr_storage sockaddr;
997         socklen_t               sockaddr_len;
998
999         struct addrinfo  ai_hints;
1000         struct addrinfo *ai_list, *ai_ptr;
1001         int              ai_return;
1002
1003         dprintf ("host = %s\n", host);
1004
1005         if (ping_host_search (obj->head, host) != NULL)
1006                 return (0);
1007
1008         memset (&ai_hints, '\0', sizeof (ai_hints));
1009         ai_hints.ai_flags     = 0;
1010 #ifdef AI_ADDRCONFIG
1011         ai_hints.ai_flags    |= AI_ADDRCONFIG;
1012 #endif
1013 #ifdef AI_CANONNAME
1014         ai_hints.ai_flags    |= AI_CANONNAME;
1015 #endif
1016         ai_hints.ai_family    = obj->addrfamily;
1017         ai_hints.ai_socktype  = SOCK_RAW;
1018
1019         if ((ph = ping_alloc ()) == NULL)
1020         {
1021                 dprintf ("Out of memory!\n");
1022                 return (-1);
1023         }
1024
1025         if ((ph->hostname = strdup (host)) == NULL)
1026         {
1027                 dprintf ("Out of memory!\n");
1028                 ping_set_error (obj, "strdup", strerror (errno));
1029                 ping_free (ph);
1030                 return (-1);
1031         }
1032
1033         /* obj->data is not garuanteed to be != NULL */
1034         if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1035         {
1036                 dprintf ("Out of memory!\n");
1037                 ping_set_error (obj, "strdup", strerror (errno));
1038                 ping_free (ph);
1039                 return (-1);
1040         }
1041
1042         if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1043         {
1044                 dprintf ("getaddrinfo failed\n");
1045                 ping_set_error (obj, "getaddrinfo",
1046                                 (ai_return == EAI_SYSTEM)
1047                                 ? strerror (errno)
1048                                 : gai_strerror (ai_return));
1049                 ping_free (ph);
1050                 return (-1);
1051         }
1052
1053         if (ai_list == NULL)
1054                 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1055
1056         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1057         {
1058                 ph->fd = -1;
1059
1060                 sockaddr_len = sizeof (sockaddr);
1061                 memset (&sockaddr, '\0', sockaddr_len);
1062
1063                 if (ai_ptr->ai_family == AF_INET)
1064                 {
1065                         struct sockaddr_in *si;
1066
1067                         si = (struct sockaddr_in *) &sockaddr;
1068                         si->sin_family = AF_INET;
1069                         si->sin_port   = htons (ph->ident);
1070                         si->sin_addr.s_addr = htonl (INADDR_ANY);
1071
1072                         ai_ptr->ai_socktype = SOCK_RAW;
1073                         ai_ptr->ai_protocol = IPPROTO_ICMP;
1074                 }
1075                 else if (ai_ptr->ai_family == AF_INET6)
1076                 {
1077                         struct sockaddr_in6 *si;
1078
1079                         si = (struct sockaddr_in6 *) &sockaddr;
1080                         si->sin6_family = AF_INET6;
1081                         si->sin6_port   = htons (ph->ident);
1082                         si->sin6_addr   = in6addr_any;
1083
1084                         ai_ptr->ai_socktype = SOCK_RAW;
1085                         ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1086                 }
1087                 else
1088                 {
1089                         char errmsg[PING_ERRMSG_LEN];
1090
1091                         snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1092                         errmsg[PING_ERRMSG_LEN - 1] = '\0';
1093
1094                         dprintf (errmsg);
1095                         ping_set_error (obj, "getaddrinfo", errmsg);
1096                         continue;
1097                 }
1098
1099                 /* TODO: Move this to a static function `ping_open_socket' and
1100                  * call it whenever the socket dies. */
1101                 ph->fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1102                 if (ph->fd == -1)
1103                 {
1104                         dprintf ("socket: %s\n", strerror (errno));
1105                         ping_set_error (obj, "socket", strerror (errno));
1106                         continue;
1107                 }
1108
1109                 if (obj->srcaddr != NULL)
1110                 {
1111                         assert (obj->srcaddrlen > 0);
1112                         assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1113
1114                         if (bind (ph->fd, (struct sockaddr *) obj->srcaddr, obj->srcaddrlen) == -1)
1115                         {
1116                                 dprintf ("bind: %s\n", strerror (errno));
1117                                 ping_set_error (obj, "bind", strerror (errno));
1118                                 close (ph->fd);
1119                                 ph->fd = -1;
1120                                 continue;
1121                         }
1122                 }
1123
1124                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1125                 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1126                 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1127                 ph->addrlen = ai_ptr->ai_addrlen;
1128                 ph->addrfamily = ai_ptr->ai_family;
1129
1130 #ifdef AI_CANONNAME
1131                 if ((ai_ptr->ai_canonname != NULL)
1132                                 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1133                 {
1134                         char *old_hostname;
1135
1136                         dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1137                                         ph->hostname, ai_ptr->ai_canonname);
1138
1139                         old_hostname = ph->hostname;
1140                         if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1141                         {
1142                                 /* strdup failed, falling back to old hostname */
1143                                 ph->hostname = old_hostname;
1144                         }
1145                         else if (old_hostname != NULL)
1146                         {
1147                                 free (old_hostname);
1148                         }
1149                 }
1150 #endif /* AI_CANONNAME */
1151
1152                 break;
1153         }
1154
1155         freeaddrinfo (ai_list);
1156
1157         if (ph->fd < 0)
1158         {
1159                 ping_free (ph);
1160                 return (-1);
1161         }
1162
1163         /*
1164          * Adding in the front is much easier, but then the iterator will
1165          * return the host that was added last as first host. That's just not
1166          * nice. -octo
1167          */
1168         if (obj->head == NULL)
1169         {
1170                 obj->head = ph;
1171         }
1172         else
1173         {
1174                 pinghost_t *hptr;
1175
1176                 hptr = obj->head;
1177                 while (hptr->next != NULL)
1178                         hptr = hptr->next;
1179
1180                 assert ((hptr != NULL) && (hptr->next == NULL));
1181                 hptr->next = ph;
1182         }
1183
1184         ping_set_ttl (ph, obj->ttl);
1185
1186         return (0);
1187 }
1188
1189 int ping_host_remove (pingobj_t *obj, const char *host)
1190 {
1191         pinghost_t *pre, *cur;
1192
1193         pre = NULL;
1194         cur = obj->head;
1195
1196         while (cur != NULL)
1197         {
1198                 if (strcasecmp (host, cur->hostname) == 0)
1199                         break;
1200
1201                 pre = cur;
1202                 cur = cur->next;
1203         }
1204
1205         if (cur == NULL)
1206         {
1207                 ping_set_error (obj, "ping_host_remove", "Host not found");
1208                 return (-1);
1209         }
1210
1211         if (pre == NULL)
1212                 obj->head = cur->next;
1213         else
1214                 pre->next = cur->next;
1215         
1216         ping_free (cur);
1217
1218         return (0);
1219 }
1220
1221 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1222 {
1223         return ((pingobj_iter_t *) obj->head);
1224 }
1225
1226 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1227 {
1228         return ((pingobj_iter_t *) iter->next);
1229 }
1230
1231 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1232                 void *buffer, size_t *buffer_len)
1233 {
1234         int ret = EINVAL;
1235
1236         size_t orig_buffer_len = *buffer_len;
1237
1238         switch (info)
1239         {
1240                 case PING_INFO_HOSTNAME:
1241                         ret = ENOMEM;
1242                         *buffer_len = strlen (iter->hostname);
1243                         if (orig_buffer_len <= *buffer_len)
1244                                 break;
1245                         /* Since (orig_buffer_len > *buffer_len) `strncpy'
1246                          * will copy `*buffer_len' and pad the rest of
1247                          * `buffer' with null-bytes */
1248                         strncpy (buffer, iter->hostname, orig_buffer_len);
1249                         ret = 0;
1250                         break;
1251
1252                 case PING_INFO_ADDRESS:
1253                         ret = getnameinfo ((struct sockaddr *) iter->addr,
1254                                         iter->addrlen,
1255                                         (char *) buffer,
1256                                         *buffer_len,
1257                                         NULL, 0,
1258                                         NI_NUMERICHOST);
1259                         if (ret != 0)
1260                         {
1261                                 if ((ret == EAI_MEMORY)
1262 #ifdef EAI_OVERFLOW
1263                                                 || (ret == EAI_OVERFLOW)
1264 #endif
1265                                    )
1266                                         ret = ENOMEM;
1267                                 else if (ret == EAI_SYSTEM)
1268                                         /* XXX: Not thread-safe! */
1269                                         ret = errno;
1270                                 else
1271                                         ret = EINVAL;
1272                         }
1273                         break;
1274
1275                 case PING_INFO_FAMILY:
1276                         ret = ENOMEM;
1277                         *buffer_len = sizeof (int);
1278                         if (orig_buffer_len < sizeof (int))
1279                                 break;
1280                         *((int *) buffer) = iter->addrfamily;
1281                         ret = 0;
1282                         break;
1283
1284                 case PING_INFO_LATENCY:
1285                         ret = ENOMEM;
1286                         *buffer_len = sizeof (double);
1287                         if (orig_buffer_len < sizeof (double))
1288                                 break;
1289                         *((double *) buffer) = iter->latency;
1290                         ret = 0;
1291                         break;
1292
1293                 case PING_INFO_SEQUENCE:
1294                         ret = ENOMEM;
1295                         *buffer_len = sizeof (unsigned int);
1296                         if (orig_buffer_len < sizeof (unsigned int))
1297                                 break;
1298                         *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1299                         ret = 0;
1300                         break;
1301
1302                 case PING_INFO_IDENT:
1303                         ret = ENOMEM;
1304                         *buffer_len = sizeof (uint16_t);
1305                         if (orig_buffer_len < sizeof (uint16_t))
1306                                 break;
1307                         *((uint16_t *) buffer) = (uint16_t) iter->ident;
1308                         ret = 0;
1309                         break;
1310
1311                 case PING_INFO_DATA:
1312                         ret = ENOMEM;
1313                         *buffer_len = strlen (iter->data);
1314                         if (orig_buffer_len < *buffer_len)
1315                                 break;
1316                         strncpy ((char *) buffer, iter->data, orig_buffer_len);
1317                         ret = 0;
1318                         break;
1319         }
1320
1321         return (ret);
1322 }
1323
1324 void *ping_iterator_get_context (pingobj_iter_t *iter)
1325 {
1326         return (iter->context);
1327 }
1328
1329 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1330 {
1331         iter->context = context;
1332 }