1/*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (C) 2019 Jan Sucan <jansucan@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/types.h>
30#include <sys/socket.h>
31
32#include <arpa/inet.h>
33#include <netdb.h>
34#include <netinet/in.h>
35
36#include <err.h>
37#include <math.h>
38#include <signal.h>
39#include <stdbool.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <sysexits.h>
44#include <unistd.h>
45
46#include "main.h"
47#ifdef INET
48#include "ping.h"
49#endif
50#ifdef INET6
51#include "ping6.h"
52#endif
53
54#if defined(INET) && defined(INET6)
55#define	OPTSTR PING6OPTS PING4OPTS
56#elif defined(INET)
57#define	OPTSTR PING4OPTS
58#elif defined(INET6)
59#define	OPTSTR PING6OPTS
60#else
61#error At least one of INET and INET6 is required
62#endif
63
64#ifdef __HAIKU__
65#define optreset optind
66#define feature_present(x) true
67#ifndef restrict
68#define restrict
69#endif
70#endif
71
72/* various options */
73u_int options;
74
75char *hostname;
76
77/* counters */
78long nreceived;		/* # of packets we got back */
79long nrepeats;		/* number of duplicates */
80long ntransmitted;	/* sequence # for outbound packets = #sent */
81long nrcvtimeout = 0;	/* # of packets we got back after waittime */
82
83/* nonzero if we've been told to finish up */
84volatile sig_atomic_t seenint;
85volatile sig_atomic_t seeninfo;
86
87/* timing */
88int timing;		/* flag to do timing */
89double tmin = 999999999.0;	/* minimum round trip time */
90double tmax = 0.0;	/* maximum round trip time */
91double tsum = 0.0;	/* sum of all times, for doing average */
92double tsumsq = 0.0;	/* sum of all times squared, for std. dev. */
93
94int
95main(int argc, char *argv[])
96{
97#if defined(INET)
98	struct in_addr a;
99#endif
100#if defined(INET6)
101	struct in6_addr a6;
102#endif
103#if defined(INET) && defined(INET6)
104	struct addrinfo hints, *res, *ai;
105	const char *target;
106	int error;
107#endif
108	int opt;
109
110#ifdef INET6
111	if (strcmp(getprogname(), "ping6") == 0)
112		return ping6(argc, argv);
113#endif
114
115	while ((opt = getopt(argc, argv, ":" OPTSTR)) != -1) {
116		switch (opt) {
117#ifdef INET
118		case '4':
119			goto ping4;
120#endif
121#ifdef INET6
122		case '6':
123			goto ping6;
124#endif
125		case 'S':
126			/*
127			 * If -S is given with a numeric parameter,
128			 * force use of the corresponding version.
129			 */
130#ifdef INET
131			if (inet_pton(AF_INET, optarg, &a) == 1)
132				goto ping4;
133#endif
134#ifdef INET6
135			if (inet_pton(AF_INET6, optarg, &a6) == 1)
136				goto ping6;
137#endif
138			break;
139		default:
140			break;
141		}
142	}
143
144	/*
145	 * For IPv4, only one positional argument, the target, is allowed.
146	 * For IPv6, multiple positional argument are allowed; the last
147	 * one is the target, and preceding ones are intermediate hops.
148	 * This nuance is lost here, but the only case where it matters is
149	 * an error.
150	 */
151	if (optind >= argc)
152		usage();
153
154#if defined(INET) && defined(INET6)
155	target = argv[argc - 1];
156	memset(&hints, 0, sizeof(hints));
157	hints.ai_socktype = SOCK_RAW;
158#ifdef __HAIKU__
159	hints.ai_flags = AI_ADDRCONFIG;
160#endif
161	if (feature_present("inet") && !feature_present("inet6"))
162		hints.ai_family = AF_INET;
163	if (feature_present("inet6") && !feature_present("inet"))
164		hints.ai_family = AF_INET6;
165	else
166		hints.ai_family = AF_UNSPEC;
167	error = getaddrinfo(target, NULL, &hints, &res);
168	if (res == NULL)
169		errx(EX_NOHOST, "cannot resolve %s: %s",
170		    target, gai_strerror(error));
171	for (ai = res; ai != NULL; ai = ai->ai_next) {
172		if (ai->ai_family == AF_INET) {
173			freeaddrinfo(res);
174			goto ping4;
175		}
176		if (ai->ai_family == AF_INET6) {
177			freeaddrinfo(res);
178			goto ping6;
179		}
180	}
181	freeaddrinfo(res);
182	errx(EX_NOHOST, "cannot resolve %s", target);
183#endif
184#ifdef INET
185ping4:
186	optreset = 1;
187	optind = 1;
188	return ping(argc, argv);
189#endif
190#ifdef INET6
191ping6:
192	optreset = 1;
193	optind = 1;
194	return ping6(argc, argv);
195#endif
196}
197
198/*
199 * onsignal --
200 *	Set the global bit that causes the main loop to quit.
201 */
202void
203onsignal(int sig)
204{
205	switch (sig) {
206	case SIGALRM:
207	case SIGINT:
208		/*
209		 * When doing reverse DNS lookups, the seenint flag might not
210		 * be noticed for a while.  Just exit if we get a second SIGINT.
211		 */
212		if (!(options & F_HOSTNAME) && seenint != 0)
213			_exit(nreceived ? 0 : 2);
214		seenint++;
215		break;
216#ifndef __HAIKU__
217	case SIGINFO:
218		seeninfo++;
219		break;
220#endif
221	}
222}
223
224/*
225 * pr_summary --
226 *	Print out summary statistics to the given output stream.
227 */
228void
229pr_summary(FILE * restrict stream)
230{
231	fprintf(stream, "\n--- %s ping statistics ---\n", hostname);
232	fprintf(stream, "%ld packets transmitted, ", ntransmitted);
233	fprintf(stream, "%ld packets received, ", nreceived);
234	if (nrepeats)
235		fprintf(stream, "+%ld duplicates, ", nrepeats);
236	if (ntransmitted) {
237		if (nreceived > ntransmitted)
238			fprintf(stream, "-- somebody's duplicating packets!");
239		else
240			fprintf(stream, "%.1f%% packet loss",
241			    ((((double)ntransmitted - nreceived) * 100.0) /
242			    ntransmitted));
243	}
244	if (nrcvtimeout)
245		fprintf(stream, ", %ld packets out of wait time", nrcvtimeout);
246	fputc('\n', stream);
247	if (nreceived && timing) {
248		/* Only display average to microseconds */
249		double num = nreceived + nrepeats;
250		double avg = tsum / num;
251		double stddev = sqrt(fmax(0, tsumsq / num - avg * avg));
252		fprintf(stream,
253		    "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
254		    tmin, avg, tmax, stddev);
255	}
256	fflush(stream);
257}
258
259void
260usage(void)
261{
262	(void)fprintf(stderr,
263	    "usage:\n"
264#ifdef INET
265	    "\tping [-4AaDdfHnoQqRrv] [-C pcp] [-c count] "
266	    "[-G sweepmaxsize]\n"
267	    "\t    [-g sweepminsize] [-h sweepincrsize] [-i wait] "
268	    "[-l preload]\n"
269	    "\t    [-M mask | time] [-m ttl] "
270#ifdef IPSEC
271	    "[-P policy] "
272#endif
273	    "[-p pattern] [-S src_addr] \n"
274	    "\t    [-s packetsize] [-t timeout] [-W waittime] [-z tos] "
275	    "IPv4-host\n"
276	    "\tping [-4AaDdfHLnoQqRrv] [-C pcp] [-c count] [-I iface] "
277	    "[-i wait]\n"
278	    "\t    [-l preload] [-M mask | time] [-m ttl] "
279#ifdef IPSEC
280	    "[-P policy] "
281#endif
282	    "[-p pattern]\n"
283	    "\t    [-S src_addr] [-s packetsize] [-T ttl] [-t timeout] [-W waittime]\n"
284	    "\t    [-z tos] IPv4-mcast-group\n"
285#endif /* INET */
286#ifdef INET6
287	    "\tping [-6AaDd"
288#if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
289	    "E"
290#endif
291	    "fHnNoOq"
292#ifdef IPV6_USE_MIN_MTU
293	    "u"
294#endif
295	    "vyY"
296#if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
297	    "Z"
298#endif
299	    "] "
300	    "[-b bufsiz] [-C pcp] [-c count] [-e gateway]\n"
301	    "\t    [-I interface] [-i wait] [-k addrtype] [-l preload] "
302	    "[-m hoplimit]\n"
303	    "\t    [-p pattern]"
304#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
305	    " [-P policy]"
306#endif
307	    " [-S sourceaddr] [-s packetsize] [-t timeout]\n"
308	    "\t    [-W waittime] [-z tclass] [IPv6-hops ...] IPv6-host\n"
309#endif	/* INET6 */
310	    );
311
312	exit(1);
313}
314