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