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/* various options */
65u_int options;
66
67char *hostname;
68
69/* counters */
70long nreceived;		/* # of packets we got back */
71long nrepeats;		/* number of duplicates */
72long ntransmitted;	/* sequence # for outbound packets = #sent */
73long nrcvtimeout = 0;	/* # of packets we got back after waittime */
74
75/* nonzero if we've been told to finish up */
76volatile sig_atomic_t seenint;
77volatile sig_atomic_t seeninfo;
78
79/* timing */
80int timing;		/* flag to do timing */
81double tmin = 999999999.0;	/* minimum round trip time */
82double tmax = 0.0;	/* maximum round trip time */
83double tsum = 0.0;	/* sum of all times, for doing average */
84double tsumsq = 0.0;	/* sum of all times squared, for std. dev. */
85
86int
87main(int argc, char *argv[])
88{
89#if defined(INET)
90	struct in_addr a;
91#endif
92#if defined(INET6)
93	struct in6_addr a6;
94#endif
95#if defined(INET) && defined(INET6)
96	struct addrinfo hints, *res, *ai;
97	const char *target;
98	int error;
99#endif
100	int opt;
101
102#ifdef INET6
103	if (strcmp(getprogname(), "ping6") == 0)
104		return ping6(argc, argv);
105#endif
106
107	while ((opt = getopt(argc, argv, ":" OPTSTR)) != -1) {
108		switch (opt) {
109#ifdef INET
110		case '4':
111			goto ping4;
112#endif
113#ifdef INET6
114		case '6':
115			goto ping6;
116#endif
117		case 'S':
118			/*
119			 * If -S is given with a numeric parameter,
120			 * force use of the corresponding version.
121			 */
122#ifdef INET
123			if (inet_pton(AF_INET, optarg, &a) == 1)
124				goto ping4;
125#endif
126#ifdef INET6
127			if (inet_pton(AF_INET6, optarg, &a6) == 1)
128				goto ping6;
129#endif
130			break;
131		default:
132			break;
133		}
134	}
135
136	/*
137	 * For IPv4, only one positional argument, the target, is allowed.
138	 * For IPv6, multiple positional argument are allowed; the last
139	 * one is the target, and preceding ones are intermediate hops.
140	 * This nuance is lost here, but the only case where it matters is
141	 * an error.
142	 */
143	if (optind >= argc)
144		usage();
145
146#if defined(INET) && defined(INET6)
147	target = argv[argc - 1];
148	memset(&hints, 0, sizeof(hints));
149	hints.ai_socktype = SOCK_RAW;
150	if (feature_present("inet") && !feature_present("inet6"))
151		hints.ai_family = AF_INET;
152	else if (feature_present("inet6") && !feature_present("inet"))
153		hints.ai_family = AF_INET6;
154	else
155		hints.ai_family = AF_UNSPEC;
156	error = getaddrinfo(target, NULL, &hints, &res);
157	if (res == NULL)
158		errx(EX_NOHOST, "cannot resolve %s: %s",
159		    target, gai_strerror(error));
160	for (ai = res; ai != NULL; ai = ai->ai_next) {
161		if (ai->ai_family == AF_INET) {
162			freeaddrinfo(res);
163			goto ping4;
164		}
165		if (ai->ai_family == AF_INET6) {
166			freeaddrinfo(res);
167			goto ping6;
168		}
169	}
170	freeaddrinfo(res);
171	errx(EX_NOHOST, "cannot resolve %s", target);
172#endif
173#ifdef INET
174ping4:
175	optreset = 1;
176	optind = 1;
177	return ping(argc, argv);
178#endif
179#ifdef INET6
180ping6:
181	optreset = 1;
182	optind = 1;
183	return ping6(argc, argv);
184#endif
185}
186
187/*
188 * onsignal --
189 *	Set the global bit that causes the main loop to quit.
190 */
191void
192onsignal(int sig)
193{
194	switch (sig) {
195	case SIGALRM:
196	case SIGINT:
197		/*
198		 * When doing reverse DNS lookups, the seenint flag might not
199		 * be noticed for a while.  Just exit if we get a second SIGINT.
200		 */
201		if (!(options & F_HOSTNAME) && seenint != 0)
202			_exit(nreceived ? 0 : 2);
203		seenint++;
204		break;
205	case SIGINFO:
206		seeninfo++;
207		break;
208	}
209}
210
211/*
212 * pr_summary --
213 *	Print out summary statistics to the given output stream.
214 */
215void
216pr_summary(FILE * restrict stream)
217{
218	fprintf(stream, "\n--- %s ping statistics ---\n", hostname);
219	fprintf(stream, "%ld packets transmitted, ", ntransmitted);
220	fprintf(stream, "%ld packets received, ", nreceived);
221	if (nrepeats)
222		fprintf(stream, "+%ld duplicates, ", nrepeats);
223	if (ntransmitted) {
224		if (nreceived > ntransmitted)
225			fprintf(stream, "-- somebody's duplicating packets!");
226		else
227			fprintf(stream, "%.1f%% packet loss",
228			    ((((double)ntransmitted - nreceived) * 100.0) /
229			    ntransmitted));
230	}
231	if (nrcvtimeout)
232		fprintf(stream, ", %ld packets out of wait time", nrcvtimeout);
233	fputc('\n', stream);
234	if (nreceived && timing) {
235		/* Only display average to microseconds */
236		double num = nreceived + nrepeats;
237		double avg = tsum / num;
238		double stddev = sqrt(fmax(0, tsumsq / num - avg * avg));
239		fprintf(stream,
240		    "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
241		    tmin, avg, tmax, stddev);
242	}
243	fflush(stream);
244}
245
246void
247usage(void)
248{
249	(void)fprintf(stderr,
250	    "usage:\n"
251#ifdef INET
252	    "\tping [-4AaDdfHnoQqRrv] [-C pcp] [-c count] "
253	    "[-G sweepmaxsize]\n"
254	    "\t    [-g sweepminsize] [-h sweepincrsize] [-i wait] "
255	    "[-l preload]\n"
256	    "\t    [-M mask | time] [-m ttl] "
257#ifdef IPSEC
258	    "[-P policy] "
259#endif
260	    "[-p pattern] [-S src_addr] \n"
261	    "\t    [-s packetsize] [-t timeout] [-W waittime] [-z tos] "
262	    "IPv4-host\n"
263	    "\tping [-4AaDdfHLnoQqRrv] [-C pcp] [-c count] [-I iface] "
264	    "[-i wait]\n"
265	    "\t    [-l preload] [-M mask | time] [-m ttl] "
266#ifdef IPSEC
267	    "[-P policy] "
268#endif
269	    "[-p pattern]\n"
270	    "\t    [-S src_addr] [-s packetsize] [-T ttl] [-t timeout] [-W waittime]\n"
271	    "\t    [-z tos] IPv4-mcast-group\n"
272#endif /* INET */
273#ifdef INET6
274	    "\tping [-6AaDd"
275#if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
276	    "E"
277#endif
278	    "fHnNoOq"
279#ifdef IPV6_USE_MIN_MTU
280	    "u"
281#endif
282	    "vyY"
283#if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
284	    "Z"
285#endif
286	    "] "
287	    "[-b bufsiz] [-C pcp] [-c count] [-e gateway]\n"
288	    "\t    [-I interface] [-i wait] [-k addrtype] [-l preload] "
289	    "[-m hoplimit]\n"
290	    "\t    [-p pattern]"
291#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
292	    " [-P policy]"
293#endif
294	    " [-S sourceaddr] [-s packetsize] [-t timeout]\n"
295	    "\t    [-W waittime] [-z tclass] [IPv6-hops ...] IPv6-host\n"
296#endif	/* INET6 */
297	    );
298
299	exit(1);
300}
301