From 1e77b24b84ec51eb9cda3988a692796c8b887ba4 Mon Sep 17 00:00:00 2001
From: Aleksandr Lysikov <lysikov@inbox.ru>
Date: Thu, 13 Dec 2018 15:10:54 +0500
Subject: [PATCH] ping realisation in progress

---
 CMakeLists.txt         |   10 +-
 iputils/ping.c         | 2765 ++++++++++++++++++++--------------------
 iputils/ping.h         |    7 +
 iputils/ping6_common.c | 1383 ++++++++++++++++++++
 4 files changed, 2786 insertions(+), 1379 deletions(-)
 create mode 100755 iputils/ping6_common.c

diff --git a/CMakeLists.txt b/CMakeLists.txt
index f79e7baedc..c6d152e315 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -14,13 +14,15 @@ set(DAP_CHAIN_NET_HEADERS
     )
 
 file(GLOB IPUTILS_SRCS iputils/*.c)
-file(GLOB IPUTILSHEADERS iputils/*.h)
+file(GLOB IPUTILS_HEADERS iputils/*.h)
 
-add_library(${PROJECT_NAME} STATIC ${DAP_CHAIN_NET_SRCS} ${DAP_CHAIN_NET_HEADERS} ${IPUTILS_SRCS} ${IPUTILSHEADERS})
+add_library(${PROJECT_NAME} STATIC ${DAP_CHAIN_NET_SRCS} ${DAP_CHAIN_NET_HEADERS} ${IPUTILS_SRCS} ${IPUTILS_HEADERS})
 
+find_package(PkgConfig REQUIRED)
+pkg_search_module(GLIB REQUIRED glib-2.0)
 
-target_link_libraries(dap_chain_net dap_core dap_crypto dap_chain dap_chain_crypto )
-target_include_directories(dap_chain_net INTERFACE .)
+target_link_libraries(dap_chain_net dap_core dap_crypto dap_chain dap_chain_crypto -lresolv ${GLIB_LDFLAGS})
+target_include_directories(dap_chain_net INTERFACE . PUBLIC ${GLIB_INCLUDE_DIRS})
 
 set(${PROJECT_NAME}_DEFINITIONS CACHE INTERNAL "${PROJECT_NAME}: Definitions" FORCE)
 
diff --git a/iputils/ping.c b/iputils/ping.c
index 979dec0ad5..144c80c878 100644
--- a/iputils/ping.c
+++ b/iputils/ping.c
@@ -56,19 +56,20 @@
 #include <netinet/ip_icmp.h>
 #include <ifaddrs.h>
 #include <math.h>
+#include <glib.h>
 
 #ifndef ICMP_FILTER
 #define ICMP_FILTER	1
 struct icmp_filter {
-	uint32_t	data;
+    uint32_t data;
 };
 #endif
 
 ping_func_set_st ping4_func_set = {
-	.send_probe = ping4_send_probe,
-	.receive_error_msg = ping4_receive_error_msg,
-	.parse_reply = ping4_parse_reply,
-	.install_filter = ping4_install_filter
+    .send_probe = ping4_send_probe,
+    .receive_error_msg = ping4_receive_error_msg,
+    .parse_reply = ping4_parse_reply,
+    .install_filter = ping4_install_filter
 };
 
 #define	MAXIPLEN	60
@@ -80,9 +81,9 @@ static int ts_type;
 static int nroute = 0;
 static uint32_t route[10];
 
-static struct sockaddr_in whereto;	/* who to ping */
+static struct sockaddr_in whereto; /* who to ping */
 static int optlen = 0;
-static int settos = 0;			/* Set TOS, Precendence or other QOS options */
+static int settos = 0; /* Set TOS, Precendence or other QOS options */
 
 static int broadcast_pings = 0;
 
@@ -99,807 +100,826 @@ int pmtudisc = -1;
 
 static void create_socket(socket_st *sock, int family, int socktype, int protocol, int requisite)
 {
-	int do_fallback = 0;
-
-	errno = 0;
-
-	assert(sock->fd == -1);
-	assert(socktype == SOCK_DGRAM || socktype == SOCK_RAW);
-
-	/* Attempt to create a ping socket if requested. Attempt to create a raw
-	 * socket otherwise or as a fallback. Well known errno values follow.
-	 *
-	 * 1) EACCES
-	 *
-	 * Kernel returns EACCES for all ping socket creation attempts when the
-	 * user isn't allowed to use ping socket. A range of group ids is
-	 * configured using the `net.ipv4.ping_group_range` sysctl. Fallback
-	 * to raw socket is necessary.
-	 *
-	 * Kernel returns EACCES for all raw socket creation attempts when the
-	 * process doesn't have the `CAP_NET_RAW` capability.
-	 *
-	 * 2) EAFNOSUPPORT
-	 *
-	 * Kernel returns EAFNOSUPPORT for IPv6 ping or raw socket creation
-	 * attempts when run with IPv6 support disabled (e.g. via `ipv6.disable=1`
-	 * kernel command-line option.
-	 *
-	 * https://github.com/iputils/iputils/issues/32
-	 *
-	 * OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
-	 * EAFNOSUPPORT for all IPv4 ping socket creation attempts due to lack
-	 * of support in the kernel. Fallback to raw socket is necessary.
-	 *
-	 * https://github.com/iputils/iputils/issues/54
-	 *
-	 * 3) EPROTONOSUPPORT
-	 *
-	 * OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
-	 * EPROTONOSUPPORT for all IPv6 ping socket creation attempts due to lack
-	 * of support in the kernel [1]. Debian 9.5 based container with kernel 4.10
-	 * returns EPROTONOSUPPORT also for IPv4 [2]. Fallback to raw socket is
-	 * necessary.
-	 *
-	 * [1] https://github.com/iputils/iputils/issues/54
-	 * [2] https://github.com/iputils/iputils/issues/129
-	 */
-	if (socktype == SOCK_DGRAM)
-		sock->fd = socket(family, socktype, protocol);
-
-	/* Kernel doesn't support ping sockets. */
-	if (sock->fd == -1 && errno == EAFNOSUPPORT && family == AF_INET)
-		do_fallback = 1;
-	if (sock->fd == -1 && errno == EPROTONOSUPPORT)
-		do_fallback = 1;
-
-	/* User is not allowed to use ping sockets. */
-	if (sock->fd == -1 && errno == EACCES)
-		do_fallback = 1;
-
-	if (socktype == SOCK_RAW || do_fallback) {
-		socktype = SOCK_RAW;
-		sock->fd = socket(family, SOCK_RAW, protocol);
-	}
-
-	if (sock->fd == -1) {
-		/* Report error related to disabled IPv6 only when IPv6 also failed or in
-		 * verbose mode. Report other errors always.
-		 */
-		if ((errno == EAFNOSUPPORT && socktype == AF_INET6) || options & F_VERBOSE || requisite)
-			error(0, errno, "socket");
-		if (requisite)
-			exit(2);
-	} else
-		sock->socktype = socktype;
+    int do_fallback = 0;
+
+    errno = 0;
+
+    assert(sock->fd == -1);
+    assert(socktype == SOCK_DGRAM || socktype == SOCK_RAW);
+
+    /* Attempt to create a ping socket if requested. Attempt to create a raw
+     * socket otherwise or as a fallback. Well known errno values follow.
+     *
+     * 1) EACCES
+     *
+     * Kernel returns EACCES for all ping socket creation attempts when the
+     * user isn't allowed to use ping socket. A range of group ids is
+     * configured using the `net.ipv4.ping_group_range` sysctl. Fallback
+     * to raw socket is necessary.
+     *
+     * Kernel returns EACCES for all raw socket creation attempts when the
+     * process doesn't have the `CAP_NET_RAW` capability.
+     *
+     * 2) EAFNOSUPPORT
+     *
+     * Kernel returns EAFNOSUPPORT for IPv6 ping or raw socket creation
+     * attempts when run with IPv6 support disabled (e.g. via `ipv6.disable=1`
+     * kernel command-line option.
+     *
+     * https://github.com/iputils/iputils/issues/32
+     *
+     * OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
+     * EAFNOSUPPORT for all IPv4 ping socket creation attempts due to lack
+     * of support in the kernel. Fallback to raw socket is necessary.
+     *
+     * https://github.com/iputils/iputils/issues/54
+     *
+     * 3) EPROTONOSUPPORT
+     *
+     * OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
+     * EPROTONOSUPPORT for all IPv6 ping socket creation attempts due to lack
+     * of support in the kernel [1]. Debian 9.5 based container with kernel 4.10
+     * returns EPROTONOSUPPORT also for IPv4 [2]. Fallback to raw socket is
+     * necessary.
+     *
+     * [1] https://github.com/iputils/iputils/issues/54
+     * [2] https://github.com/iputils/iputils/issues/129
+     */
+    if(socktype == SOCK_DGRAM)
+        sock->fd = socket(family, socktype, protocol);
+
+    /* Kernel doesn't support ping sockets. */
+    if(sock->fd == -1 && errno == EAFNOSUPPORT && family == AF_INET)
+        do_fallback = 1;
+    if(sock->fd == -1 && errno == EPROTONOSUPPORT)
+        do_fallback = 1;
+
+    /* User is not allowed to use ping sockets. */
+    if(sock->fd == -1 && errno == EACCES)
+        do_fallback = 1;
+
+    if(socktype == SOCK_RAW || do_fallback) {
+        socktype = SOCK_RAW;
+        sock->fd = socket(family, SOCK_RAW, protocol);
+    }
+
+    if(sock->fd == -1) {
+        /* Report error related to disabled IPv6 only when IPv6 also failed or in
+         * verbose mode. Report other errors always.
+         */
+        if((errno == EAFNOSUPPORT && socktype == AF_INET6) || options & F_VERBOSE || requisite)
+            error(0, errno, "socket");
+        if(requisite)
+            exit(2);
+    } else
+        sock->socktype = socktype;
 }
 
 static void set_socket_option(socket_st *sock, int level, int optname, const void *optval, socklen_t olen)
 {
-	if (sock->fd == -1)
-		return;
+    if(sock->fd == -1)
+        return;
 
-	if (setsockopt(sock->fd, level, optname, optval, olen) == -1)
-		error(2, errno, "setsockopt");
+    if(setsockopt(sock->fd, level, optname, optval, olen) == -1)
+        error(2, errno, "setsockopt");
 }
 
 /* Much like stdtod(3, but will fails if str is not valid number. */
 static double ping_strtod(const char *str, const char *err_msg)
 {
-	double num;
-	char *end = NULL;
+    double num;
+    char *end = NULL;
 
-	if (str == NULL || *str == '\0')
-		goto err;
-	errno = 0;
+    if(str == NULL || *str == '\0')
+        goto err;
+    errno = 0;
 #ifdef USE_IDN
-	setlocale(LC_ALL, "C");
+    setlocale(LC_ALL, "C");
 #endif
-	num = strtod(str, &end);
+    num = strtod(str, &end);
 #ifdef USE_IDN
-	setlocale(LC_ALL, "");
+    setlocale(LC_ALL, "");
 #endif
-	if (errno || str == end || (end && *end))
-		goto err;
-	switch (fpclassify(num)) {
-	case FP_NORMAL:
-	case FP_ZERO:
-		break;
-	default:
-		errno = ERANGE;
-		goto err;
-	}
-	return num;
- err:
-	error(2, errno, "%s: %s", err_msg, str);
-	abort();	/* cannot be reached, above error() will exit */
-	return 0.0;
+    if(errno || str == end || (end && *end))
+        goto err;
+    switch (fpclassify(num)) {
+    case FP_NORMAL:
+        case FP_ZERO:
+        break;
+    default:
+        errno = ERANGE;
+        goto err;
+    }
+    return num;
+    err:
+    error(2, errno, "%s: %s", err_msg, str);
+    abort(); /* cannot be reached, above error() will exit */
+    return 0.0;
 }
 
-int
-ping_util()
+static int
+ping_main(int argc, char **argv)
 {
-    return 0;
-}
+    struct addrinfo hints = { .ai_family = AF_UNSPEC, .ai_protocol = IPPROTO_UDP, .ai_socktype = SOCK_DGRAM, .ai_flags =
+    getaddrinfo_flags };
+    struct addrinfo *result, *ai;
+    int status;
+    int ch;
+    socket_st sock4 = { .fd = -1 };
+    socket_st sock6 = { .fd = -1 };
+    char *target;
 
-int
-main2(int argc, char **argv)
-{
-	struct addrinfo hints = { .ai_family = AF_UNSPEC, .ai_protocol = IPPROTO_UDP, .ai_socktype = SOCK_DGRAM, .ai_flags = getaddrinfo_flags };
-	struct addrinfo *result, *ai;
-	int status;
-	int ch;
-	socket_st sock4 = { .fd = -1 };
-	socket_st sock6 = { .fd = -1 };
-	char *target;
-
-	limit_capabilities();
+    limit_capabilities();
 
 #ifdef USE_IDN
-	setlocale(LC_ALL, "");
-	if (!strcmp(setlocale(LC_ALL, NULL), "C"))
-		hints.ai_flags &= ~ AI_CANONIDN;
+    setlocale(LC_ALL, "");
+    if (!strcmp(setlocale(LC_ALL, NULL), "C"))
+    hints.ai_flags &= ~ AI_CANONIDN;
 #endif
 
-	/* Support being called using `ping4` or `ping6` symlinks */
-	if (argv[0][strlen(argv[0])-1] == '4')
-		hints.ai_family = AF_INET;
-	else if (argv[0][strlen(argv[0])-1] == '6')
-		hints.ai_family = AF_INET6;
-
-	/* Parse command line options */
-	while ((ch = getopt(argc, argv, "h?" "4bRT:" "6F:N:" "aABc:dDfi:I:l:Lm:M:nOp:qQ:rs:S:t:UvVw:W:")) != EOF) {
-		switch(ch) {
-		/* IPv4 specific options */
-		case '4':
-			if (hints.ai_family != AF_UNSPEC)
-				error(2, 0, "only one -4 or -6 option may be specified");
-			hints.ai_family = AF_INET;
-			break;
-		case 'b':
-			broadcast_pings = 1;
-			break;
-		case 'R':
-			if (options & F_TIMESTAMP)
-				error(2, 0, "only one of -T or -R may be used");
-			options |= F_RROUTE;
-			break;
-		case 'T':
-			if (options & F_RROUTE)
-				error(2, 0, "only one of -T or -R may be used");
-			options |= F_TIMESTAMP;
-			if (strcmp(optarg, "tsonly") == 0)
-				ts_type = IPOPT_TS_TSONLY;
-			else if (strcmp(optarg, "tsandaddr") == 0)
-				ts_type = IPOPT_TS_TSANDADDR;
-			else if (strcmp(optarg, "tsprespec") == 0)
-				ts_type = IPOPT_TS_PRESPEC;
-			else
-				error(2, 0, "invalid timestamp type: %s", optarg);
-			break;
-		/* IPv6 specific options */
-		case '6':
-			if (hints.ai_family != AF_UNSPEC)
-				error(2, 0, "only one -4 or -6 option may be specified");
-			hints.ai_family = AF_INET6;
-			break;
-		case 'F':
-			flowlabel = parseflow(optarg);
-			options |= F_FLOWINFO;
-			break;
-		case 'N':
-			if (niquery_option_handler(optarg) < 0)
-				usage();
-			hints.ai_socktype = SOCK_RAW;
-			break;
-		/* Common options */
-		case 'a':
-			options |= F_AUDIBLE;
-			break;
-		case 'A':
-			options |= F_ADAPTIVE;
-			break;
-		case 'B':
-			options |= F_STRICTSOURCE;
-			break;
-		case 'c':
-			npackets = atoi(optarg);
-			if (npackets <= 0)
-				error(2, 0, "bad number of packets to transmit: %ld", npackets);
-			break;
-		case 'd':
-			options |= F_SO_DEBUG;
-			break;
-		case 'D':
-			options |= F_PTIMEOFDAY;
-			break;
-		case 'i':
-		{
-			double optval;
-
-			optval = ping_strtod(optarg, "bad timing interval");
-			if (isgreater(optval, (double)(INT_MAX / 1000)))
-				error(2, 0, "bad timing interval: %s", optarg);
-			interval = (int)(optval * 1000);
-			options |= F_INTERVAL;
-		}
-			break;
-		case 'I':
-			/* IPv6 */
-			if (strchr(optarg, ':')) {
-				char *p, *addr = strdup(optarg);
-
-				if (!addr)
-					error(2, errno, "cannot copy: %s", optarg);
-
-				p = strchr(addr, SCOPE_DELIMITER);
-				if (p) {
-					*p = '\0';
-					device = optarg + (p - addr) + 1;
-				}
-
-				if (inet_pton(AF_INET6, addr, (char*)&source6.sin6_addr) <= 0)
-					error(2, 0, "invalid source address: %s", optarg);
-
-				options |= F_STRICTSOURCE;
-
-				free(addr);
-			} else if (inet_pton(AF_INET, optarg, &source.sin_addr) > 0) {
-				options |= F_STRICTSOURCE;
-			} else {
-				device = optarg;
-			}
-			break;
-		case 'l':
-			preload = atoi(optarg);
-			if (preload <= 0)
-				error(2, 0, "bad preload value: %s, should be 1..%d", optarg, MAX_DUP_CHK);
-			if (preload > MAX_DUP_CHK)
-				preload = MAX_DUP_CHK;
-			if (uid && preload > 3)
-				error(2, 0, "cannot set preload to value greater than 3: %d", preload);
-			break;
-		case 'L':
-			options |= F_NOLOOP;
-			break;
-		case 'm':
-		{
-			char *endp;
-			mark = (int)strtoul(optarg, &endp, 10);
-			if (mark < 0 || *endp != '\0')
-				error(2, 0, "mark cannot be negative: %s", optarg);
-			options |= F_MARK;
-			break;
-		}
-		case 'M':
-			if (strcmp(optarg, "do") == 0)
-				pmtudisc = IP_PMTUDISC_DO;
-			else if (strcmp(optarg, "dont") == 0)
-				pmtudisc = IP_PMTUDISC_DONT;
-			else if (strcmp(optarg, "want") == 0)
-				pmtudisc = IP_PMTUDISC_WANT;
-			else
-				error(2, 0, "invalid -M argument: %s", optarg);
-			break;
-		case 'n':
-			options |= F_NUMERIC;
-			break;
-		case 'O':
-			options |= F_OUTSTANDING;
-			break;
-		case 'f':
-			/* avoid `getaddrinfo()` during flood */
-			options |= F_FLOOD | F_NUMERIC;
-			setbuf(stdout, (char *)NULL);
-			break;
-		case 'p':
-			options |= F_PINGFILLED;
-			fill(optarg, outpack, sizeof(outpack));
-			break;
-		case 'q':
-			options |= F_QUIET;
-			break;
-		case 'Q':
-			settos = parsetos(optarg); /* IPv4 */
-			tclass = settos; /* IPv6 */
-			break;
-		case 'r':
-			options |= F_SO_DONTROUTE;
-			break;
-		case 's':
-			datalen = atoi(optarg);
-			if (datalen < 0)
-				error(2, 0, "illegal packet size: %d", datalen);
-			if (datalen > MAXPACKET - 8)
-				error(2, 0, "packet size too large: %d", datalen);
-			break;
-		case 'S':
-			sndbuf = atoi(optarg);
-			if (sndbuf <= 0)
-				error(2, 0, "bad sndbuf value: %s", optarg);
-			break;
-		case 't':
-			options |= F_TTL;
-			ttl = atoi(optarg);
-			if (ttl < 0 || ttl > 255)
-				error(2, 0, "ttl out of range: %s", optarg);
-			break;
-		case 'U':
-			options |= F_LATENCY;
-			break;
-		case 'v':
-			options |= F_VERBOSE;
-			break;
-		case 'V':
-			printf(IPUTILS_VERSION("ping"));
-			exit(0);
-		case 'w':
-			deadline = atoi(optarg);
-			if (deadline < 0)
-				error(2, 0, "bad wait time: %s", optarg);
-			break;
-		case 'W':
-		{
-			double optval;
-
-			optval = ping_strtod(optarg, "bad linger time");
-			if (isless(optval, 0.001) || isgreater(optval, (double)(INT_MAX / 1000)))
-				error(2, 0, "bad linger time: %s", optarg);
-			/* lingertime will be converted to usec later */
-			lingertime = (int)(optval * 1000);
-		}
-			break;
-		default:
-			usage();
-			break;
-		}
-	}
-
-	argc -= optind;
-	argv += optind;
-
-	if (!argc)
-		error(1, EDESTADDRREQ, "usage error");
-
-	target = argv[argc-1];
-
-	/* Create sockets */
-	enable_capability_raw();
-	if (hints.ai_family != AF_INET6)
-		create_socket(&sock4, AF_INET, hints.ai_socktype, IPPROTO_ICMP, hints.ai_family == AF_INET);
-	if (hints.ai_family != AF_INET) {
-		create_socket(&sock6, AF_INET6, hints.ai_socktype, IPPROTO_ICMPV6, sock4.fd == -1);
-		/* This may not be needed if both protocol versions always had the same value, but
-		 * since I don't know that, it's better to be safe than sorry. */
-		pmtudisc = pmtudisc == IP_PMTUDISC_DO   ? IPV6_PMTUDISC_DO :
-			   pmtudisc == IP_PMTUDISC_DONT ? IPV6_PMTUDISC_DONT :
-			   pmtudisc == IP_PMTUDISC_WANT ? IPV6_PMTUDISC_WANT : pmtudisc;
-	}
-	disable_capability_raw();
-
-	/* Limit address family on single-protocol systems */
-	if (hints.ai_family == AF_UNSPEC) {
-		if (sock4.fd == -1)
-			hints.ai_family = AF_INET6;
-		else if (sock6.fd == -1)
-			hints.ai_family = AF_INET;
-	}
-
-	/* Set socket options */
-	if (settos)
-		set_socket_option(&sock4, IPPROTO_IP, IP_TOS, &settos, sizeof settos);
-	if (tclass)
-		set_socket_option(&sock6, IPPROTO_IPV6, IPV6_TCLASS, &tclass, sizeof tclass);
-
-	status = getaddrinfo(target, NULL, &hints, &result);
-	if (status)
-		error(2, 0, "%s: %s", target, gai_strerror(status));
-
-	for (ai = result; ai; ai = ai->ai_next) {
-		switch (ai->ai_family) {
-		case AF_INET:
-			status = ping4_run(argc, argv, ai, &sock4);
-			break;
-		case AF_INET6:
-			status = ping6_run(argc, argv, ai, &sock6);
-			break;
-		default:
-			error(2, 0, "unknown protocol family: %d", ai->ai_family);
-		}
-
-		if (status == 0)
-			break;
-	}
-
-	freeaddrinfo(result);
-
-	return status;
+    /* Support being called using `ping4` or `ping6` symlinks */
+    if(argv[0][strlen(argv[0]) - 1] == '4')
+        hints.ai_family = AF_INET;
+    else if(argv[0][strlen(argv[0]) - 1] == '6')
+        hints.ai_family = AF_INET6;
+
+    /* Parse command line options */
+    while((ch = getopt(argc, argv, "h?" "4bRT:" "6F:N:" "aABc:dDfi:I:l:Lm:M:nOp:qQ:rs:S:t:UvVw:W:")) != EOF) {
+        switch (ch) {
+        /* IPv4 specific options */
+        case '4':
+            if(hints.ai_family != AF_UNSPEC)
+                error(2, 0, "only one -4 or -6 option may be specified");
+            hints.ai_family = AF_INET;
+            break;
+        case 'b':
+            broadcast_pings = 1;
+            break;
+        case 'R':
+            if(options & F_TIMESTAMP)
+                error(2, 0, "only one of -T or -R may be used");
+            options |= F_RROUTE;
+            break;
+        case 'T':
+            if(options & F_RROUTE)
+                error(2, 0, "only one of -T or -R may be used");
+            options |= F_TIMESTAMP;
+            if(strcmp(optarg, "tsonly") == 0)
+                ts_type = IPOPT_TS_TSONLY;
+            else if(strcmp(optarg, "tsandaddr") == 0)
+                ts_type = IPOPT_TS_TSANDADDR;
+            else if(strcmp(optarg, "tsprespec") == 0)
+                ts_type = IPOPT_TS_PRESPEC;
+            else
+                error(2, 0, "invalid timestamp type: %s", optarg);
+            break;
+            /* IPv6 specific options */
+        case '6':
+            if(hints.ai_family != AF_UNSPEC)
+                error(2, 0, "only one -4 or -6 option may be specified");
+            hints.ai_family = AF_INET6;
+            break;
+        case 'F':
+            flowlabel = parseflow(optarg);
+            options |= F_FLOWINFO;
+            break;
+        case 'N':
+            if(niquery_option_handler(optarg) < 0)
+                usage();
+            hints.ai_socktype = SOCK_RAW;
+            break;
+            /* Common options */
+        case 'a':
+            options |= F_AUDIBLE;
+            break;
+        case 'A':
+            options |= F_ADAPTIVE;
+            break;
+        case 'B':
+            options |= F_STRICTSOURCE;
+            break;
+        case 'c':
+            npackets = atoi(optarg);
+            if(npackets <= 0)
+                error(2, 0, "bad number of packets to transmit: %ld", npackets);
+            break;
+        case 'd':
+            options |= F_SO_DEBUG;
+            break;
+        case 'D':
+            options |= F_PTIMEOFDAY;
+            break;
+        case 'i':
+            {
+            double optval;
+
+            optval = ping_strtod(optarg, "bad timing interval");
+            if(isgreater(optval, (double)(INT_MAX / 1000)))
+                error(2, 0, "bad timing interval: %s", optarg);
+            interval = (int) (optval * 1000);
+            options |= F_INTERVAL;
+        }
+            break;
+        case 'I':
+            /* IPv6 */
+            if(strchr(optarg, ':')) {
+                char *p, *addr = strdup(optarg);
+
+                if(!addr)
+                    error(2, errno, "cannot copy: %s", optarg);
+
+                p = strchr(addr, SCOPE_DELIMITER);
+                if(p) {
+                    *p = '\0';
+                    device = optarg + (p - addr) + 1;
+                }
+
+                if(inet_pton(AF_INET6, addr, (char*) &source6.sin6_addr) <= 0)
+                    error(2, 0, "invalid source address: %s", optarg);
+
+                options |= F_STRICTSOURCE;
+
+                free(addr);
+            } else if(inet_pton(AF_INET, optarg, &source.sin_addr) > 0) {
+                options |= F_STRICTSOURCE;
+            } else {
+                device = optarg;
+            }
+            break;
+        case 'l':
+            preload = atoi(optarg);
+            if(preload <= 0)
+                error(2, 0, "bad preload value: %s, should be 1..%d", optarg, MAX_DUP_CHK);
+            if(preload > MAX_DUP_CHK)
+                preload = MAX_DUP_CHK;
+            if(uid && preload > 3)
+                error(2, 0, "cannot set preload to value greater than 3: %d", preload);
+            break;
+        case 'L':
+            options |= F_NOLOOP;
+            break;
+        case 'm':
+            {
+            char *endp;
+            mark = (int) strtoul(optarg, &endp, 10);
+            if(mark < 0 || *endp != '\0')
+                error(2, 0, "mark cannot be negative: %s", optarg);
+            options |= F_MARK;
+            break;
+        }
+        case 'M':
+            if(strcmp(optarg, "do") == 0)
+                pmtudisc = IP_PMTUDISC_DO;
+            else if(strcmp(optarg, "dont") == 0)
+                pmtudisc = IP_PMTUDISC_DONT;
+            else if(strcmp(optarg, "want") == 0)
+                pmtudisc = IP_PMTUDISC_WANT;
+            else
+                error(2, 0, "invalid -M argument: %s", optarg);
+            break;
+        case 'n':
+            options |= F_NUMERIC;
+            break;
+        case 'O':
+            options |= F_OUTSTANDING;
+            break;
+        case 'f':
+            /* avoid `getaddrinfo()` during flood */
+            options |= F_FLOOD | F_NUMERIC;
+            setbuf(stdout, (char *) NULL);
+            break;
+        case 'p':
+            options |= F_PINGFILLED;
+            fill(optarg, outpack, sizeof(outpack));
+            break;
+        case 'q':
+            options |= F_QUIET;
+            break;
+        case 'Q':
+            settos = parsetos(optarg); /* IPv4 */
+            tclass = settos; /* IPv6 */
+            break;
+        case 'r':
+            options |= F_SO_DONTROUTE;
+            break;
+        case 's':
+            datalen = atoi(optarg);
+            if(datalen < 0)
+                error(2, 0, "illegal packet size: %d", datalen);
+            if(datalen > MAXPACKET - 8)
+                error(2, 0, "packet size too large: %d", datalen);
+            break;
+        case 'S':
+            sndbuf = atoi(optarg);
+            if(sndbuf <= 0)
+                error(2, 0, "bad sndbuf value: %s", optarg);
+            break;
+        case 't':
+            options |= F_TTL;
+            ttl = atoi(optarg);
+            if(ttl < 0 || ttl > 255)
+                error(2, 0, "ttl out of range: %s", optarg);
+            break;
+        case 'U':
+            options |= F_LATENCY;
+            break;
+        case 'v':
+            options |= F_VERBOSE;
+            break;
+        case 'V':
+            printf(IPUTILS_VERSION("ping"));
+            exit(0);
+        case 'w':
+            deadline = atoi(optarg);
+            if(deadline < 0)
+                error(2, 0, "bad wait time: %s", optarg);
+            break;
+        case 'W':
+            {
+            double optval;
+
+            optval = ping_strtod(optarg, "bad linger time");
+            if(isless(optval, 0.001) || isgreater(optval, (double)(INT_MAX / 1000)))
+                error(2, 0, "bad linger time: %s", optarg);
+            /* lingertime will be converted to usec later */
+            lingertime = (int) (optval * 1000);
+        }
+            break;
+        default:
+            usage();
+            break;
+        }
+    }
+
+    argc -= optind;
+    argv += optind;
+
+    if(!argc)
+        error(1, EDESTADDRREQ, "usage error");
+
+    target = argv[argc - 1];
+
+    /* Create sockets */
+    enable_capability_raw();
+    if(hints.ai_family != AF_INET6)
+        create_socket(&sock4, AF_INET, hints.ai_socktype, IPPROTO_ICMP, hints.ai_family == AF_INET);
+    if(hints.ai_family != AF_INET) {
+        create_socket(&sock6, AF_INET6, hints.ai_socktype, IPPROTO_ICMPV6, sock4.fd == -1);
+        /* This may not be needed if both protocol versions always had the same value, but
+         * since I don't know that, it's better to be safe than sorry. */
+        pmtudisc = pmtudisc == IP_PMTUDISC_DO ? IPV6_PMTUDISC_DO :
+                   pmtudisc == IP_PMTUDISC_DONT ? IPV6_PMTUDISC_DONT :
+                   pmtudisc == IP_PMTUDISC_WANT ? IPV6_PMTUDISC_WANT : pmtudisc;
+    }
+    disable_capability_raw();
+
+    /* Limit address family on single-protocol systems */
+    if(hints.ai_family == AF_UNSPEC) {
+        if(sock4.fd == -1)
+            hints.ai_family = AF_INET6;
+        else if(sock6.fd == -1)
+            hints.ai_family = AF_INET;
+    }
+
+    /* Set socket options */
+    if(settos)
+        set_socket_option(&sock4, IPPROTO_IP, IP_TOS, &settos, sizeof settos);
+    if(tclass)
+        set_socket_option(&sock6, IPPROTO_IPV6, IPV6_TCLASS, &tclass, sizeof tclass);
+
+    status = getaddrinfo(target, NULL, &hints, &result);
+    if(status)
+        error(2, 0, "%s: %s", target, gai_strerror(status));
+
+    for(ai = result; ai; ai = ai->ai_next) {
+        switch (ai->ai_family) {
+        case AF_INET:
+            status = ping4_run(argc, argv, ai, &sock4);
+            break;
+        case AF_INET6:
+            status = ping6_run(argc, argv, ai, &sock6);
+            break;
+        default:
+            error(2, 0, "unknown protocol family: %d", ai->ai_family);
+        }
+
+        if(status == 0)
+            break;
+    }
+
+    freeaddrinfo(result);
+
+    return status;
 }
 
-int ping4_run(int argc, char **argv, struct addrinfo *ai, socket_st *sock)
+int ping_util(const char *addr, int count)
 {
-	static const struct addrinfo hints = { .ai_family = AF_INET, .ai_protocol = IPPROTO_UDP, .ai_flags = getaddrinfo_flags };
-	int hold, packlen;
-	unsigned char *packet;
-	char *target;
-	char hnamebuf[NI_MAXHOST];
-	unsigned char rspace[3 + 4 * NROUTES + 1];	/* record route space */
-	uint32_t *tmp_rspace;
-
-	if (argc > 1) {
-		if (options & F_RROUTE)
-			usage();
-		else if (options & F_TIMESTAMP) {
-			if (ts_type != IPOPT_TS_PRESPEC)
-				usage();
-			if (argc > 5)
-				usage();
-		} else {
-			if (argc > 10)
-				usage();
-			options |= F_SOURCEROUTE;
-		}
-	}
-	while (argc > 0) {
-		target = *argv;
-
-		memset((char *)&whereto, 0, sizeof(whereto));
-		whereto.sin_family = AF_INET;
-		if (inet_aton(target, &whereto.sin_addr) == 1) {
-			hostname = target;
-			if (argc == 1)
-				options |= F_NUMERIC;
-		} else {
-			struct addrinfo *result = NULL;
-			int status;
-
-			if (argc > 1 || !ai) {
-				status = getaddrinfo(target, NULL, &hints, &result);
-				if (status)
-					error(2, 0, "%s: %s", target, gai_strerror(status));
-				ai = result;
-			}
-
-			memcpy(&whereto, ai->ai_addr, sizeof whereto);
-			memset(hnamebuf, 0, sizeof hnamebuf);
-			if (ai->ai_canonname)
-				strncpy(hnamebuf, ai->ai_canonname, sizeof hnamebuf - 1);
-			hostname = hnamebuf;
-
-			if (result)
-				freeaddrinfo(result);
-		}
-		if (argc > 1)
-			route[nroute++] = whereto.sin_addr.s_addr;
-		argc--;
-		argv++;
-	}
-
-	if (source.sin_addr.s_addr == 0) {
-		socklen_t alen;
-		struct sockaddr_in dst = whereto;
-		int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
-
-		if (probe_fd < 0)
-			error(2, errno, "socket");
-		if (device) {
-			struct ifreq ifr;
-			int i;
-			int fds[2] = {probe_fd, sock->fd};
-
-			memset(&ifr, 0, sizeof(ifr));
-			strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
-
-			for (i = 0; i < 2; i++) {
-				int fd = fds[i];
-				int rc;
-				int errno_save;
-
-				enable_capability_raw();
-				rc = setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1);
-				errno_save = errno;
-				disable_capability_raw();
-
-				if (rc == -1) {
-					if (IN_MULTICAST(ntohl(dst.sin_addr.s_addr))) {
-						struct ip_mreqn imr;
-						if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0)
-							error(2, 0, "unknown iface: %s", device);
-						memset(&imr, 0, sizeof(imr));
-						imr.imr_ifindex = ifr.ifr_ifindex;
-						if (setsockopt(fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1)
-							error(2, errno, "IP_MULTICAST_IF");
-					} else
-						error(2, errno_save, "SO_BINDTODEVICE %s", device);
-				}
-			}
-		}
-
-		if (settos &&
-		    setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *)&settos, sizeof(int)) < 0)
-			error(0, errno, "warning: QOS sockopts");
-
-		dst.sin_port = htons(1025);
-		if (nroute)
-			dst.sin_addr.s_addr = route[0];
-		if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
-			if (errno == EACCES) {
-				if (broadcast_pings == 0)
-					error(2, 0,
-						"Do you want to ping broadcast? Then -b. If not, check your local firewall rules");
-				fprintf(stderr, "WARNING: pinging broadcast address\n");
-				if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
-					       &broadcast_pings, sizeof(broadcast_pings)) < 0)
-					error(2, errno, "cannot set broadcasting");
-				if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1)
-					error(2, errno, "connect");
-			} else
-				error(2, errno, "connect");
-		}
-		alen = sizeof(source);
-		if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1)
-			error(2, errno, "getsockname");
-		source.sin_port = 0;
-
-		if (device) {
-			struct ifaddrs *ifa0, *ifa;
-			int ret;
-
-			ret = getifaddrs(&ifa0);
-			if (ret)
-				error(2, errno, "gatifaddrs failed");
-			for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
-				if (!ifa->ifa_name || !ifa->ifa_addr ||
-				    ifa->ifa_addr->sa_family != AF_INET)
-					continue;
-				if (!strcmp(ifa->ifa_name, device) &&
-				    !memcmp(&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
-					    &source.sin_addr, sizeof(source.sin_addr)))
-					break;
-			}
-			if (ifa && !memcmp(&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
-			    &dst.sin_addr, sizeof(source.sin_addr))) {
-				enable_capability_raw();
-				setsockopt(sock->fd, SOL_SOCKET, SO_BINDTODEVICE, "", 0);
-				disable_capability_raw();
-			}
-			freeifaddrs(ifa0);
-			if (!ifa)
-				error(0, 0, "Warning: source address might be selected on device other than: %s", device);
-		}
-		close(probe_fd);
-	} while (0);
-
-	if (whereto.sin_addr.s_addr == 0)
-		whereto.sin_addr.s_addr = source.sin_addr.s_addr;
-
-	if (device) {
-		struct ifreq ifr;
-
-		memset(&ifr, 0, sizeof(ifr));
-		strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
-		if (ioctl(sock->fd, SIOCGIFINDEX, &ifr) < 0)
-			error(2, 0, "unknown iface: %s", device);
-	}
-
-	if (broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
-		if (uid) {
-			if (interval < 1000)
-				error(2, 0, "broadcast ping with too short interval: %d", interval);
-			if (pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO)
-				error(2, 0, "broadcast ping does not fragment");
-		}
-		if (pmtudisc < 0)
-			pmtudisc = IP_PMTUDISC_DO;
-	}
-
-	if (pmtudisc >= 0) {
-		if (setsockopt(sock->fd, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof pmtudisc) == -1)
-			error(2, errno, "IP_MTU_DISCOVER");
-	}
-
-	if ((options&F_STRICTSOURCE) &&
-	    bind(sock->fd, (struct sockaddr *) &source, sizeof source) == -1)
-		error(2, errno, "bind");
-
-	if (sock->socktype == SOCK_RAW) {
-		struct icmp_filter filt;
-		filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
-			      (1<<ICMP_DEST_UNREACH)|
-			      (1<<ICMP_TIME_EXCEEDED)|
-			      (1<<ICMP_PARAMETERPROB)|
-			      (1<<ICMP_REDIRECT)|
-			      (1<<ICMP_ECHOREPLY));
-		if (setsockopt(sock->fd, SOL_RAW, ICMP_FILTER, &filt, sizeof filt) == -1)
-			error(0, errno, "WARNING: setsockopt(ICMP_FILTER)");
-	}
-
-	hold = 1;
-	if (setsockopt(sock->fd, SOL_IP, IP_RECVERR, &hold, sizeof hold))
-		error(0, 0, "WARNING: your kernel is veeery old. No problems.");
-
-	if (sock->socktype == SOCK_DGRAM) {
-		if (setsockopt(sock->fd, SOL_IP, IP_RECVTTL, &hold, sizeof hold))
-			error(0, errno, "WARNING: setsockopt(IP_RECVTTL)");
-		if (setsockopt(sock->fd, SOL_IP, IP_RETOPTS, &hold, sizeof hold))
-			error(0, errno, "WARNING: setsockopt(IP_RETOPTS)");
-	}
-
-	/* record route option */
-	if (options & F_RROUTE) {
-		memset(rspace, 0, sizeof(rspace));
-		rspace[0] = IPOPT_NOP;
-		rspace[1+IPOPT_OPTVAL] = IPOPT_RR;
-		rspace[1+IPOPT_OLEN] = sizeof(rspace)-1;
-		rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
-		optlen = 40;
-		if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, sizeof rspace) < 0)
-			error(2, errno, "record route");
-	}
-	if (options & F_TIMESTAMP) {
-		memset(rspace, 0, sizeof(rspace));
-		rspace[0] = IPOPT_TIMESTAMP;
-		rspace[1] = (ts_type==IPOPT_TS_TSONLY ? 40 : 36);
-		rspace[2] = 5;
-		rspace[3] = ts_type;
-		if (ts_type == IPOPT_TS_PRESPEC) {
-			int i;
-			rspace[1] = 4+nroute*8;
-			for (i = 0; i < nroute; i++) {
-				tmp_rspace = (uint32_t*)&rspace[4+i*8];
-				*tmp_rspace = route[i];
-			}
-		}
-		if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
-			rspace[3] = 2;
-			if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0)
-				error(2, errno, "ts option");
-		}
-		optlen = 40;
-	}
-	if (options & F_SOURCEROUTE) {
-		int i;
-		memset(rspace, 0, sizeof(rspace));
-		rspace[0] = IPOPT_NOOP;
-		rspace[1+IPOPT_OPTVAL] = (options & F_SO_DONTROUTE) ? IPOPT_SSRR
-			: IPOPT_LSRR;
-		rspace[1+IPOPT_OLEN] = 3 + nroute*4;
-		rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
-		for (i = 0; i < nroute; i++) {
-			tmp_rspace = (uint32_t*)&rspace[4+i*4];
-			*tmp_rspace = route[i];
-		}
-
-		if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute*4) < 0)
-			error(2, errno, "record route");
-		optlen = 40;
-	}
-
-	/* Estimate memory eaten by single packet. It is rough estimate.
-	 * Actually, for small datalen's it depends on kernel side a lot. */
-	hold = datalen + 8;
-	hold += ((hold+511)/512)*(optlen + 20 + 16 + 64 + 160);
-	sock_setbufs(sock, hold);
-
-	if (broadcast_pings) {
-		if (setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, &broadcast_pings, sizeof broadcast_pings) < 0)
-			error(2, errno, "cannot set broadcasting");
-	}
-
-	if (options & F_NOLOOP) {
-		int loop = 0;
-		if (setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof loop) == -1)
-			error(2, errno, "cannot disable multicast loopback");
-	}
-	if (options & F_TTL) {
-		int ittl = ttl;
-		if (setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof ttl) == -1)
-			error(2, errno, "cannot set multicast time-to-live");
-		if (setsockopt(sock->fd, IPPROTO_IP, IP_TTL, &ittl, sizeof ittl) == -1)
-			error(2, errno, "cannot set unicast time-to-live");
-	}
-
-	if (datalen > 0xFFFF - 8 - optlen - 20)
-		error(2, 0, "packet size %d is too large. Maximum is %d",
-		      datalen, 0xFFFF - 8 - 20 - optlen);
-
-	if (datalen >= (int) sizeof(struct timeval))	/* can we time transfer */
-		timing = 1;
-	packlen = datalen + MAXIPLEN + MAXICMPLEN;
-	if (!(packet = (unsigned char *)malloc((unsigned int)packlen)))
-		error(2, errno, "memory allocation failed");
-
-	printf("PING %s (%s) ", hostname, inet_ntoa(whereto.sin_addr));
-	if (device || (options&F_STRICTSOURCE))
-		printf("from %s %s: ", inet_ntoa(source.sin_addr), device ? device : "");
-	printf("%d(%d) bytes of data.\n", datalen, datalen+8+optlen+20);
-
-	setup(sock);
-
-	main_loop(&ping4_func_set, sock, packet, packlen);
+
+    /*
+     rights for /bin/ping: -rwsr-xr-x 1 root root
+     current parametr:
+     # sysctl net.ipv4.ping_group_range
+     net.ipv4.ping_group_range = 1   0
+     Need change range for other users:
+     # sysctl net.ipv4.ping_group_range="1 65000"
+
+     */
+    int argc = 3;
+    const char *argv[argc];
+    argv[0] = "ping4";
+    argv[1] = g_strdup_printf("-c%d", count);
+    argv[2] = addr;
+    int res = ping_main(argc, (char**) argv);
+    return res;
 }
 
+int ping4_run(int argc, char **argv, struct addrinfo *ai, socket_st *sock)
+{
+    static const struct addrinfo hints = { .ai_family = AF_INET, .ai_protocol = IPPROTO_UDP, .ai_flags =
+    getaddrinfo_flags };
+    int hold, packlen;
+    unsigned char *packet;
+    char *target;
+    char hnamebuf[NI_MAXHOST];
+    unsigned char rspace[3 + 4 * NROUTES + 1]; /* record route space */
+    uint32_t *tmp_rspace;
+
+    if(argc > 1) {
+        if(options & F_RROUTE)
+            usage();
+        else if(options & F_TIMESTAMP) {
+            if(ts_type != IPOPT_TS_PRESPEC)
+                usage();
+            if(argc > 5)
+                usage();
+        } else {
+            if(argc > 10)
+                usage();
+            options |= F_SOURCEROUTE;
+        }
+    }
+    while(argc > 0) {
+        target = *argv;
+
+        memset((char *) &whereto, 0, sizeof(whereto));
+        whereto.sin_family = AF_INET;
+        if(inet_aton(target, &whereto.sin_addr) == 1) {
+            hostname = target;
+            if(argc == 1)
+                options |= F_NUMERIC;
+        } else {
+            struct addrinfo *result = NULL;
+            int status;
+
+            if(argc > 1 || !ai) {
+                status = getaddrinfo(target, NULL, &hints, &result);
+                if(status)
+                    error(2, 0, "%s: %s", target, gai_strerror(status));
+                ai = result;
+            }
+
+            memcpy(&whereto, ai->ai_addr, sizeof whereto);
+            memset(hnamebuf, 0, sizeof hnamebuf);
+            if(ai->ai_canonname)
+                strncpy(hnamebuf, ai->ai_canonname, sizeof hnamebuf - 1);
+            hostname = hnamebuf;
+
+            if(result)
+                freeaddrinfo(result);
+        }
+        if(argc > 1)
+            route[nroute++] = whereto.sin_addr.s_addr;
+        argc--;
+        argv++;
+    }
+
+    if(source.sin_addr.s_addr == 0) {
+        socklen_t alen;
+        struct sockaddr_in dst = whereto;
+        int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
+
+        if(probe_fd < 0)
+            error(2, errno, "socket");
+        if(device) {
+            struct ifreq ifr;
+            int i;
+            int fds[2] = { probe_fd, sock->fd };
+
+            memset(&ifr, 0, sizeof(ifr));
+            strncpy(ifr.ifr_name, device, IFNAMSIZ - 1);
+
+            for(i = 0; i < 2; i++) {
+                int fd = fds[i];
+                int rc;
+                int errno_save;
+
+                enable_capability_raw();
+                rc = setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device) + 1);
+                errno_save = errno;
+                disable_capability_raw();
+
+                if(rc == -1) {
+                    if(IN_MULTICAST(ntohl(dst.sin_addr.s_addr))) {
+                        struct ip_mreqn imr;
+                        if(ioctl(fd, SIOCGIFINDEX, &ifr) < 0)
+                            error(2, 0, "unknown iface: %s", device);
+                        memset(&imr, 0, sizeof(imr));
+                        imr.imr_ifindex = ifr.ifr_ifindex;
+                        if(setsockopt(fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1)
+                            error(2, errno, "IP_MULTICAST_IF");
+                    } else
+                        error(2, errno_save, "SO_BINDTODEVICE %s", device);
+                }
+            }
+        }
+
+        if(settos &&
+                setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *) &settos, sizeof(int)) < 0)
+            error(0, errno, "warning: QOS sockopts");
+
+        dst.sin_port = htons(1025);
+        if(nroute)
+            dst.sin_addr.s_addr = route[0];
+        if(connect(probe_fd, (struct sockaddr*) &dst, sizeof(dst)) == -1) {
+            if(errno == EACCES) {
+                if(broadcast_pings == 0)
+                    error(2, 0,
+                            "Do you want to ping broadcast? Then -b. If not, check your local firewall rules");
+                fprintf(stderr, "WARNING: pinging broadcast address\n");
+                if(setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
+                        &broadcast_pings, sizeof(broadcast_pings)) < 0)
+                    error(2, errno, "cannot set broadcasting");
+                if(connect(probe_fd, (struct sockaddr*) &dst, sizeof(dst)) == -1)
+                    error(2, errno, "connect");
+            } else
+                error(2, errno, "connect");
+        }
+        alen = sizeof(source);
+        if(getsockname(probe_fd, (struct sockaddr*) &source, &alen) == -1)
+            error(2, errno, "getsockname");
+        source.sin_port = 0;
+
+        if(device) {
+            struct ifaddrs *ifa0, *ifa;
+            int ret;
+
+            ret = getifaddrs(&ifa0);
+            if(ret)
+                error(2, errno, "gatifaddrs failed");
+            for(ifa = ifa0; ifa; ifa = ifa->ifa_next) {
+                if(!ifa->ifa_name || !ifa->ifa_addr ||
+                        ifa->ifa_addr->sa_family != AF_INET)
+                    continue;
+                if(!strcmp(ifa->ifa_name, device) &&
+                        !memcmp(&((struct sockaddr_in *) ifa->ifa_addr)->sin_addr,
+                                &source.sin_addr, sizeof(source.sin_addr)))
+                    break;
+            }
+            if(ifa && !memcmp(&((struct sockaddr_in *) ifa->ifa_addr)->sin_addr,
+                    &dst.sin_addr, sizeof(source.sin_addr))) {
+                enable_capability_raw();
+                setsockopt(sock->fd, SOL_SOCKET, SO_BINDTODEVICE, "", 0);
+                disable_capability_raw();
+            }
+            freeifaddrs(ifa0);
+            if(!ifa)
+                error(0, 0, "Warning: source address might be selected on device other than: %s", device);
+        }
+        close(probe_fd);
+    }
+    while(0)
+        ;
+
+    if(whereto.sin_addr.s_addr == 0)
+        whereto.sin_addr.s_addr = source.sin_addr.s_addr;
+
+    if(device) {
+        struct ifreq ifr;
+
+        memset(&ifr, 0, sizeof(ifr));
+        strncpy(ifr.ifr_name, device, IFNAMSIZ - 1);
+        if(ioctl(sock->fd, SIOCGIFINDEX, &ifr) < 0)
+            error(2, 0, "unknown iface: %s", device);
+    }
+
+    if(broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
+        if(uid) {
+            if(interval < 1000)
+                error(2, 0, "broadcast ping with too short interval: %d", interval);
+            if(pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO)
+                error(2, 0, "broadcast ping does not fragment");
+        }
+        if(pmtudisc < 0)
+            pmtudisc = IP_PMTUDISC_DO;
+    }
+
+    if(pmtudisc >= 0) {
+        if(setsockopt(sock->fd, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof pmtudisc) == -1)
+            error(2, errno, "IP_MTU_DISCOVER");
+    }
+
+    if((options & F_STRICTSOURCE) &&
+            bind(sock->fd, (struct sockaddr *) &source, sizeof source) == -1)
+        error(2, errno, "bind");
+
+    if(sock->socktype == SOCK_RAW) {
+        struct icmp_filter filt;
+        filt.data = ~((1 << ICMP_SOURCE_QUENCH) |
+                (1 << ICMP_DEST_UNREACH) |
+                (1 << ICMP_TIME_EXCEEDED) |
+                (1 << ICMP_PARAMETERPROB) |
+                (1 << ICMP_REDIRECT) |
+                (1 << ICMP_ECHOREPLY));
+        if(setsockopt(sock->fd, SOL_RAW, ICMP_FILTER, &filt, sizeof filt) == -1)
+            error(0, errno, "WARNING: setsockopt(ICMP_FILTER)");
+    }
+
+    hold = 1;
+    if(setsockopt(sock->fd, SOL_IP, IP_RECVERR, &hold, sizeof hold))
+        error(0, 0, "WARNING: your kernel is veeery old. No problems.");
+
+    if(sock->socktype == SOCK_DGRAM) {
+        if(setsockopt(sock->fd, SOL_IP, IP_RECVTTL, &hold, sizeof hold))
+            error(0, errno, "WARNING: setsockopt(IP_RECVTTL)");
+        if(setsockopt(sock->fd, SOL_IP, IP_RETOPTS, &hold, sizeof hold))
+            error(0, errno, "WARNING: setsockopt(IP_RETOPTS)");
+    }
+
+    /* record route option */
+    if(options & F_RROUTE) {
+        memset(rspace, 0, sizeof(rspace));
+        rspace[0] = IPOPT_NOP;
+        rspace[1 + IPOPT_OPTVAL] = IPOPT_RR;
+        rspace[1 + IPOPT_OLEN] = sizeof(rspace) - 1;
+        rspace[1 + IPOPT_OFFSET] = IPOPT_MINOFF;
+        optlen = 40;
+        if(setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, sizeof rspace) < 0)
+            error(2, errno, "record route");
+    }
+    if(options & F_TIMESTAMP) {
+        memset(rspace, 0, sizeof(rspace));
+        rspace[0] = IPOPT_TIMESTAMP;
+        rspace[1] = (ts_type == IPOPT_TS_TSONLY ? 40 : 36);
+        rspace[2] = 5;
+        rspace[3] = ts_type;
+        if(ts_type == IPOPT_TS_PRESPEC) {
+            int i;
+            rspace[1] = 4 + nroute * 8;
+            for(i = 0; i < nroute; i++) {
+                tmp_rspace = (uint32_t*) &rspace[4 + i * 8];
+                *tmp_rspace = route[i];
+            }
+        }
+        if(setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
+            rspace[3] = 2;
+            if(setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0)
+                error(2, errno, "ts option");
+        }
+        optlen = 40;
+    }
+    if(options & F_SOURCEROUTE) {
+        int i;
+        memset(rspace, 0, sizeof(rspace));
+        rspace[0] = IPOPT_NOOP;
+        rspace[1 + IPOPT_OPTVAL] = (options & F_SO_DONTROUTE) ? IPOPT_SSRR
+                                                                :
+                                                                IPOPT_LSRR;
+        rspace[1 + IPOPT_OLEN] = 3 + nroute * 4;
+        rspace[1 + IPOPT_OFFSET] = IPOPT_MINOFF;
+        for(i = 0; i < nroute; i++) {
+            tmp_rspace = (uint32_t*) &rspace[4 + i * 4];
+            *tmp_rspace = route[i];
+        }
+
+        if(setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute * 4) < 0)
+            error(2, errno, "record route");
+        optlen = 40;
+    }
+
+    /* Estimate memory eaten by single packet. It is rough estimate.
+     * Actually, for small datalen's it depends on kernel side a lot. */
+    hold = datalen + 8;
+    hold += ((hold + 511) / 512) * (optlen + 20 + 16 + 64 + 160);
+    sock_setbufs(sock, hold);
+
+    if(broadcast_pings) {
+        if(setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, &broadcast_pings, sizeof broadcast_pings) < 0)
+            error(2, errno, "cannot set broadcasting");
+    }
+
+    if(options & F_NOLOOP) {
+        int loop = 0;
+        if(setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof loop) == -1)
+            error(2, errno, "cannot disable multicast loopback");
+    }
+    if(options & F_TTL) {
+        int ittl = ttl;
+        if(setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof ttl) == -1)
+            error(2, errno, "cannot set multicast time-to-live");
+        if(setsockopt(sock->fd, IPPROTO_IP, IP_TTL, &ittl, sizeof ittl) == -1)
+            error(2, errno, "cannot set unicast time-to-live");
+    }
+
+    if(datalen > 0xFFFF - 8 - optlen - 20)
+        error(2, 0, "packet size %d is too large. Maximum is %d",
+                datalen, 0xFFFF - 8 - 20 - optlen);
+
+    if(datalen >= (int) sizeof(struct timeval)) /* can we time transfer */
+        timing = 1;
+    packlen = datalen + MAXIPLEN + MAXICMPLEN;
+    if(!(packet = (unsigned char *) malloc((unsigned int) packlen)))
+        error(2, errno, "memory allocation failed");
+
+    printf("PING %s (%s) ", hostname, inet_ntoa(whereto.sin_addr));
+    if(device || (options & F_STRICTSOURCE))
+        printf("from %s %s: ", inet_ntoa(source.sin_addr), device ? device : "");
+    printf("%d(%d) bytes of data.\n", datalen, datalen + 8 + optlen + 20);
+
+    setup(sock);
+
+    main_loop(&ping4_func_set, sock, packet, packlen);
+}
 
 int ping4_receive_error_msg(socket_st *sock)
 {
-	ssize_t res;
-	char cbuf[512];
-	struct iovec  iov;
-	struct msghdr msg;
-	struct cmsghdr *cmsgh;
-	struct sock_extended_err *e;
-	struct icmphdr icmph;
-	struct sockaddr_in target;
-	int net_errors = 0;
-	int local_errors = 0;
-	int saved_errno = errno;
-
-	iov.iov_base = &icmph;
-	iov.iov_len = sizeof(icmph);
-	msg.msg_name = (void*)&target;
-	msg.msg_namelen = sizeof(target);
-	msg.msg_iov = &iov;
-	msg.msg_iovlen = 1;
-	msg.msg_flags = 0;
-	msg.msg_control = cbuf;
-	msg.msg_controllen = sizeof(cbuf);
-
-	res = recvmsg(sock->fd, &msg, MSG_ERRQUEUE|MSG_DONTWAIT);
-	if (res < 0)
-		goto out;
-
-	e = NULL;
-	for (cmsgh = CMSG_FIRSTHDR(&msg); cmsgh; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
-		if (cmsgh->cmsg_level == SOL_IP) {
-			if (cmsgh->cmsg_type == IP_RECVERR)
-				e = (struct sock_extended_err *)CMSG_DATA(cmsgh);
-		}
-	}
-	if (e == NULL)
-		abort();
-
-	if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
-		local_errors++;
-		if (options & F_QUIET)
-			goto out;
-		if (options & F_FLOOD)
-			write_stdout("E", 1);
-		else if (e->ee_errno != EMSGSIZE)
-			error(0, 0, "local error: %s", strerror(e->ee_errno));
-		else
-			error(0, 0, "local error: message too long, mtu=%u", e->ee_info);
-		nerrors++;
-	} else if (e->ee_origin == SO_EE_ORIGIN_ICMP) {
-		struct sockaddr_in *sin = (struct sockaddr_in*)(e+1);
-
-		if (res < (ssize_t) sizeof(icmph) ||
-		    target.sin_addr.s_addr != whereto.sin_addr.s_addr ||
-		    icmph.type != ICMP_ECHO ||
-		    !is_ours(sock, icmph.un.echo.id)) {
-			/* Not our error, not an error at all. Clear. */
-			saved_errno = 0;
-			goto out;
-		}
-
-		acknowledge(ntohs(icmph.un.echo.sequence));
-
-		net_errors++;
-		nerrors++;
-		if (options & F_QUIET)
-			goto out;
-		if (options & F_FLOOD) {
-			write_stdout("\bE", 2);
-		} else {
-			print_timestamp();
-			printf("From %s icmp_seq=%u ", pr_addr(sin, sizeof *sin), ntohs(icmph.un.echo.sequence));
-			pr_icmph(e->ee_type, e->ee_code, e->ee_info, NULL);
-			fflush(stdout);
-		}
-	}
-
-out:
-	errno = saved_errno;
-	return net_errors ? net_errors : -local_errors;
+    ssize_t res;
+    char cbuf[512];
+    struct iovec iov;
+    struct msghdr msg;
+    struct cmsghdr *cmsgh;
+    struct sock_extended_err *e;
+    struct icmphdr icmph;
+    struct sockaddr_in target;
+    int net_errors = 0;
+    int local_errors = 0;
+    int saved_errno = errno;
+
+    iov.iov_base = &icmph;
+    iov.iov_len = sizeof(icmph);
+    msg.msg_name = (void*) &target;
+    msg.msg_namelen = sizeof(target);
+    msg.msg_iov = &iov;
+    msg.msg_iovlen = 1;
+    msg.msg_flags = 0;
+    msg.msg_control = cbuf;
+    msg.msg_controllen = sizeof(cbuf);
+
+    res = recvmsg(sock->fd, &msg, MSG_ERRQUEUE | MSG_DONTWAIT);
+    if(res < 0)
+        goto out;
+
+    e = NULL;
+    for(cmsgh = CMSG_FIRSTHDR(&msg); cmsgh; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
+        if(cmsgh->cmsg_level == SOL_IP) {
+            if(cmsgh->cmsg_type == IP_RECVERR)
+                e = (struct sock_extended_err *) CMSG_DATA(cmsgh);
+        }
+    }
+    if(e == NULL)
+        abort();
+
+    if(e->ee_origin == SO_EE_ORIGIN_LOCAL) {
+        local_errors++;
+        if(options & F_QUIET)
+            goto out;
+        if(options & F_FLOOD)
+            write_stdout("E", 1);
+        else if(e->ee_errno != EMSGSIZE)
+            error(0, 0, "local error: %s", strerror(e->ee_errno));
+        else
+            error(0, 0, "local error: message too long, mtu=%u", e->ee_info);
+        nerrors++;
+    } else if(e->ee_origin == SO_EE_ORIGIN_ICMP) {
+        struct sockaddr_in *sin = (struct sockaddr_in*) (e + 1);
+
+        if(res < (ssize_t) sizeof(icmph) ||
+                target.sin_addr.s_addr != whereto.sin_addr.s_addr ||
+                icmph.type != ICMP_ECHO ||
+                !is_ours(sock, icmph.un.echo.id)) {
+            /* Not our error, not an error at all. Clear. */
+            saved_errno = 0;
+            goto out;
+        }
+
+        acknowledge(ntohs(icmph.un.echo.sequence));
+
+        net_errors++;
+        nerrors++;
+        if(options & F_QUIET)
+            goto out;
+        if(options & F_FLOOD) {
+            write_stdout("\bE", 2);
+        } else {
+            print_timestamp();
+            printf("From %s icmp_seq=%u ", pr_addr(sin, sizeof *sin), ntohs(icmph.un.echo.sequence));
+            pr_icmph(e->ee_type, e->ee_code, e->ee_info, NULL);
+            fflush(stdout);
+        }
+    }
+
+    out:
+    errno = saved_errno;
+    return net_errors ? net_errors : -local_errors;
 }
 
 /*
@@ -912,44 +932,44 @@ out:
  */
 int ping4_send_probe(socket_st *sock, void *packet, unsigned packet_size __attribute__((__unused__)))
 {
-	struct icmphdr *icp;
-	int cc;
-	int i;
-
-	icp = (struct icmphdr *)packet;
-	icp->type = ICMP_ECHO;
-	icp->code = 0;
-	icp->checksum = 0;
-	icp->un.echo.sequence = htons(ntransmitted+1);
-	icp->un.echo.id = ident;			/* ID */
-
-	rcvd_clear(ntransmitted+1);
-
-	if (timing) {
-		if (options&F_LATENCY) {
-			struct timeval tmp_tv;
-			gettimeofday(&tmp_tv, NULL);
-			memcpy(icp+1, &tmp_tv, sizeof(tmp_tv));
-		} else {
-			memset(icp+1, 0, sizeof(struct timeval));
-		}
-	}
-
-	cc = datalen + 8;			/* skips ICMP portion */
-
-	/* compute ICMP checksum here */
-	icp->checksum = in_cksum((unsigned short *)icp, cc, 0);
-
-	if (timing && !(options&F_LATENCY)) {
-		struct timeval tmp_tv;
-		gettimeofday(&tmp_tv, NULL);
-		memcpy(icp+1, &tmp_tv, sizeof(tmp_tv));
-		icp->checksum = in_cksum((unsigned short *)&tmp_tv, sizeof(tmp_tv), ~icp->checksum);
-	}
-
-	i = sendto(sock->fd, icp, cc, 0, (struct sockaddr*)&whereto, sizeof(whereto));
-
-	return (cc == i ? 0 : i);
+    struct icmphdr *icp;
+    int cc;
+    int i;
+
+    icp = (struct icmphdr *) packet;
+    icp->type = ICMP_ECHO;
+    icp->code = 0;
+    icp->checksum = 0;
+    icp->un.echo.sequence = htons(ntransmitted + 1);
+    icp->un.echo.id = ident; /* ID */
+
+    rcvd_clear(ntransmitted + 1);
+
+    if(timing) {
+        if(options & F_LATENCY) {
+            struct timeval tmp_tv;
+            gettimeofday(&tmp_tv, NULL);
+            memcpy(icp + 1, &tmp_tv, sizeof(tmp_tv));
+        } else {
+            memset(icp + 1, 0, sizeof(struct timeval));
+        }
+    }
+
+    cc = datalen + 8; /* skips ICMP portion */
+
+    /* compute ICMP checksum here */
+    icp->checksum = in_cksum((unsigned short *) icp, cc, 0);
+
+    if(timing && !(options & F_LATENCY)) {
+        struct timeval tmp_tv;
+        gettimeofday(&tmp_tv, NULL);
+        memcpy(icp + 1, &tmp_tv, sizeof(tmp_tv));
+        icp->checksum = in_cksum((unsigned short *) &tmp_tv, sizeof(tmp_tv), ~icp->checksum);
+    }
+
+    i = sendto(sock->fd, icp, cc, 0, (struct sockaddr*) &whereto, sizeof(whereto));
+
+    return (cc == i ? 0 : i);
 }
 
 /*
@@ -962,156 +982,155 @@ int ping4_send_probe(socket_st *sock, void *packet, unsigned packet_size __attri
 static
 void pr_echo_reply(uint8_t *_icp, int len __attribute__((__unused__)))
 {
-	struct icmphdr *icp = (struct icmphdr *)_icp;
-	printf(" icmp_seq=%u", ntohs(icp->un.echo.sequence));
+    struct icmphdr *icp = (struct icmphdr *) _icp;
+    printf(" icmp_seq=%u", ntohs(icp->un.echo.sequence));
 }
 
 int
 ping4_parse_reply(struct socket_st *sock, struct msghdr *msg, int cc, void *addr, struct timeval *tv)
 {
-	struct sockaddr_in *from = addr;
-	uint8_t *buf = msg->msg_iov->iov_base;
-	struct icmphdr *icp;
-	struct iphdr *ip;
-	int hlen;
-	int csfailed;
-	struct cmsghdr *cmsgh;
-	int reply_ttl;
-	uint8_t *opts, *tmp_ttl;
-	int olen;
-
-	/* Check the IP header */
-	ip = (struct iphdr *)buf;
-	if (sock->socktype == SOCK_RAW) {
-		hlen = ip->ihl*4;
-		if (cc < hlen + 8 || ip->ihl < 5) {
-			if (options & F_VERBOSE)
-				error(0, 0, "packet too short (%d bytes) from %s", cc,
-					pr_addr(from, sizeof *from));
-			return 1;
-		}
-		reply_ttl = ip->ttl;
-		opts = buf + sizeof(struct iphdr);
-		olen = hlen - sizeof(struct iphdr);
-	} else {
-		hlen = 0;
-		reply_ttl = 0;
-		opts = buf;
-		olen = 0;
-		for (cmsgh = CMSG_FIRSTHDR(msg); cmsgh; cmsgh = CMSG_NXTHDR(msg, cmsgh)) {
-			if (cmsgh->cmsg_level != SOL_IP)
-				continue;
-			if (cmsgh->cmsg_type == IP_TTL) {
-				if (cmsgh->cmsg_len < sizeof(int))
-					continue;
-				tmp_ttl = (uint8_t *) CMSG_DATA(cmsgh);
-				reply_ttl = (int)*tmp_ttl;
-			} else if (cmsgh->cmsg_type == IP_RETOPTS) {
-				opts = (uint8_t *) CMSG_DATA(cmsgh);
-				olen = cmsgh->cmsg_len;
-			}
-		}
-	}
-
-	/* Now the ICMP part */
-	cc -= hlen;
-	icp = (struct icmphdr *)(buf + hlen);
-	csfailed = in_cksum((unsigned short *)icp, cc, 0);
-
-	if (icp->type == ICMP_ECHOREPLY) {
-		if (!is_ours(sock, icp->un.echo.id))
-			return 1;			/* 'Twas not our ECHO */
-		if (!contains_pattern_in_payload((uint8_t*)(icp+1)))
-			return 1;			/* 'Twas really not our ECHO */
-		if (gather_statistics((uint8_t*)icp, sizeof(*icp), cc,
-				      ntohs(icp->un.echo.sequence),
-				      reply_ttl, 0, tv, pr_addr(from, sizeof *from),
-				      pr_echo_reply)) {
-			fflush(stdout);
-			return 0;
-		}
-	} else {
-		/* We fall here when a redirect or source quench arrived. */
-
-		switch (icp->type) {
-		case ICMP_ECHO:
-			/* MUST NOT */
-			return 1;
-		case ICMP_SOURCE_QUENCH:
-		case ICMP_REDIRECT:
-		case ICMP_DEST_UNREACH:
-		case ICMP_TIME_EXCEEDED:
-		case ICMP_PARAMETERPROB:
-			{
-				struct iphdr * iph = (struct  iphdr *)(&icp[1]);
-				struct icmphdr *icp1 = (struct icmphdr*)((unsigned char *)iph + iph->ihl*4);
-				int error_pkt;
-				if (cc < (int) (8 + sizeof(struct iphdr) + 8) ||
-				    cc < 8+iph->ihl*4+8)
-					return 1;
-				if (icp1->type != ICMP_ECHO ||
-				    iph->daddr != whereto.sin_addr.s_addr ||
-				    !is_ours(sock, icp1->un.echo.id))
-					return 1;
-				error_pkt = (icp->type != ICMP_REDIRECT &&
-					     icp->type != ICMP_SOURCE_QUENCH);
-				if (error_pkt) {
-					acknowledge(ntohs(icp1->un.echo.sequence));
-					return 0;
-				}
-				if (options & (F_QUIET | F_FLOOD))
-					return 1;
-				print_timestamp();
-				printf("From %s: icmp_seq=%u ",
-				       pr_addr(from, sizeof *from),
-				       ntohs(icp1->un.echo.sequence));
-				if (csfailed)
-					printf("(BAD CHECKSUM)");
-				pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
-				return 1;
-			}
-		default:
-			/* MUST NOT */
-			break;
-		}
-		if ((options & F_FLOOD) && !(options & (F_VERBOSE|F_QUIET))) {
-			if (!csfailed)
-				write_stdout("!E", 2);
-			else
-				write_stdout("!EC", 3);
-			return 0;
-		}
-		if (!(options & F_VERBOSE) || uid)
-			return 0;
-		if (options & F_PTIMEOFDAY) {
-			struct timeval recv_time;
-			gettimeofday(&recv_time, NULL);
-			printf("%lu.%06lu ", (unsigned long)recv_time.tv_sec, (unsigned long)recv_time.tv_usec);
-		}
-		printf("From %s: ", pr_addr(from, sizeof *from));
-		if (csfailed) {
-			printf("(BAD CHECKSUM)\n");
-			return 0;
-		}
-		pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
-		return 0;
-	}
-
-	if (options & F_AUDIBLE) {
-		putchar('\a');
-		if(options & F_FLOOD)
-			fflush(stdout);
-	}
-	if (!(options & F_FLOOD)) {
-		pr_options(opts, olen + sizeof(struct iphdr));
-
-		putchar('\n');
-		fflush(stdout);
-	}
-	return 0;
+    struct sockaddr_in *from = addr;
+    uint8_t *buf = msg->msg_iov->iov_base;
+    struct icmphdr *icp;
+    struct iphdr *ip;
+    int hlen;
+    int csfailed;
+    struct cmsghdr *cmsgh;
+    int reply_ttl;
+    uint8_t *opts, *tmp_ttl;
+    int olen;
+
+    /* Check the IP header */
+    ip = (struct iphdr *) buf;
+    if(sock->socktype == SOCK_RAW) {
+        hlen = ip->ihl * 4;
+        if(cc < hlen + 8 || ip->ihl < 5) {
+            if(options & F_VERBOSE)
+                error(0, 0, "packet too short (%d bytes) from %s", cc,
+                        pr_addr(from, sizeof *from));
+            return 1;
+        }
+        reply_ttl = ip->ttl;
+        opts = buf + sizeof(struct iphdr);
+        olen = hlen - sizeof(struct iphdr);
+    } else {
+        hlen = 0;
+        reply_ttl = 0;
+        opts = buf;
+        olen = 0;
+        for(cmsgh = CMSG_FIRSTHDR(msg); cmsgh; cmsgh = CMSG_NXTHDR(msg, cmsgh)) {
+            if(cmsgh->cmsg_level != SOL_IP)
+                continue;
+            if(cmsgh->cmsg_type == IP_TTL) {
+                if(cmsgh->cmsg_len < sizeof(int))
+                    continue;
+                tmp_ttl = (uint8_t *) CMSG_DATA(cmsgh);
+                reply_ttl = (int) *tmp_ttl;
+            } else if(cmsgh->cmsg_type == IP_RETOPTS) {
+                opts = (uint8_t *) CMSG_DATA(cmsgh);
+                olen = cmsgh->cmsg_len;
+            }
+        }
+    }
+
+    /* Now the ICMP part */
+    cc -= hlen;
+    icp = (struct icmphdr *) (buf + hlen);
+    csfailed = in_cksum((unsigned short *) icp, cc, 0);
+
+    if(icp->type == ICMP_ECHOREPLY) {
+        if(!is_ours(sock, icp->un.echo.id))
+            return 1; /* 'Twas not our ECHO */
+        if(!contains_pattern_in_payload((uint8_t*) (icp + 1)))
+            return 1; /* 'Twas really not our ECHO */
+        if(gather_statistics((uint8_t*) icp, sizeof(*icp), cc,
+                ntohs(icp->un.echo.sequence),
+                reply_ttl, 0, tv, pr_addr(from, sizeof *from),
+                pr_echo_reply)) {
+            fflush(stdout);
+            return 0;
+        }
+    } else {
+        /* We fall here when a redirect or source quench arrived. */
+
+        switch (icp->type) {
+        case ICMP_ECHO:
+            /* MUST NOT */
+            return 1;
+        case ICMP_SOURCE_QUENCH:
+            case ICMP_REDIRECT:
+            case ICMP_DEST_UNREACH:
+            case ICMP_TIME_EXCEEDED:
+            case ICMP_PARAMETERPROB:
+            {
+            struct iphdr * iph = (struct iphdr *) (&icp[1]);
+            struct icmphdr *icp1 = (struct icmphdr*) ((unsigned char *) iph + iph->ihl * 4);
+            int error_pkt;
+            if(cc < (int) (8 + sizeof(struct iphdr) + 8) ||
+                    cc < 8 + iph->ihl * 4 + 8)
+                return 1;
+            if(icp1->type != ICMP_ECHO ||
+                    iph->daddr != whereto.sin_addr.s_addr ||
+                    !is_ours(sock, icp1->un.echo.id))
+                return 1;
+            error_pkt = (icp->type != ICMP_REDIRECT &&
+                    icp->type != ICMP_SOURCE_QUENCH);
+            if(error_pkt) {
+                acknowledge(ntohs(icp1->un.echo.sequence));
+                return 0;
+            }
+            if(options & (F_QUIET | F_FLOOD))
+                return 1;
+            print_timestamp();
+            printf("From %s: icmp_seq=%u ",
+                    pr_addr(from, sizeof *from),
+                    ntohs(icp1->un.echo.sequence));
+            if(csfailed)
+                printf("(BAD CHECKSUM)");
+            pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
+            return 1;
+        }
+        default:
+            /* MUST NOT */
+            break;
+        }
+        if((options & F_FLOOD) && !(options & (F_VERBOSE | F_QUIET))) {
+            if(!csfailed)
+                write_stdout("!E", 2);
+            else
+                write_stdout("!EC", 3);
+            return 0;
+        }
+        if(!(options & F_VERBOSE) || uid)
+            return 0;
+        if(options & F_PTIMEOFDAY) {
+            struct timeval recv_time;
+            gettimeofday(&recv_time, NULL);
+            printf("%lu.%06lu ", (unsigned long) recv_time.tv_sec, (unsigned long) recv_time.tv_usec);
+        }
+        printf("From %s: ", pr_addr(from, sizeof *from));
+        if(csfailed) {
+            printf("(BAD CHECKSUM)\n");
+            return 0;
+        }
+        pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
+        return 0;
+    }
+
+    if(options & F_AUDIBLE) {
+        putchar('\a');
+        if(options & F_FLOOD)
+            fflush(stdout);
+    }
+    if(!(options & F_FLOOD)) {
+        pr_options(opts, olen + sizeof(struct iphdr));
+
+        putchar('\n');
+        fflush(stdout);
+    }
+    return 0;
 }
 
-
 #if BYTE_ORDER == LITTLE_ENDIAN
 # define ODDBYTE(v)	(v)
 #elif BYTE_ORDER == BIG_ENDIAN
@@ -1123,33 +1142,33 @@ ping4_parse_reply(struct socket_st *sock, struct msghdr *msg, int cc, void *addr
 unsigned short
 in_cksum(const unsigned short *addr, int len, unsigned short csum)
 {
-	int nleft = len;
-	const unsigned short *w = addr;
-	unsigned short answer;
-	int sum = csum;
-
-	/*
-	 *  Our algorithm is simple, using a 32 bit accumulator (sum),
-	 *  we add sequential 16 bit words to it, and at the end, fold
-	 *  back all the carry bits from the top 16 bits into the lower
-	 *  16 bits.
-	 */
-	while (nleft > 1)  {
-		sum += *w++;
-		nleft -= 2;
-	}
-
-	/* mop up an odd byte, if necessary */
-	if (nleft == 1)
-		sum += ODDBYTE(*(unsigned char *)w); /* le16toh() may be unavailable on old systems */
-
-	/*
-	 * add back carry outs from top 16 bits to low 16 bits
-	 */
-	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
-	sum += (sum >> 16);			/* add carry */
-	answer = ~sum;				/* truncate to 16 bits */
-	return (answer);
+    int nleft = len;
+    const unsigned short *w = addr;
+    unsigned short answer;
+    int sum = csum;
+
+    /*
+     *  Our algorithm is simple, using a 32 bit accumulator (sum),
+     *  we add sequential 16 bit words to it, and at the end, fold
+     *  back all the carry bits from the top 16 bits into the lower
+     *  16 bits.
+     */
+    while(nleft > 1) {
+        sum += *w++;
+        nleft -= 2;
+    }
+
+    /* mop up an odd byte, if necessary */
+    if(nleft == 1)
+        sum += ODDBYTE(*(unsigned char * )w); /* le16toh() may be unavailable on old systems */
+
+    /*
+     * add back carry outs from top 16 bits to low 16 bits
+     */
+    sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
+    sum += (sum >> 16); /* add carry */
+    answer = ~sum; /* truncate to 16 bits */
+    return (answer);
 }
 
 /*
@@ -1158,330 +1177,329 @@ in_cksum(const unsigned short *addr, int len, unsigned short csum)
  */
 void pr_icmph(uint8_t type, uint8_t code, uint32_t info, struct icmphdr *icp)
 {
-	switch(type) {
-	case ICMP_ECHOREPLY:
-		printf("Echo Reply\n");
-		/* XXX ID + Seq + Data */
-		break;
-	case ICMP_DEST_UNREACH:
-		switch(code) {
-		case ICMP_NET_UNREACH:
-			printf("Destination Net Unreachable\n");
-			break;
-		case ICMP_HOST_UNREACH:
-			printf("Destination Host Unreachable\n");
-			break;
-		case ICMP_PROT_UNREACH:
-			printf("Destination Protocol Unreachable\n");
-			break;
-		case ICMP_PORT_UNREACH:
-			printf("Destination Port Unreachable\n");
-			break;
-		case ICMP_FRAG_NEEDED:
-			printf("Frag needed and DF set (mtu = %u)\n", info);
-			break;
-		case ICMP_SR_FAILED:
-			printf("Source Route Failed\n");
-			break;
-		case ICMP_NET_UNKNOWN:
-			printf("Destination Net Unknown\n");
-			break;
-		case ICMP_HOST_UNKNOWN:
-			printf("Destination Host Unknown\n");
-			break;
-		case ICMP_HOST_ISOLATED:
-			printf("Source Host Isolated\n");
-			break;
-		case ICMP_NET_ANO:
-			printf("Destination Net Prohibited\n");
-			break;
-		case ICMP_HOST_ANO:
-			printf("Destination Host Prohibited\n");
-			break;
-		case ICMP_NET_UNR_TOS:
-			printf("Destination Net Unreachable for Type of Service\n");
-			break;
-		case ICMP_HOST_UNR_TOS:
-			printf("Destination Host Unreachable for Type of Service\n");
-			break;
-		case ICMP_PKT_FILTERED:
-			printf("Packet filtered\n");
-			break;
-		case ICMP_PREC_VIOLATION:
-			printf("Precedence Violation\n");
-			break;
-		case ICMP_PREC_CUTOFF:
-			printf("Precedence Cutoff\n");
-			break;
-		default:
-			printf("Dest Unreachable, Bad Code: %d\n", code);
-			break;
-		}
-		if (icp && (options & F_VERBOSE))
-			pr_iph((struct iphdr*)(icp + 1));
-		break;
-	case ICMP_SOURCE_QUENCH:
-		printf("Source Quench\n");
-		if (icp && (options & F_VERBOSE))
-			pr_iph((struct iphdr*)(icp + 1));
-		break;
-	case ICMP_REDIRECT:
-		switch(code) {
-		case ICMP_REDIR_NET:
-			printf("Redirect Network");
-			break;
-		case ICMP_REDIR_HOST:
-			printf("Redirect Host");
-			break;
-		case ICMP_REDIR_NETTOS:
-			printf("Redirect Type of Service and Network");
-			break;
-		case ICMP_REDIR_HOSTTOS:
-			printf("Redirect Type of Service and Host");
-			break;
-		default:
-			printf("Redirect, Bad Code: %d", code);
-			break;
-		}
-		{
-			struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr =  { icp ? icp->un.gateway : info } };
-
-			printf("(New nexthop: %s)\n", pr_addr(&sin, sizeof sin));
-		}
-		if (icp && (options & F_VERBOSE))
-			pr_iph((struct iphdr*)(icp + 1));
-		break;
-	case ICMP_ECHO:
-		printf("Echo Request\n");
-		/* XXX ID + Seq + Data */
-		break;
-	case ICMP_TIME_EXCEEDED:
-		switch(code) {
-		case ICMP_EXC_TTL:
-			printf("Time to live exceeded\n");
-			break;
-		case ICMP_EXC_FRAGTIME:
-			printf("Frag reassembly time exceeded\n");
-			break;
-		default:
-			printf("Time exceeded, Bad Code: %d\n", code);
-			break;
-		}
-		if (icp && (options & F_VERBOSE))
-			pr_iph((struct iphdr*)(icp + 1));
-		break;
-	case ICMP_PARAMETERPROB:
-		printf("Parameter problem: pointer = %u\n", icp ? (ntohl(icp->un.gateway)>>24) : info);
-		if (icp && (options & F_VERBOSE))
-			pr_iph((struct iphdr*)(icp + 1));
-		break;
-	case ICMP_TIMESTAMP:
-		printf("Timestamp\n");
-		/* XXX ID + Seq + 3 timestamps */
-		break;
-	case ICMP_TIMESTAMPREPLY:
-		printf("Timestamp Reply\n");
-		/* XXX ID + Seq + 3 timestamps */
-		break;
-	case ICMP_INFO_REQUEST:
-		printf("Information Request\n");
-		/* XXX ID + Seq */
-		break;
-	case ICMP_INFO_REPLY:
-		printf("Information Reply\n");
-		/* XXX ID + Seq */
-		break;
+    switch (type) {
+    case ICMP_ECHOREPLY:
+        printf("Echo Reply\n");
+        /* XXX ID + Seq + Data */
+        break;
+    case ICMP_DEST_UNREACH:
+        switch (code) {
+        case ICMP_NET_UNREACH:
+            printf("Destination Net Unreachable\n");
+            break;
+        case ICMP_HOST_UNREACH:
+            printf("Destination Host Unreachable\n");
+            break;
+        case ICMP_PROT_UNREACH:
+            printf("Destination Protocol Unreachable\n");
+            break;
+        case ICMP_PORT_UNREACH:
+            printf("Destination Port Unreachable\n");
+            break;
+        case ICMP_FRAG_NEEDED:
+            printf("Frag needed and DF set (mtu = %u)\n", info);
+            break;
+        case ICMP_SR_FAILED:
+            printf("Source Route Failed\n");
+            break;
+        case ICMP_NET_UNKNOWN:
+            printf("Destination Net Unknown\n");
+            break;
+        case ICMP_HOST_UNKNOWN:
+            printf("Destination Host Unknown\n");
+            break;
+        case ICMP_HOST_ISOLATED:
+            printf("Source Host Isolated\n");
+            break;
+        case ICMP_NET_ANO:
+            printf("Destination Net Prohibited\n");
+            break;
+        case ICMP_HOST_ANO:
+            printf("Destination Host Prohibited\n");
+            break;
+        case ICMP_NET_UNR_TOS:
+            printf("Destination Net Unreachable for Type of Service\n");
+            break;
+        case ICMP_HOST_UNR_TOS:
+            printf("Destination Host Unreachable for Type of Service\n");
+            break;
+        case ICMP_PKT_FILTERED:
+            printf("Packet filtered\n");
+            break;
+        case ICMP_PREC_VIOLATION:
+            printf("Precedence Violation\n");
+            break;
+        case ICMP_PREC_CUTOFF:
+            printf("Precedence Cutoff\n");
+            break;
+        default:
+            printf("Dest Unreachable, Bad Code: %d\n", code);
+            break;
+        }
+        if(icp && (options & F_VERBOSE))
+            pr_iph((struct iphdr*) (icp + 1));
+        break;
+    case ICMP_SOURCE_QUENCH:
+        printf("Source Quench\n");
+        if(icp && (options & F_VERBOSE))
+            pr_iph((struct iphdr*) (icp + 1));
+        break;
+    case ICMP_REDIRECT:
+        switch (code) {
+        case ICMP_REDIR_NET:
+            printf("Redirect Network");
+            break;
+        case ICMP_REDIR_HOST:
+            printf("Redirect Host");
+            break;
+        case ICMP_REDIR_NETTOS:
+            printf("Redirect Type of Service and Network");
+            break;
+        case ICMP_REDIR_HOSTTOS:
+            printf("Redirect Type of Service and Host");
+            break;
+        default:
+            printf("Redirect, Bad Code: %d", code);
+            break;
+        }
+        {
+            struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { icp ? icp->un.gateway : info } };
+
+            printf("(New nexthop: %s)\n", pr_addr(&sin, sizeof sin));
+        }
+        if(icp && (options & F_VERBOSE))
+            pr_iph((struct iphdr*) (icp + 1));
+        break;
+    case ICMP_ECHO:
+        printf("Echo Request\n");
+        /* XXX ID + Seq + Data */
+        break;
+    case ICMP_TIME_EXCEEDED:
+        switch (code) {
+        case ICMP_EXC_TTL:
+            printf("Time to live exceeded\n");
+            break;
+        case ICMP_EXC_FRAGTIME:
+            printf("Frag reassembly time exceeded\n");
+            break;
+        default:
+            printf("Time exceeded, Bad Code: %d\n", code);
+            break;
+        }
+        if(icp && (options & F_VERBOSE))
+            pr_iph((struct iphdr*) (icp + 1));
+        break;
+    case ICMP_PARAMETERPROB:
+        printf("Parameter problem: pointer = %u\n", icp ? (ntohl(icp->un.gateway) >> 24) : info);
+        if(icp && (options & F_VERBOSE))
+            pr_iph((struct iphdr*) (icp + 1));
+        break;
+    case ICMP_TIMESTAMP:
+        printf("Timestamp\n");
+        /* XXX ID + Seq + 3 timestamps */
+        break;
+    case ICMP_TIMESTAMPREPLY:
+        printf("Timestamp Reply\n");
+        /* XXX ID + Seq + 3 timestamps */
+        break;
+    case ICMP_INFO_REQUEST:
+        printf("Information Request\n");
+        /* XXX ID + Seq */
+        break;
+    case ICMP_INFO_REPLY:
+        printf("Information Reply\n");
+        /* XXX ID + Seq */
+        break;
 #ifdef ICMP_MASKREQ
-	case ICMP_MASKREQ:
-		printf("Address Mask Request\n");
-		break;
+    case ICMP_MASKREQ:
+        printf("Address Mask Request\n");
+        break;
 #endif
 #ifdef ICMP_MASKREPLY
-	case ICMP_MASKREPLY:
-		printf("Address Mask Reply\n");
-		break;
+    case ICMP_MASKREPLY:
+        printf("Address Mask Reply\n");
+        break;
 #endif
-	default:
-		printf("Bad ICMP type: %d\n", type);
-	}
+    default:
+        printf("Bad ICMP type: %d\n", type);
+    }
 }
 
 void pr_options(unsigned char * cp, int hlen)
 {
-	int i, j;
-	int olen, totlen;
-	unsigned char * optptr;
-	static int old_rrlen;
-	static char old_rr[MAX_IPOPTLEN];
-
-	totlen = hlen-sizeof(struct iphdr);
-	optptr = cp;
-
-	while (totlen > 0) {
-		if (*optptr == IPOPT_EOL)
-			break;
-		if (*optptr == IPOPT_NOP) {
-			totlen--;
-			optptr++;
-			printf("\nNOP");
-			continue;
-		}
-		cp = optptr;
-		olen = optptr[1];
-		if (olen < 2 || olen > totlen)
-			break;
-
-		switch (*cp) {
-		case IPOPT_SSRR:
-		case IPOPT_LSRR:
-			printf("\n%cSRR: ", *cp==IPOPT_SSRR ? 'S' : 'L');
-			j = *++cp;
-			cp++;
-			if (j > IPOPT_MINOFF) {
-				for (;;) {
-					uint32_t address;
-					memcpy(&address, cp, 4);
-					cp += 4;
-					if (address == 0)
-						printf("\t0.0.0.0");
-					else {
-						struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { address } };
-
-						printf("\t%s", pr_addr(&sin, sizeof sin));
-					}
-					j -= 4;
-					putchar('\n');
-					if (j <= IPOPT_MINOFF)
-						break;
-				}
-			}
-			break;
-		case IPOPT_RR:
-			j = *++cp;		/* get length */
-			i = *++cp;		/* and pointer */
-			if (i > j)
-				i = j;
-			i -= IPOPT_MINOFF;
-			if (i <= 0)
-				break;
-			if (i == old_rrlen
-			    && !memcmp(cp, old_rr, i)
-			    && !(options & F_FLOOD)) {
-				printf("\t(same route)");
-				break;
-			}
-			old_rrlen = i;
-			memcpy(old_rr, (char *)cp, i);
-			printf("\nRR: ");
-			cp++;
-			for (;;) {
-				uint32_t address;
-				memcpy(&address, cp, 4);
-				cp += 4;
-				if (address == 0)
-					printf("\t0.0.0.0");
-				else {
-					struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { address } };
-
-					printf("\t%s", pr_addr(&sin, sizeof sin));
-				}
-				i -= 4;
-				putchar('\n');
-				if (i <= 0)
-					break;
-			}
-			break;
-		case IPOPT_TS:
-		{
-			int stdtime = 0, nonstdtime = 0;
-			uint8_t flags;
-			j = *++cp;		/* get length */
-			i = *++cp;		/* and pointer */
-			if (i > j)
-				i = j;
-			i -= 5;
-			if (i <= 0)
-				break;
-			flags = *++cp;
-			printf("\nTS: ");
-			cp++;
-			for (;;) {
-				long l;
-
-				if ((flags&0xF) != IPOPT_TS_TSONLY) {
-					uint32_t address;
-					memcpy(&address, cp, 4);
-					cp += 4;
-					if (address == 0)
-						printf("\t0.0.0.0");
-					else {
-						struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { address } };
-
-						printf("\t%s", pr_addr(&sin, sizeof sin));
-					}
-					i -= 4;
-					if (i <= 0)
-						break;
-				}
-				l = *cp++;
-				l = (l<<8) + *cp++;
-				l = (l<<8) + *cp++;
-				l = (l<<8) + *cp++;
-
-				if  (l & 0x80000000) {
-					if (nonstdtime==0)
-						printf("\t%ld absolute not-standard", l&0x7fffffff);
-					else
-						printf("\t%ld not-standard", (l&0x7fffffff) - nonstdtime);
-					nonstdtime = l&0x7fffffff;
-				} else {
-					if (stdtime==0)
-						printf("\t%ld absolute", l);
-					else
-						printf("\t%ld", l - stdtime);
-					stdtime = l;
-				}
-				i -= 4;
-				putchar('\n');
-				if (i <= 0)
-					break;
-			}
-			if (flags>>4)
-				printf("Unrecorded hops: %d\n", flags>>4);
-			break;
-		}
-		default:
-			printf("\nunknown option %x", *cp);
-			break;
-		}
-		totlen -= olen;
-		optptr += olen;
-	}
+    int i, j;
+    int olen, totlen;
+    unsigned char * optptr;
+    static int old_rrlen;
+    static char old_rr[MAX_IPOPTLEN];
+
+    totlen = hlen - sizeof(struct iphdr);
+    optptr = cp;
+
+    while(totlen > 0) {
+        if(*optptr == IPOPT_EOL)
+            break;
+        if(*optptr == IPOPT_NOP) {
+            totlen--;
+            optptr++;
+            printf("\nNOP");
+            continue;
+        }
+        cp = optptr;
+        olen = optptr[1];
+        if(olen < 2 || olen > totlen)
+            break;
+
+        switch (*cp) {
+        case IPOPT_SSRR:
+            case IPOPT_LSRR:
+            printf("\n%cSRR: ", *cp == IPOPT_SSRR ? 'S' : 'L');
+            j = *++cp;
+            cp++;
+            if(j > IPOPT_MINOFF) {
+                for(;;) {
+                    uint32_t address;
+                    memcpy(&address, cp, 4);
+                    cp += 4;
+                    if(address == 0)
+                        printf("\t0.0.0.0");
+                    else {
+                        struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { address } };
+
+                        printf("\t%s", pr_addr(&sin, sizeof sin));
+                    }
+                    j -= 4;
+                    putchar('\n');
+                    if(j <= IPOPT_MINOFF)
+                        break;
+                }
+            }
+            break;
+        case IPOPT_RR:
+            j = *++cp; /* get length */
+            i = *++cp; /* and pointer */
+            if(i > j)
+                i = j;
+            i -= IPOPT_MINOFF;
+            if(i <= 0)
+                break;
+            if(i == old_rrlen
+                    && !memcmp(cp, old_rr, i)
+                    && !(options & F_FLOOD)) {
+                printf("\t(same route)");
+                break;
+            }
+            old_rrlen = i;
+            memcpy(old_rr, (char *) cp, i);
+            printf("\nRR: ");
+            cp++;
+            for(;;) {
+                uint32_t address;
+                memcpy(&address, cp, 4);
+                cp += 4;
+                if(address == 0)
+                    printf("\t0.0.0.0");
+                else {
+                    struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { address } };
+
+                    printf("\t%s", pr_addr(&sin, sizeof sin));
+                }
+                i -= 4;
+                putchar('\n');
+                if(i <= 0)
+                    break;
+            }
+            break;
+        case IPOPT_TS:
+            {
+            int stdtime = 0, nonstdtime = 0;
+            uint8_t flags;
+            j = *++cp; /* get length */
+            i = *++cp; /* and pointer */
+            if(i > j)
+                i = j;
+            i -= 5;
+            if(i <= 0)
+                break;
+            flags = *++cp;
+            printf("\nTS: ");
+            cp++;
+            for(;;) {
+                long l;
+
+                if((flags & 0xF) != IPOPT_TS_TSONLY) {
+                    uint32_t address;
+                    memcpy(&address, cp, 4);
+                    cp += 4;
+                    if(address == 0)
+                        printf("\t0.0.0.0");
+                    else {
+                        struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { address } };
+
+                        printf("\t%s", pr_addr(&sin, sizeof sin));
+                    }
+                    i -= 4;
+                    if(i <= 0)
+                        break;
+                }
+                l = *cp++;
+                l = (l << 8) + *cp++;
+                l = (l << 8) + *cp++;
+                l = (l << 8) + *cp++;
+
+                if(l & 0x80000000) {
+                    if(nonstdtime == 0)
+                        printf("\t%ld absolute not-standard", l & 0x7fffffff);
+                    else
+                        printf("\t%ld not-standard", (l & 0x7fffffff) - nonstdtime);
+                    nonstdtime = l & 0x7fffffff;
+                } else {
+                    if(stdtime == 0)
+                        printf("\t%ld absolute", l);
+                    else
+                        printf("\t%ld", l - stdtime);
+                    stdtime = l;
+                }
+                i -= 4;
+                putchar('\n');
+                if(i <= 0)
+                    break;
+            }
+            if(flags >> 4)
+                printf("Unrecorded hops: %d\n", flags >> 4);
+            break;
+        }
+        default:
+            printf("\nunknown option %x", *cp);
+            break;
+        }
+        totlen -= olen;
+        optptr += olen;
+    }
 }
 
-
 /*
  * pr_iph --
  *	Print an IP header with options.
  */
 void pr_iph(struct iphdr *ip)
 {
-	int hlen;
-	unsigned char *cp;
-
-	hlen = ip->ihl << 2;
-	cp = (unsigned char *)ip + 20;		/* point to options */
-
-	printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst Data\n");
-	printf(" %1x  %1x  %02x %04x %04x",
-	       ip->version, ip->ihl, ip->tos, ip->tot_len, ip->id);
-	printf("   %1x %04x", ((ip->frag_off) & 0xe000) >> 13,
-	       (ip->frag_off) & 0x1fff);
-	printf("  %02x  %02x %04x", ip->ttl, ip->protocol, ip->check);
-	printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->saddr));
-	printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->daddr));
-	printf("\n");
-	pr_options(cp, hlen);
+    int hlen;
+    unsigned char *cp;
+
+    hlen = ip->ihl << 2;
+    cp = (unsigned char *) ip + 20; /* point to options */
+
+    printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst Data\n");
+    printf(" %1x  %1x  %02x %04x %04x",
+            ip->version, ip->ihl, ip->tos, ip->tot_len, ip->id);
+    printf("   %1x %04x", ((ip->frag_off) & 0xe000) >> 13,
+            (ip->frag_off) & 0x1fff);
+    printf("  %02x  %02x %04x", ip->ttl, ip->protocol, ip->check);
+    printf(" %s ", inet_ntoa(*(struct in_addr *) &ip->saddr));
+    printf(" %s ", inet_ntoa(*(struct in_addr *) &ip->daddr));
+    printf("\n");
+    pr_options(cp, hlen);
 }
 
 /*
@@ -1492,106 +1510,103 @@ void pr_iph(struct iphdr *ip)
 char *
 pr_addr(void *sa, socklen_t salen)
 {
-	static char buffer[4096] = "";
-	static struct sockaddr_storage last_sa = { 0, {0}, 0 };
-	static socklen_t last_salen = 0;
-	char name[NI_MAXHOST] = "";
-	char address[NI_MAXHOST] = "";
+    static char buffer[4096] = "";
+    static struct sockaddr_storage last_sa = { 0, { 0 }, 0 };
+    static socklen_t last_salen = 0;
+    char name[NI_MAXHOST] = "";
+    char address[NI_MAXHOST] = "";
 
-	if (salen == last_salen && !memcmp(sa, &last_sa, salen))
-		return buffer;
+    if(salen == last_salen && !memcmp(sa, &last_sa, salen))
+        return buffer;
 
-	memcpy(&last_sa, sa, (last_salen = salen));
+    memcpy(&last_sa, sa, (last_salen = salen));
 
-	in_pr_addr = !setjmp(pr_addr_jmp);
+    in_pr_addr = !setjmp(pr_addr_jmp);
 
-	getnameinfo(sa, salen, address, sizeof address, NULL, 0, getnameinfo_flags | NI_NUMERICHOST);
-	if (!exiting && !(options & F_NUMERIC))
-		getnameinfo(sa, salen, name, sizeof name, NULL, 0, getnameinfo_flags);
+    getnameinfo(sa, salen, address, sizeof address, NULL, 0, getnameinfo_flags | NI_NUMERICHOST);
+    if(!exiting && !(options & F_NUMERIC))
+        getnameinfo(sa, salen, name, sizeof name, NULL, 0, getnameinfo_flags);
 
-	if (*name)
-		snprintf(buffer, sizeof buffer, "%s (%s)", name, address);
-	else
-		snprintf(buffer, sizeof buffer, "%s", address);
+    if(*name)
+        snprintf(buffer, sizeof buffer, "%s (%s)", name, address);
+    else
+        snprintf(buffer, sizeof buffer, "%s", address);
 
-	in_pr_addr = 0;
+    in_pr_addr = 0;
 
-	return(buffer);
+    return (buffer);
 }
 
-
 /* Set Type of Service (TOS) and other Quality of Service relating bits */
 int parsetos(char *str)
 {
-	const char *cp;
-	int tos;
-	char *ep;
-
-	/* handle both hex and decimal values */
-	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
-		cp = str + 2;
-		tos = (int)strtol(cp, &ep, 16);
-	} else
-		tos = (int)strtol(str, &ep, 10);
-
-	/* doesn't look like decimal or hex, eh? */
-	if (*ep != '\0')
-		error(2, 0, "bad TOS value: %s", str);
-
-	if (tos > TOS_MAX)
-		error(2, 0, "the decimal value of TOS bits must be in range 0-255: %d", tos);
-	return(tos);
+    const char *cp;
+    int tos;
+    char *ep;
+
+    /* handle both hex and decimal values */
+    if(str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
+        cp = str + 2;
+        tos = (int) strtol(cp, &ep, 16);
+    } else
+        tos = (int) strtol(str, &ep, 10);
+
+    /* doesn't look like decimal or hex, eh? */
+    if(*ep != '\0')
+        error(2, 0, "bad TOS value: %s", str);
+
+    if(tos > TOS_MAX)
+        error(2, 0, "the decimal value of TOS bits must be in range 0-255: %d", tos);
+    return (tos);
 }
 
 int parseflow(char *str)
 {
-	const char *cp;
-	unsigned long val;
-	char *ep;
-
-	/* handle both hex and decimal values */
-	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
-		cp = str + 2;
-		val = (int)strtoul(cp, &ep, 16);
-	} else
-		val = (int)strtoul(str, &ep, 10);
-
-	/* doesn't look like decimal or hex, eh? */
-	if (*ep != '\0')
-		error(2, 0, "bad value for flowinfo: %s", str);
-
-	if (val & ~IPV6_FLOWINFO_FLOWLABEL)
-		error(2, 0, "flow value is greater than 20 bits: %s", str);
-	return(val);
+    const char *cp;
+    unsigned long val;
+    char *ep;
+
+    /* handle both hex and decimal values */
+    if(str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
+        cp = str + 2;
+        val = (int) strtoul(cp, &ep, 16);
+    } else
+        val = (int) strtoul(str, &ep, 10);
+
+    /* doesn't look like decimal or hex, eh? */
+    if(*ep != '\0')
+        error(2, 0, "bad value for flowinfo: %s", str);
+
+    if(val & ~IPV6_FLOWINFO_FLOWLABEL)
+        error(2, 0, "flow value is greater than 20 bits: %s", str);
+    return (val);
 }
 
-
-
 void ping4_install_filter(socket_st *sock)
 {
-	static int once;
-	static struct sock_filter insns[] = {
-		BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* Skip IP header. F..g BSD... Look into ping6. */
-		BPF_STMT(BPF_LD|BPF_H|BPF_IND, 4), /* Load icmp echo ident */
-		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xAAAA, 0, 1), /* Ours? */
-		BPF_STMT(BPF_RET|BPF_K, ~0U), /* Yes, it passes. */
-		BPF_STMT(BPF_LD|BPF_B|BPF_IND, 0), /* Load icmp type */
-		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */
-		BPF_STMT(BPF_RET|BPF_K, 0xFFFFFFF), /* No. It passes. */
-		BPF_STMT(BPF_RET|BPF_K, 0) /* Echo with wrong ident. Reject. */
-	};
-	static struct sock_fprog filter = {
-		sizeof insns / sizeof(insns[0]),
-		insns
-	};
-
-	if (once)
-		return;
-	once = 1;
-
-	/* Patch bpflet for current identifier. */
-	insns[2] = (struct sock_filter)BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, htons(ident), 0, 1);
-
-	if (setsockopt(sock->fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)))
-		error(0, errno, "WARNING: failed to install socket filter");
+    static int once;
+    static struct sock_filter insns[] = {
+    BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* Skip IP header. F..g BSD... Look into ping6. */
+    BPF_STMT(BPF_LD|BPF_H|BPF_IND, 4), /* Load icmp echo ident */
+    BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xAAAA, 0, 1), /* Ours? */
+    BPF_STMT(BPF_RET|BPF_K, ~0U), /* Yes, it passes. */
+    BPF_STMT(BPF_LD|BPF_B|BPF_IND, 0), /* Load icmp type */
+    BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */
+    BPF_STMT(BPF_RET|BPF_K, 0xFFFFFFF), /* No. It passes. */
+    BPF_STMT(BPF_RET|BPF_K, 0) /* Echo with wrong ident. Reject. */
+    };
+    static struct sock_fprog filter = {
+        sizeof insns / sizeof(insns[0]),
+        insns
+    };
+
+    if(once)
+        return;
+    once = 1;
+
+    /* Patch bpflet for current identifier. */
+    insns[2] = (struct sock_filter )BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, htons(ident), 0, 1);
+
+    if(setsockopt(sock->fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)))
+        error(0, errno, "WARNING: failed to install socket filter");
 }
diff --git a/iputils/ping.h b/iputils/ping.h
index 91cff9bd76..bc8483cf7c 100644
--- a/iputils/ping.h
+++ b/iputils/ping.h
@@ -420,3 +420,10 @@ struct ni_hdr {
 
 #define NI_IPV4ADDR_F_TRUNCATE		NI_IPV6ADDR_F_TRUNCATE
 #define NI_IPV4ADDR_F_ALL		NI_IPV6ADDR_F_ALL
+
+#define PACKAGE_NAME "ping"
+#define PACKAGE_VERSION "0.1"
+#define IPUTILS_VERSION(_prog) "%s from %s %s\n", _prog, PACKAGE_NAME, PACKAGE_VERSION
+
+int ping_util(const char *addr, int count);
+
diff --git a/iputils/ping6_common.c b/iputils/ping6_common.c
new file mode 100755
index 0000000000..b0d53daafa
--- /dev/null
+++ b/iputils/ping6_common.c
@@ -0,0 +1,1383 @@
+/*
+ *
+ *	Modified for AF_INET6 by Pedro Roque
+ *
+ *	<roque@di.fc.ul.pt>
+ *
+ *	Original copyright notice included bellow
+ */
+
+/*
+ * Copyright (c) 1989 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Muuss.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/*
+ *			P I N G . C
+ *
+ * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
+ * measure round-trip-delays and packet loss across network paths.
+ *
+ * Author -
+ *	Mike Muuss
+ *	U. S. Army Ballistic Research Laboratory
+ *	December, 1983
+ *
+ * Status -
+ *	Public Domain.  Distribution Unlimited.
+ * Bugs -
+ *	More statistics could always be gathered.
+ *	If kernel does not support non-raw ICMP sockets or
+ *	if -N option is used, this program has to run SUID to ROOT or
+ *	with net_cap_raw enabled.
+ */
+#include "ping.h"
+
+ping_func_set_st ping6_func_set = {
+	.send_probe = ping6_send_probe,
+	.receive_error_msg = ping6_receive_error_msg,
+	.parse_reply = ping6_parse_reply,
+	.install_filter = ping6_install_filter
+};
+
+#ifndef SCOPE_DELIMITER
+# define SCOPE_DELIMITER '%'
+#endif
+
+uint32_t flowlabel;
+uint32_t tclass;
+
+static struct sockaddr_in6 whereto;
+static struct sockaddr_in6 firsthop;
+
+static unsigned char cmsgbuf[4096];
+static size_t cmsglen = 0;
+
+static int pr_icmph(uint8_t type, uint8_t code, uint32_t info);
+
+struct sockaddr_in6 source6 = { .sin6_family = AF_INET6 };
+extern char *device;
+
+#if defined(USE_GCRYPT) || defined(USE_OPENSSL) || defined(USE_NETTLE)
+#include "iputils_md5dig.h"
+#define USE_CRYPTO
+#endif
+
+/* Node Information query */
+int ni_query = -1;
+int ni_flag = 0;
+void *ni_subject = NULL;
+int ni_subject_len = 0;
+int ni_subject_type = -1;
+char *ni_group;
+
+static inline int ntohsp(uint16_t *p)
+{
+	uint16_t v;
+	memcpy(&v, p, sizeof(v));
+	return ntohs(v);
+}
+
+unsigned int if_name2index(const char *ifname)
+{
+	unsigned int i = if_nametoindex(ifname);
+	if (!i)
+		error(2, 0, "unknown iface: %s", ifname);
+	return i;
+}
+
+struct niquery_option {
+	char *name;
+	int namelen;
+	int has_arg;
+	int data;
+	int (*handler)(int index, const char *arg);
+};
+
+#define NIQUERY_OPTION(_name, _has_arg, _data, _handler)	\
+	{							\
+		.name = _name,					\
+		.namelen = sizeof(_name) - 1,			\
+		.has_arg = _has_arg,				\
+		.data = _data,					\
+		.handler = _handler				\
+	}
+
+static int niquery_option_name_handler(int index __attribute__((__unused__)), const char *arg __attribute__((__unused__)));
+static int niquery_option_ipv6_handler(int index __attribute__((__unused__)), const char *arg __attribute__((__unused__)));
+static int niquery_option_ipv6_flag_handler(int index, const char *arg);
+static int niquery_option_ipv4_handler(int index, const char *arg);
+static int niquery_option_ipv4_flag_handler(int index, const char *arg);
+static int niquery_option_subject_addr_handler(int index, const char *arg);
+static int niquery_option_subject_name_handler(int index, const char *arg);
+static int niquery_option_help_handler(int index, const char *arg);
+
+struct niquery_option niquery_options[] = {
+	NIQUERY_OPTION("name",			0,	0,				niquery_option_name_handler),
+	NIQUERY_OPTION("fqdn",			0,	0,				niquery_option_name_handler),
+	NIQUERY_OPTION("ipv6",			0,	0,				niquery_option_ipv6_handler),
+	NIQUERY_OPTION("ipv6-all",		0,	NI_IPV6ADDR_F_ALL,		niquery_option_ipv6_flag_handler),
+	NIQUERY_OPTION("ipv6-compatible",	0,	NI_IPV6ADDR_F_COMPAT,		niquery_option_ipv6_flag_handler),
+	NIQUERY_OPTION("ipv6-linklocal",	0,	NI_IPV6ADDR_F_LINKLOCAL,	niquery_option_ipv6_flag_handler),
+	NIQUERY_OPTION("ipv6-sitelocal",	0,	NI_IPV6ADDR_F_SITELOCAL,	niquery_option_ipv6_flag_handler),
+	NIQUERY_OPTION("ipv6-global",		0,	NI_IPV6ADDR_F_GLOBAL,		niquery_option_ipv6_flag_handler),
+	NIQUERY_OPTION("ipv4",			0,	0,				niquery_option_ipv4_handler),
+	NIQUERY_OPTION("ipv4-all",		0,	NI_IPV4ADDR_F_ALL,		niquery_option_ipv4_flag_handler),
+	NIQUERY_OPTION("subject-ipv6",		1,	NI_SUBJ_IPV6,			niquery_option_subject_addr_handler),
+	NIQUERY_OPTION("subject-ipv4",		1,	NI_SUBJ_IPV4,			niquery_option_subject_addr_handler),
+	NIQUERY_OPTION("subject-name",		1,	0,				niquery_option_subject_name_handler),
+	NIQUERY_OPTION("subject-fqdn",		1,	-1,				niquery_option_subject_name_handler),
+	NIQUERY_OPTION("help",			0,	0,				niquery_option_help_handler),
+	{NULL, 0, 0, 0, NULL}
+};
+
+static inline int niquery_is_enabled(void)
+{
+	return ni_query >= 0;
+}
+
+#if PING6_NONCE_MEMORY
+uint8_t *ni_nonce_ptr;
+#else
+struct {
+	struct timeval tv;
+	pid_t pid;
+} ni_nonce_secret;
+#endif
+
+static void niquery_init_nonce(void)
+{
+#if PING6_NONCE_MEMORY
+	struct timeval tv;
+	unsigned long seed;
+
+	seed = (unsigned long)getpid();
+	if (!gettimeofday(&tv, NULL))
+		seed ^= tv.tv_usec;
+	srand(seed);
+
+	ni_nonce_ptr = calloc(NI_NONCE_SIZE, MAX_DUP_CHK);
+	if (!ni_nonce_ptr)
+		error(2, errno, "calloc");
+
+	ni_nonce_ptr[0] = ~0;
+#else
+	gettimeofday(&ni_nonce_secret.tv, NULL);
+	ni_nonce_secret.pid = getpid();
+#endif
+}
+
+#if !PING6_NONCE_MEMORY
+static int niquery_nonce(uint8_t *nonce, int fill)
+{
+# ifdef USE_CRYPTO
+	static uint8_t digest[MD5_DIGEST_LENGTH];
+	static int seq = -1;
+
+	if (fill || seq != *(uint16_t *)nonce || seq < 0) {
+		MD5_CTX ctxt;
+
+		MD5_Init(&ctxt);
+		MD5_Update(&ctxt, &ni_nonce_secret, sizeof(ni_nonce_secret));
+		MD5_Update(&ctxt, nonce, sizeof(uint16_t));
+		MD5_Final(digest, &ctxt);
+
+		seq = *(uint16_t *)nonce;
+	}
+
+	if (fill) {
+		memcpy(nonce + sizeof(uint16_t), digest, NI_NONCE_SIZE - sizeof(uint16_t));
+		return 0;
+	} else {
+		if (memcmp(nonce + sizeof(uint16_t), digest, NI_NONCE_SIZE - sizeof(uint16_t)))
+			return -1;
+		return ntohsp((uint16_t *)nonce);
+	}
+# else
+	error(3, ENOSYS, "niquery_nonce() crypto disabled");
+# endif
+}
+#endif
+
+static inline void niquery_fill_nonce(uint16_t seq, uint8_t *nonce)
+{
+	uint16_t v = htons(seq);
+#if PING6_NONCE_MEMORY
+	int i;
+
+	memcpy(&ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK)], &v, sizeof(v));
+
+	for (i = sizeof(v); i < NI_NONCE_SIZE; i++)
+		ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK) + i] = 0x100 * (rand() / (RAND_MAX + 1.0));
+
+	memcpy(nonce, &ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK)], NI_NONCE_SIZE);
+#else
+	memcpy(nonce, &v, sizeof(v));
+	niquery_nonce(nonce, 1);
+#endif
+}
+
+static inline int niquery_check_nonce(uint8_t *nonce)
+{
+#if PING6_NONCE_MEMORY
+	uint16_t seq = ntohsp((uint16_t *)nonce);
+	if (memcmp(nonce, &ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK)], NI_NONCE_SIZE))
+		return -1;
+	return seq;
+#else
+	return niquery_nonce(nonce, 0);
+#endif
+}
+
+static int niquery_set_qtype(int type)
+{
+	if (niquery_is_enabled() && ni_query != type) {
+		printf("Qtype conflict\n");
+		return -1;
+	}
+	ni_query = type;
+	return 0;
+}
+
+static int niquery_option_name_handler(int index __attribute__((__unused__)), const char *arg __attribute__((__unused__)))
+{
+	if (niquery_set_qtype(NI_QTYPE_NAME) < 0)
+		return -1;
+	return 0;
+}
+
+static int niquery_option_ipv6_handler(int index __attribute__((__unused__)), const char *arg __attribute__((__unused__)))
+{
+	if (niquery_set_qtype(NI_QTYPE_IPV6ADDR) < 0)
+		return -1;
+	return 0;
+}
+
+static int niquery_option_ipv6_flag_handler(int index, const char *arg __attribute__((__unused__)))
+{
+	if (niquery_set_qtype(NI_QTYPE_IPV6ADDR) < 0)
+		return -1;
+	ni_flag |= niquery_options[index].data;
+	return 0;
+}
+
+static int niquery_option_ipv4_handler(int index __attribute__((__unused__)), const char *arg __attribute__((__unused__)))
+{
+	if (niquery_set_qtype(NI_QTYPE_IPV4ADDR) < 0)
+		return -1;
+	return 0;
+}
+
+static int niquery_option_ipv4_flag_handler(int index, const char *arg __attribute__((__unused__)))
+{
+	if (niquery_set_qtype(NI_QTYPE_IPV4ADDR) < 0)
+		return -1;
+	ni_flag |= niquery_options[index].data;
+	return 0;
+}
+
+static inline int niquery_is_subject_valid(void)
+{
+	return ni_subject_type >= 0 && ni_subject;
+}
+
+static int niquery_set_subject_type(int type)
+{
+	if (niquery_is_subject_valid() && ni_subject_type != type) {
+		printf("Subject type conflict\n");
+		return -1;
+	}
+	ni_subject_type = type;
+	return 0;
+}
+
+#define ARRAY_SIZE(array)	(sizeof(array) / sizeof(array[0]))
+#define OFFSET_OF(type,elem)	((size_t)&((type *)0)->elem)
+
+static int niquery_option_subject_addr_handler(int index, const char *arg)
+{
+	struct addrinfo hints = { .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = getaddrinfo_flags };
+	struct addrinfo *result, *ai;
+	int status;
+	int offset;
+
+	if (niquery_set_subject_type(niquery_options[index].data) < 0)
+		return -1;
+
+	ni_subject_type = niquery_options[index].data;
+
+	switch (niquery_options[index].data) {
+	case NI_SUBJ_IPV6:
+		ni_subject_len = sizeof(struct in6_addr);
+		offset = OFFSET_OF(struct sockaddr_in6, sin6_addr);
+		hints.ai_family = AF_INET6;
+		break;
+	case NI_SUBJ_IPV4:
+		ni_subject_len = sizeof(struct in_addr);
+		offset = OFFSET_OF(struct sockaddr_in, sin_addr);
+		hints.ai_family = AF_INET;
+		break;
+	default:
+		/* should not happen. */
+		offset = -1;
+	}
+
+	status = getaddrinfo(arg, 0, &hints, &result);
+	if (status) {
+		error(0, 0, "%s: %s", arg, gai_strerror(status));
+		return -1;
+	}
+
+	for (ai = result; ai; ai = ai->ai_next) {
+		void *p = malloc(ni_subject_len);
+		if (!p)
+			continue;
+		memcpy(p, (uint8_t *)ai->ai_addr + offset, ni_subject_len);
+		free(ni_subject);
+		ni_subject = p;
+		break;
+	}
+	freeaddrinfo(result);
+
+	return 0;
+}
+
+#ifdef USE_IDN
+# if IDN2_VERSION_NUMBER >= 0x02000000
+#  define IDN2_FLAGS IDN2_NONTRANSITIONAL
+# else
+#  define IDN2_FLAGS 0
+# endif
+#endif
+
+#ifdef USE_CRYPTO
+static int niquery_option_subject_name_handler(int index, const char *name)
+{
+	static char nigroup_buf[INET6_ADDRSTRLEN + 1 + IFNAMSIZ];
+	unsigned char *dnptrs[2], **dpp, **lastdnptr;
+	int n;
+	size_t i;
+	char *p;
+	char *canonname = NULL, *idn = NULL;
+	unsigned char *buf = NULL;
+	size_t namelen;
+	size_t buflen;
+	int dots, fqdn = niquery_options[index].data;
+	MD5_CTX ctxt;
+	uint8_t digest[MD5_DIGEST_LENGTH];
+#ifdef USE_IDN
+	int rc;
+#endif
+
+	if (niquery_set_subject_type(NI_SUBJ_NAME) < 0)
+		return -1;
+
+#ifdef USE_IDN
+	rc = idn2_lookup_ul(name, &idn, IDN2_FLAGS);
+	if (rc)
+		error(2, 0, "IDN encoding error: %s", idn2_strerror(rc));
+#else
+	idn = strdup(name);
+	if (!idn)
+		goto oomexit;
+#endif
+
+	p = strchr(idn, SCOPE_DELIMITER);
+	if (p) {
+		*p = '\0';
+		if (strlen(p + 1) >= IFNAMSIZ)
+			error(1, 0, "too long scope name");
+	}
+
+	namelen = strlen(idn);
+	canonname = malloc(namelen + 1);
+	if (!canonname)
+		goto oomexit;
+
+	dots = 0;
+	for (i = 0; i < namelen + 1; i++) {
+		canonname[i] = isupper(idn[i]) ? tolower(idn[i]) : idn[i];
+		if (idn[i] == '.')
+			dots++;
+	}
+
+	if (fqdn == 0) {
+		/* guess if hostname is FQDN */
+		fqdn = dots ? 1 : -1;
+	}
+
+	buflen = namelen + 3 + 1;	/* dn_comp() requrires strlen() + 3,
+					   plus non-fqdn indicator. */
+	buf = malloc(buflen);
+	if (!buf) {
+		error(0, errno, "memory allocation failed");
+		goto errexit;
+	}
+
+	dpp = dnptrs;
+	lastdnptr = &dnptrs[ARRAY_SIZE(dnptrs)];
+
+	*dpp++ = (unsigned char *)buf;
+	*dpp++ = NULL;
+
+	n = dn_comp(canonname, (unsigned char *)buf, buflen, dnptrs, lastdnptr);
+	if (n < 0) {
+		error(0, 0, "inappropriate subject name: %s", canonname);
+		goto errexit;
+	} else if ((size_t) n >= buflen) {
+		error(0, 0, "dn_comp() returned too long result");
+		goto errexit;
+	}
+
+	MD5_Init(&ctxt);
+	MD5_Update(&ctxt, buf, buf[0]);
+	MD5_Final(digest, &ctxt);
+
+	sprintf(nigroup_buf, "ff02::2:%02x%02x:%02x%02x%s%s",
+		digest[0], digest[1], digest[2], digest[3],
+		p ? "%" : "",
+		p ? p + 1 : "");
+
+	if (fqdn < 0)
+		buf[n] = 0;
+
+	free(ni_subject);
+
+	ni_group = nigroup_buf;
+	ni_subject = buf;
+	ni_subject_len = n + (fqdn < 0);
+	ni_group = nigroup_buf;
+
+	free(canonname);
+	free(idn);
+
+	return 0;
+oomexit:
+	error(0, errno, "memory allocation failed");
+errexit:
+	free(buf);
+	free(canonname);
+	free(idn);
+	exit(1);
+}
+#else
+static int niquery_option_subject_name_handler(int index __attribute__((__unused__)),
+					       const char *name __attribute__((__unused__)))
+{
+	error(3, ENOSYS, "niquery_option_subject_name_handler() crypto disabled");
+}
+#endif
+
+int niquery_option_help_handler(int index __attribute__((__unused__)), const char *arg __attribute__((__unused__)))
+{
+	fprintf(stderr, "ping -6 -N <nodeinfo opt>\n"
+			"Help:\n"
+			"  help\n"
+			"Query:\n"
+			"  name\n"
+			"  ipv6\n"
+			"  ipv6-all\n"
+			"  ipv6-compatible\n"
+			"  ipv6-global\n"
+			"  ipv6-linklocal\n"
+			"  ipv6-sitelocal\n"
+			"  ipv4\n"
+			"  ipv4-all\n"
+			"Subject:\n"
+			"  subject-ipv6=addr\n"
+			"  subject-ipv4=addr\n"
+			"  subject-name=name\n"
+			"  subject-fqdn=name\n"
+		);
+	exit(2);
+}
+
+int niquery_option_handler(const char *opt_arg)
+{
+	struct niquery_option *p;
+	int i;
+	int ret = -1;
+	for (i = 0, p = niquery_options; p->name; i++, p++) {
+		if (strncmp(p->name, opt_arg, p->namelen))
+			continue;
+		if (!p->has_arg) {
+			if (opt_arg[p->namelen] == '\0') {
+				ret = p->handler(i, NULL);
+				if (ret >= 0)
+					break;
+			}
+		} else {
+			if (opt_arg[p->namelen] == '=') {
+				ret = p->handler(i, &opt_arg[p->namelen] + 1);
+				if (ret >= 0)
+					break;
+			}
+		}
+	}
+	if (!p->name)
+		ret = niquery_option_help_handler(0, NULL);
+	return ret;
+}
+
+int ping6_run(int argc, char **argv, struct addrinfo *ai, struct socket_st *sock)
+{
+	static const struct addrinfo hints = { .ai_family = AF_INET6, .ai_flags = getaddrinfo_flags };
+	struct addrinfo *result = NULL;
+	int status;
+	int hold, packlen;
+	unsigned char *packet;
+	char *target;
+	struct icmp6_filter filter;
+	int err;
+	static uint32_t scope_id = 0;
+
+	if (niquery_is_enabled()) {
+		niquery_init_nonce();
+
+		if (!niquery_is_subject_valid()) {
+			ni_subject = &whereto.sin6_addr;
+			ni_subject_len = sizeof(whereto.sin6_addr);
+			ni_subject_type = NI_SUBJ_IPV6;
+		}
+	}
+
+	if (argc > 1) {
+		usage();
+	} else if (argc == 1) {
+		target = *argv;
+	} else {
+		if (ni_query < 0 && ni_subject_type != NI_SUBJ_NAME)
+			usage();
+		target = ni_group;
+	}
+
+	if (!ai) {
+		status = getaddrinfo(target, NULL, &hints, &result);
+		if (status)
+			error(2, 0, "%s: %s", target, gai_strerror(status));
+		ai = result;
+	}
+
+	memcpy(&whereto, ai->ai_addr, sizeof(whereto));
+	whereto.sin6_port = htons(IPPROTO_ICMPV6);
+
+	if (result)
+		freeaddrinfo(result);
+
+	if (memchr(target, ':', strlen(target)))
+		options |= F_NUMERIC;
+
+	if (IN6_IS_ADDR_UNSPECIFIED(&firsthop.sin6_addr)) {
+		memcpy(&firsthop.sin6_addr, &whereto.sin6_addr, 16);
+		firsthop.sin6_scope_id = whereto.sin6_scope_id;
+		/* Verify scope_id is the same as intermediate nodes */
+		if (firsthop.sin6_scope_id && scope_id && firsthop.sin6_scope_id != scope_id)
+			error(2, 0, "scope discrepancy among the nodes");
+		else if (!scope_id)
+			scope_id = firsthop.sin6_scope_id;
+	}
+
+	hostname = target;
+
+	if (IN6_IS_ADDR_UNSPECIFIED(&source6.sin6_addr)) {
+		socklen_t alen;
+		int probe_fd = socket(AF_INET6, SOCK_DGRAM, 0);
+
+		if (probe_fd < 0)
+			error(2, errno, "socket");
+		if (device) {
+			unsigned int iface = if_name2index(device);
+#ifdef IPV6_RECVPKTINFO
+			struct in6_pktinfo ipi;
+
+			memset(&ipi, 0, sizeof(ipi));
+			ipi.ipi6_ifindex = iface;
+#endif
+
+			if (IN6_IS_ADDR_LINKLOCAL(&firsthop.sin6_addr) ||
+			    IN6_IS_ADDR_MC_LINKLOCAL(&firsthop.sin6_addr))
+				firsthop.sin6_scope_id = iface;
+			enable_capability_raw();
+#ifdef IPV6_RECVPKTINFO
+			if (
+				setsockopt(probe_fd, IPPROTO_IPV6, IPV6_PKTINFO, &ipi, sizeof ipi) == -1 ||
+				setsockopt(sock->fd, IPPROTO_IPV6, IPV6_PKTINFO, &ipi, sizeof ipi) == -1) {
+				perror("setsockopt(IPV6_PKTINFO)");
+				exit(2);
+			}
+#endif
+			if (
+				setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1 ||
+				setsockopt(sock->fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1) {
+					error(2, errno, "setsockopt(SO_BINDTODEVICE) %s", device);
+			}
+			disable_capability_raw();
+		}
+
+		if (!IN6_IS_ADDR_LINKLOCAL(&firsthop.sin6_addr) &&
+			!IN6_IS_ADDR_MC_LINKLOCAL(&firsthop.sin6_addr))
+			firsthop.sin6_family = AF_INET6;
+
+		firsthop.sin6_port = htons(1025);
+		if (connect(probe_fd, (struct sockaddr*)&firsthop, sizeof(firsthop)) == -1)
+			error(2, errno, "connect");
+		alen = sizeof source6;
+		if (getsockname(probe_fd, (struct sockaddr *) &source6, &alen) == -1)
+			error(2, errno, "getsockname");
+		source6.sin6_port = 0;
+		close(probe_fd);
+
+		if (device) {
+			struct ifaddrs *ifa0, *ifa;
+
+			if (getifaddrs(&ifa0))
+				error(2, errno, "getifaddrs");
+
+			for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
+				if (!ifa->ifa_name || !ifa->ifa_addr ||
+				    ifa->ifa_addr->sa_family != AF_INET6)
+					continue;
+				if (!strcmp(ifa->ifa_name, device) &&
+				    IN6_ARE_ADDR_EQUAL(&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr,
+						       &source6.sin6_addr))
+					break;
+			}
+			if (!ifa)
+				error(0, 0, "Warning: source address might be selected on device other than: %s", device);
+
+			freeifaddrs(ifa0);
+		}
+	}
+	else if (device && (IN6_IS_ADDR_LINKLOCAL(&source6.sin6_addr) ||
+			    IN6_IS_ADDR_MC_LINKLOCAL(&source6.sin6_addr)))
+		source6.sin6_scope_id = if_name2index(device);
+
+	if (device) {
+		struct cmsghdr *cmsg;
+		struct in6_pktinfo *ipi;
+
+		cmsg = (struct cmsghdr*)(cmsgbuf+cmsglen);
+		cmsglen += CMSG_SPACE(sizeof(*ipi));
+		cmsg->cmsg_len = CMSG_LEN(sizeof(*ipi));
+		cmsg->cmsg_level = IPPROTO_IPV6;
+		cmsg->cmsg_type = IPV6_PKTINFO;
+
+		ipi = (struct in6_pktinfo*)CMSG_DATA(cmsg);
+		memset(ipi, 0, sizeof(*ipi));
+		ipi->ipi6_ifindex = if_name2index(device);
+	}
+
+	if ((whereto.sin6_addr.s6_addr16[0]&htons(0xff00)) == htons (0xff00)) {
+		if (uid) {
+			if (interval < 1000)
+				error(2, 0, "multicast ping with too short interval: %d", interval);
+			if (pmtudisc >= 0 && pmtudisc != IPV6_PMTUDISC_DO)
+				error(2, 0, "multicast ping does not fragment");
+		}
+		if (pmtudisc < 0)
+			pmtudisc = IPV6_PMTUDISC_DO;
+	}
+
+	if (pmtudisc >= 0) {
+		if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &pmtudisc, sizeof pmtudisc) == -1)
+			error(2, errno, "IPV6_MTU_DISCOVER");
+	}
+
+	if ((options&F_STRICTSOURCE) &&
+	    bind(sock->fd, (struct sockaddr *) &source6, sizeof source6) == -1)
+		error(2, errno, "bind icmp socket");
+
+	if ((ssize_t) datalen >= (ssize_t) sizeof(struct timeval) && (ni_query < 0)) {
+		/* can we time transfer */
+		timing = 1;
+	}
+	packlen = datalen + 8 + 4096 + 40 + 8; /* 4096 for rthdr */
+	if (!(packet = (unsigned char *)malloc((unsigned int)packlen)))
+		error(2, errno, "memory allocation failed");
+
+	hold = 1;
+
+	/* Estimate memory eaten by single packet. It is rough estimate.
+	 * Actually, for small datalen's it depends on kernel side a lot. */
+	hold = datalen+8;
+	hold += ((hold+511)/512)*(40+16+64+160);
+	sock_setbufs(sock, hold);
+
+#ifdef __linux__
+	if (sock->socktype == SOCK_RAW) {
+		int csum_offset = 2;
+		int sz_opt = sizeof(int);
+
+		err = setsockopt(sock->fd, SOL_RAW, IPV6_CHECKSUM, &csum_offset, sz_opt);
+		if (err < 0) {
+			/* checksum should be enabled by default and setting this
+			 * option might fail anyway.
+			 */
+			error(0, errno, "setsockopt(RAW_CHECKSUM) failed - try to continue");
+		}
+#else
+	{
+#endif
+
+		/*
+		 *	select icmp echo reply as icmp type to receive
+		 */
+
+		ICMP6_FILTER_SETBLOCKALL(&filter);
+
+		ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &filter);
+		ICMP6_FILTER_SETPASS(ICMP6_PACKET_TOO_BIG, &filter);
+		ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &filter);
+		ICMP6_FILTER_SETPASS(ICMP6_PARAM_PROB, &filter);
+
+		if (niquery_is_enabled())
+			ICMP6_FILTER_SETPASS(ICMPV6_NI_REPLY, &filter);
+		else
+			ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filter);
+
+		err = setsockopt(sock->fd, IPPROTO_ICMPV6, ICMP6_FILTER, &filter, sizeof filter);
+
+		if (err < 0)
+			error(2, errno, "setsockopt(ICMP6_FILTER)");
+	}
+
+	if (options & F_NOLOOP) {
+		int loop = 0;
+		if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof loop) == -1)
+			error(2, errno, "can't disable multicast loopback");
+	}
+	if (options & F_TTL) {
+		if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof ttl) == -1)
+			error(2, errno, "can't set multicast hop limit");
+		if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof ttl) == -1)
+			error(2, errno, "can't set unicast hop limit");
+	}
+
+	const int on = 1;
+	if (
+#ifdef IPV6_RECVHOPLIMIT
+	    setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof on) == -1 &&
+	    setsockopt(sock->fd, IPPROTO_IPV6, IPV6_2292HOPLIMIT, &on, sizeof on) == -1
+#else
+	    setsockopt(sock->fd, IPPROTO_IPV6, IPV6_HOPLIMIT, &on, sizeof on) == -1
+#endif
+	   )
+		error(2, errno, "can't receive hop limit");
+
+	if (options & F_TCLASS) {
+#ifdef IPV6_TCLASS
+		if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_TCLASS, &tclass, sizeof tclass) == -1)
+			error(2, errno, "setsockopt(IPV6_TCLASS)");
+#else
+		error(0, 0, "traffic class is not supported");
+#endif
+	}
+
+	if (options&F_FLOWINFO) {
+#ifdef IPV6_FLOWLABEL_MGR
+		char freq_buf[CMSG_ALIGN(sizeof(struct in6_flowlabel_req)) + cmsglen];
+		struct in6_flowlabel_req *freq = (struct in6_flowlabel_req *)freq_buf;
+		int freq_len = sizeof(*freq);
+		memset(freq, 0, sizeof(*freq));
+		freq->flr_label = htonl(flowlabel & IPV6_FLOWINFO_FLOWLABEL);
+		freq->flr_action = IPV6_FL_A_GET;
+		freq->flr_flags = IPV6_FL_F_CREATE;
+		freq->flr_share = IPV6_FL_S_EXCL;
+		memcpy(&freq->flr_dst, &whereto.sin6_addr, 16);
+		if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_FLOWLABEL_MGR, freq, freq_len) == -1)
+			error(2, errno, "can't set flowlabel");
+		flowlabel = freq->flr_label;
+#else
+		error(2, 0, "flow labels are not supported");
+#endif
+
+#ifdef IPV6_FLOWINFO_SEND
+		whereto.sin6_flowinfo = flowlabel;
+		if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_FLOWINFO_SEND, &on, sizeof on) == -1)
+			error(2, errno, "can't send flowinfo");
+#else
+		error(2, 0, "flowinfo is not supported");
+#endif
+	}
+
+	printf("PING %s(%s) ", hostname, pr_addr(&whereto, sizeof whereto));
+	if (flowlabel)
+		printf(", flow 0x%05x, ", (unsigned)ntohl(flowlabel));
+	if (device || (options&F_STRICTSOURCE)) {
+		int saved_options = options;
+
+		options |= F_NUMERIC;
+		printf("from %s %s: ", pr_addr(&source6, sizeof source6), device ? device : "");
+		options = saved_options;
+	}
+	printf("%d data bytes\n", datalen);
+
+	setup(sock);
+
+	drop_capabilities();
+
+	main_loop(&ping6_func_set, sock, packet, packlen);
+}
+
+int ping6_receive_error_msg(socket_st *sock)
+{
+	ssize_t res;
+	char cbuf[512];
+	struct iovec  iov;
+	struct msghdr msg;
+	struct cmsghdr *cmsg;
+	struct sock_extended_err *e;
+	struct icmp6_hdr icmph;
+	struct sockaddr_in6 target;
+	int net_errors = 0;
+	int local_errors = 0;
+	int saved_errno = errno;
+
+	iov.iov_base = &icmph;
+	iov.iov_len = sizeof(icmph);
+	msg.msg_name = (void*)&target;
+	msg.msg_namelen = sizeof(target);
+	msg.msg_iov = &iov;
+	msg.msg_iovlen = 1;
+	msg.msg_flags = 0;
+	msg.msg_control = cbuf;
+	msg.msg_controllen = sizeof(cbuf);
+
+	res = recvmsg(sock->fd, &msg, MSG_ERRQUEUE|MSG_DONTWAIT);
+	if (res < 0)
+		goto out;
+
+	e = NULL;
+	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+		if (cmsg->cmsg_level == IPPROTO_IPV6) {
+			if (cmsg->cmsg_type == IPV6_RECVERR)
+				e = (struct sock_extended_err *)CMSG_DATA(cmsg);
+		}
+	}
+	if (e == NULL)
+		abort();
+
+	if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
+		local_errors++;
+		if (options & F_QUIET)
+			goto out;
+		if (options & F_FLOOD)
+			write_stdout("E", 1);
+		else if (e->ee_errno != EMSGSIZE)
+			error(0, e->ee_errno, "local error");
+		else
+			error(0, 0, "local error: message too long, mtu: %u", e->ee_info);
+		nerrors++;
+	} else if (e->ee_origin == SO_EE_ORIGIN_ICMP6) {
+		struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)(e+1);
+
+		if ((size_t) res < sizeof(icmph) ||
+		    memcmp(&target.sin6_addr, &whereto.sin6_addr, 16) ||
+		    icmph.icmp6_type != ICMP6_ECHO_REQUEST ||
+		    !is_ours(sock, icmph.icmp6_id)) {
+			/* Not our error, not an error at all. Clear. */
+			saved_errno = 0;
+			goto out;
+		}
+
+		net_errors++;
+		nerrors++;
+		if (options & F_QUIET)
+			goto out;
+		if (options & F_FLOOD) {
+			write_stdout("\bE", 2);
+		} else {
+			print_timestamp();
+			printf("From %s icmp_seq=%u ", pr_addr(sin6, sizeof *sin6), ntohs(icmph.icmp6_seq));
+			pr_icmph(e->ee_type, e->ee_code, e->ee_info);
+			putchar('\n');
+			fflush(stdout);
+		}
+	}
+
+out:
+	errno = saved_errno;
+	return net_errors ? net_errors : -local_errors;
+}
+
+/*
+ * pinger --
+ * 	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
+ * will be added on by the kernel.  The ID field is our UNIX process ID,
+ * and the sequence number is an ascending integer.  The first several bytes
+ * of the data portion are used to hold a UNIX "timeval" struct in VAX
+ * byte-order, to compute the round-trip time.
+ */
+int build_echo(uint8_t *_icmph, unsigned packet_size __attribute__((__unused__)))
+{
+	struct icmp6_hdr *icmph;
+	int cc;
+
+	icmph = (struct icmp6_hdr *)_icmph;
+	icmph->icmp6_type = ICMP6_ECHO_REQUEST;
+	icmph->icmp6_code = 0;
+	icmph->icmp6_cksum = 0;
+	icmph->icmp6_seq = htons(ntransmitted+1);
+	icmph->icmp6_id = ident;
+
+	if (timing)
+		gettimeofday((struct timeval *)&_icmph[8],
+		    (struct timezone *)NULL);
+
+	cc = datalen + 8;			/* skips ICMP portion */
+
+	return cc;
+}
+
+
+int build_niquery(uint8_t *_nih, unsigned packet_size __attribute__((__unused__)))
+{
+	struct ni_hdr *nih;
+	int cc;
+
+	nih = (struct ni_hdr *)_nih;
+	nih->ni_cksum = 0;
+
+	nih->ni_type = ICMPV6_NI_QUERY;
+	cc = sizeof(*nih);
+	datalen = 0;
+
+	niquery_fill_nonce(ntransmitted + 1, nih->ni_nonce);
+	nih->ni_code = ni_subject_type;
+	nih->ni_qtype = htons(ni_query);
+	nih->ni_flags = ni_flag;
+	memcpy(nih + 1, ni_subject, ni_subject_len);
+	cc += ni_subject_len;
+
+	return cc;
+}
+
+int ping6_send_probe(socket_st *sock, void *packet, unsigned packet_size)
+{
+	int len, cc;
+
+	rcvd_clear(ntransmitted + 1);
+
+	if (niquery_is_enabled())
+		len = build_niquery(packet, packet_size);
+	else
+		len = build_echo(packet, packet_size);
+
+	if (cmsglen == 0) {
+		cc = sendto(sock->fd, (char *)packet, len, confirm,
+			    (struct sockaddr *) &whereto,
+			    sizeof(struct sockaddr_in6));
+	} else {
+		struct msghdr mhdr;
+		struct iovec iov;
+
+		iov.iov_len  = len;
+		iov.iov_base = packet;
+
+		memset(&mhdr, 0, sizeof(mhdr));
+		mhdr.msg_name = &whereto;
+		mhdr.msg_namelen = sizeof(struct sockaddr_in6);
+		mhdr.msg_iov = &iov;
+		mhdr.msg_iovlen = 1;
+		mhdr.msg_control = cmsgbuf;
+		mhdr.msg_controllen = cmsglen;
+
+		cc = sendmsg(sock->fd, &mhdr, confirm);
+	}
+	confirm = 0;
+
+	return (cc == len ? 0 : cc);
+}
+
+void pr_echo_reply(uint8_t *_icmph, int cc __attribute__((__unused__)))
+{
+	struct icmp6_hdr *icmph = (struct icmp6_hdr *) _icmph;
+	printf(" icmp_seq=%u", ntohs(icmph->icmp6_seq));
+}
+
+static void putchar_safe(char c)
+{
+	if (isprint(c))
+		putchar(c);
+	else
+		printf("\\%03o", c);
+}
+
+static
+void pr_niquery_reply_name(struct ni_hdr *nih, int len)
+{
+	uint8_t *h = (uint8_t *)(nih + 1);
+	uint8_t *p = h + 4;
+	uint8_t *end = (uint8_t *)nih + len;
+	int continued = 0;
+	char buf[1024];
+	int ret;
+
+	len -= sizeof(struct ni_hdr) + 4;
+
+	if (len < 0) {
+		printf(" parse error (too short)");
+		return;
+	}
+	while (p < end) {
+		int fqdn = 1;
+		size_t i;
+
+		memset(buf, 0xff, sizeof(buf));
+
+		if (continued)
+			putchar(',');
+
+		ret = dn_expand(h, end, p, buf, sizeof(buf));
+		if (ret < 0) {
+			printf(" parse error (truncated)");
+			break;
+		}
+		if (p + ret < end && *(p + ret) == '\0')
+			fqdn = 0;
+
+		putchar(' ');
+		for (i = 0; i < strlen(buf); i++)
+			putchar_safe(buf[i]);
+		if (fqdn)
+			putchar('.');
+
+		p += ret + !fqdn;
+
+		continued = 1;
+	}
+}
+
+static
+void pr_niquery_reply_addr(struct ni_hdr *nih, int len)
+{
+	uint8_t *h = (uint8_t *)(nih + 1);
+	uint8_t *p;
+	uint8_t *end = (uint8_t *)nih + len;
+	int af;
+	int aflen;
+	int continued = 0;
+	int truncated;
+	char buf[1024];
+
+	switch (ntohs(nih->ni_qtype)) {
+	case NI_QTYPE_IPV4ADDR:
+		af = AF_INET;
+		aflen = sizeof(struct in_addr);
+		truncated = nih->ni_flags & NI_IPV6ADDR_F_TRUNCATE;
+		break;
+	case NI_QTYPE_IPV6ADDR:
+		af = AF_INET6;
+		aflen = sizeof(struct in6_addr);
+		truncated = nih->ni_flags & NI_IPV4ADDR_F_TRUNCATE;
+		break;
+	default:
+		/* should not happen */
+		af = aflen = truncated = 0;
+	}
+	p = h;
+	if (len < 0) {
+		printf(" parse error (too short)");
+		return;
+	}
+
+	while (p < end) {
+		if (continued)
+			putchar(',');
+
+		if (p + sizeof(uint32_t) + aflen > end) {
+			printf(" parse error (truncated)");
+			break;
+		}
+		if (!inet_ntop(af, p + sizeof(uint32_t), buf, sizeof(buf)))
+			printf(" unexpeced error in inet_ntop(%s)",
+			       strerror(errno));
+		else
+			printf(" %s", buf);
+		p += sizeof(uint32_t) + aflen;
+
+		continued = 1;
+	}
+	if (truncated)
+		printf(" (truncated)");
+}
+
+static
+void pr_niquery_reply(uint8_t *_nih, int len)
+{
+	struct ni_hdr *nih = (struct ni_hdr *)_nih;
+
+	switch (nih->ni_code) {
+	case NI_SUCCESS:
+		switch (ntohs(nih->ni_qtype)) {
+		case NI_QTYPE_NAME:
+			pr_niquery_reply_name(nih, len);
+			break;
+		case NI_QTYPE_IPV4ADDR:
+		case NI_QTYPE_IPV6ADDR:
+			pr_niquery_reply_addr(nih, len);
+			break;
+		default:
+			printf(" unknown qtype(0x%02x)", ntohs(nih->ni_qtype));
+		}
+		break;
+	case NI_REFUSED:
+		printf(" refused");
+		break;
+	case NI_UNKNOWN:
+		printf(" unknown");
+		break;
+	default:
+		printf(" unknown code(%02x)", ntohs(nih->ni_code));
+	}
+	printf("; seq=%u;", ntohsp((uint16_t*)nih->ni_nonce));
+}
+
+/*
+ * parse_reply --
+ *	Print out the packet, if it came from us.  This logic is necessary
+ * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
+ * which arrive ('tis only fair).  This permits multiple copies of this
+ * program to be run without having intermingled output (or statistics!).
+ */
+int
+ping6_parse_reply(socket_st *sock, struct msghdr *msg, int cc, void *addr, struct timeval *tv)
+{
+	struct sockaddr_in6 *from = addr;
+	uint8_t *buf = msg->msg_iov->iov_base;
+	struct cmsghdr *c;
+	struct icmp6_hdr *icmph;
+	int hops = -1;
+
+	for (c = CMSG_FIRSTHDR(msg); c; c = CMSG_NXTHDR(msg, c)) {
+		if (c->cmsg_level != IPPROTO_IPV6)
+			continue;
+		switch(c->cmsg_type) {
+		case IPV6_HOPLIMIT:
+#ifdef IPV6_2292HOPLIMIT
+		case IPV6_2292HOPLIMIT:
+#endif
+			if (c->cmsg_len < CMSG_LEN(sizeof(int)))
+				continue;
+			memcpy(&hops, CMSG_DATA(c), sizeof(hops));
+		}
+	}
+
+
+	/* Now the ICMP part */
+
+	icmph = (struct icmp6_hdr *) buf;
+	if (cc < 8) {
+		if (options & F_VERBOSE)
+			error(0, 0, "packet too short: %d bytes", cc);
+		return 1;
+	}
+
+	if (icmph->icmp6_type == ICMP6_ECHO_REPLY) {
+		if (!is_ours(sock, icmph->icmp6_id))
+			return 1;
+               if (!contains_pattern_in_payload((uint8_t*)(icmph+1)))
+               		return 1;            /* 'Twas really not our ECHO */
+		if (gather_statistics((uint8_t*)icmph, sizeof(*icmph), cc,
+				      ntohs(icmph->icmp6_seq),
+				      hops, 0, tv, pr_addr(from, sizeof *from),
+				      pr_echo_reply)) {
+			fflush(stdout);
+			return 0;
+		}
+	} else if (icmph->icmp6_type == ICMPV6_NI_REPLY) {
+		struct ni_hdr *nih = (struct ni_hdr *)icmph;
+		int seq = niquery_check_nonce(nih->ni_nonce);
+		if (seq < 0)
+			return 1;
+		if (gather_statistics((uint8_t*)icmph, sizeof(*icmph), cc,
+				      seq,
+				      hops, 0, tv, pr_addr(from, sizeof *from),
+				      pr_niquery_reply))
+			return 0;
+	} else {
+		int nexthdr;
+		struct ip6_hdr *iph1 = (struct ip6_hdr*)(icmph+1);
+		struct icmp6_hdr *icmph1 = (struct icmp6_hdr *)(iph1+1);
+
+		/* We must not ever fall here. All the messages but
+		 * echo reply are blocked by filter and error are
+		 * received with IPV6_RECVERR. Ugly code is preserved
+		 * however, just to remember what crap we avoided
+		 * using RECVRERR. :-)
+		 */
+
+		if (cc < (int) (8 + sizeof(struct ip6_hdr) + 8))
+			return 1;
+
+		if (memcmp(&iph1->ip6_dst, &whereto.sin6_addr, 16))
+			return 1;
+
+		nexthdr = iph1->ip6_nxt;
+
+		if (nexthdr == 44) {
+			nexthdr = *(uint8_t*)icmph1;
+			icmph1++;
+		}
+		if (nexthdr == IPPROTO_ICMPV6) {
+			if (icmph1->icmp6_type != ICMP6_ECHO_REQUEST ||
+			    !is_ours(sock, icmph1->icmp6_id))
+				return 1;
+			acknowledge(ntohs(icmph1->icmp6_seq));
+			nerrors++;
+			if (options & F_FLOOD) {
+				write_stdout("\bE", 2);
+				return 0;
+			}
+			print_timestamp();
+			printf("From %s: icmp_seq=%u ", pr_addr(from, sizeof *from), ntohs(icmph1->icmp6_seq));
+		} else {
+			/* We've got something other than an ECHOREPLY */
+			if (!(options & F_VERBOSE) || uid)
+				return 1;
+			print_timestamp();
+			printf("From %s: ", pr_addr(from, sizeof *from));
+		}
+		pr_icmph(icmph->icmp6_type, icmph->icmp6_code, ntohl(icmph->icmp6_mtu));
+	}
+
+	if (options & F_AUDIBLE) {
+		putchar('\a');
+		if(options & F_FLOOD)
+			fflush(stdout);
+	}
+	if (!(options & F_FLOOD)) {
+		putchar('\n');
+		fflush(stdout);
+	}
+	return 0;
+}
+
+
+int pr_icmph(uint8_t type, uint8_t code, uint32_t info)
+{
+	switch(type) {
+	case ICMP6_DST_UNREACH:
+		printf("Destination unreachable: ");
+		switch (code) {
+		case ICMP6_DST_UNREACH_NOROUTE:
+			printf("No route");
+			break;
+		case ICMP6_DST_UNREACH_ADMIN:
+			printf("Administratively prohibited");
+			break;
+		case ICMP6_DST_UNREACH_BEYONDSCOPE:
+			printf("Beyond scope of source address");
+			break;
+		case ICMP6_DST_UNREACH_ADDR:
+			printf("Address unreachable");
+			break;
+		case ICMP6_DST_UNREACH_NOPORT:
+			printf("Port unreachable");
+			break;
+		default:
+			printf("Unknown code %d", code);
+			break;
+		}
+		break;
+	case ICMP6_PACKET_TOO_BIG:
+		printf("Packet too big: mtu=%u", info);
+		if (code)
+			printf(", code=%d", code);
+		break;
+	case ICMP6_TIME_EXCEEDED:
+		printf("Time exceeded: ");
+		if (code == ICMP6_TIME_EXCEED_TRANSIT)
+			printf("Hop limit");
+		else if (code == ICMP6_TIME_EXCEED_REASSEMBLY)
+			printf("Defragmentation failure");
+		else
+			printf("code %d", code);
+		break;
+	case ICMP6_PARAM_PROB:
+		printf("Parameter problem: ");
+		if (code == ICMP6_PARAMPROB_HEADER)
+			printf("Wrong header field ");
+		else if (code == ICMP6_PARAMPROB_NEXTHEADER)
+			printf("Unknown header ");
+		else if (code == ICMP6_PARAMPROB_OPTION)
+			printf("Unknown option ");
+		else
+			printf("code %d ", code);
+		printf ("at %u", info);
+		break;
+	case ICMP6_ECHO_REQUEST:
+		printf("Echo request");
+		break;
+	case ICMP6_ECHO_REPLY:
+		printf("Echo reply");
+		break;
+	case MLD_LISTENER_QUERY:
+		printf("MLD Query");
+		break;
+	case MLD_LISTENER_REPORT:
+		printf("MLD Report");
+		break;
+	case MLD_LISTENER_REDUCTION:
+		printf("MLD Reduction");
+		break;
+	default:
+		printf("unknown icmp type: %u", type);
+
+	}
+	return 0;
+}
+
+void ping6_install_filter(socket_st *sock)
+{
+	static int once;
+	static struct sock_filter insns[] = {
+		BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 4),  /* Load icmp echo ident */
+		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xAAAA, 0, 1),  /* Ours? */
+		BPF_STMT(BPF_RET|BPF_K, ~0U),  /* Yes, it passes. */
+		BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 0),  /* Load icmp type */
+		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ICMP6_ECHO_REPLY, 1, 0), /* Echo? */
+		BPF_STMT(BPF_RET|BPF_K, ~0U), /* No. It passes. This must not happen. */
+		BPF_STMT(BPF_RET|BPF_K, 0), /* Echo with wrong ident. Reject. */
+	};
+	static struct sock_fprog filter = {
+		sizeof insns / sizeof(insns[0]),
+		insns
+	};
+
+	if (once)
+		return;
+	once = 1;
+
+	/* Patch bpflet for current identifier. */
+	insns[1] = (struct sock_filter)BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, htons(ident), 0, 1);
+
+	if (setsockopt(sock->fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)))
+		error(0, errno, "WARNING: failed to install socket filter");
+}
-- 
GitLab