2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2016 Florian octo Forster <ff at octo.it>
5 * This library is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as published by the
7 * Free Software Foundation; either version 2.1 of the License, or (at your
8 * option) any later version.
10 * This library is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define __APPLE_USE_RFC_3542
32 # include <inttypes.h>
36 # error "You don't have the standard C99 header files installed"
37 #endif /* STDC_HEADERS */
51 # include <sys/types.h>
54 # include <sys/stat.h>
57 #if TIME_WITH_SYS_TIME
58 # include <sys/time.h>
62 # include <sys/time.h>
69 # include <sys/socket.h>
76 #if HAVE_NETINET_IN_SYSTM_H
77 # include <netinet/in_systm.h>
80 # include <netinet/in.h>
83 # include <netinet/ip.h>
85 #if HAVE_NETINET_IP_ICMP_H
86 # include <netinet/ip_icmp.h>
88 #ifdef HAVE_NETINET_IP_VAR_H
89 # include <netinet/ip_var.h>
91 #if HAVE_NETINET_IP6_H
92 # include <netinet/ip6.h>
94 #if HAVE_NETINET_ICMP6_H
95 # include <netinet/icmp6.h>
101 # define dprintf(...) printf ("%s[%4i]: %-20s: ", __FILE__, __LINE__, __FUNCTION__); printf (__VA_ARGS__)
103 # define dprintf(...) /**/
106 #define PING_ERRMSG_LEN 256
107 #define PING_TABLE_LEN 5381
111 /* username: name passed in by the user */
113 /* hostname: name returned by the reverse lookup */
115 struct sockaddr_storage *addr;
120 struct timeval *timer;
129 struct pinghost *next;
130 struct pinghost *table_next;
144 struct sockaddr *srcaddr;
145 socklen_t srcaddrlen;
152 char errmsg[PING_ERRMSG_LEN];
155 pinghost_t *table[PING_TABLE_LEN];
159 * private (static) functions
161 /* Even though Posix requires "strerror_r" to return an "int",
162 * some systems (e.g. the GNU libc) return a "char *" _and_
163 * ignore the second argument ... -tokkee */
164 static char *sstrerror (int errnum, char *buf, size_t buflen)
170 snprintf (buf, buflen, "Error %i (%#x)", errnum, errnum);
172 /* #endif !HAVE_STRERROR_R */
174 #elif STRERROR_R_CHAR_P
177 temp = strerror_r (errnum, buf, buflen);
180 if ((temp != NULL) && (temp != buf) && (temp[0] != 0))
181 strncpy (buf, temp, buflen);
183 strncpy (buf, "strerror_r did not return "
184 "an error message", buflen);
187 /* #endif STRERROR_R_CHAR_P */
190 if (strerror_r (errnum, buf, buflen) != 0)
192 snprintf (buf, buflen, "Error %i (%#x); "
193 "Additionally, strerror_r failed.",
196 #endif /* STRERROR_R_CHAR_P */
201 } /* char *sstrerror */
203 static void ping_set_error (pingobj_t *obj, const char *function,
206 snprintf (obj->errmsg, sizeof (obj->errmsg),
207 "%s: %s", function, message);
208 obj->errmsg[sizeof (obj->errmsg) - 1] = 0;
211 static void ping_set_errno (pingobj_t *obj, int error_number)
213 sstrerror (error_number, obj->errmsg, sizeof (obj->errmsg));
216 static int ping_timeval_add (struct timeval *tv1, struct timeval *tv2,
219 res->tv_sec = tv1->tv_sec + tv2->tv_sec;
220 res->tv_usec = tv1->tv_usec + tv2->tv_usec;
222 while (res->tv_usec > 1000000)
224 res->tv_usec -= 1000000;
231 static int ping_timeval_sub (struct timeval *tv1, struct timeval *tv2,
234 if ((tv1->tv_sec < tv2->tv_sec)
235 || ((tv1->tv_sec == tv2->tv_sec)
236 && (tv1->tv_usec < tv2->tv_usec)))
239 res->tv_sec = tv1->tv_sec - tv2->tv_sec;
240 res->tv_usec = tv1->tv_usec - tv2->tv_usec;
242 assert ((res->tv_sec > 0) || ((res->tv_sec == 0) && (res->tv_usec >= 0)));
244 while (res->tv_usec < 0)
246 res->tv_usec += 1000000;
253 static uint16_t ping_icmp4_checksum (char *buf, size_t len)
260 for (ptr = (uint16_t *) buf; len > 1; ptr++, len -= 2)
265 *(char *) &ret = *(char *) ptr;
269 /* Do this twice to get all possible carries.. */
270 sum = (sum >> 16) + (sum & 0xFFFF);
271 sum = (sum >> 16) + (sum & 0xFFFF);
278 static pinghost_t *ping_receive_ipv4 (pingobj_t *obj, char *buffer,
282 struct icmp *icmp_hdr;
286 uint16_t recv_checksum;
287 uint16_t calc_checksum;
294 if (buffer_len < sizeof (struct ip))
297 ip_hdr = (struct ip *) buffer;
298 ip_hdr_len = ip_hdr->ip_hl << 2;
300 if (buffer_len < ip_hdr_len)
303 buffer += ip_hdr_len;
304 buffer_len -= ip_hdr_len;
306 if (buffer_len < ICMP_MINLEN)
309 icmp_hdr = (struct icmp *) buffer;
310 if (icmp_hdr->icmp_type != ICMP_ECHOREPLY)
312 dprintf ("Unexpected ICMP type: %"PRIu8"\n", icmp_hdr->icmp_type);
316 recv_checksum = icmp_hdr->icmp_cksum;
317 /* This writes to buffer. */
318 icmp_hdr->icmp_cksum = 0;
319 calc_checksum = ping_icmp4_checksum (buffer, buffer_len);
321 if (recv_checksum != calc_checksum)
323 dprintf ("Checksum missmatch: Got 0x%04"PRIx16", "
324 "calculated 0x%04"PRIx16"\n",
325 recv_checksum, calc_checksum);
329 ident = ntohs (icmp_hdr->icmp_id);
330 seq = ntohs (icmp_hdr->icmp_seq);
332 for (ptr = obj->table[ident % PING_TABLE_LEN];
333 ptr != NULL; ptr = ptr->table_next)
335 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
336 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
338 if (ptr->addrfamily != AF_INET)
341 if (!timerisset (ptr->timer))
344 if (ptr->ident != ident)
347 if (((ptr->sequence - 1) & 0xFFFF) != seq)
350 dprintf ("Match found: hostname = %s, ident = 0x%04"PRIx16", "
352 ptr->hostname, ident, seq);
359 dprintf ("No match found for ident = 0x%04"PRIx16", seq = %"PRIu16"\n",
364 ptr->recv_ttl = (int) ip_hdr->ip_ttl;
365 ptr->recv_qos = (uint8_t) ip_hdr->ip_tos;
370 #ifndef ICMP6_ECHO_REQUEST
371 # ifdef ICMP6_ECHO /* AIX netinet/ip6_icmp.h */
372 # define ICMP6_ECHO_REQUEST ICMP6_ECHO
374 # define ICMP6_ECHO_REQUEST 128
378 #ifndef ICMP6_ECHO_REPLY
379 # ifdef ICMP6_ECHOREPLY /* AIX netinet/ip6_icmp.h */
380 # define ICMP6_ECHO_REPLY ICMP6_ECHOREPLY
382 # define ICMP6_ECHO_REPLY 129
386 static pinghost_t *ping_receive_ipv6 (pingobj_t *obj, char *buffer,
389 struct icmp6_hdr *icmp_hdr;
396 if (buffer_len < ICMP_MINLEN)
399 icmp_hdr = (struct icmp6_hdr *) buffer;
400 buffer += ICMP_MINLEN;
401 buffer_len -= ICMP_MINLEN;
403 if (icmp_hdr->icmp6_type != ICMP6_ECHO_REPLY)
405 dprintf ("Unexpected ICMP type: %02x\n", icmp_hdr->icmp6_type);
409 if (icmp_hdr->icmp6_code != 0)
411 dprintf ("Unexpected ICMP code: %02x\n", icmp_hdr->icmp6_code);
415 ident = ntohs (icmp_hdr->icmp6_id);
416 seq = ntohs (icmp_hdr->icmp6_seq);
418 /* We have to iterate over all hosts, since ICMPv6 packets may
419 * be received on any raw v6 socket. */
420 for (ptr = obj->head; ptr != NULL; ptr = ptr->next)
422 dprintf ("hostname = %s, ident = 0x%04x, seq = %i\n",
423 ptr->hostname, ptr->ident, ((ptr->sequence - 1) & 0xFFFF));
425 if (ptr->addrfamily != AF_INET6)
428 if (!timerisset (ptr->timer))
431 if (ptr->ident != ident)
434 if (((ptr->sequence - 1) & 0xFFFF) != seq)
437 dprintf ("Match found: hostname = %s, ident = 0x%04"PRIx16", "
439 ptr->hostname, ident, seq);
446 dprintf ("No match found for ident = 0x%04"PRIx16", "
454 static int ping_receive_one (pingobj_t *obj, struct timeval *now, int addrfam)
456 int fd = addrfam == AF_INET6 ? obj->fd6 : obj->fd4;
457 struct timeval diff, pkt_now = *now;
458 pinghost_t *host = NULL;
463 * Set up the receive buffer..
465 struct msghdr msghdr;
466 struct cmsghdr *cmsg;
467 char payload_buffer[4096];
468 ssize_t payload_buffer_len;
469 char control_buffer[4096];
470 struct iovec payload_iovec;
472 memset (&payload_iovec, 0, sizeof (payload_iovec));
473 payload_iovec.iov_base = payload_buffer;
474 payload_iovec.iov_len = sizeof (payload_buffer);
476 memset (&msghdr, 0, sizeof (msghdr));
477 /* unspecified source address */
478 msghdr.msg_name = NULL;
479 msghdr.msg_namelen = 0;
480 /* output buffer vector, see readv(2) */
481 msghdr.msg_iov = &payload_iovec;
482 msghdr.msg_iovlen = 1;
483 /* output buffer for control messages */
484 msghdr.msg_control = control_buffer;
485 msghdr.msg_controllen = sizeof (control_buffer);
486 /* flags; this is an output only field.. */
487 msghdr.msg_flags = 0;
489 msghdr.msg_flags |= MSG_XPG4_2;
492 payload_buffer_len = recvmsg (fd, &msghdr, /* flags = */ 0);
493 if (payload_buffer_len < 0)
496 char errbuf[PING_ERRMSG_LEN];
497 dprintf ("recvfrom: %s\n",
498 sstrerror (errno, errbuf, sizeof (errbuf)));
502 dprintf ("Read %zi bytes from fd = %i\n", payload_buffer_len, fd);
504 /* Iterate over all auxiliary data in msghdr */
507 for (cmsg = CMSG_FIRSTHDR (&msghdr); /* {{{ */
509 cmsg = CMSG_NXTHDR (&msghdr, cmsg))
511 if (cmsg->cmsg_level == SOL_SOCKET)
514 if (cmsg->cmsg_type == SO_TIMESTAMP)
515 memcpy (&pkt_now, CMSG_DATA (cmsg), sizeof (pkt_now));
516 #endif /* SO_TIMESTAMP */
518 else if (addrfam == AF_INET) /* {{{ */
520 if (cmsg->cmsg_level != IPPROTO_IP)
523 if (cmsg->cmsg_type == IP_TOS)
525 memcpy (&recv_qos, CMSG_DATA (cmsg),
527 dprintf ("TOSv4 = 0x%02"PRIx8";\n", recv_qos);
529 if (cmsg->cmsg_type == IP_TTL)
531 memcpy (&recv_ttl, CMSG_DATA (cmsg),
533 dprintf ("TTLv4 = %i;\n", recv_ttl);
537 dprintf ("Not handling option %i.\n",
541 else if (addrfam == AF_INET6) /* {{{ */
543 if (cmsg->cmsg_level != IPPROTO_IPV6)
546 if (cmsg->cmsg_type == IPV6_TCLASS)
548 memcpy (&recv_qos, CMSG_DATA (cmsg),
550 dprintf ("TOSv6 = 0x%02"PRIx8";\n", recv_qos);
553 if (cmsg->cmsg_type == IPV6_HOPLIMIT)
555 memcpy (&recv_ttl, CMSG_DATA (cmsg),
557 dprintf ("TTLv6 = %i;\n", recv_ttl);
561 #ifdef IPV6_UNICAST_HOPS
562 if (cmsg->cmsg_type == IPV6_UNICAST_HOPS)
564 memcpy (&recv_ttl, CMSG_DATA (cmsg),
566 dprintf ("TTLv6 = %i;\n", recv_ttl);
570 #ifdef IPV6_MULTICAST_HOPS
571 if (cmsg->cmsg_type == IPV6_MULTICAST_HOPS)
573 memcpy (&recv_ttl, CMSG_DATA (cmsg),
575 dprintf ("TTLv6 = %i;\n", recv_ttl);
580 dprintf ("Not handling option %i.\n",
586 dprintf ("Don't know how to handle "
587 "unknown protocol %i.\n",
590 } /* }}} for (cmsg) */
592 if (addrfam == AF_INET)
594 host = ping_receive_ipv4 (obj, payload_buffer, payload_buffer_len);
598 else if (addrfam == AF_INET6)
600 host = ping_receive_ipv6 (obj, payload_buffer, payload_buffer_len);
606 dprintf ("ping_receive_one: Unknown address family %i.\n",
611 dprintf ("rcvd: %12i.%06i\n",
612 (int) pkt_now.tv_sec,
613 (int) pkt_now.tv_usec);
614 dprintf ("sent: %12i.%06i\n",
615 (int) host->timer->tv_sec,
616 (int) host->timer->tv_usec);
618 if (ping_timeval_sub (&pkt_now, host->timer, &diff) < 0)
620 timerclear (host->timer);
624 dprintf ("diff: %12i.%06i\n",
629 host->recv_ttl = recv_ttl;
630 host->recv_qos = recv_qos;
632 host->latency = ((double) diff.tv_usec) / 1000.0;
633 host->latency += ((double) diff.tv_sec) * 1000.0;
635 timerclear (host->timer);
640 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
641 * Sending functions: *
644 * +-> ping_send_one_ipv4 *
645 * `-> ping_send_one_ipv6 *
646 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
647 static ssize_t ping_sendto (pingobj_t *obj, pinghost_t *ph,
648 const void *buf, size_t buflen, int fd)
652 if (gettimeofday (ph->timer, NULL) == -1)
654 timerclear (ph->timer);
658 ret = sendto (fd, buf, buflen, 0,
659 (struct sockaddr *) ph->addr, ph->addrlen);
663 #if defined(EHOSTUNREACH)
664 if (errno == EHOSTUNREACH)
667 #if defined(ENETUNREACH)
668 if (errno == ENETUNREACH)
671 ping_set_errno (obj, errno);
677 static int ping_send_one_ipv4 (pingobj_t *obj, pinghost_t *ph, int fd)
682 char buf[4096] = {0};
688 dprintf ("ph->hostname = %s\n", ph->hostname);
690 icmp4 = (struct icmp *) buf;
691 *icmp4 = (struct icmp) {
692 .icmp_type = ICMP_ECHO,
693 .icmp_id = htons (ph->ident),
694 .icmp_seq = htons (ph->sequence),
697 datalen = strlen (ph->data);
698 buflen = ICMP_MINLEN + datalen;
699 if (sizeof (buf) < buflen)
702 data = buf + ICMP_MINLEN;
703 memcpy (data, ph->data, datalen);
705 icmp4->icmp_cksum = ping_icmp4_checksum (buf, buflen);
707 dprintf ("Sending ICMPv4 package with ID 0x%04x\n", ph->ident);
709 status = ping_sendto (obj, ph, buf, buflen, fd);
712 perror ("ping_sendto");
716 dprintf ("sendto: status = %i\n", status);
721 static int ping_send_one_ipv6 (pingobj_t *obj, pinghost_t *ph, int fd)
723 struct icmp6_hdr *icmp6;
726 char buf[4096] = {0};
732 dprintf ("ph->hostname = %s\n", ph->hostname);
734 icmp6 = (struct icmp6_hdr *) buf;
735 *icmp6 = (struct icmp6_hdr) {
736 .icmp6_type = ICMP6_ECHO_REQUEST,
737 .icmp6_id = htons (ph->ident),
738 .icmp6_seq = htons (ph->sequence),
741 datalen = strlen (ph->data);
742 buflen = sizeof (*icmp6) + datalen;
743 if (sizeof (buf) < buflen)
746 data = buf + ICMP_MINLEN;
747 memcpy (data, ph->data, datalen);
749 /* The checksum will be calculated by the TCP/IP stack. */
751 dprintf ("Sending ICMPv6 package with ID 0x%04x\n", ph->ident);
753 status = ping_sendto (obj, ph, buf, buflen, fd);
756 perror ("ping_sendto");
760 dprintf ("sendto: status = %i\n", status);
765 static int ping_send_one (pingobj_t *obj, pinghost_t *ptr, int fd)
767 if (gettimeofday (ptr->timer, NULL) == -1)
769 /* start timer.. The GNU `ping6' starts the timer before
770 * sending the packet, so I will do that too */
772 char errbuf[PING_ERRMSG_LEN];
773 dprintf ("gettimeofday: %s\n",
774 sstrerror (errno, errbuf, sizeof (errbuf)));
776 timerclear (ptr->timer);
781 dprintf ("timer set for hostname = %s\n", ptr->hostname);
784 if (ptr->addrfamily == AF_INET6)
786 dprintf ("Sending ICMPv6 echo request to `%s'\n", ptr->hostname);
787 if (ping_send_one_ipv6 (obj, ptr, fd) != 0)
789 timerclear (ptr->timer);
793 else if (ptr->addrfamily == AF_INET)
795 dprintf ("Sending ICMPv4 echo request to `%s'\n", ptr->hostname);
796 if (ping_send_one_ipv4 (obj, ptr, fd) != 0)
798 timerclear (ptr->timer);
802 else /* this should not happen */
804 dprintf ("Unknown address family: %i\n", ptr->addrfamily);
805 timerclear (ptr->timer);
815 * Set the TTL of a socket protocol independently.
817 static int ping_set_ttl (pingobj_t *obj, int ttl)
820 char errbuf[PING_ERRMSG_LEN];
824 if (setsockopt (obj->fd4, IPPROTO_IP, IP_TTL,
828 ping_set_error (obj, "ping_set_ttl",
829 sstrerror (ret, errbuf, sizeof (errbuf)));
830 dprintf ("Setting TTLv4 failed: %s\n", errbuf);
836 dprintf ("Setting TTLv6 to %i\n", ttl);
837 if (setsockopt (obj->fd6, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
841 ping_set_error (obj, "ping_set_ttl",
842 sstrerror (ret, errbuf, sizeof (errbuf)));
843 dprintf ("Setting TTLv6 failed: %s\n", errbuf);
851 * Set the TOS of a socket protocol independently.
853 * Using SOL_SOCKET / SO_PRIORITY might be a protocol independent way to
854 * set this. See socket(7) for details.
856 static int ping_set_qos (pingobj_t *obj, uint8_t qos)
859 char errbuf[PING_ERRMSG_LEN];
863 dprintf ("Setting TP_TOS to %#04"PRIx8"\n", qos);
864 if (setsockopt (obj->fd4, IPPROTO_IP, IP_TOS,
868 ping_set_error (obj, "ping_set_qos",
869 sstrerror (ret, errbuf, sizeof (errbuf)));
870 dprintf ("Setting TP_TOS failed: %s\n", errbuf);
876 /* IPV6_TCLASS requires an "int". */
879 dprintf ("Setting IPV6_TCLASS to %#04"PRIx8" (%i)\n", qos, tmp);
880 if (setsockopt (obj->fd6, IPPROTO_IPV6, IPV6_TCLASS,
884 ping_set_error (obj, "ping_set_qos",
885 sstrerror (ret, errbuf, sizeof (errbuf)));
886 dprintf ("Setting IPV6_TCLASS failed: %s\n", errbuf);
893 static int ping_get_ident (void)
896 static int did_seed = 0;
902 if ((fd = open ("/dev/urandom", O_RDONLY)) != -1)
906 if (read (fd, &seed, sizeof (seed)) != -1)
909 dprintf ("Random seed: %#x\n", seed);
918 char errbuf[PING_ERRMSG_LEN];
919 dprintf ("open (/dev/urandom): %s\n",
920 sstrerror (errno, errbuf, sizeof (errbuf)));
925 retval = (int) random ();
927 dprintf ("Random number: %#x\n", retval);
932 static pinghost_t *ping_alloc (void)
937 ph_size = sizeof (pinghost_t)
938 + sizeof (struct sockaddr_storage)
939 + sizeof (struct timeval);
941 ph = (pinghost_t *) malloc (ph_size);
945 memset (ph, '\0', ph_size);
947 ph->timer = (struct timeval *) (ph + 1);
948 ph->addr = (struct sockaddr_storage *) (ph->timer + 1);
950 ph->addrlen = sizeof (struct sockaddr_storage);
953 ph->ident = ping_get_ident () & 0xFFFF;
958 static void ping_free (pinghost_t *ph)
970 /* ping_open_socket opens, initializes and returns a new raw socket to use for
971 * ICMPv4 or ICMPv6 packets. addrfam must be either AF_INET or AF_INET6. On
972 * error, -1 is returned and obj->errmsg is set appropriately. */
973 static int ping_open_socket(pingobj_t *obj, int addrfam)
976 if (addrfam == AF_INET6)
978 fd = socket(addrfam, SOCK_RAW, IPPROTO_ICMPV6);
980 else if (addrfam == AF_INET)
982 fd = socket(addrfam, SOCK_RAW, IPPROTO_ICMP);
984 else /* this should not happen */
986 ping_set_error (obj, "ping_open_socket", "Unknown address family");
987 dprintf ("Unknown address family: %i\n", addrfam);
993 ping_set_errno (obj, errno);
995 char errbuf[PING_ERRMSG_LEN];
996 dprintf ("socket: %s\n",
997 sstrerror (errno, errbuf, sizeof (errbuf)));
1001 else if (fd >= FD_SETSIZE)
1003 ping_set_errno (obj, EMFILE);
1004 dprintf ("socket(2) returned file descriptor %d, which is above the file "
1005 "descriptor limit for select(2) (FD_SETSIZE = %d)\n",
1011 if (obj->srcaddr != NULL)
1013 assert (obj->srcaddrlen > 0);
1014 assert (obj->srcaddrlen <= sizeof (struct sockaddr_storage));
1016 if (bind (fd, obj->srcaddr, obj->srcaddrlen) == -1)
1018 ping_set_errno (obj, errno);
1020 char errbuf[PING_ERRMSG_LEN];
1021 dprintf ("bind: %s\n",
1022 sstrerror (errno, errbuf, sizeof (errbuf)));
1029 #ifdef SO_BINDTODEVICE
1030 if (obj->device != NULL)
1032 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1033 obj->device, strlen (obj->device) + 1) != 0)
1035 ping_set_errno (obj, errno);
1037 char errbuf[PING_ERRMSG_LEN];
1038 dprintf ("setsockopt (SO_BINDTODEVICE): %s\n",
1039 sstrerror (errno, errbuf, sizeof (errbuf)));
1045 #endif /* SO_BINDTODEVICE */
1049 if (setsockopt(fd, SOL_SOCKET, SO_MARK,
1050 &obj->mark, sizeof(obj->mark)) != 0)
1052 ping_set_errno (obj, errno);
1054 char errbuf[PING_ERRMSG_LEN];
1055 dprintf ("setsockopt (SO_MARK): %s\n",
1056 sstrerror (errno, errbuf, sizeof (errbuf)));
1069 status = setsockopt (fd,
1070 SOL_SOCKET, SO_TIMESTAMP,
1071 &opt, sizeof (opt));
1074 ping_set_errno (obj, errno);
1076 char errbuf[PING_ERRMSG_LEN];
1077 dprintf ("setsockopt (SO_TIMESTAMP): %s\n",
1078 sstrerror (errno, errbuf, sizeof (errbuf)));
1084 #endif /* SO_TIMESTAMP */
1086 if (addrfam == AF_INET)
1091 /* Enable receiving the TOS field */
1093 setsockopt (fd, IPPROTO_IP, IP_RECVTOS,
1094 &opt, sizeof (opt));
1095 #endif /* IP_RECVTOS */
1097 /* Enable receiving the TTL field */
1099 setsockopt (fd, IPPROTO_IP, IP_RECVTTL,
1100 &opt, sizeof (opt));
1102 #if defined(IPV6_RECVHOPLIMIT) || defined(IPV6_RECVTCLASS)
1103 else if (addrfam == AF_INET6)
1107 # if defined(IPV6_RECVHOPLIMIT)
1108 /* For details see RFC 3542, section 6.3. */
1110 setsockopt (fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
1111 &opt, sizeof (opt));
1112 # endif /* IPV6_RECVHOPLIMIT */
1114 # if defined(IPV6_RECVTCLASS)
1115 /* For details see RFC 3542, section 6.5. */
1117 setsockopt (fd, IPPROTO_IPV6, IPV6_RECVTCLASS,
1118 &opt, sizeof (opt));
1119 # endif /* IPV6_RECVTCLASS */
1121 #endif /* IPV6_RECVHOPLIMIT || IPV6_RECVTCLASS */
1129 const char *ping_get_error (pingobj_t *obj)
1133 return (obj->errmsg);
1136 pingobj_t *ping_construct (void)
1140 if ((obj = (pingobj_t *) malloc (sizeof (pingobj_t))) == NULL)
1142 memset (obj, 0, sizeof (pingobj_t));
1144 obj->timeout = PING_DEF_TIMEOUT;
1145 obj->ttl = PING_DEF_TTL;
1146 obj->addrfamily = PING_DEF_AF;
1147 obj->data = strdup (PING_DEF_DATA);
1155 void ping_destroy (pingobj_t *obj)
1157 pinghost_t *current;
1163 current = obj->head;
1166 while (current != NULL)
1168 next = current->next;
1169 ping_free (current);
1174 free (obj->srcaddr);
1188 int ping_setopt (pingobj_t *obj, int option, void *value)
1192 if ((obj == NULL) || (value == NULL))
1199 obj->qos = *((uint8_t *) value);
1200 ret = ping_set_qos (obj, obj->qos);
1204 case PING_OPT_TIMEOUT:
1205 obj->timeout = *((double *) value);
1206 if (obj->timeout < 0.0)
1208 obj->timeout = PING_DEF_TIMEOUT;
1214 ret = *((int *) value);
1215 if ((ret < 1) || (ret > 255))
1217 obj->ttl = PING_DEF_TTL;
1223 ret = ping_set_ttl (obj, obj->ttl);
1228 obj->addrfamily = *((int *) value);
1229 if ((obj->addrfamily != AF_UNSPEC)
1230 && (obj->addrfamily != AF_INET)
1231 && (obj->addrfamily != AF_INET6))
1233 obj->addrfamily = PING_DEF_AF;
1236 if (obj->srcaddr != NULL)
1238 free (obj->srcaddr);
1239 obj->srcaddr = NULL;
1244 if (obj->data != NULL)
1249 obj->data = strdup ((const char *) value);
1252 case PING_OPT_SOURCE:
1254 char *hostname = (char *) value;
1255 struct addrinfo ai_hints;
1256 struct addrinfo *ai_list;
1259 if (obj->addrfamily != AF_UNSPEC)
1261 dprintf ("Resetting obj->addrfamily to AF_UNSPEC.\n");
1264 memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
1265 ai_hints.ai_family = obj->addrfamily = AF_UNSPEC;
1266 #if defined(AI_ADDRCONFIG)
1267 ai_hints.ai_flags = AI_ADDRCONFIG;
1269 status = getaddrinfo (hostname, NULL, &ai_hints, &ai_list);
1272 #if defined(EAI_SYSTEM)
1273 char errbuf[PING_ERRMSG_LEN];
1275 ping_set_error (obj, "getaddrinfo",
1276 #if defined(EAI_SYSTEM)
1277 (status == EAI_SYSTEM)
1278 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1280 gai_strerror (status));
1285 if (ai_list->ai_next != NULL)
1287 dprintf ("hostname = `%s' is ambiguous.\n", hostname);
1290 if (obj->srcaddr == NULL)
1292 obj->srcaddrlen = 0;
1293 obj->srcaddr = malloc (sizeof (struct sockaddr_storage));
1294 if (obj->srcaddr == NULL)
1296 ping_set_errno (obj, errno);
1298 freeaddrinfo (ai_list);
1302 memset ((void *) obj->srcaddr, 0, sizeof (struct sockaddr_storage));
1303 assert (ai_list->ai_addrlen <= sizeof (struct sockaddr_storage));
1304 memcpy ((void *) obj->srcaddr, (const void *) ai_list->ai_addr,
1305 ai_list->ai_addrlen);
1306 obj->srcaddrlen = ai_list->ai_addrlen;
1307 obj->addrfamily = ai_list->ai_family;
1309 freeaddrinfo (ai_list);
1310 } /* case PING_OPT_SOURCE */
1313 case PING_OPT_DEVICE:
1315 #ifdef SO_BINDTODEVICE
1316 char *device = strdup ((char *) value);
1320 ping_set_errno (obj, errno);
1325 if (obj->device != NULL)
1327 obj->device = device;
1328 #else /* ! SO_BINDTODEVICE */
1329 ping_set_errno (obj, ENOTSUP);
1331 #endif /* ! SO_BINDTODEVICE */
1332 } /* case PING_OPT_DEVICE */
1338 obj->mark = *(int*)(value);
1341 ping_set_errno (obj, ENOTSUP);
1343 #endif /* !SO_MARK */
1345 } /* case PING_OPT_MARK */
1350 } /* switch (option) */
1353 } /* int ping_setopt */
1355 int ping_send (pingobj_t *obj)
1359 struct timeval endtime;
1360 struct timeval nowtime;
1361 struct timeval timeout;
1363 _Bool need_ipv4_socket = 0;
1364 _Bool need_ipv6_socket = 0;
1366 for (ptr = obj->head; ptr != NULL; ptr = ptr->next)
1368 ptr->latency = -1.0;
1371 if (ptr->addrfamily == AF_INET)
1372 need_ipv4_socket = 1;
1373 else if (ptr->addrfamily == AF_INET6)
1374 need_ipv6_socket = 1;
1377 if (!need_ipv4_socket && !need_ipv6_socket)
1379 ping_set_error (obj, "ping_send", "No hosts to ping");
1383 if (need_ipv4_socket && obj->fd4 == -1)
1385 obj->fd4 = ping_open_socket(obj, AF_INET);
1388 ping_set_ttl (obj, obj->ttl);
1389 ping_set_qos (obj, obj->qos);
1391 if (need_ipv6_socket && obj->fd6 == -1)
1393 obj->fd6 = ping_open_socket(obj, AF_INET6);
1396 ping_set_ttl (obj, obj->ttl);
1397 ping_set_qos (obj, obj->qos);
1400 if (gettimeofday (&nowtime, NULL) == -1)
1402 ping_set_errno (obj, errno);
1406 /* Set up timeout */
1407 timeout.tv_sec = (time_t) obj->timeout;
1408 timeout.tv_usec = (suseconds_t) (1000000 * (obj->timeout - ((double) timeout.tv_sec)));
1410 dprintf ("Set timeout to %i.%06i seconds\n",
1411 (int) timeout.tv_sec,
1412 (int) timeout.tv_usec);
1414 ping_timeval_add (&nowtime, &timeout, &endtime);
1416 /* host_to_ping points to the host to which to send the next ping. The
1417 * pointer is advanced to the next host in the linked list after the
1418 * ping has been sent. If host_to_ping is NULL, no more pings need to be
1420 pinghost_t *host_to_ping = obj->head;
1422 /* pings_in_flight is the number of hosts we sent a "ping" to but didn't
1423 * receive a "pong" yet. */
1424 int pings_in_flight = 0;
1426 /* pongs_received is the number of echo replies received. Unless there
1427 * is an error, this is used as the return value of ping_send(). */
1428 int pongs_received = 0;
1430 int error_count = 0;
1432 while (pings_in_flight > 0 || host_to_ping != NULL)
1440 FD_ZERO (&read_fds);
1441 FD_ZERO (&write_fds);
1445 FD_SET(obj->fd4, &read_fds);
1446 if (host_to_ping != NULL && host_to_ping->addrfamily == AF_INET)
1447 write_fd = obj->fd4;
1449 if (max_fd < obj->fd4)
1455 FD_SET(obj->fd6, &read_fds);
1456 if (host_to_ping != NULL && host_to_ping->addrfamily == AF_INET6)
1457 write_fd = obj->fd6;
1459 if (max_fd < obj->fd6)
1464 FD_SET(write_fd, &write_fds);
1466 assert (max_fd != -1);
1467 assert (max_fd < FD_SETSIZE);
1469 if (gettimeofday (&nowtime, NULL) == -1)
1471 ping_set_errno (obj, errno);
1475 if (ping_timeval_sub (&endtime, &nowtime, &timeout) == -1)
1478 dprintf ("Waiting on %i sockets for %u.%06u seconds\n",
1479 ((obj->fd4 != -1) ? 1 : 0) + ((obj->fd6 != -1) ? 1 : 0),
1480 (unsigned) timeout.tv_sec,
1481 (unsigned) timeout.tv_usec);
1483 int status = select (max_fd + 1, &read_fds, &write_fds, NULL, &timeout);
1485 if (gettimeofday (&nowtime, NULL) == -1)
1487 ping_set_errno (obj, errno);
1493 ping_set_errno (obj, errno);
1494 dprintf ("select: %s\n", obj->errmsg);
1497 else if (status == 0)
1499 dprintf ("select timed out\n");
1502 for (ph = obj->head; ph != NULL; ph = ph->next)
1503 if (ph->latency < 0.0)
1508 /* first, check if we can receive a reply ... */
1509 if (obj->fd6 != -1 && FD_ISSET (obj->fd6, &read_fds))
1511 if (ping_receive_one (obj, &nowtime, AF_INET6) == 0)
1518 if (obj->fd4 != -1 && FD_ISSET (obj->fd4, &read_fds))
1520 if (ping_receive_one (obj, &nowtime, AF_INET) == 0)
1528 /* ... and if no reply is available to read, continue sending
1531 /* this condition should always be true. We keep it for
1532 * consistency with the read blocks above and just to be on the
1534 if (write_fd != -1 && FD_ISSET (write_fd, &write_fds))
1536 if (ping_send_one (obj, host_to_ping, write_fd) == 0)
1540 host_to_ping = host_to_ping->next;
1546 return (-1 * error_count);
1547 return (pongs_received);
1548 } /* int ping_send */
1550 static pinghost_t *ping_host_search (pinghost_t *ph, const char *host)
1554 if (strcasecmp (ph->username, host) == 0)
1563 int ping_host_add (pingobj_t *obj, const char *host)
1567 struct addrinfo ai_hints;
1568 struct addrinfo *ai_list, *ai_ptr;
1571 if ((obj == NULL) || (host == NULL))
1574 dprintf ("host = %s\n", host);
1576 if (ping_host_search (obj->head, host) != NULL)
1579 memset (&ai_hints, '\0', sizeof (ai_hints));
1580 ai_hints.ai_flags = 0;
1581 #ifdef AI_ADDRCONFIG
1582 ai_hints.ai_flags |= AI_ADDRCONFIG;
1585 ai_hints.ai_flags |= AI_CANONNAME;
1587 ai_hints.ai_family = obj->addrfamily;
1588 ai_hints.ai_socktype = SOCK_RAW;
1590 if ((ph = ping_alloc ()) == NULL)
1592 dprintf ("Out of memory!\n");
1596 if ((ph->username = strdup (host)) == NULL)
1598 dprintf ("Out of memory!\n");
1599 ping_set_errno (obj, errno);
1604 if ((ph->hostname = strdup (host)) == NULL)
1606 dprintf ("Out of memory!\n");
1607 ping_set_errno (obj, errno);
1612 /* obj->data is not garuanteed to be != NULL */
1613 if ((ph->data = strdup (obj->data == NULL ? PING_DEF_DATA : obj->data)) == NULL)
1615 dprintf ("Out of memory!\n");
1616 ping_set_errno (obj, errno);
1621 if ((ai_return = getaddrinfo (host, NULL, &ai_hints, &ai_list)) != 0)
1623 #if defined(EAI_SYSTEM)
1624 char errbuf[PING_ERRMSG_LEN];
1626 dprintf ("getaddrinfo failed\n");
1627 ping_set_error (obj, "getaddrinfo",
1628 #if defined(EAI_SYSTEM)
1629 (ai_return == EAI_SYSTEM)
1630 ? sstrerror (errno, errbuf, sizeof (errbuf)) :
1632 gai_strerror (ai_return));
1637 if (ai_list == NULL)
1638 ping_set_error (obj, "getaddrinfo", "No hosts returned");
1640 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1642 if (ai_ptr->ai_family == AF_INET)
1644 ai_ptr->ai_socktype = SOCK_RAW;
1645 ai_ptr->ai_protocol = IPPROTO_ICMP;
1647 else if (ai_ptr->ai_family == AF_INET6)
1649 ai_ptr->ai_socktype = SOCK_RAW;
1650 ai_ptr->ai_protocol = IPPROTO_ICMPV6;
1654 char errmsg[PING_ERRMSG_LEN];
1656 snprintf (errmsg, PING_ERRMSG_LEN, "Unknown `ai_family': %i", ai_ptr->ai_family);
1657 errmsg[PING_ERRMSG_LEN - 1] = '\0';
1659 dprintf ("%s", errmsg);
1660 ping_set_error (obj, "getaddrinfo", errmsg);
1664 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1665 memset (ph->addr, '\0', sizeof (struct sockaddr_storage));
1666 memcpy (ph->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1667 ph->addrlen = ai_ptr->ai_addrlen;
1668 ph->addrfamily = ai_ptr->ai_family;
1671 if ((ai_ptr->ai_canonname != NULL)
1672 && (strcmp (ph->hostname, ai_ptr->ai_canonname) != 0))
1676 dprintf ("ph->hostname = %s; ai_ptr->ai_canonname = %s;\n",
1677 ph->hostname, ai_ptr->ai_canonname);
1679 old_hostname = ph->hostname;
1680 if ((ph->hostname = strdup (ai_ptr->ai_canonname)) == NULL)
1682 /* strdup failed, falling back to old hostname */
1683 ph->hostname = old_hostname;
1685 else if (old_hostname != NULL)
1687 free (old_hostname);
1690 #endif /* AI_CANONNAME */
1691 } /* for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) */
1693 freeaddrinfo (ai_list);
1696 * Adding in the front is much easier, but then the iterator will
1697 * return the host that was added last as first host. That's just not
1700 if (obj->head == NULL)
1709 while (hptr->next != NULL)
1712 assert ((hptr != NULL) && (hptr->next == NULL));
1716 ph->table_next = obj->table[ph->ident % PING_TABLE_LEN];
1717 obj->table[ph->ident % PING_TABLE_LEN] = ph;
1720 } /* int ping_host_add */
1722 int ping_host_remove (pingobj_t *obj, const char *host)
1724 pinghost_t *pre, *cur, *target;
1726 if ((obj == NULL) || (host == NULL))
1734 if (strcasecmp (host, cur->username) == 0)
1743 ping_set_error (obj, "ping_host_remove", "Host not found");
1748 obj->head = cur->next;
1750 pre->next = cur->next;
1755 cur = obj->table[target->ident % PING_TABLE_LEN];
1763 cur = cur->table_next;
1768 ping_set_error(obj, "ping_host_remove", "Host not found (T)");
1774 obj->table[target->ident % PING_TABLE_LEN] = cur->table_next;
1776 pre->table_next = cur->table_next;
1783 pingobj_iter_t *ping_iterator_get (pingobj_t *obj)
1787 return ((pingobj_iter_t *) obj->head);
1790 pingobj_iter_t *ping_iterator_next (pingobj_iter_t *iter)
1794 return ((pingobj_iter_t *) iter->next);
1797 int ping_iterator_count (pingobj_t *obj)
1803 pingobj_iter_t *iter = obj->head;
1811 int ping_iterator_get_info (pingobj_iter_t *iter, int info,
1812 void *buffer, size_t *buffer_len)
1816 size_t orig_buffer_len = *buffer_len;
1818 if ((iter == NULL) || (buffer_len == NULL))
1821 if ((buffer == NULL) && (*buffer_len != 0 ))
1826 case PING_INFO_USERNAME:
1828 *buffer_len = strlen (iter->username) + 1;
1829 if (orig_buffer_len <= *buffer_len)
1831 /* Since (orig_buffer_len > *buffer_len) `strncpy'
1832 * will copy `*buffer_len' and pad the rest of
1833 * `buffer' with null-bytes */
1834 strncpy (buffer, iter->username, orig_buffer_len);
1838 case PING_INFO_HOSTNAME:
1840 *buffer_len = strlen (iter->hostname) + 1;
1841 if (orig_buffer_len < *buffer_len)
1843 /* Since (orig_buffer_len > *buffer_len) `strncpy'
1844 * will copy `*buffer_len' and pad the rest of
1845 * `buffer' with null-bytes */
1846 strncpy (buffer, iter->hostname, orig_buffer_len);
1850 case PING_INFO_ADDRESS:
1851 ret = getnameinfo ((struct sockaddr *) iter->addr,
1859 if ((ret == EAI_MEMORY)
1861 || (ret == EAI_OVERFLOW)
1865 #if defined(EAI_SYSTEM)
1866 else if (ret == EAI_SYSTEM)
1874 case PING_INFO_FAMILY:
1876 *buffer_len = sizeof (int);
1877 if (orig_buffer_len < sizeof (int))
1879 *((int *) buffer) = iter->addrfamily;
1883 case PING_INFO_LATENCY:
1885 *buffer_len = sizeof (double);
1886 if (orig_buffer_len < sizeof (double))
1888 *((double *) buffer) = iter->latency;
1892 case PING_INFO_DROPPED:
1894 *buffer_len = sizeof (uint32_t);
1895 if (orig_buffer_len < sizeof (uint32_t))
1897 *((uint32_t *) buffer) = iter->dropped;
1901 case PING_INFO_SEQUENCE:
1903 *buffer_len = sizeof (unsigned int);
1904 if (orig_buffer_len < sizeof (unsigned int))
1906 *((unsigned int *) buffer) = (unsigned int) iter->sequence;
1910 case PING_INFO_IDENT:
1912 *buffer_len = sizeof (uint16_t);
1913 if (orig_buffer_len < sizeof (uint16_t))
1915 *((uint16_t *) buffer) = (uint16_t) iter->ident;
1919 case PING_INFO_DATA:
1921 *buffer_len = strlen (iter->data);
1922 if (orig_buffer_len < *buffer_len)
1924 strncpy ((char *) buffer, iter->data, orig_buffer_len);
1928 case PING_INFO_RECV_TTL:
1930 *buffer_len = sizeof (int);
1931 if (orig_buffer_len < sizeof (int))
1933 *((int *) buffer) = iter->recv_ttl;
1937 case PING_INFO_RECV_QOS:
1939 if (*buffer_len>sizeof(unsigned)) *buffer_len=sizeof(unsigned);
1940 if (!*buffer_len) *buffer_len=1;
1941 if (orig_buffer_len < *buffer_len)
1943 memcpy(buffer,&iter->recv_qos,*buffer_len);
1949 } /* ping_iterator_get_info */
1951 void *ping_iterator_get_context (pingobj_iter_t *iter)
1955 return (iter->context);
1958 void ping_iterator_set_context (pingobj_iter_t *iter, void *context)
1962 iter->context = context;