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