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