11558Srgrimes/*
21558Srgrimes * Copyright (c) 1989, 1993
31558Srgrimes *	The Regents of the University of California.  All rights reserved.
41558Srgrimes *
51558Srgrimes * This code is derived from software contributed to Berkeley by
61558Srgrimes * Mike Muuss.
71558Srgrimes *
81558Srgrimes * Redistribution and use in source and binary forms, with or without
91558Srgrimes * modification, are permitted provided that the following conditions
101558Srgrimes * are met:
111558Srgrimes * 1. Redistributions of source code must retain the above copyright
121558Srgrimes *    notice, this list of conditions and the following disclaimer.
131558Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141558Srgrimes *    notice, this list of conditions and the following disclaimer in the
151558Srgrimes *    documentation and/or other materials provided with the distribution.
161558Srgrimes * 4. Neither the name of the University nor the names of its contributors
171558Srgrimes *    may be used to endorse or promote products derived from this software
181558Srgrimes *    without specific prior written permission.
191558Srgrimes *
201558Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211558Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221558Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231558Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241558Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251558Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261558Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271558Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281558Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291558Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301558Srgrimes * SUCH DAMAGE.
311558Srgrimes */
321558Srgrimes
33114589Sobrien#if 0
341558Srgrimes#ifndef lint
3523247Swollmanstatic const char copyright[] =
361558Srgrimes"@(#) Copyright (c) 1989, 1993\n\
371558Srgrimes	The Regents of the University of California.  All rights reserved.\n";
381558Srgrimes#endif /* not lint */
391558Srgrimes
401558Srgrimes#ifndef lint
411558Srgrimesstatic char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
42114589Sobrien#endif /* not lint */
4337671Scharnier#endif
44114589Sobrien#include <sys/cdefs.h>
45114589Sobrien__FBSDID("$FreeBSD$");
461558Srgrimes
471558Srgrimes/*
481558Srgrimes *			P I N G . C
491558Srgrimes *
5037671Scharnier * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
511558Srgrimes * measure round-trip-delays and packet loss across network paths.
521558Srgrimes *
531558Srgrimes * Author -
541558Srgrimes *	Mike Muuss
551558Srgrimes *	U. S. Army Ballistic Research Laboratory
561558Srgrimes *	December, 1983
571558Srgrimes *
581558Srgrimes * Status -
591558Srgrimes *	Public Domain.  Distribution Unlimited.
601558Srgrimes * Bugs -
611558Srgrimes *	More statistics could always be gathered.
621558Srgrimes *	This program has to run SUID to ROOT to access the ICMP socket.
631558Srgrimes */
641558Srgrimes
6523247Swollman#include <sys/param.h>		/* NB: we rely on this for <sys/types.h> */
66109733Smaxim#include <sys/socket.h>
67109731Smaxim#include <sys/sysctl.h>
68109733Smaxim#include <sys/time.h>
69109733Smaxim#include <sys/uio.h>
7023247Swollman
71109733Smaxim#include <netinet/in.h>
72109733Smaxim#include <netinet/in_systm.h>
73109733Smaxim#include <netinet/ip.h>
74109733Smaxim#include <netinet/ip_icmp.h>
75109733Smaxim#include <netinet/ip_var.h>
76109733Smaxim#include <arpa/inet.h>
77109733Smaxim
78109733Smaxim#ifdef IPSEC
79171135Sgnn#include <netipsec/ipsec.h>
80109733Smaxim#endif /*IPSEC*/
81109733Smaxim
8223247Swollman#include <ctype.h>
8323247Swollman#include <err.h>
8423247Swollman#include <errno.h>
8527508Swollman#include <math.h>
8623247Swollman#include <netdb.h>
8723247Swollman#include <signal.h>
8823247Swollman#include <stdio.h>
8923247Swollman#include <stdlib.h>
9023247Swollman#include <string.h>
9123247Swollman#include <sysexits.h>
9223247Swollman#include <unistd.h>
9323247Swollman
9499446Smaxim#define	INADDR_LEN	((int)sizeof(in_addr_t))
95135957Smaxim#define	TIMEVAL_LEN	((int)sizeof(struct tv32))
96111765Smdodd#define	MASK_LEN	(ICMP_MASKLEN - ICMP_MINLEN)
97111765Smdodd#define	TS_LEN		(ICMP_TSLEN - ICMP_MINLEN)
98112729Smdodd#define	DEFDATALEN	56		/* default data length */
9927533Sbde#define	FLOOD_BACKOFF	20000		/* usecs to back off if F_FLOOD mode */
10027533Sbde					/* runs out of buffer space */
10199447Smaxim#define	MAXIPLEN	(sizeof(struct ip) + MAX_IPOPTLEN)
10299447Smaxim#define	MAXICMPLEN	(ICMP_ADVLENMIN + MAX_IPOPTLEN)
103157535Sglebius#define	MAXWAIT		10000		/* max ms to wait for response */
10456342Sbillf#define	MAXALARM	(60 * 60)	/* max seconds for alarm timeout */
105109731Smaxim#define	MAXTOS		255
1061558Srgrimes
1071558Srgrimes#define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
1081558Srgrimes#define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
1091558Srgrimes#define	SET(bit)	(A(bit) |= B(bit))
1101558Srgrimes#define	CLR(bit)	(A(bit) &= (~B(bit)))
1111558Srgrimes#define	TST(bit)	(A(bit) & B(bit))
1121558Srgrimes
113135957Smaximstruct tv32 {
114135957Smaxim	int32_t tv32_sec;
115135957Smaxim	int32_t tv32_usec;
116135957Smaxim};
117135957Smaxim
1181558Srgrimes/* various options */
1191558Srgrimesint options;
12020540Sfenner#define	F_FLOOD		0x0001
12120540Sfenner#define	F_INTERVAL	0x0002
12220540Sfenner#define	F_NUMERIC	0x0004
12320540Sfenner#define	F_PINGFILLED	0x0008
12420540Sfenner#define	F_QUIET		0x0010
12520540Sfenner#define	F_RROUTE	0x0020
12620540Sfenner#define	F_SO_DEBUG	0x0040
12720540Sfenner#define	F_SO_DONTROUTE	0x0080
12820540Sfenner#define	F_VERBOSE	0x0100
12920540Sfenner#define	F_QUIET2	0x0200
13020540Sfenner#define	F_NOLOOP	0x0400
13120540Sfenner#define	F_MTTL		0x0800
13220540Sfenner#define	F_MIF		0x1000
13322417Sdanny#define	F_AUDIBLE	0x2000
13455505Sshin#ifdef IPSEC
13555505Sshin#ifdef IPSEC_POLICY_IPSEC
13655505Sshin#define F_POLICY	0x4000
13755505Sshin#endif /*IPSEC_POLICY_IPSEC*/
13855505Sshin#endif /*IPSEC*/
13974029Sru#define	F_TTL		0x8000
14077119Sphk#define	F_MISSED	0x10000
141104339Sdd#define	F_ONCE		0x20000
142109731Smaxim#define	F_HDRINCL	0x40000
143110009Smdodd#define	F_MASK		0x80000
144111765Smdodd#define	F_TIME		0x100000
145149086Sglebius#define	F_SWEEP		0x200000
146157535Sglebius#define	F_WAITTIME	0x400000
1471558Srgrimes
1481558Srgrimes/*
1491558Srgrimes * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
1501558Srgrimes * number of received sequence numbers we can keep track of.  Change 128
1511558Srgrimes * to 8192 for complete accuracy...
1521558Srgrimes */
1531558Srgrimes#define	MAX_DUP_CHK	(8 * 128)
1541558Srgrimesint mx_dup_ck = MAX_DUP_CHK;
1551558Srgrimeschar rcvd_tbl[MAX_DUP_CHK / 8];
1561558Srgrimes
15779403Smjacobstruct sockaddr_in whereto;	/* who to ping */
1581558Srgrimesint datalen = DEFDATALEN;
159112531Sbdeint maxpayload;
1601558Srgrimesint s;				/* socket file descriptor */
161109731Smaximu_char outpackhdr[IP_MAXPACKET], *outpack;
162109733Smaximchar BBELL = '\a';		/* characters written for MISSED and AUDIBLE */
1631558Srgrimeschar BSPACE = '\b';		/* characters written for flood */
1641558Srgrimeschar DOT = '.';
1651558Srgrimeschar *hostname;
16642337Simpchar *shostname;
1671558Srgrimesint ident;			/* process id to identify our packets */
16823295Simpint uid;			/* cached uid for micro-optimization */
169111765Smdoddu_char icmp_type = ICMP_ECHO;
170111765Smdoddu_char icmp_type_rsp = ICMP_ECHOREPLY;
171111765Smdoddint phdr_len = 0;
172117548Smaximint send_len;
1731558Srgrimes
1741558Srgrimes/* counters */
175109733Smaximlong nmissedmax;		/* max value of ntransmitted - nreceived - 1 */
1761558Srgrimeslong npackets;			/* max packets to transmit */
1771558Srgrimeslong nreceived;			/* # of packets we got back */
1781558Srgrimeslong nrepeats;			/* number of duplicates */
1791558Srgrimeslong ntransmitted;		/* sequence # for outbound packets = #sent */
180149086Sglebiuslong snpackets;			/* max packets to transmit in one sweep */
181149086Sglebiuslong snreceived;		/* # of packets we got back in this sweep */
182149086Sglebiuslong sntransmitted;		/* # of packets we sent in this sweep */
183149086Sglebiusint sweepmax;			/* max value of payload in sweep */
184149086Sglebiusint sweepmin = 0;		/* start value of payload in sweep */
185149086Sglebiusint sweepincr = 1;		/* payload increment in sweep */
18638549Sdillonint interval = 1000;		/* interval between packets, ms */
187157535Sglebiusint waittime = MAXWAIT;		/* timeout for each packet */
188157535Sglebiuslong nrcvtimeout = 0;		/* # of packets we got back after waittime */
1891558Srgrimes
1901558Srgrimes/* timing */
1911558Srgrimesint timing;			/* flag to do timing */
1921558Srgrimesdouble tmin = 999999999.0;	/* minimum round trip time */
1931558Srgrimesdouble tmax = 0.0;		/* maximum round trip time */
1941558Srgrimesdouble tsum = 0.0;		/* sum of all times, for doing average */
19527508Swollmandouble tsumsq = 0.0;		/* sum of all times squared, for std. dev. */
1961558Srgrimes
19727533Sbdevolatile sig_atomic_t finish_up;  /* nonzero if we've been told to finish up */
19827533Sbdevolatile sig_atomic_t siginfo_p;
1993792Ssef
20023247Swollmanstatic void fill(char *, char *);
20123247Swollmanstatic u_short in_cksum(u_short *, int);
20223247Swollmanstatic void check_status(void);
20327533Sbdestatic void finish(void) __dead2;
20423247Swollmanstatic void pinger(void);
20523247Swollmanstatic char *pr_addr(struct in_addr);
206111765Smdoddstatic char *pr_ntime(n_time);
20723247Swollmanstatic void pr_icmph(struct icmp *);
20823247Swollmanstatic void pr_iph(struct ip *);
20936378Sfennerstatic void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
21023247Swollmanstatic void pr_retip(struct ip *);
21123247Swollmanstatic void status(int);
21227533Sbdestatic void stopit(int);
213209366Sedstatic void tvsub(struct timeval *, const struct timeval *);
21437671Scharnierstatic void usage(void) __dead2;
2151558Srgrimes
21623247Swollmanint
217209366Sedmain(int argc, char *const *argv)
2181558Srgrimes{
219111932Sseanc	struct sockaddr_in from, sock_in;
22093035Sobrien	struct in_addr ifaddr;
221109733Smaxim	struct timeval last, intvl;
22293035Sobrien	struct iovec iov;
223109731Smaxim	struct ip *ip;
22493035Sobrien	struct msghdr msg;
22593035Sobrien	struct sigaction si_sa;
226109731Smaxim	size_t sz;
227169833Scognet	u_char *datap, packet[IP_MAXPACKET] __aligned(4);
228110054Smdodd	char *ep, *source, *target, *payload;
229109733Smaxim	struct hostent *hp;
23093035Sobrien#ifdef IPSEC_POLICY_IPSEC
23193035Sobrien	char *policy_in, *policy_out;
23293035Sobrien#endif
233109733Smaxim	struct sockaddr_in *to;
234109733Smaxim	double t;
23593035Sobrien	u_long alarmtimeout, ultmp;
236117548Smaxim	int almost_done, ch, df, hold, i, icmp_len, mib[4], preload, sockerrno,
237109733Smaxim	    tos, ttl;
23893035Sobrien	char ctrl[CMSG_SPACE(sizeof(struct timeval))];
23993035Sobrien	char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
2401558Srgrimes#ifdef IP_OPTIONS
24199447Smaxim	char rspace[MAX_IPOPTLEN];	/* record route space */
2421558Srgrimes#endif
243109733Smaxim	unsigned char loop, mttl;
24493035Sobrien
245111932Sseanc	payload = source = NULL;
24655505Sshin#ifdef IPSEC_POLICY_IPSEC
24793035Sobrien	policy_in = policy_out = NULL;
24855505Sshin#endif
2491558Srgrimes
25017474Sfenner	/*
25117474Sfenner	 * Do the stuff that we need root priv's for *first*, and
25217474Sfenner	 * then drop our setuid bit.  Save error reporting for
25317474Sfenner	 * after arg parsing.
25417474Sfenner	 */
25523247Swollman	s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
25623247Swollman	sockerrno = errno;
25717474Sfenner
258241852Seadler	if (setuid(getuid()) != 0)
259241852Seadler		err(EX_NOPERM, "setuid() failed");
26023295Simp	uid = getuid();
26117474Sfenner
262109731Smaxim	alarmtimeout = df = preload = tos = 0;
2633792Ssef
264109731Smaxim	outpack = outpackhdr + sizeof(struct ip);
26574029Sru	while ((ch = getopt(argc, argv,
266157535Sglebius		"Aac:DdfG:g:h:I:i:Ll:M:m:nop:QqRrS:s:T:t:vW:z:"
26774029Sru#ifdef IPSEC
26855505Sshin#ifdef IPSEC_POLICY_IPSEC
26974029Sru		"P:"
27055505Sshin#endif /*IPSEC_POLICY_IPSEC*/
27174029Sru#endif /*IPSEC*/
27274029Sru		)) != -1)
27355505Sshin	{
2741558Srgrimes		switch(ch) {
27577119Sphk		case 'A':
27677119Sphk			options |= F_MISSED;
27777119Sphk			break;
27822417Sdanny		case 'a':
27922417Sdanny			options |= F_AUDIBLE;
28022417Sdanny			break;
2811558Srgrimes		case 'c':
28223247Swollman			ultmp = strtoul(optarg, &ep, 0);
28323247Swollman			if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
28423247Swollman				errx(EX_USAGE,
28523247Swollman				    "invalid count of packets to transmit: `%s'",
28623247Swollman				    optarg);
28723247Swollman			npackets = ultmp;
2881558Srgrimes			break;
289109731Smaxim		case 'D':
290109731Smaxim			options |= F_HDRINCL;
291109731Smaxim			df = 1;
292109731Smaxim			break;
2931558Srgrimes		case 'd':
2941558Srgrimes			options |= F_SO_DEBUG;
2951558Srgrimes			break;
2961558Srgrimes		case 'f':
29738549Sdillon			if (uid) {
29823247Swollman				errno = EPERM;
29923247Swollman				err(EX_NOPERM, "-f flag");
3001558Srgrimes			}
3011558Srgrimes			options |= F_FLOOD;
3021558Srgrimes			setbuf(stdout, (char *)NULL);
3031558Srgrimes			break;
304149086Sglebius		case 'G': /* Maximum packet size for ping sweep */
305149086Sglebius			ultmp = strtoul(optarg, &ep, 0);
306149086Sglebius			if (*ep || ep == optarg)
307149086Sglebius				errx(EX_USAGE, "invalid packet size: `%s'",
308149086Sglebius				    optarg);
309149086Sglebius			if (uid != 0 && ultmp > DEFDATALEN) {
310149086Sglebius				errno = EPERM;
311149086Sglebius				err(EX_NOPERM,
312149086Sglebius				    "packet size too large: %lu > %u",
313149086Sglebius				    ultmp, DEFDATALEN);
314149086Sglebius			}
315149086Sglebius			options |= F_SWEEP;
316149086Sglebius			sweepmax = ultmp;
317149086Sglebius			break;
318149086Sglebius		case 'g': /* Minimum packet size for ping sweep */
319149086Sglebius			ultmp = strtoul(optarg, &ep, 0);
320149086Sglebius			if (*ep || ep == optarg)
321149086Sglebius				errx(EX_USAGE, "invalid packet size: `%s'",
322149086Sglebius				    optarg);
323149086Sglebius			if (uid != 0 && ultmp > DEFDATALEN) {
324149086Sglebius				errno = EPERM;
325149086Sglebius				err(EX_NOPERM,
326149086Sglebius				    "packet size too large: %lu > %u",
327149086Sglebius				    ultmp, DEFDATALEN);
328149086Sglebius			}
329149086Sglebius			options |= F_SWEEP;
330149086Sglebius			sweepmin = ultmp;
331149086Sglebius			break;
332149086Sglebius		case 'h': /* Packet size increment for ping sweep */
333149086Sglebius			ultmp = strtoul(optarg, &ep, 0);
334149086Sglebius			if (*ep || ep == optarg || ultmp < 1)
335149086Sglebius				errx(EX_USAGE, "invalid increment size: `%s'",
336149086Sglebius				    optarg);
337149086Sglebius			if (uid != 0 && ultmp > DEFDATALEN) {
338149086Sglebius				errno = EPERM;
339149086Sglebius				err(EX_NOPERM,
340149086Sglebius				    "packet size too large: %lu > %u",
341149086Sglebius				    ultmp, DEFDATALEN);
342149086Sglebius			}
343149086Sglebius			options |= F_SWEEP;
344149086Sglebius			sweepincr = ultmp;
345149086Sglebius			break;
346111287Sru		case 'I':		/* multicast interface */
347111287Sru			if (inet_aton(optarg, &ifaddr) == 0)
348111287Sru				errx(EX_USAGE,
349111287Sru				    "invalid multicast interface: `%s'",
350111287Sru				    optarg);
351111287Sru			options |= F_MIF;
352111287Sru			break;
3531558Srgrimes		case 'i':		/* wait between sending packets */
35493638Smaxim			t = strtod(optarg, &ep) * 1000.0;
35593638Smaxim			if (*ep || ep == optarg || t > (double)INT_MAX)
35693638Smaxim				errx(EX_USAGE, "invalid timing interval: `%s'",
35793638Smaxim				    optarg);
35893638Smaxim			options |= F_INTERVAL;
35993638Smaxim			interval = (int)t;
36093638Smaxim			if (uid && interval < 1000) {
36193638Smaxim				errno = EPERM;
36293638Smaxim				err(EX_NOPERM, "-i interval too short");
36338549Sdillon			}
3641558Srgrimes			break;
365111287Sru		case 'L':
366111287Sru			options |= F_NOLOOP;
367111287Sru			loop = 0;
36820540Sfenner			break;
3691558Srgrimes		case 'l':
37023247Swollman			ultmp = strtoul(optarg, &ep, 0);
37123247Swollman			if (*ep || ep == optarg || ultmp > INT_MAX)
37293638Smaxim				errx(EX_USAGE,
37393638Smaxim				    "invalid preload value: `%s'", optarg);
37446643Smckay			if (uid) {
37523251Simp				errno = EPERM;
37623251Simp				err(EX_NOPERM, "-l flag");
37723251Simp			}
37823247Swollman			preload = ultmp;
3791558Srgrimes			break;
380111287Sru		case 'M':
381111765Smdodd			switch(optarg[0]) {
382111765Smdodd			case 'M':
383111765Smdodd			case 'm':
384111765Smdodd				options |= F_MASK;
385111765Smdodd				break;
386111765Smdodd			case 'T':
387111765Smdodd			case 't':
388111765Smdodd				options |= F_TIME;
389111765Smdodd				break;
390111765Smdodd			default:
391111765Smdodd				errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
392111765Smdodd				break;
393111765Smdodd			}
39420540Sfenner			break;
39574029Sru		case 'm':		/* TTL */
39674029Sru			ultmp = strtoul(optarg, &ep, 0);
397109732Smaxim			if (*ep || ep == optarg || ultmp > MAXTTL)
39893638Smaxim				errx(EX_USAGE, "invalid TTL: `%s'", optarg);
39974029Sru			ttl = ultmp;
40074029Sru			options |= F_TTL;
40174029Sru			break;
4021558Srgrimes		case 'n':
4031558Srgrimes			options |= F_NUMERIC;
4041558Srgrimes			break;
405104339Sdd		case 'o':
406104339Sdd			options |= F_ONCE;
407104339Sdd			break;
408111287Sru#ifdef IPSEC
409111287Sru#ifdef IPSEC_POLICY_IPSEC
410111287Sru		case 'P':
411111287Sru			options |= F_POLICY;
412111287Sru			if (!strncmp("in", optarg, 2))
413111287Sru				policy_in = strdup(optarg);
414111287Sru			else if (!strncmp("out", optarg, 3))
415111287Sru				policy_out = strdup(optarg);
416111287Sru			else
417111287Sru				errx(1, "invalid security policy");
418111287Sru			break;
419111287Sru#endif /*IPSEC_POLICY_IPSEC*/
420111287Sru#endif /*IPSEC*/
4211558Srgrimes		case 'p':		/* fill buffer with user pattern */
4221558Srgrimes			options |= F_PINGFILLED;
423110054Smdodd			payload = optarg;
424109733Smaxim			break;
42517724Sfenner		case 'Q':
42617724Sfenner			options |= F_QUIET2;
42717724Sfenner			break;
4281558Srgrimes		case 'q':
4291558Srgrimes			options |= F_QUIET;
4301558Srgrimes			break;
4311558Srgrimes		case 'R':
4321558Srgrimes			options |= F_RROUTE;
4331558Srgrimes			break;
4341558Srgrimes		case 'r':
4351558Srgrimes			options |= F_SO_DONTROUTE;
4361558Srgrimes			break;
437111287Sru		case 'S':
438111287Sru			source = optarg;
439111287Sru			break;
4401558Srgrimes		case 's':		/* size of packet to send */
44123247Swollman			ultmp = strtoul(optarg, &ep, 0);
44299447Smaxim			if (*ep || ep == optarg)
44393638Smaxim				errx(EX_USAGE, "invalid packet size: `%s'",
44493638Smaxim				    optarg);
445109734Smaxim			if (uid != 0 && ultmp > DEFDATALEN) {
446109734Smaxim				errno = EPERM;
447109734Smaxim				err(EX_NOPERM,
448109734Smaxim				    "packet size too large: %lu > %u",
449109734Smaxim				    ultmp, DEFDATALEN);
450109734Smaxim			}
45123247Swollman			datalen = ultmp;
4521558Srgrimes			break;
453111287Sru		case 'T':		/* multicast TTL */
454111287Sru			ultmp = strtoul(optarg, &ep, 0);
455111287Sru			if (*ep || ep == optarg || ultmp > MAXTTL)
456111287Sru				errx(EX_USAGE, "invalid multicast TTL: `%s'",
457111287Sru				    optarg);
458111287Sru			mttl = ultmp;
459111287Sru			options |= F_MTTL;
46042337Simp			break;
46155996Sbillf		case 't':
46256342Sbillf			alarmtimeout = strtoul(optarg, &ep, 0);
46356342Sbillf			if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
46455996Sbillf				errx(EX_USAGE, "invalid timeout: `%s'",
46555996Sbillf				    optarg);
46656342Sbillf			if (alarmtimeout > MAXALARM)
46756342Sbillf				errx(EX_USAGE, "invalid timeout: `%s' > %d",
46856342Sbillf				    optarg, MAXALARM);
46956342Sbillf			alarm((int)alarmtimeout);
47055996Sbillf			break;
4711558Srgrimes		case 'v':
4721558Srgrimes			options |= F_VERBOSE;
4731558Srgrimes			break;
474157535Sglebius		case 'W':		/* wait ms for answer */
475157535Sglebius			t = strtod(optarg, &ep);
476157535Sglebius			if (*ep || ep == optarg || t > (double)INT_MAX)
477157535Sglebius				errx(EX_USAGE, "invalid timing interval: `%s'",
478157535Sglebius				    optarg);
479157535Sglebius			options |= F_WAITTIME;
480157535Sglebius			waittime = (int)t;
481157535Sglebius			break;
482109731Smaxim		case 'z':
483109731Smaxim			options |= F_HDRINCL;
484109731Smaxim			ultmp = strtoul(optarg, &ep, 0);
485109731Smaxim			if (*ep || ep == optarg || ultmp > MAXTOS)
486109731Smaxim				errx(EX_USAGE, "invalid TOS: `%s'", optarg);
487109731Smaxim			tos = ultmp;
488109731Smaxim			break;
4891558Srgrimes		default:
49037671Scharnier			usage();
4911558Srgrimes		}
49223247Swollman	}
4931558Srgrimes
49423247Swollman	if (argc - optind != 1)
49537671Scharnier		usage();
49623247Swollman	target = argv[optind];
4971558Srgrimes
498112568Smdodd	switch (options & (F_MASK|F_TIME)) {
499112568Smdodd	case 0: break;
500112568Smdodd	case F_MASK:
501111765Smdodd		icmp_type = ICMP_MASKREQ;
502111765Smdodd		icmp_type_rsp = ICMP_MASKREPLY;
503112568Smdodd		phdr_len = MASK_LEN;
504111765Smdodd		if (!(options & F_QUIET))
505111765Smdodd			(void)printf("ICMP_MASKREQ\n");
506112568Smdodd		break;
507112568Smdodd	case F_TIME:
508111765Smdodd		icmp_type = ICMP_TSTAMP;
509111765Smdodd		icmp_type_rsp = ICMP_TSTAMPREPLY;
510112568Smdodd		phdr_len = TS_LEN;
511111765Smdodd		if (!(options & F_QUIET))
512111765Smdodd			(void)printf("ICMP_TSTAMP\n");
513112568Smdodd		break;
514112568Smdodd	default:
515112568Smdodd		errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
516112568Smdodd		break;
517111765Smdodd	}
518117549Smaxim	icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len;
519109734Smaxim	if (options & F_RROUTE)
520117548Smaxim		icmp_len += MAX_IPOPTLEN;
521117548Smaxim	maxpayload = IP_MAXPACKET - icmp_len;
522109734Smaxim	if (datalen > maxpayload)
523112531Sbde		errx(EX_USAGE, "packet size too large: %d > %d", datalen,
524109734Smaxim		    maxpayload);
525117548Smaxim	send_len = icmp_len + datalen;
526117549Smaxim	datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN];
527110054Smdodd	if (options & F_PINGFILLED) {
528110054Smdodd		fill((char *)datap, payload);
529110054Smdodd	}
53042337Simp	if (source) {
531111932Sseanc		bzero((char *)&sock_in, sizeof(sock_in));
532111932Sseanc		sock_in.sin_family = AF_INET;
533111932Sseanc		if (inet_aton(source, &sock_in.sin_addr) != 0) {
53442337Simp			shostname = source;
53542337Simp		} else {
53642337Simp			hp = gethostbyname2(source, AF_INET);
53742337Simp			if (!hp)
53842337Simp				errx(EX_NOHOST, "cannot resolve %s: %s",
53993638Smaxim				    source, hstrerror(h_errno));
54042337Simp
541111932Sseanc			sock_in.sin_len = sizeof sock_in;
542111932Sseanc			if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
54399447Smaxim			    hp->h_length < 0)
54493638Smaxim				errx(1, "gethostbyname2: illegal address");
545111932Sseanc			memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
546111932Sseanc			    sizeof(sock_in.sin_addr));
54793638Smaxim			(void)strncpy(snamebuf, hp->h_name,
54893638Smaxim			    sizeof(snamebuf) - 1);
54942337Simp			snamebuf[sizeof(snamebuf) - 1] = '\0';
55042337Simp			shostname = snamebuf;
55142337Simp		}
552111932Sseanc		if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
55342337Simp			err(1, "bind");
55442337Simp	}
55542337Simp
55679403Smjacob	bzero(&whereto, sizeof(whereto));
55779403Smjacob	to = &whereto;
5581558Srgrimes	to->sin_family = AF_INET;
55979403Smjacob	to->sin_len = sizeof *to;
56023247Swollman	if (inet_aton(target, &to->sin_addr) != 0) {
5611558Srgrimes		hostname = target;
56223247Swollman	} else {
56323247Swollman		hp = gethostbyname2(target, AF_INET);
56423247Swollman		if (!hp)
56523247Swollman			errx(EX_NOHOST, "cannot resolve %s: %s",
56693638Smaxim			    target, hstrerror(h_errno));
56723247Swollman
568111932Sseanc		if ((unsigned)hp->h_length > sizeof(to->sin_addr))
56993638Smaxim			errx(1, "gethostbyname2 returned an illegal address");
57023247Swollman		memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
5711558Srgrimes		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
57231956Simp		hnamebuf[sizeof(hnamebuf) - 1] = '\0';
5731558Srgrimes		hostname = hnamebuf;
5741558Srgrimes	}
5751558Srgrimes
57623247Swollman	if (options & F_FLOOD && options & F_INTERVAL)
57723247Swollman		errx(EX_USAGE, "-f and -i: incompatible options");
5781558Srgrimes
57923247Swollman	if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
58093638Smaxim		errx(EX_USAGE,
58193638Smaxim		    "-f flag cannot be used with multicast destination");
58223247Swollman	if (options & (F_MIF | F_NOLOOP | F_MTTL)
58323247Swollman	    && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
58493638Smaxim		errx(EX_USAGE,
58593638Smaxim		    "-I, -L, -T flags cannot be used with unicast destination");
58623247Swollman
587112568Smdodd	if (datalen >= TIMEVAL_LEN)	/* can we time transfer */
5881558Srgrimes		timing = 1;
58923247Swollman
5901558Srgrimes	if (!(options & F_PINGFILLED))
591112568Smdodd		for (i = TIMEVAL_LEN; i < datalen; ++i)
5921558Srgrimes			*datap++ = i;
5931558Srgrimes
5941558Srgrimes	ident = getpid() & 0xFFFF;
5951558Srgrimes
59617474Sfenner	if (s < 0) {
59717474Sfenner		errno = sockerrno;
59823247Swollman		err(EX_OSERR, "socket");
5991558Srgrimes	}
6001558Srgrimes	hold = 1;
6011558Srgrimes	if (options & F_SO_DEBUG)
6021558Srgrimes		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
6031558Srgrimes		    sizeof(hold));
6041558Srgrimes	if (options & F_SO_DONTROUTE)
6051558Srgrimes		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
6061558Srgrimes		    sizeof(hold));
60755505Sshin#ifdef IPSEC
60855505Sshin#ifdef IPSEC_POLICY_IPSEC
60955505Sshin	if (options & F_POLICY) {
61055505Sshin		char *buf;
61155505Sshin		if (policy_in != NULL) {
61255505Sshin			buf = ipsec_set_policy(policy_in, strlen(policy_in));
61355505Sshin			if (buf == NULL)
61468905Skris				errx(EX_CONFIG, "%s", ipsec_strerror());
61555505Sshin			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
61655505Sshin					buf, ipsec_get_policylen(buf)) < 0)
61793638Smaxim				err(EX_CONFIG,
61893638Smaxim				    "ipsec policy cannot be configured");
61955505Sshin			free(buf);
62055505Sshin		}
6211558Srgrimes
62255505Sshin		if (policy_out != NULL) {
62355505Sshin			buf = ipsec_set_policy(policy_out, strlen(policy_out));
62455505Sshin			if (buf == NULL)
62568905Skris				errx(EX_CONFIG, "%s", ipsec_strerror());
62655505Sshin			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
62755505Sshin					buf, ipsec_get_policylen(buf)) < 0)
62893638Smaxim				err(EX_CONFIG,
62993638Smaxim				    "ipsec policy cannot be configured");
63055505Sshin			free(buf);
63155505Sshin		}
63255505Sshin	}
63355505Sshin#endif /*IPSEC_POLICY_IPSEC*/
63455505Sshin#endif /*IPSEC*/
63555505Sshin
636109731Smaxim	if (options & F_HDRINCL) {
637109731Smaxim		ip = (struct ip*)outpackhdr;
638109731Smaxim		if (!(options & (F_TTL | F_MTTL))) {
639109731Smaxim			mib[0] = CTL_NET;
640109731Smaxim			mib[1] = PF_INET;
641109731Smaxim			mib[2] = IPPROTO_IP;
642109731Smaxim			mib[3] = IPCTL_DEFTTL;
643109731Smaxim			sz = sizeof(ttl);
644109731Smaxim			if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
645109731Smaxim				err(1, "sysctl(net.inet.ip.ttl)");
646109731Smaxim		}
647109731Smaxim		setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
648109731Smaxim		ip->ip_v = IPVERSION;
649109731Smaxim		ip->ip_hl = sizeof(struct ip) >> 2;
650109731Smaxim		ip->ip_tos = tos;
651109731Smaxim		ip->ip_id = 0;
652109731Smaxim		ip->ip_off = df ? IP_DF : 0;
653109731Smaxim		ip->ip_ttl = ttl;
654109731Smaxim		ip->ip_p = IPPROTO_ICMP;
655111932Sseanc		ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
656109731Smaxim		ip->ip_dst = to->sin_addr;
657109731Smaxim        }
6581558Srgrimes	/* record route option */
6591558Srgrimes	if (options & F_RROUTE) {
6601558Srgrimes#ifdef IP_OPTIONS
66136378Sfenner		bzero(rspace, sizeof(rspace));
6621558Srgrimes		rspace[IPOPT_OPTVAL] = IPOPT_RR;
66336378Sfenner		rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
6641558Srgrimes		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
66536378Sfenner		rspace[sizeof(rspace) - 1] = IPOPT_EOL;
6661558Srgrimes		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
66723247Swollman		    sizeof(rspace)) < 0)
66823247Swollman			err(EX_OSERR, "setsockopt IP_OPTIONS");
6691558Srgrimes#else
67023247Swollman		errx(EX_UNAVAILABLE,
67193638Smaxim		    "record route not available in this implementation");
6721558Srgrimes#endif /* IP_OPTIONS */
6731558Srgrimes	}
6741558Srgrimes
67574029Sru	if (options & F_TTL) {
67674029Sru		if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
67774029Sru		    sizeof(ttl)) < 0) {
67874029Sru			err(EX_OSERR, "setsockopt IP_TTL");
67974029Sru		}
68074029Sru	}
68120540Sfenner	if (options & F_NOLOOP) {
68220540Sfenner		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
68320540Sfenner		    sizeof(loop)) < 0) {
68423247Swollman			err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
68520540Sfenner		}
68620540Sfenner	}
68720540Sfenner	if (options & F_MTTL) {
68874029Sru		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
68974029Sru		    sizeof(mttl)) < 0) {
69023247Swollman			err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
69120540Sfenner		}
69220540Sfenner	}
69320540Sfenner	if (options & F_MIF) {
69420540Sfenner		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
69520540Sfenner		    sizeof(ifaddr)) < 0) {
69623247Swollman			err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
69720540Sfenner		}
69820540Sfenner	}
69936378Sfenner#ifdef SO_TIMESTAMP
70036378Sfenner	{ int on = 1;
70136378Sfenner	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
70236378Sfenner		err(EX_OSERR, "setsockopt SO_TIMESTAMP");
70336378Sfenner	}
70436378Sfenner#endif
705149086Sglebius	if (sweepmax) {
706149086Sglebius		if (sweepmin >= sweepmax)
707149086Sglebius			errx(EX_USAGE, "Maximum packet size must be greater than the minimum packet size");
70820540Sfenner
709149086Sglebius		if (datalen != DEFDATALEN)
710149086Sglebius			errx(EX_USAGE, "Packet size and ping sweep are mutually exclusive");
711149086Sglebius
712149086Sglebius		if (npackets > 0) {
713149086Sglebius			snpackets = npackets;
714149086Sglebius			npackets = 0;
715149086Sglebius		} else
716149086Sglebius			snpackets = 1;
717149086Sglebius		datalen = sweepmin;
718149086Sglebius		send_len = icmp_len + sweepmin;
719149086Sglebius	}
720149086Sglebius	if (options & F_SWEEP && !sweepmax)
721149086Sglebius		errx(EX_USAGE, "Maximum sweep size must be specified");
722149086Sglebius
7231558Srgrimes	/*
7241558Srgrimes	 * When pinging the broadcast address, you can get a lot of answers.
7251558Srgrimes	 * Doing something so evil is useful if you are trying to stress the
7261558Srgrimes	 * ethernet, or just want to fill the arp cache to get some stuff for
72723247Swollman	 * /etc/ethers.  But beware: RFC 1122 allows hosts to ignore broadcast
72823247Swollman	 * or multicast pings if they wish.
7291558Srgrimes	 */
73099447Smaxim
73199447Smaxim	/*
73299447Smaxim	 * XXX receive buffer needs undetermined space for mbuf overhead
73399447Smaxim	 * as well.
73499447Smaxim	 */
73599447Smaxim	hold = IP_MAXPACKET + 128;
7361558Srgrimes	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
7371558Srgrimes	    sizeof(hold));
738109733Smaxim	if (uid == 0)
73979018Srwatson		(void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
74079018Srwatson		    sizeof(hold));
74179018Srwatson
74242337Simp	if (to->sin_family == AF_INET) {
74342337Simp		(void)printf("PING %s (%s)", hostname,
74442337Simp		    inet_ntoa(to->sin_addr));
74542337Simp		if (source)
74642337Simp			(void)printf(" from %s", shostname);
747149086Sglebius		if (sweepmax)
748149086Sglebius			(void)printf(": (%d ... %d) data bytes\n",
749149086Sglebius			    sweepmin, sweepmax);
750149086Sglebius		else
751149086Sglebius			(void)printf(": %d data bytes\n", datalen);
752149086Sglebius
753149086Sglebius	} else {
754149086Sglebius		if (sweepmax)
755149086Sglebius			(void)printf("PING %s: (%d ... %d) data bytes\n",
756149086Sglebius			    hostname, sweepmin, sweepmax);
757149086Sglebius		else
758149086Sglebius			(void)printf("PING %s: %d data bytes\n", hostname, datalen);
759149086Sglebius	}
7601558Srgrimes
76120280Sbde	/*
76227354Ssef	 * Use sigaction() instead of signal() to get unambiguous semantics,
76327354Ssef	 * in particular with SA_RESTART not set.
76420280Sbde	 */
76527354Ssef
76620205Spst	sigemptyset(&si_sa.sa_mask);
76720195Ssef	si_sa.sa_flags = 0;
76827354Ssef
76927354Ssef	si_sa.sa_handler = stopit;
77027354Ssef	if (sigaction(SIGINT, &si_sa, 0) == -1) {
77127354Ssef		err(EX_OSERR, "sigaction SIGINT");
77227354Ssef	}
77327354Ssef
77427354Ssef	si_sa.sa_handler = status;
77520195Ssef	if (sigaction(SIGINFO, &si_sa, 0) == -1) {
77623385Simp		err(EX_OSERR, "sigaction");
77720195Ssef	}
77820195Ssef
77956342Sbillf        if (alarmtimeout > 0) {
78056342Sbillf		si_sa.sa_handler = stopit;
78156342Sbillf		if (sigaction(SIGALRM, &si_sa, 0) == -1)
78256342Sbillf			err(EX_OSERR, "sigaction SIGALRM");
78356342Sbillf        }
78456342Sbillf
78536378Sfenner	bzero(&msg, sizeof(msg));
78636378Sfenner	msg.msg_name = (caddr_t)&from;
78736378Sfenner	msg.msg_iov = &iov;
78836378Sfenner	msg.msg_iovlen = 1;
78936378Sfenner#ifdef SO_TIMESTAMP
79036378Sfenner	msg.msg_control = (caddr_t)ctrl;
79136378Sfenner#endif
79236378Sfenner	iov.iov_base = packet;
793117548Smaxim	iov.iov_len = IP_MAXPACKET;
79436378Sfenner
79589349Sru	if (preload == 0)
79689349Sru		pinger();		/* send the first ping */
79789349Sru	else {
79889349Sru		if (npackets != 0 && preload > npackets)
79989349Sru			preload = npackets;
80089349Sru		while (preload--)	/* fire off them quickies */
80189349Sru			pinger();
80289349Sru	}
80389349Sru	(void)gettimeofday(&last, NULL);
8041558Srgrimes
80536378Sfenner	if (options & F_FLOOD) {
80636378Sfenner		intvl.tv_sec = 0;
80736378Sfenner		intvl.tv_usec = 10000;
80836378Sfenner	} else {
80938549Sdillon		intvl.tv_sec = interval / 1000;
81038549Sdillon		intvl.tv_usec = interval % 1000 * 1000;
81136378Sfenner	}
8121558Srgrimes
813109733Smaxim	almost_done = 0;
81427533Sbde	while (!finish_up) {
815109733Smaxim		struct timeval now, timeout;
81636378Sfenner		fd_set rfds;
817109733Smaxim		int cc, n;
8181558Srgrimes
81920280Sbde		check_status();
820111932Sseanc		if ((unsigned)s >= FD_SETSIZE)
821103146Snectar			errx(EX_OSERR, "descriptor too large");
82236378Sfenner		FD_ZERO(&rfds);
82336378Sfenner		FD_SET(s, &rfds);
82436378Sfenner		(void)gettimeofday(&now, NULL);
82536378Sfenner		timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
82636378Sfenner		timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
82736378Sfenner		while (timeout.tv_usec < 0) {
82836378Sfenner			timeout.tv_usec += 1000000;
82936378Sfenner			timeout.tv_sec--;
8301558Srgrimes		}
83137671Scharnier		while (timeout.tv_usec >= 1000000) {
83236378Sfenner			timeout.tv_usec -= 1000000;
83336378Sfenner			timeout.tv_sec++;
83436378Sfenner		}
83536378Sfenner		if (timeout.tv_sec < 0)
836237942Sdelphij			timerclear(&timeout);
83736378Sfenner		n = select(s + 1, &rfds, NULL, NULL, &timeout);
83846643Smckay		if (n < 0)
83946643Smckay			continue;	/* Must be EINTR. */
84036378Sfenner		if (n == 1) {
841111932Sseanc			struct timeval *tv = NULL;
84236378Sfenner#ifdef SO_TIMESTAMP
84336378Sfenner			struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
84436378Sfenner
84536378Sfenner			msg.msg_controllen = sizeof(ctrl);
84636378Sfenner#endif
84736378Sfenner			msg.msg_namelen = sizeof(from);
84836378Sfenner			if ((cc = recvmsg(s, &msg, 0)) < 0) {
84936378Sfenner				if (errno == EINTR)
85036378Sfenner					continue;
85137671Scharnier				warn("recvmsg");
8521558Srgrimes				continue;
85336378Sfenner			}
85436378Sfenner#ifdef SO_TIMESTAMP
85536378Sfenner			if (cmsg->cmsg_level == SOL_SOCKET &&
85636378Sfenner			    cmsg->cmsg_type == SCM_TIMESTAMP &&
857111932Sseanc			    cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
85836713Sjb				/* Copy to avoid alignment problems: */
859103229Speter				memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
860111932Sseanc				tv = &now;
86136713Sjb			}
86236378Sfenner#endif
863111932Sseanc			if (tv == NULL) {
86436378Sfenner				(void)gettimeofday(&now, NULL);
865111932Sseanc				tv = &now;
86636378Sfenner			}
867111932Sseanc			pr_pack((char *)packet, cc, &from, tv);
868111932Sseanc			if ((options & F_ONCE && nreceived) ||
869111932Sseanc			    (npackets && nreceived >= npackets))
87036378Sfenner				break;
8711558Srgrimes		}
87246643Smckay		if (n == 0 || options & F_FLOOD) {
873149086Sglebius			if (sweepmax && sntransmitted == snpackets) {
874149086Sglebius				for (i = 0; i < sweepincr ; ++i)
875149086Sglebius					*datap++ = i;
876149086Sglebius				datalen += sweepincr;
877149086Sglebius				if (datalen > sweepmax)
878149086Sglebius					break;
879149086Sglebius				send_len = icmp_len + datalen;
880149086Sglebius				sntransmitted = 0;
881149086Sglebius			}
88236378Sfenner			if (!npackets || ntransmitted < npackets)
88336378Sfenner				pinger();
88436378Sfenner			else {
88536378Sfenner				if (almost_done)
88636378Sfenner					break;
88736378Sfenner				almost_done = 1;
88846643Smckay				intvl.tv_usec = 0;
88936378Sfenner				if (nreceived) {
89036378Sfenner					intvl.tv_sec = 2 * tmax / 1000;
89136378Sfenner					if (!intvl.tv_sec)
89236378Sfenner						intvl.tv_sec = 1;
893157535Sglebius				} else {
894157535Sglebius					intvl.tv_sec = waittime / 1000;
895157535Sglebius					intvl.tv_usec = waittime % 1000 * 1000;
896157535Sglebius				}
89736378Sfenner			}
89836378Sfenner			(void)gettimeofday(&last, NULL);
89983940Siedowse			if (ntransmitted - nreceived - 1 > nmissedmax) {
90083940Siedowse				nmissedmax = ntransmitted - nreceived - 1;
90183940Siedowse				if (options & F_MISSED)
90283940Siedowse					(void)write(STDOUT_FILENO, &BBELL, 1);
90383940Siedowse			}
90436378Sfenner		}
9051558Srgrimes	}
90627533Sbde	finish();
9071558Srgrimes	/* NOTREACHED */
90823251Simp	exit(0);	/* Make the compiler happy */
9091558Srgrimes}
9101558Srgrimes
9111558Srgrimes/*
91227533Sbde * stopit --
91327533Sbde *	Set the global bit that causes the main loop to quit.
91427533Sbde * Do NOT call finish() from here, since finish() does far too much
91527533Sbde * to be called from a signal handler.
91627299Sjulian */
91727299Sjulianvoid
918209366Sedstopit(int sig __unused)
91927299Sjulian{
92093035Sobrien
921125605Siedowse	/*
922125605Siedowse	 * When doing reverse DNS lookups, the finish_up flag might not
923125605Siedowse	 * be noticed for a while.  Just exit if we get a second SIGINT.
924125605Siedowse	 */
925125605Siedowse	if (!(options & F_NUMERIC) && finish_up)
926125605Siedowse		_exit(nreceived ? 0 : 2);
92727299Sjulian	finish_up = 1;
92827299Sjulian}
92927299Sjulian
93027299Sjulian/*
9311558Srgrimes * pinger --
9321558Srgrimes *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
9331558Srgrimes * will be added on by the kernel.  The ID field is our UNIX process ID,
934111765Smdodd * and the sequence number is an ascending integer.  The first TIMEVAL_LEN
93599447Smaxim * bytes of the data portion are used to hold a UNIX "timeval" struct in
93699447Smaxim * host byte-order, to compute the round-trip time.
9371558Srgrimes */
93823247Swollmanstatic void
93923247Swollmanpinger(void)
9401558Srgrimes{
941111765Smdodd	struct timeval now;
942135957Smaxim	struct tv32 tv32;
943109731Smaxim	struct ip *ip;
94492806Sobrien	struct icmp *icp;
94593035Sobrien	int cc, i;
946109731Smaxim	u_char *packet;
9471558Srgrimes
948109731Smaxim	packet = outpack;
9491558Srgrimes	icp = (struct icmp *)outpack;
950111765Smdodd	icp->icmp_type = icmp_type;
9511558Srgrimes	icp->icmp_code = 0;
9521558Srgrimes	icp->icmp_cksum = 0;
95391432Sfenner	icp->icmp_seq = htons(ntransmitted);
9541558Srgrimes	icp->icmp_id = ident;			/* ID */
9551558Srgrimes
95691432Sfenner	CLR(ntransmitted % mx_dup_ck);
9571558Srgrimes
958111765Smdodd	if ((options & F_TIME) || timing) {
959111765Smdodd		(void)gettimeofday(&now, NULL);
9601558Srgrimes
961135957Smaxim		tv32.tv32_sec = htonl(now.tv_sec);
962135957Smaxim		tv32.tv32_usec = htonl(now.tv_usec);
963111765Smdodd		if (options & F_TIME)
964111765Smdodd			icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
965111765Smdodd				* 1000 + now.tv_usec / 1000);
966111765Smdodd		if (timing)
967135957Smaxim			bcopy((void *)&tv32,
968117549Smaxim			    (void *)&outpack[ICMP_MINLEN + phdr_len],
969135957Smaxim			    sizeof(tv32));
970111765Smdodd	}
9711558Srgrimes
972117549Smaxim	cc = ICMP_MINLEN + phdr_len + datalen;
973111765Smdodd
9741558Srgrimes	/* compute ICMP checksum here */
9751558Srgrimes	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
9761558Srgrimes
977109731Smaxim	if (options & F_HDRINCL) {
978109731Smaxim		cc += sizeof(struct ip);
979109731Smaxim		ip = (struct ip *)outpackhdr;
980109731Smaxim		ip->ip_len = cc;
981109731Smaxim		ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
982109731Smaxim		packet = outpackhdr;
983109731Smaxim	}
984109731Smaxim	i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
98579403Smjacob	    sizeof(whereto));
9861558Srgrimes
9871558Srgrimes	if (i < 0 || i != cc)  {
98823247Swollman		if (i < 0) {
98927533Sbde			if (options & F_FLOOD && errno == ENOBUFS) {
99027299Sjulian				usleep(FLOOD_BACKOFF);
99127299Sjulian				return;
99227299Sjulian			}
99323247Swollman			warn("sendto");
99423247Swollman		} else {
99523247Swollman			warn("%s: partial write: %d of %d bytes",
99635216Sphk			     hostname, i, cc);
99723247Swollman		}
99827945Sjulian	}
99927945Sjulian	ntransmitted++;
1000149086Sglebius	sntransmitted++;
10011558Srgrimes	if (!(options & F_QUIET) && options & F_FLOOD)
10021558Srgrimes		(void)write(STDOUT_FILENO, &DOT, 1);
10031558Srgrimes}
10041558Srgrimes
10051558Srgrimes/*
10061558Srgrimes * pr_pack --
10071558Srgrimes *	Print out the packet, if it came from us.  This logic is necessary
10081558Srgrimes * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
10091558Srgrimes * which arrive ('tis only fair).  This permits multiple copies of this
10101558Srgrimes * program to be run without having intermingled output (or statistics!).
10111558Srgrimes */
101223247Swollmanstatic void
1013209366Sedpr_pack(char *buf, int cc, struct sockaddr_in *from, struct timeval *tv)
10141558Srgrimes{
1015103229Speter	struct in_addr ina;
1016103229Speter	u_char *cp, *dp;
101792806Sobrien	struct icmp *icp;
101893035Sobrien	struct ip *ip;
1019103227Speter	const void *tp;
102093035Sobrien	double triptime;
1021117548Smaxim	int dupflag, hlen, i, j, recv_len, seq;
10221558Srgrimes	static int old_rrlen;
10231558Srgrimes	static char old_rr[MAX_IPOPTLEN];
10241558Srgrimes
10251558Srgrimes	/* Check the IP header */
10261558Srgrimes	ip = (struct ip *)buf;
10271558Srgrimes	hlen = ip->ip_hl << 2;
1028117548Smaxim	recv_len = cc;
10291558Srgrimes	if (cc < hlen + ICMP_MINLEN) {
10301558Srgrimes		if (options & F_VERBOSE)
103123247Swollman			warn("packet too short (%d bytes) from %s", cc,
103223247Swollman			     inet_ntoa(from->sin_addr));
10331558Srgrimes		return;
10341558Srgrimes	}
10351558Srgrimes
10361558Srgrimes	/* Now the ICMP part */
10371558Srgrimes	cc -= hlen;
10381558Srgrimes	icp = (struct icmp *)(buf + hlen);
1039111765Smdodd	if (icp->icmp_type == icmp_type_rsp) {
10401558Srgrimes		if (icp->icmp_id != ident)
10411558Srgrimes			return;			/* 'Twas not our ECHO */
10421558Srgrimes		++nreceived;
104327533Sbde		triptime = 0.0;
10441558Srgrimes		if (timing) {
104536089Sjb			struct timeval tv1;
1046135957Smaxim			struct tv32 tv32;
10471558Srgrimes#ifndef icmp_data
1048103227Speter			tp = &icp->icmp_ip;
10491558Srgrimes#else
1050103227Speter			tp = icp->icmp_data;
10511558Srgrimes#endif
1052133723Sstefanf			tp = (const char *)tp + phdr_len;
1053110009Smdodd
1054113217Smdodd			if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) {
1055113217Smdodd				/* Copy to avoid alignment problems: */
1056135957Smaxim				memcpy(&tv32, tp, sizeof(tv32));
1057135957Smaxim				tv1.tv_sec = ntohl(tv32.tv32_sec);
1058135957Smaxim				tv1.tv_usec = ntohl(tv32.tv32_usec);
1059113217Smdodd				tvsub(tv, &tv1);
1060113217Smdodd 				triptime = ((double)tv->tv_sec) * 1000.0 +
1061113217Smdodd 				    ((double)tv->tv_usec) / 1000.0;
1062113217Smdodd				tsum += triptime;
1063113217Smdodd				tsumsq += triptime * triptime;
1064113217Smdodd				if (triptime < tmin)
1065113217Smdodd					tmin = triptime;
1066113217Smdodd				if (triptime > tmax)
1067113217Smdodd					tmax = triptime;
1068113217Smdodd			} else
1069113217Smdodd				timing = 0;
10701558Srgrimes		}
10711558Srgrimes
107291432Sfenner		seq = ntohs(icp->icmp_seq);
107391432Sfenner
107491432Sfenner		if (TST(seq % mx_dup_ck)) {
10751558Srgrimes			++nrepeats;
10761558Srgrimes			--nreceived;
10771558Srgrimes			dupflag = 1;
10781558Srgrimes		} else {
107991432Sfenner			SET(seq % mx_dup_ck);
10801558Srgrimes			dupflag = 0;
10811558Srgrimes		}
10821558Srgrimes
10831558Srgrimes		if (options & F_QUIET)
10841558Srgrimes			return;
1085157535Sglebius
1086157535Sglebius		if (options & F_WAITTIME && triptime > waittime) {
1087157535Sglebius			++nrcvtimeout;
1088157535Sglebius			return;
1089157535Sglebius		}
10901558Srgrimes
10911558Srgrimes		if (options & F_FLOOD)
10921558Srgrimes			(void)write(STDOUT_FILENO, &BSPACE, 1);
10931558Srgrimes		else {
10941558Srgrimes			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
10951558Srgrimes			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
109691432Sfenner			   seq);
10971558Srgrimes			(void)printf(" ttl=%d", ip->ip_ttl);
10981558Srgrimes			if (timing)
10991859Sdg				(void)printf(" time=%.3f ms", triptime);
11001558Srgrimes			if (dupflag)
11011558Srgrimes				(void)printf(" (DUP!)");
110222417Sdanny			if (options & F_AUDIBLE)
110377119Sphk				(void)write(STDOUT_FILENO, &BBELL, 1);
1104110009Smdodd			if (options & F_MASK) {
1105110009Smdodd				/* Just prentend this cast isn't ugly */
1106110009Smdodd				(void)printf(" mask=%s",
1107110009Smdodd					pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1108110009Smdodd			}
1109111765Smdodd			if (options & F_TIME) {
1110111765Smdodd				(void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1111111765Smdodd				(void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1112111765Smdodd				(void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1113111765Smdodd			}
1114117548Smaxim			if (recv_len != send_len) {
1115117548Smaxim                        	(void)printf(
1116117548Smaxim				     "\nwrong total length %d instead of %d",
1117117548Smaxim				     recv_len, send_len);
1118117548Smaxim			}
11191558Srgrimes			/* check the data */
1120111765Smdodd			cp = (u_char*)&icp->icmp_data[phdr_len];
1121117549Smaxim			dp = &outpack[ICMP_MINLEN + phdr_len];
1122113217Smdodd			cc -= ICMP_MINLEN + phdr_len;
1123113463Smaxim			i = 0;
1124113463Smaxim			if (timing) {   /* don't check variable timestamp */
1125113463Smaxim				cp += TIMEVAL_LEN;
1126113463Smaxim				dp += TIMEVAL_LEN;
1127113463Smaxim				cc -= TIMEVAL_LEN;
1128113463Smaxim				i += TIMEVAL_LEN;
1129113463Smaxim			}
1130113463Smaxim			for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
11311558Srgrimes				if (*cp != *dp) {
11321558Srgrimes	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
11331558Srgrimes	    i, *dp, *cp);
113493638Smaxim					(void)printf("\ncp:");
11351558Srgrimes					cp = (u_char*)&icp->icmp_data[0];
113636089Sjb					for (i = 0; i < datalen; ++i, ++cp) {
1137117548Smaxim						if ((i % 16) == 8)
11381558Srgrimes							(void)printf("\n\t");
1139117548Smaxim						(void)printf("%2x ", *cp);
11401558Srgrimes					}
114193638Smaxim					(void)printf("\ndp:");
1142117549Smaxim					cp = &outpack[ICMP_MINLEN];
114336089Sjb					for (i = 0; i < datalen; ++i, ++cp) {
1144117548Smaxim						if ((i % 16) == 8)
114536089Sjb							(void)printf("\n\t");
1146117548Smaxim						(void)printf("%2x ", *cp);
114736089Sjb					}
11481558Srgrimes					break;
11491558Srgrimes				}
11501558Srgrimes			}
11511558Srgrimes		}
11521558Srgrimes	} else {
115317724Sfenner		/*
115417724Sfenner		 * We've got something other than an ECHOREPLY.
115517724Sfenner		 * See if it's a reply to something that we sent.
115617724Sfenner		 * We can compare IP destination, protocol,
115717724Sfenner		 * and ICMP type and ID.
115823251Simp		 *
115923251Simp		 * Only print all the error messages if we are running
116093638Smaxim		 * as root to avoid leaking information not normally
116123251Simp		 * available to those not running as root.
116217724Sfenner		 */
116317724Sfenner#ifndef icmp_data
116417724Sfenner		struct ip *oip = &icp->icmp_ip;
116517724Sfenner#else
116617724Sfenner		struct ip *oip = (struct ip *)icp->icmp_data;
116717724Sfenner#endif
116817724Sfenner		struct icmp *oicmp = (struct icmp *)(oip + 1);
116917724Sfenner
117023295Simp		if (((options & F_VERBOSE) && uid == 0) ||
117117724Sfenner		    (!(options & F_QUIET2) &&
117279403Smjacob		     (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
117317724Sfenner		     (oip->ip_p == IPPROTO_ICMP) &&
117417724Sfenner		     (oicmp->icmp_type == ICMP_ECHO) &&
117517724Sfenner		     (oicmp->icmp_id == ident))) {
117617724Sfenner		    (void)printf("%d bytes from %s: ", cc,
117723247Swollman			pr_addr(from->sin_addr));
117817724Sfenner		    pr_icmph(icp);
117917724Sfenner		} else
118017724Sfenner		    return;
11811558Srgrimes	}
11821558Srgrimes
11831558Srgrimes	/* Display any IP options */
11841558Srgrimes	cp = (u_char *)buf + sizeof(struct ip);
11851558Srgrimes
11861558Srgrimes	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
11871558Srgrimes		switch (*cp) {
11881558Srgrimes		case IPOPT_EOL:
11891558Srgrimes			hlen = 0;
11901558Srgrimes			break;
11911558Srgrimes		case IPOPT_LSRR:
1192109730Smaxim		case IPOPT_SSRR:
1193109730Smaxim			(void)printf(*cp == IPOPT_LSRR ?
1194109730Smaxim			    "\nLSRR: " : "\nSSRR: ");
119599446Smaxim			j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
11961558Srgrimes			hlen -= 2;
119799446Smaxim			cp += 2;
1198105624Smaxim			if (j >= INADDR_LEN &&
1199105624Smaxim			    j <= hlen - (int)sizeof(struct ip)) {
12001558Srgrimes				for (;;) {
120199446Smaxim					bcopy(++cp, &ina.s_addr, INADDR_LEN);
120299446Smaxim					if (ina.s_addr == 0)
120393638Smaxim						(void)printf("\t0.0.0.0");
120499446Smaxim					else
120593638Smaxim						(void)printf("\t%s",
120693638Smaxim						     pr_addr(ina));
120799446Smaxim					hlen -= INADDR_LEN;
120899446Smaxim					cp += INADDR_LEN - 1;
120999446Smaxim					j -= INADDR_LEN;
121099446Smaxim					if (j < INADDR_LEN)
121199446Smaxim						break;
121299446Smaxim					(void)putchar('\n');
121399446Smaxim				}
121499446Smaxim			} else
121599446Smaxim				(void)printf("\t(truncated route)\n");
12161558Srgrimes			break;
12171558Srgrimes		case IPOPT_RR:
121899446Smaxim			j = cp[IPOPT_OLEN];		/* get length */
121999446Smaxim			i = cp[IPOPT_OFFSET];		/* and pointer */
12201558Srgrimes			hlen -= 2;
122199446Smaxim			cp += 2;
12221558Srgrimes			if (i > j)
12231558Srgrimes				i = j;
122499446Smaxim			i = i - IPOPT_MINOFF + 1;
122599446Smaxim			if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
122699446Smaxim				old_rrlen = 0;
12271558Srgrimes				continue;
122899446Smaxim			}
12291558Srgrimes			if (i == old_rrlen
12301558Srgrimes			    && !bcmp((char *)cp, old_rr, i)
12311558Srgrimes			    && !(options & F_FLOOD)) {
12321558Srgrimes				(void)printf("\t(same route)");
12331558Srgrimes				hlen -= i;
12341558Srgrimes				cp += i;
12351558Srgrimes				break;
12361558Srgrimes			}
123799446Smaxim			old_rrlen = i;
123899446Smaxim			bcopy((char *)cp, old_rr, i);
12391558Srgrimes			(void)printf("\nRR: ");
124099446Smaxim			if (i >= INADDR_LEN &&
124199446Smaxim			    i <= hlen - (int)sizeof(struct ip)) {
124299446Smaxim				for (;;) {
124399446Smaxim					bcopy(++cp, &ina.s_addr, INADDR_LEN);
124499446Smaxim					if (ina.s_addr == 0)
124599446Smaxim						(void)printf("\t0.0.0.0");
124699446Smaxim					else
124799446Smaxim						(void)printf("\t%s",
124899446Smaxim						     pr_addr(ina));
124999446Smaxim					hlen -= INADDR_LEN;
125099446Smaxim					cp += INADDR_LEN - 1;
125199446Smaxim					i -= INADDR_LEN;
125299446Smaxim					if (i < INADDR_LEN)
125399446Smaxim						break;
125499446Smaxim					(void)putchar('\n');
125523247Swollman				}
125699446Smaxim			} else
125799446Smaxim				(void)printf("\t(truncated route)");
12581558Srgrimes			break;
12591558Srgrimes		case IPOPT_NOP:
12601558Srgrimes			(void)printf("\nNOP");
12611558Srgrimes			break;
12621558Srgrimes		default:
12631558Srgrimes			(void)printf("\nunknown option %x", *cp);
12641558Srgrimes			break;
12651558Srgrimes		}
12661558Srgrimes	if (!(options & F_FLOOD)) {
12671558Srgrimes		(void)putchar('\n');
12681558Srgrimes		(void)fflush(stdout);
12691558Srgrimes	}
12701558Srgrimes}
12711558Srgrimes
12721558Srgrimes/*
12731558Srgrimes * in_cksum --
12741558Srgrimes *	Checksum routine for Internet Protocol family headers (C Version)
12751558Srgrimes */
127623247Swollmanu_short
1277209366Sedin_cksum(u_short *addr, int len)
12781558Srgrimes{
127993035Sobrien	int nleft, sum;
128093035Sobrien	u_short *w;
128153191Spb	union {
128253369Spb		u_short	us;
128353369Spb		u_char	uc[2];
128453369Spb	} last;
128553369Spb	u_short answer;
12861558Srgrimes
128793035Sobrien	nleft = len;
128893035Sobrien	sum = 0;
128993035Sobrien	w = addr;
129093035Sobrien
12911558Srgrimes	/*
12921558Srgrimes	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
12931558Srgrimes	 * sequential 16 bit words to it, and at the end, fold back all the
12941558Srgrimes	 * carry bits from the top 16 bits into the lower 16 bits.
12951558Srgrimes	 */
12961558Srgrimes	while (nleft > 1)  {
12971558Srgrimes		sum += *w++;
12981558Srgrimes		nleft -= 2;
12991558Srgrimes	}
13001558Srgrimes
13011558Srgrimes	/* mop up an odd byte, if necessary */
13021558Srgrimes	if (nleft == 1) {
130353369Spb		last.uc[0] = *(u_char *)w;
130453369Spb		last.uc[1] = 0;
130553369Spb		sum += last.us;
13061558Srgrimes	}
13071558Srgrimes
13081558Srgrimes	/* add back carry outs from top 16 bits to low 16 bits */
13091558Srgrimes	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
13101558Srgrimes	sum += (sum >> 16);			/* add carry */
131153369Spb	answer = ~sum;				/* truncate to 16 bits */
131253369Spb	return(answer);
13131558Srgrimes}
13141558Srgrimes
13151558Srgrimes/*
13161558Srgrimes * tvsub --
13171558Srgrimes *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
13181558Srgrimes * be >= in.
13191558Srgrimes */
132023247Swollmanstatic void
1321209366Sedtvsub(struct timeval *out, const struct timeval *in)
13221558Srgrimes{
132393035Sobrien
13241558Srgrimes	if ((out->tv_usec -= in->tv_usec) < 0) {
13251558Srgrimes		--out->tv_sec;
13261558Srgrimes		out->tv_usec += 1000000;
13271558Srgrimes	}
13281558Srgrimes	out->tv_sec -= in->tv_sec;
13291558Srgrimes}
13301558Srgrimes
13311558Srgrimes/*
13323792Ssef * status --
13333792Ssef *	Print out statistics when SIGINFO is received.
13343792Ssef */
13353792Ssef
133623247Swollmanstatic void
1337209366Sedstatus(int sig __unused)
133820280Sbde{
133993035Sobrien
134020195Ssef	siginfo_p = 1;
134120195Ssef}
134220195Ssef
134323247Swollmanstatic void
1344209366Sedcheck_status(void)
13453792Ssef{
134693035Sobrien
134720195Ssef	if (siginfo_p) {
134820195Ssef		siginfo_p = 0;
1349161273Sdd		(void)fprintf(stderr, "\r%ld/%ld packets received (%.1f%%)",
135020280Sbde		    nreceived, ntransmitted,
1351115691Smaxim		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0);
1352115691Smaxim		if (nreceived && timing)
1353115691Smaxim			(void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max",
1354115691Smaxim			    tmin, tsum / (nreceived + nrepeats), tmax);
1355115691Smaxim		(void)fprintf(stderr, "\n");
135620195Ssef	}
13573792Ssef}
13583792Ssef
13593792Ssef/*
13601558Srgrimes * finish --
13611558Srgrimes *	Print out statistics, and give up.
13621558Srgrimes */
136323247Swollmanstatic void
1364209366Sedfinish(void)
13651558Srgrimes{
13661558Srgrimes
13671558Srgrimes	(void)signal(SIGINT, SIG_IGN);
136827354Ssef	(void)signal(SIGALRM, SIG_IGN);
13691558Srgrimes	(void)putchar('\n');
13701558Srgrimes	(void)fflush(stdout);
13711558Srgrimes	(void)printf("--- %s ping statistics ---\n", hostname);
13721558Srgrimes	(void)printf("%ld packets transmitted, ", ntransmitted);
13731558Srgrimes	(void)printf("%ld packets received, ", nreceived);
13741558Srgrimes	if (nrepeats)
13751558Srgrimes		(void)printf("+%ld duplicates, ", nrepeats);
137646080Simp	if (ntransmitted) {
13771558Srgrimes		if (nreceived > ntransmitted)
13781558Srgrimes			(void)printf("-- somebody's printing up packets!");
13791558Srgrimes		else
1380161273Sdd			(void)printf("%.1f%% packet loss",
1381161273Sdd			    ((ntransmitted - nreceived) * 100.0) /
1382161273Sdd			    ntransmitted);
138346080Simp	}
1384157535Sglebius	if (nrcvtimeout)
1385157535Sglebius		(void)printf(", %ld packets out of wait time", nrcvtimeout);
13861558Srgrimes	(void)putchar('\n');
138727508Swollman	if (nreceived && timing) {
138827508Swollman		double n = nreceived + nrepeats;
138927508Swollman		double avg = tsum / n;
139027508Swollman		double vari = tsumsq / n - avg * avg;
139193638Smaxim		(void)printf(
139293638Smaxim		    "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
139327508Swollman		    tmin, avg, tmax, sqrt(vari));
139427508Swollman	}
13953792Ssef
13968871Srgrimes	if (nreceived)
13974862Sdg		exit(0);
13984862Sdg	else
13994862Sdg		exit(2);
14001558Srgrimes}
14011558Srgrimes
14021558Srgrimes#ifdef notdef
14031558Srgrimesstatic char *ttab[] = {
14041558Srgrimes	"Echo Reply",		/* ip + seq + udata */
14051558Srgrimes	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
14061558Srgrimes	"Source Quench",	/* IP */
14071558Srgrimes	"Redirect",		/* redirect type, gateway, + IP  */
14081558Srgrimes	"Echo",
14091558Srgrimes	"Time Exceeded",	/* transit, frag reassem + IP */
14101558Srgrimes	"Parameter Problem",	/* pointer + IP */
14111558Srgrimes	"Timestamp",		/* id + seq + three timestamps */
14121558Srgrimes	"Timestamp Reply",	/* " */
14131558Srgrimes	"Info Request",		/* id + sq */
14141558Srgrimes	"Info Reply"		/* " */
14151558Srgrimes};
14161558Srgrimes#endif
14171558Srgrimes
14181558Srgrimes/*
14191558Srgrimes * pr_icmph --
14201558Srgrimes *	Print a descriptive string about an ICMP header.
14211558Srgrimes */
142223247Swollmanstatic void
1423209366Sedpr_icmph(struct icmp *icp)
14241558Srgrimes{
142593035Sobrien
14261558Srgrimes	switch(icp->icmp_type) {
14271558Srgrimes	case ICMP_ECHOREPLY:
14281558Srgrimes		(void)printf("Echo Reply\n");
14291558Srgrimes		/* XXX ID + Seq + Data */
14301558Srgrimes		break;
14311558Srgrimes	case ICMP_UNREACH:
14321558Srgrimes		switch(icp->icmp_code) {
14331558Srgrimes		case ICMP_UNREACH_NET:
14341558Srgrimes			(void)printf("Destination Net Unreachable\n");
14351558Srgrimes			break;
14361558Srgrimes		case ICMP_UNREACH_HOST:
14371558Srgrimes			(void)printf("Destination Host Unreachable\n");
14381558Srgrimes			break;
14391558Srgrimes		case ICMP_UNREACH_PROTOCOL:
14401558Srgrimes			(void)printf("Destination Protocol Unreachable\n");
14411558Srgrimes			break;
14421558Srgrimes		case ICMP_UNREACH_PORT:
14431558Srgrimes			(void)printf("Destination Port Unreachable\n");
14441558Srgrimes			break;
14451558Srgrimes		case ICMP_UNREACH_NEEDFRAG:
144617724Sfenner			(void)printf("frag needed and DF set (MTU %d)\n",
144728059Sfenner					ntohs(icp->icmp_nextmtu));
14481558Srgrimes			break;
14491558Srgrimes		case ICMP_UNREACH_SRCFAIL:
14501558Srgrimes			(void)printf("Source Route Failed\n");
14511558Srgrimes			break;
145217724Sfenner		case ICMP_UNREACH_FILTER_PROHIB:
145317724Sfenner			(void)printf("Communication prohibited by filter\n");
145417724Sfenner			break;
14551558Srgrimes		default:
14561558Srgrimes			(void)printf("Dest Unreachable, Bad Code: %d\n",
14571558Srgrimes			    icp->icmp_code);
14581558Srgrimes			break;
14591558Srgrimes		}
14601558Srgrimes		/* Print returned IP header information */
14611558Srgrimes#ifndef icmp_data
14621558Srgrimes		pr_retip(&icp->icmp_ip);
14631558Srgrimes#else
14641558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
14651558Srgrimes#endif
14661558Srgrimes		break;
14671558Srgrimes	case ICMP_SOURCEQUENCH:
14681558Srgrimes		(void)printf("Source Quench\n");
14691558Srgrimes#ifndef icmp_data
14701558Srgrimes		pr_retip(&icp->icmp_ip);
14711558Srgrimes#else
14721558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
14731558Srgrimes#endif
14741558Srgrimes		break;
14751558Srgrimes	case ICMP_REDIRECT:
14761558Srgrimes		switch(icp->icmp_code) {
14771558Srgrimes		case ICMP_REDIRECT_NET:
14781558Srgrimes			(void)printf("Redirect Network");
14791558Srgrimes			break;
14801558Srgrimes		case ICMP_REDIRECT_HOST:
14811558Srgrimes			(void)printf("Redirect Host");
14821558Srgrimes			break;
14831558Srgrimes		case ICMP_REDIRECT_TOSNET:
14841558Srgrimes			(void)printf("Redirect Type of Service and Network");
14851558Srgrimes			break;
14861558Srgrimes		case ICMP_REDIRECT_TOSHOST:
14871558Srgrimes			(void)printf("Redirect Type of Service and Host");
14881558Srgrimes			break;
14891558Srgrimes		default:
14901558Srgrimes			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
14911558Srgrimes			break;
14921558Srgrimes		}
149328059Sfenner		(void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
14941558Srgrimes#ifndef icmp_data
14951558Srgrimes		pr_retip(&icp->icmp_ip);
14961558Srgrimes#else
14971558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
14981558Srgrimes#endif
14991558Srgrimes		break;
15001558Srgrimes	case ICMP_ECHO:
15011558Srgrimes		(void)printf("Echo Request\n");
15021558Srgrimes		/* XXX ID + Seq + Data */
15031558Srgrimes		break;
15041558Srgrimes	case ICMP_TIMXCEED:
15051558Srgrimes		switch(icp->icmp_code) {
15061558Srgrimes		case ICMP_TIMXCEED_INTRANS:
15071558Srgrimes			(void)printf("Time to live exceeded\n");
15081558Srgrimes			break;
15091558Srgrimes		case ICMP_TIMXCEED_REASS:
15101558Srgrimes			(void)printf("Frag reassembly time exceeded\n");
15111558Srgrimes			break;
15121558Srgrimes		default:
15131558Srgrimes			(void)printf("Time exceeded, Bad Code: %d\n",
15141558Srgrimes			    icp->icmp_code);
15151558Srgrimes			break;
15161558Srgrimes		}
15171558Srgrimes#ifndef icmp_data
15181558Srgrimes		pr_retip(&icp->icmp_ip);
15191558Srgrimes#else
15201558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
15211558Srgrimes#endif
15221558Srgrimes		break;
15231558Srgrimes	case ICMP_PARAMPROB:
15241558Srgrimes		(void)printf("Parameter problem: pointer = 0x%02x\n",
15251558Srgrimes		    icp->icmp_hun.ih_pptr);
15261558Srgrimes#ifndef icmp_data
15271558Srgrimes		pr_retip(&icp->icmp_ip);
15281558Srgrimes#else
15291558Srgrimes		pr_retip((struct ip *)icp->icmp_data);
15301558Srgrimes#endif
15311558Srgrimes		break;
15321558Srgrimes	case ICMP_TSTAMP:
15331558Srgrimes		(void)printf("Timestamp\n");
15341558Srgrimes		/* XXX ID + Seq + 3 timestamps */
15351558Srgrimes		break;
15361558Srgrimes	case ICMP_TSTAMPREPLY:
15371558Srgrimes		(void)printf("Timestamp Reply\n");
15381558Srgrimes		/* XXX ID + Seq + 3 timestamps */
15391558Srgrimes		break;
15401558Srgrimes	case ICMP_IREQ:
15411558Srgrimes		(void)printf("Information Request\n");
15421558Srgrimes		/* XXX ID + Seq */
15431558Srgrimes		break;
15441558Srgrimes	case ICMP_IREQREPLY:
15451558Srgrimes		(void)printf("Information Reply\n");
15461558Srgrimes		/* XXX ID + Seq */
15471558Srgrimes		break;
15481558Srgrimes	case ICMP_MASKREQ:
15491558Srgrimes		(void)printf("Address Mask Request\n");
15501558Srgrimes		break;
15511558Srgrimes	case ICMP_MASKREPLY:
15521558Srgrimes		(void)printf("Address Mask Reply\n");
15531558Srgrimes		break;
155417724Sfenner	case ICMP_ROUTERADVERT:
155517724Sfenner		(void)printf("Router Advertisement\n");
155617724Sfenner		break;
155717724Sfenner	case ICMP_ROUTERSOLICIT:
155817724Sfenner		(void)printf("Router Solicitation\n");
155917724Sfenner		break;
15601558Srgrimes	default:
15611558Srgrimes		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
15621558Srgrimes	}
15631558Srgrimes}
15641558Srgrimes
15651558Srgrimes/*
15661558Srgrimes * pr_iph --
15671558Srgrimes *	Print an IP header with options.
15681558Srgrimes */
156923247Swollmanstatic void
1570209366Sedpr_iph(struct ip *ip)
15711558Srgrimes{
157293035Sobrien	u_char *cp;
15731558Srgrimes	int hlen;
15741558Srgrimes
15751558Srgrimes	hlen = ip->ip_hl << 2;
15761558Srgrimes	cp = (u_char *)ip + 20;		/* point to options */
15771558Srgrimes
157817724Sfenner	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
15791558Srgrimes	(void)printf(" %1x  %1x  %02x %04x %04x",
158017724Sfenner	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
158117724Sfenner	    ntohs(ip->ip_id));
158236089Sjb	(void)printf("   %1lx %04lx",
158336089Sjb	    (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
158436089Sjb	    (u_long) ntohl(ip->ip_off) & 0x1fff);
158517724Sfenner	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
158617724Sfenner							    ntohs(ip->ip_sum));
15871558Srgrimes	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
15881558Srgrimes	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
158917724Sfenner	/* dump any option bytes */
15901558Srgrimes	while (hlen-- > 20) {
15911558Srgrimes		(void)printf("%02x", *cp++);
15921558Srgrimes	}
15931558Srgrimes	(void)putchar('\n');
15941558Srgrimes}
15951558Srgrimes
15961558Srgrimes/*
15971558Srgrimes * pr_addr --
15981558Srgrimes *	Return an ascii host address as a dotted quad and optionally with
15991558Srgrimes * a hostname.
16001558Srgrimes */
160123247Swollmanstatic char *
1602209366Sedpr_addr(struct in_addr ina)
16031558Srgrimes{
16041558Srgrimes	struct hostent *hp;
160523251Simp	static char buf[16 + 3 + MAXHOSTNAMELEN];
16061558Srgrimes
16071558Srgrimes	if ((options & F_NUMERIC) ||
160823247Swollman	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
160923247Swollman		return inet_ntoa(ina);
16101558Srgrimes	else
161117320Speter		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
161223247Swollman		    inet_ntoa(ina));
16131558Srgrimes	return(buf);
16141558Srgrimes}
16151558Srgrimes
16161558Srgrimes/*
16171558Srgrimes * pr_retip --
16181558Srgrimes *	Dump some info on a returned (via ICMP) IP packet.
16191558Srgrimes */
162023247Swollmanstatic void
1621209366Sedpr_retip(struct ip *ip)
16221558Srgrimes{
162393035Sobrien	u_char *cp;
16241558Srgrimes	int hlen;
16251558Srgrimes
16261558Srgrimes	pr_iph(ip);
16271558Srgrimes	hlen = ip->ip_hl << 2;
16281558Srgrimes	cp = (u_char *)ip + hlen;
16291558Srgrimes
16301558Srgrimes	if (ip->ip_p == 6)
16311558Srgrimes		(void)printf("TCP: from port %u, to port %u (decimal)\n",
16321558Srgrimes		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
16331558Srgrimes	else if (ip->ip_p == 17)
16341558Srgrimes		(void)printf("UDP: from port %u, to port %u (decimal)\n",
16351558Srgrimes			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
16361558Srgrimes}
16371558Srgrimes
1638111765Smdoddstatic char *
1639209366Sedpr_ntime(n_time timestamp)
1640111765Smdodd{
1641111765Smdodd	static char buf[10];
1642117550Smaxim	int hour, min, sec;
1643111765Smdodd
1644117550Smaxim	sec = ntohl(timestamp) / 1000;
1645117550Smaxim	hour = sec / 60 / 60;
1646117550Smaxim	min = (sec % (60 * 60)) / 60;
1647117550Smaxim	sec = (sec % (60 * 60)) % 60;
1648111765Smdodd
1649117550Smaxim	(void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1650111765Smdodd
1651111765Smdodd	return (buf);
1652111765Smdodd}
1653111765Smdodd
165423247Swollmanstatic void
1655209366Sedfill(char *bp, char *patp)
16561558Srgrimes{
165793035Sobrien	char *cp;
165893035Sobrien	int pat[16];
165999447Smaxim	u_int ii, jj, kk;
16601558Srgrimes
166123247Swollman	for (cp = patp; *cp; cp++) {
166223247Swollman		if (!isxdigit(*cp))
166393638Smaxim			errx(EX_USAGE,
166493638Smaxim			    "patterns must be specified as hex digits");
166593638Smaxim
166623247Swollman	}
16671558Srgrimes	ii = sscanf(patp,
16681558Srgrimes	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
16691558Srgrimes	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
16701558Srgrimes	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
16711558Srgrimes	    &pat[13], &pat[14], &pat[15]);
16721558Srgrimes
16731558Srgrimes	if (ii > 0)
1674112568Smdodd		for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
16751558Srgrimes			for (jj = 0; jj < ii; ++jj)
16761558Srgrimes				bp[jj + kk] = pat[jj];
16771558Srgrimes	if (!(options & F_QUIET)) {
16781558Srgrimes		(void)printf("PATTERN: 0x");
16791558Srgrimes		for (jj = 0; jj < ii; ++jj)
16801558Srgrimes			(void)printf("%02x", bp[jj] & 0xFF);
16811558Srgrimes		(void)printf("\n");
16821558Srgrimes	}
16831558Srgrimes}
16841558Srgrimes
1685112228Sru#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
1686112228Sru#define	SECOPT		" [-P policy]"
1687112228Sru#else
1688112228Sru#define	SECOPT		""
1689112228Sru#endif
169023247Swollmanstatic void
1691209366Sedusage(void)
16921558Srgrimes{
1693112228Sru
1694157535Sglebius	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
1695152996Sru"usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize] [-g sweepminsize]",
1696152996Sru"            [-h sweepincrsize] [-i wait] [-l preload] [-M mask | time] [-m ttl]",
1697152996Sru"           " SECOPT " [-p pattern] [-S src_addr] [-s packetsize] [-t timeout]",
1698157535Sglebius"            [-W waittime] [-z tos] host",
1699112110Sru"       ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]",
1700112228Sru"            [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]",
1701157535Sglebius"            [-s packetsize] [-T ttl] [-t timeout] [-W waittime]",
1702157535Sglebius"            [-z tos] mcast-group");
170323247Swollman	exit(EX_USAGE);
17041558Srgrimes}
1705