Deleted Added
full compact
ping.c (113463) ping.c (114589)
1/*
2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Mike Muuss.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
1/*
2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Mike Muuss.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#if 0
37#ifndef lint
38static const char copyright[] =
39"@(#) Copyright (c) 1989, 1993\n\
40 The Regents of the University of California. All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
38#ifndef lint
39static const char copyright[] =
40"@(#) Copyright (c) 1989, 1993\n\
41 The Regents of the University of California. All rights reserved.\n";
42#endif /* not lint */
43
44#ifndef lint
44#if 0
45static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93";
45static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93";
46#endif
47static const char rcsid[] =
48 "$FreeBSD: head/sbin/ping/ping.c 113463 2003-04-14 08:34:14Z maxim $";
49#endif /* not lint */
46#endif /* not lint */
47#endif
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD: head/sbin/ping/ping.c 114589 2003-05-03 18:41:59Z obrien $");
50
51/*
52 * P I N G . C
53 *
54 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
55 * measure round-trip-delays and packet loss across network paths.
56 *
57 * Author -
58 * Mike Muuss
59 * U. S. Army Ballistic Research Laboratory
60 * December, 1983
61 *
62 * Status -
63 * Public Domain. Distribution Unlimited.
64 * Bugs -
65 * More statistics could always be gathered.
66 * This program has to run SUID to ROOT to access the ICMP socket.
67 */
68
69#include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
70#include <sys/socket.h>
71#include <sys/sysctl.h>
72#include <sys/time.h>
73#include <sys/uio.h>
74
75#include <netinet/in.h>
76#include <netinet/in_systm.h>
77#include <netinet/ip.h>
78#include <netinet/ip_icmp.h>
79#include <netinet/ip_var.h>
80#include <arpa/inet.h>
81
82#ifdef IPSEC
83#include <netinet6/ipsec.h>
84#endif /*IPSEC*/
85
86#include <ctype.h>
87#include <err.h>
88#include <errno.h>
89#include <math.h>
90#include <netdb.h>
91#include <signal.h>
92#include <stdio.h>
93#include <stdlib.h>
94#include <string.h>
95#include <sysexits.h>
96#include <termios.h>
97#include <unistd.h>
98
99#define INADDR_LEN ((int)sizeof(in_addr_t))
100#define TIMEVAL_LEN ((int)sizeof(struct timeval))
101#define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN)
102#define TS_LEN (ICMP_TSLEN - ICMP_MINLEN)
103#define DEFDATALEN 56 /* default data length */
104#define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
105 /* runs out of buffer space */
106#define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
107#define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
108#define MINICMPLEN ICMP_MINLEN
109#define MAXWAIT 10 /* max seconds to wait for response */
110#define MAXALARM (60 * 60) /* max seconds for alarm timeout */
111#define MAXTOS 255
112
113#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
114#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
115#define SET(bit) (A(bit) |= B(bit))
116#define CLR(bit) (A(bit) &= (~B(bit)))
117#define TST(bit) (A(bit) & B(bit))
118
119/* various options */
120int options;
121#define F_FLOOD 0x0001
122#define F_INTERVAL 0x0002
123#define F_NUMERIC 0x0004
124#define F_PINGFILLED 0x0008
125#define F_QUIET 0x0010
126#define F_RROUTE 0x0020
127#define F_SO_DEBUG 0x0040
128#define F_SO_DONTROUTE 0x0080
129#define F_VERBOSE 0x0100
130#define F_QUIET2 0x0200
131#define F_NOLOOP 0x0400
132#define F_MTTL 0x0800
133#define F_MIF 0x1000
134#define F_AUDIBLE 0x2000
135#ifdef IPSEC
136#ifdef IPSEC_POLICY_IPSEC
137#define F_POLICY 0x4000
138#endif /*IPSEC_POLICY_IPSEC*/
139#endif /*IPSEC*/
140#define F_TTL 0x8000
141#define F_MISSED 0x10000
142#define F_ONCE 0x20000
143#define F_HDRINCL 0x40000
144#define F_MASK 0x80000
145#define F_TIME 0x100000
146
147/*
148 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
149 * number of received sequence numbers we can keep track of. Change 128
150 * to 8192 for complete accuracy...
151 */
152#define MAX_DUP_CHK (8 * 128)
153int mx_dup_ck = MAX_DUP_CHK;
154char rcvd_tbl[MAX_DUP_CHK / 8];
155
156struct sockaddr_in whereto; /* who to ping */
157int datalen = DEFDATALEN;
158int maxpayload;
159int s; /* socket file descriptor */
160u_char outpackhdr[IP_MAXPACKET], *outpack;
161char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
162char BSPACE = '\b'; /* characters written for flood */
163char DOT = '.';
164char *hostname;
165char *shostname;
166int ident; /* process id to identify our packets */
167int uid; /* cached uid for micro-optimization */
168u_char icmp_type = ICMP_ECHO;
169u_char icmp_type_rsp = ICMP_ECHOREPLY;
170int phdr_len = 0;
171
172/* counters */
173long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
174long npackets; /* max packets to transmit */
175long nreceived; /* # of packets we got back */
176long nrepeats; /* number of duplicates */
177long ntransmitted; /* sequence # for outbound packets = #sent */
178int interval = 1000; /* interval between packets, ms */
179
180/* timing */
181int timing; /* flag to do timing */
182double tmin = 999999999.0; /* minimum round trip time */
183double tmax = 0.0; /* maximum round trip time */
184double tsum = 0.0; /* sum of all times, for doing average */
185double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
186
187volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */
188int reset_kerninfo;
189volatile sig_atomic_t siginfo_p;
190
191static void fill(char *, char *);
192static u_short in_cksum(u_short *, int);
193static void check_status(void);
194static void finish(void) __dead2;
195static void pinger(void);
196static char *pr_addr(struct in_addr);
197static char *pr_ntime(n_time);
198static void pr_icmph(struct icmp *);
199static void pr_iph(struct ip *);
200static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
201static void pr_retip(struct ip *);
202static void status(int);
203static void stopit(int);
204static void tvsub(struct timeval *, struct timeval *);
205static void usage(void) __dead2;
206
207int
208main(argc, argv)
209 int argc;
210 char *const *argv;
211{
212 struct sockaddr_in from, sock_in;
213 struct in_addr ifaddr;
214 struct timeval last, intvl;
215 struct iovec iov;
216 struct ip *ip;
217 struct msghdr msg;
218 struct sigaction si_sa;
219 struct termios ts;
220 size_t sz;
221 u_char *datap, packet[IP_MAXPACKET];
222 char *ep, *source, *target, *payload;
223 struct hostent *hp;
224#ifdef IPSEC_POLICY_IPSEC
225 char *policy_in, *policy_out;
226#endif
227 struct sockaddr_in *to;
228 double t;
229 u_long alarmtimeout, ultmp;
230 int almost_done, ch, df, hold, i, mib[4], packlen, preload, sockerrno,
231 tos, ttl;
232 char ctrl[CMSG_SPACE(sizeof(struct timeval))];
233 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
234#ifdef IP_OPTIONS
235 char rspace[MAX_IPOPTLEN]; /* record route space */
236#endif
237 unsigned char loop, mttl;
238
239 payload = source = NULL;
240#ifdef IPSEC_POLICY_IPSEC
241 policy_in = policy_out = NULL;
242#endif
243
244 /*
245 * Do the stuff that we need root priv's for *first*, and
246 * then drop our setuid bit. Save error reporting for
247 * after arg parsing.
248 */
249 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
250 sockerrno = errno;
251
252 setuid(getuid());
253 uid = getuid();
254
255 alarmtimeout = df = preload = tos = 0;
256
257 outpack = outpackhdr + sizeof(struct ip);
258 while ((ch = getopt(argc, argv,
259 "Aac:DdfI:i:Ll:M:m:nop:QqRrS:s:T:t:vz:"
260#ifdef IPSEC
261#ifdef IPSEC_POLICY_IPSEC
262 "P:"
263#endif /*IPSEC_POLICY_IPSEC*/
264#endif /*IPSEC*/
265 )) != -1)
266 {
267 switch(ch) {
268 case 'A':
269 options |= F_MISSED;
270 break;
271 case 'a':
272 options |= F_AUDIBLE;
273 break;
274 case 'c':
275 ultmp = strtoul(optarg, &ep, 0);
276 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
277 errx(EX_USAGE,
278 "invalid count of packets to transmit: `%s'",
279 optarg);
280 npackets = ultmp;
281 break;
282 case 'D':
283 options |= F_HDRINCL;
284 df = 1;
285 break;
286 case 'd':
287 options |= F_SO_DEBUG;
288 break;
289 case 'f':
290 if (uid) {
291 errno = EPERM;
292 err(EX_NOPERM, "-f flag");
293 }
294 options |= F_FLOOD;
295 setbuf(stdout, (char *)NULL);
296 break;
297 case 'I': /* multicast interface */
298 if (inet_aton(optarg, &ifaddr) == 0)
299 errx(EX_USAGE,
300 "invalid multicast interface: `%s'",
301 optarg);
302 options |= F_MIF;
303 break;
304 case 'i': /* wait between sending packets */
305 t = strtod(optarg, &ep) * 1000.0;
306 if (*ep || ep == optarg || t > (double)INT_MAX)
307 errx(EX_USAGE, "invalid timing interval: `%s'",
308 optarg);
309 options |= F_INTERVAL;
310 interval = (int)t;
311 if (uid && interval < 1000) {
312 errno = EPERM;
313 err(EX_NOPERM, "-i interval too short");
314 }
315 break;
316 case 'L':
317 options |= F_NOLOOP;
318 loop = 0;
319 break;
320 case 'l':
321 ultmp = strtoul(optarg, &ep, 0);
322 if (*ep || ep == optarg || ultmp > INT_MAX)
323 errx(EX_USAGE,
324 "invalid preload value: `%s'", optarg);
325 if (uid) {
326 errno = EPERM;
327 err(EX_NOPERM, "-l flag");
328 }
329 preload = ultmp;
330 break;
331 case 'M':
332 switch(optarg[0]) {
333 case 'M':
334 case 'm':
335 options |= F_MASK;
336 break;
337 case 'T':
338 case 't':
339 options |= F_TIME;
340 break;
341 default:
342 errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
343 break;
344 }
345 break;
346 case 'm': /* TTL */
347 ultmp = strtoul(optarg, &ep, 0);
348 if (*ep || ep == optarg || ultmp > MAXTTL)
349 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
350 ttl = ultmp;
351 options |= F_TTL;
352 break;
353 case 'n':
354 options |= F_NUMERIC;
355 break;
356 case 'o':
357 options |= F_ONCE;
358 break;
359#ifdef IPSEC
360#ifdef IPSEC_POLICY_IPSEC
361 case 'P':
362 options |= F_POLICY;
363 if (!strncmp("in", optarg, 2))
364 policy_in = strdup(optarg);
365 else if (!strncmp("out", optarg, 3))
366 policy_out = strdup(optarg);
367 else
368 errx(1, "invalid security policy");
369 break;
370#endif /*IPSEC_POLICY_IPSEC*/
371#endif /*IPSEC*/
372 case 'p': /* fill buffer with user pattern */
373 options |= F_PINGFILLED;
374 payload = optarg;
375 break;
376 case 'Q':
377 options |= F_QUIET2;
378 break;
379 case 'q':
380 options |= F_QUIET;
381 break;
382 case 'R':
383 options |= F_RROUTE;
384 break;
385 case 'r':
386 options |= F_SO_DONTROUTE;
387 break;
388 case 'S':
389 source = optarg;
390 break;
391 case 's': /* size of packet to send */
392 ultmp = strtoul(optarg, &ep, 0);
393 if (*ep || ep == optarg)
394 errx(EX_USAGE, "invalid packet size: `%s'",
395 optarg);
396 if (uid != 0 && ultmp > DEFDATALEN) {
397 errno = EPERM;
398 err(EX_NOPERM,
399 "packet size too large: %lu > %u",
400 ultmp, DEFDATALEN);
401 }
402 datalen = ultmp;
403 break;
404 case 'T': /* multicast TTL */
405 ultmp = strtoul(optarg, &ep, 0);
406 if (*ep || ep == optarg || ultmp > MAXTTL)
407 errx(EX_USAGE, "invalid multicast TTL: `%s'",
408 optarg);
409 mttl = ultmp;
410 options |= F_MTTL;
411 break;
412 case 't':
413 alarmtimeout = strtoul(optarg, &ep, 0);
414 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
415 errx(EX_USAGE, "invalid timeout: `%s'",
416 optarg);
417 if (alarmtimeout > MAXALARM)
418 errx(EX_USAGE, "invalid timeout: `%s' > %d",
419 optarg, MAXALARM);
420 alarm((int)alarmtimeout);
421 break;
422 case 'v':
423 options |= F_VERBOSE;
424 break;
425 case 'z':
426 options |= F_HDRINCL;
427 ultmp = strtoul(optarg, &ep, 0);
428 if (*ep || ep == optarg || ultmp > MAXTOS)
429 errx(EX_USAGE, "invalid TOS: `%s'", optarg);
430 tos = ultmp;
431 break;
432 default:
433 usage();
434 }
435 }
436
437 if (argc - optind != 1)
438 usage();
439 target = argv[optind];
440
441 switch (options & (F_MASK|F_TIME)) {
442 case 0: break;
443 case F_MASK:
444 icmp_type = ICMP_MASKREQ;
445 icmp_type_rsp = ICMP_MASKREPLY;
446 phdr_len = MASK_LEN;
447 if (!(options & F_QUIET))
448 (void)printf("ICMP_MASKREQ\n");
449 break;
450 case F_TIME:
451 icmp_type = ICMP_TSTAMP;
452 icmp_type_rsp = ICMP_TSTAMPREPLY;
453 phdr_len = TS_LEN;
454 if (!(options & F_QUIET))
455 (void)printf("ICMP_TSTAMP\n");
456 break;
457 default:
458 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
459 break;
460 }
461 maxpayload = IP_MAXPACKET - sizeof(struct ip) - MINICMPLEN - phdr_len;
462 if (options & F_RROUTE)
463 maxpayload -= MAX_IPOPTLEN;
464 if (datalen > maxpayload)
465 errx(EX_USAGE, "packet size too large: %d > %d", datalen,
466 maxpayload);
467 datap = &outpack[MINICMPLEN + phdr_len + TIMEVAL_LEN];
468 if (options & F_PINGFILLED) {
469 fill((char *)datap, payload);
470 }
471 if (source) {
472 bzero((char *)&sock_in, sizeof(sock_in));
473 sock_in.sin_family = AF_INET;
474 if (inet_aton(source, &sock_in.sin_addr) != 0) {
475 shostname = source;
476 } else {
477 hp = gethostbyname2(source, AF_INET);
478 if (!hp)
479 errx(EX_NOHOST, "cannot resolve %s: %s",
480 source, hstrerror(h_errno));
481
482 sock_in.sin_len = sizeof sock_in;
483 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
484 hp->h_length < 0)
485 errx(1, "gethostbyname2: illegal address");
486 memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
487 sizeof(sock_in.sin_addr));
488 (void)strncpy(snamebuf, hp->h_name,
489 sizeof(snamebuf) - 1);
490 snamebuf[sizeof(snamebuf) - 1] = '\0';
491 shostname = snamebuf;
492 }
493 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
494 err(1, "bind");
495 }
496
497 bzero(&whereto, sizeof(whereto));
498 to = &whereto;
499 to->sin_family = AF_INET;
500 to->sin_len = sizeof *to;
501 if (inet_aton(target, &to->sin_addr) != 0) {
502 hostname = target;
503 } else {
504 hp = gethostbyname2(target, AF_INET);
505 if (!hp)
506 errx(EX_NOHOST, "cannot resolve %s: %s",
507 target, hstrerror(h_errno));
508
509 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
510 errx(1, "gethostbyname2 returned an illegal address");
511 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
512 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
513 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
514 hostname = hnamebuf;
515 }
516
517 if (options & F_FLOOD && options & F_INTERVAL)
518 errx(EX_USAGE, "-f and -i: incompatible options");
519
520 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
521 errx(EX_USAGE,
522 "-f flag cannot be used with multicast destination");
523 if (options & (F_MIF | F_NOLOOP | F_MTTL)
524 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
525 errx(EX_USAGE,
526 "-I, -L, -T flags cannot be used with unicast destination");
527
528 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
529 timing = 1;
530 packlen = MAXIPLEN + MAXICMPLEN + datalen;
531 packlen = packlen > IP_MAXPACKET ? IP_MAXPACKET : packlen;
532
533 if (!(options & F_PINGFILLED))
534 for (i = TIMEVAL_LEN; i < datalen; ++i)
535 *datap++ = i;
536
537 ident = getpid() & 0xFFFF;
538
539 if (s < 0) {
540 errno = sockerrno;
541 err(EX_OSERR, "socket");
542 }
543 hold = 1;
544 if (options & F_SO_DEBUG)
545 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
546 sizeof(hold));
547 if (options & F_SO_DONTROUTE)
548 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
549 sizeof(hold));
550#ifdef IPSEC
551#ifdef IPSEC_POLICY_IPSEC
552 if (options & F_POLICY) {
553 char *buf;
554 if (policy_in != NULL) {
555 buf = ipsec_set_policy(policy_in, strlen(policy_in));
556 if (buf == NULL)
557 errx(EX_CONFIG, "%s", ipsec_strerror());
558 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
559 buf, ipsec_get_policylen(buf)) < 0)
560 err(EX_CONFIG,
561 "ipsec policy cannot be configured");
562 free(buf);
563 }
564
565 if (policy_out != NULL) {
566 buf = ipsec_set_policy(policy_out, strlen(policy_out));
567 if (buf == NULL)
568 errx(EX_CONFIG, "%s", ipsec_strerror());
569 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
570 buf, ipsec_get_policylen(buf)) < 0)
571 err(EX_CONFIG,
572 "ipsec policy cannot be configured");
573 free(buf);
574 }
575 }
576#endif /*IPSEC_POLICY_IPSEC*/
577#endif /*IPSEC*/
578
579 if (options & F_HDRINCL) {
580 ip = (struct ip*)outpackhdr;
581 if (!(options & (F_TTL | F_MTTL))) {
582 mib[0] = CTL_NET;
583 mib[1] = PF_INET;
584 mib[2] = IPPROTO_IP;
585 mib[3] = IPCTL_DEFTTL;
586 sz = sizeof(ttl);
587 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
588 err(1, "sysctl(net.inet.ip.ttl)");
589 }
590 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
591 ip->ip_v = IPVERSION;
592 ip->ip_hl = sizeof(struct ip) >> 2;
593 ip->ip_tos = tos;
594 ip->ip_id = 0;
595 ip->ip_off = df ? IP_DF : 0;
596 ip->ip_ttl = ttl;
597 ip->ip_p = IPPROTO_ICMP;
598 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
599 ip->ip_dst = to->sin_addr;
600 }
601 /* record route option */
602 if (options & F_RROUTE) {
603#ifdef IP_OPTIONS
604 bzero(rspace, sizeof(rspace));
605 rspace[IPOPT_OPTVAL] = IPOPT_RR;
606 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
607 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
608 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
609 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
610 sizeof(rspace)) < 0)
611 err(EX_OSERR, "setsockopt IP_OPTIONS");
612#else
613 errx(EX_UNAVAILABLE,
614 "record route not available in this implementation");
615#endif /* IP_OPTIONS */
616 }
617
618 if (options & F_TTL) {
619 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
620 sizeof(ttl)) < 0) {
621 err(EX_OSERR, "setsockopt IP_TTL");
622 }
623 }
624 if (options & F_NOLOOP) {
625 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
626 sizeof(loop)) < 0) {
627 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
628 }
629 }
630 if (options & F_MTTL) {
631 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
632 sizeof(mttl)) < 0) {
633 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
634 }
635 }
636 if (options & F_MIF) {
637 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
638 sizeof(ifaddr)) < 0) {
639 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
640 }
641 }
642#ifdef SO_TIMESTAMP
643 { int on = 1;
644 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
645 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
646 }
647#endif
648
649 /*
650 * When pinging the broadcast address, you can get a lot of answers.
651 * Doing something so evil is useful if you are trying to stress the
652 * ethernet, or just want to fill the arp cache to get some stuff for
653 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
654 * or multicast pings if they wish.
655 */
656
657 /*
658 * XXX receive buffer needs undetermined space for mbuf overhead
659 * as well.
660 */
661 hold = IP_MAXPACKET + 128;
662 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
663 sizeof(hold));
664 if (uid == 0)
665 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
666 sizeof(hold));
667
668 if (to->sin_family == AF_INET) {
669 (void)printf("PING %s (%s)", hostname,
670 inet_ntoa(to->sin_addr));
671 if (source)
672 (void)printf(" from %s", shostname);
673 (void)printf(": %d data bytes\n", datalen);
674 } else
675 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
676
677 /*
678 * Use sigaction() instead of signal() to get unambiguous semantics,
679 * in particular with SA_RESTART not set.
680 */
681
682 sigemptyset(&si_sa.sa_mask);
683 si_sa.sa_flags = 0;
684
685 si_sa.sa_handler = stopit;
686 if (sigaction(SIGINT, &si_sa, 0) == -1) {
687 err(EX_OSERR, "sigaction SIGINT");
688 }
689
690 si_sa.sa_handler = status;
691 if (sigaction(SIGINFO, &si_sa, 0) == -1) {
692 err(EX_OSERR, "sigaction");
693 }
694
695 if (alarmtimeout > 0) {
696 si_sa.sa_handler = stopit;
697 if (sigaction(SIGALRM, &si_sa, 0) == -1)
698 err(EX_OSERR, "sigaction SIGALRM");
699 }
700
701 bzero(&msg, sizeof(msg));
702 msg.msg_name = (caddr_t)&from;
703 msg.msg_iov = &iov;
704 msg.msg_iovlen = 1;
705#ifdef SO_TIMESTAMP
706 msg.msg_control = (caddr_t)ctrl;
707#endif
708 iov.iov_base = packet;
709 iov.iov_len = packlen;
710
711 if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
712 reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
713 ts.c_lflag |= NOKERNINFO;
714 tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
715 }
716
717 if (preload == 0)
718 pinger(); /* send the first ping */
719 else {
720 if (npackets != 0 && preload > npackets)
721 preload = npackets;
722 while (preload--) /* fire off them quickies */
723 pinger();
724 }
725 (void)gettimeofday(&last, NULL);
726
727 if (options & F_FLOOD) {
728 intvl.tv_sec = 0;
729 intvl.tv_usec = 10000;
730 } else {
731 intvl.tv_sec = interval / 1000;
732 intvl.tv_usec = interval % 1000 * 1000;
733 }
734
735 almost_done = 0;
736 while (!finish_up) {
737 struct timeval now, timeout;
738 fd_set rfds;
739 int cc, n;
740
741 check_status();
742 if ((unsigned)s >= FD_SETSIZE)
743 errx(EX_OSERR, "descriptor too large");
744 FD_ZERO(&rfds);
745 FD_SET(s, &rfds);
746 (void)gettimeofday(&now, NULL);
747 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
748 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
749 while (timeout.tv_usec < 0) {
750 timeout.tv_usec += 1000000;
751 timeout.tv_sec--;
752 }
753 while (timeout.tv_usec >= 1000000) {
754 timeout.tv_usec -= 1000000;
755 timeout.tv_sec++;
756 }
757 if (timeout.tv_sec < 0)
758 timeout.tv_sec = timeout.tv_usec = 0;
759 n = select(s + 1, &rfds, NULL, NULL, &timeout);
760 if (n < 0)
761 continue; /* Must be EINTR. */
762 if (n == 1) {
763 struct timeval *tv = NULL;
764#ifdef SO_TIMESTAMP
765 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
766
767 msg.msg_controllen = sizeof(ctrl);
768#endif
769 msg.msg_namelen = sizeof(from);
770 if ((cc = recvmsg(s, &msg, 0)) < 0) {
771 if (errno == EINTR)
772 continue;
773 warn("recvmsg");
774 continue;
775 }
776#ifdef SO_TIMESTAMP
777 if (cmsg->cmsg_level == SOL_SOCKET &&
778 cmsg->cmsg_type == SCM_TIMESTAMP &&
779 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
780 /* Copy to avoid alignment problems: */
781 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
782 tv = &now;
783 }
784#endif
785 if (tv == NULL) {
786 (void)gettimeofday(&now, NULL);
787 tv = &now;
788 }
789 pr_pack((char *)packet, cc, &from, tv);
790 if ((options & F_ONCE && nreceived) ||
791 (npackets && nreceived >= npackets))
792 break;
793 }
794 if (n == 0 || options & F_FLOOD) {
795 if (!npackets || ntransmitted < npackets)
796 pinger();
797 else {
798 if (almost_done)
799 break;
800 almost_done = 1;
801 intvl.tv_usec = 0;
802 if (nreceived) {
803 intvl.tv_sec = 2 * tmax / 1000;
804 if (!intvl.tv_sec)
805 intvl.tv_sec = 1;
806 } else
807 intvl.tv_sec = MAXWAIT;
808 }
809 (void)gettimeofday(&last, NULL);
810 if (ntransmitted - nreceived - 1 > nmissedmax) {
811 nmissedmax = ntransmitted - nreceived - 1;
812 if (options & F_MISSED)
813 (void)write(STDOUT_FILENO, &BBELL, 1);
814 }
815 }
816 }
817 finish();
818 /* NOTREACHED */
819 exit(0); /* Make the compiler happy */
820}
821
822/*
823 * stopit --
824 * Set the global bit that causes the main loop to quit.
825 * Do NOT call finish() from here, since finish() does far too much
826 * to be called from a signal handler.
827 */
828void
829stopit(sig)
830 int sig __unused;
831{
832
833 finish_up = 1;
834}
835
836/*
837 * pinger --
838 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
839 * will be added on by the kernel. The ID field is our UNIX process ID,
840 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
841 * bytes of the data portion are used to hold a UNIX "timeval" struct in
842 * host byte-order, to compute the round-trip time.
843 */
844static void
845pinger(void)
846{
847 struct timeval now;
848 struct ip *ip;
849 struct icmp *icp;
850 int cc, i;
851 u_char *packet;
852
853 packet = outpack;
854 icp = (struct icmp *)outpack;
855 icp->icmp_type = icmp_type;
856 icp->icmp_code = 0;
857 icp->icmp_cksum = 0;
858 icp->icmp_seq = htons(ntransmitted);
859 icp->icmp_id = ident; /* ID */
860
861 CLR(ntransmitted % mx_dup_ck);
862
863 if ((options & F_TIME) || timing) {
864 (void)gettimeofday(&now, NULL);
865
866 if (options & F_TIME)
867 icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
868 * 1000 + now.tv_usec / 1000);
869 if (timing)
870 bcopy((void *)&now,
871 (void *)&outpack[MINICMPLEN + phdr_len],
872 sizeof(struct timeval));
873 }
874
875 cc = MINICMPLEN + phdr_len + datalen;
876
877 /* compute ICMP checksum here */
878 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
879
880 if (options & F_HDRINCL) {
881 cc += sizeof(struct ip);
882 ip = (struct ip *)outpackhdr;
883 ip->ip_len = cc;
884 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
885 packet = outpackhdr;
886 }
887 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
888 sizeof(whereto));
889
890 if (i < 0 || i != cc) {
891 if (i < 0) {
892 if (options & F_FLOOD && errno == ENOBUFS) {
893 usleep(FLOOD_BACKOFF);
894 return;
895 }
896 warn("sendto");
897 } else {
898 warn("%s: partial write: %d of %d bytes",
899 hostname, i, cc);
900 }
901 }
902 ntransmitted++;
903 if (!(options & F_QUIET) && options & F_FLOOD)
904 (void)write(STDOUT_FILENO, &DOT, 1);
905}
906
907/*
908 * pr_pack --
909 * Print out the packet, if it came from us. This logic is necessary
910 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
911 * which arrive ('tis only fair). This permits multiple copies of this
912 * program to be run without having intermingled output (or statistics!).
913 */
914static void
915pr_pack(buf, cc, from, tv)
916 char *buf;
917 int cc;
918 struct sockaddr_in *from;
919 struct timeval *tv;
920{
921 struct in_addr ina;
922 u_char *cp, *dp;
923 struct icmp *icp;
924 struct ip *ip;
925 const void *tp;
926 double triptime;
927 int dupflag, hlen, i, j, seq;
928 static int old_rrlen;
929 static char old_rr[MAX_IPOPTLEN];
930
931 /* Check the IP header */
932 ip = (struct ip *)buf;
933 hlen = ip->ip_hl << 2;
934 if (cc < hlen + ICMP_MINLEN) {
935 if (options & F_VERBOSE)
936 warn("packet too short (%d bytes) from %s", cc,
937 inet_ntoa(from->sin_addr));
938 return;
939 }
940
941 /* Now the ICMP part */
942 cc -= hlen;
943 icp = (struct icmp *)(buf + hlen);
944 if (icp->icmp_type == icmp_type_rsp) {
945 if (icp->icmp_id != ident)
946 return; /* 'Twas not our ECHO */
947 ++nreceived;
948 triptime = 0.0;
949 if (timing) {
950 struct timeval tv1;
951#ifndef icmp_data
952 tp = &icp->icmp_ip;
953#else
954 tp = icp->icmp_data;
955#endif
956 tp += phdr_len;
957
958 if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) {
959 /* Copy to avoid alignment problems: */
960 memcpy(&tv1, tp, sizeof(tv1));
961 tvsub(tv, &tv1);
962 triptime = ((double)tv->tv_sec) * 1000.0 +
963 ((double)tv->tv_usec) / 1000.0;
964 tsum += triptime;
965 tsumsq += triptime * triptime;
966 if (triptime < tmin)
967 tmin = triptime;
968 if (triptime > tmax)
969 tmax = triptime;
970 } else
971 timing = 0;
972 }
973
974 seq = ntohs(icp->icmp_seq);
975
976 if (TST(seq % mx_dup_ck)) {
977 ++nrepeats;
978 --nreceived;
979 dupflag = 1;
980 } else {
981 SET(seq % mx_dup_ck);
982 dupflag = 0;
983 }
984
985 if (options & F_QUIET)
986 return;
987
988 if (options & F_FLOOD)
989 (void)write(STDOUT_FILENO, &BSPACE, 1);
990 else {
991 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
992 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
993 seq);
994 (void)printf(" ttl=%d", ip->ip_ttl);
995 if (timing)
996 (void)printf(" time=%.3f ms", triptime);
997 if (dupflag)
998 (void)printf(" (DUP!)");
999 if (options & F_AUDIBLE)
1000 (void)write(STDOUT_FILENO, &BBELL, 1);
1001 if (options & F_MASK) {
1002 /* Just prentend this cast isn't ugly */
1003 (void)printf(" mask=%s",
1004 pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1005 }
1006 if (options & F_TIME) {
1007 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1008 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1009 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1010 }
1011 /* check the data */
1012 cp = (u_char*)&icp->icmp_data[phdr_len];
1013 dp = &outpack[MINICMPLEN + phdr_len];
1014 cc -= ICMP_MINLEN + phdr_len;
1015 i = 0;
1016 if (timing) { /* don't check variable timestamp */
1017 cp += TIMEVAL_LEN;
1018 dp += TIMEVAL_LEN;
1019 cc -= TIMEVAL_LEN;
1020 i += TIMEVAL_LEN;
1021 }
1022 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
1023 if (*cp != *dp) {
1024 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1025 i, *dp, *cp);
1026 (void)printf("\ncp:");
1027 cp = (u_char*)&icp->icmp_data[0];
1028 for (i = 0; i < datalen; ++i, ++cp) {
1029 if ((i % 32) == 8)
1030 (void)printf("\n\t");
1031 (void)printf("%x ", *cp);
1032 }
1033 (void)printf("\ndp:");
1034 cp = &outpack[MINICMPLEN];
1035 for (i = 0; i < datalen; ++i, ++cp) {
1036 if ((i % 32) == 8)
1037 (void)printf("\n\t");
1038 (void)printf("%x ", *cp);
1039 }
1040 break;
1041 }
1042 }
1043 }
1044 } else {
1045 /*
1046 * We've got something other than an ECHOREPLY.
1047 * See if it's a reply to something that we sent.
1048 * We can compare IP destination, protocol,
1049 * and ICMP type and ID.
1050 *
1051 * Only print all the error messages if we are running
1052 * as root to avoid leaking information not normally
1053 * available to those not running as root.
1054 */
1055#ifndef icmp_data
1056 struct ip *oip = &icp->icmp_ip;
1057#else
1058 struct ip *oip = (struct ip *)icp->icmp_data;
1059#endif
1060 struct icmp *oicmp = (struct icmp *)(oip + 1);
1061
1062 if (((options & F_VERBOSE) && uid == 0) ||
1063 (!(options & F_QUIET2) &&
1064 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1065 (oip->ip_p == IPPROTO_ICMP) &&
1066 (oicmp->icmp_type == ICMP_ECHO) &&
1067 (oicmp->icmp_id == ident))) {
1068 (void)printf("%d bytes from %s: ", cc,
1069 pr_addr(from->sin_addr));
1070 pr_icmph(icp);
1071 } else
1072 return;
1073 }
1074
1075 /* Display any IP options */
1076 cp = (u_char *)buf + sizeof(struct ip);
1077
1078 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1079 switch (*cp) {
1080 case IPOPT_EOL:
1081 hlen = 0;
1082 break;
1083 case IPOPT_LSRR:
1084 case IPOPT_SSRR:
1085 (void)printf(*cp == IPOPT_LSRR ?
1086 "\nLSRR: " : "\nSSRR: ");
1087 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1088 hlen -= 2;
1089 cp += 2;
1090 if (j >= INADDR_LEN &&
1091 j <= hlen - (int)sizeof(struct ip)) {
1092 for (;;) {
1093 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1094 if (ina.s_addr == 0)
1095 (void)printf("\t0.0.0.0");
1096 else
1097 (void)printf("\t%s",
1098 pr_addr(ina));
1099 hlen -= INADDR_LEN;
1100 cp += INADDR_LEN - 1;
1101 j -= INADDR_LEN;
1102 if (j < INADDR_LEN)
1103 break;
1104 (void)putchar('\n');
1105 }
1106 } else
1107 (void)printf("\t(truncated route)\n");
1108 break;
1109 case IPOPT_RR:
1110 j = cp[IPOPT_OLEN]; /* get length */
1111 i = cp[IPOPT_OFFSET]; /* and pointer */
1112 hlen -= 2;
1113 cp += 2;
1114 if (i > j)
1115 i = j;
1116 i = i - IPOPT_MINOFF + 1;
1117 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1118 old_rrlen = 0;
1119 continue;
1120 }
1121 if (i == old_rrlen
1122 && !bcmp((char *)cp, old_rr, i)
1123 && !(options & F_FLOOD)) {
1124 (void)printf("\t(same route)");
1125 hlen -= i;
1126 cp += i;
1127 break;
1128 }
1129 old_rrlen = i;
1130 bcopy((char *)cp, old_rr, i);
1131 (void)printf("\nRR: ");
1132 if (i >= INADDR_LEN &&
1133 i <= hlen - (int)sizeof(struct ip)) {
1134 for (;;) {
1135 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1136 if (ina.s_addr == 0)
1137 (void)printf("\t0.0.0.0");
1138 else
1139 (void)printf("\t%s",
1140 pr_addr(ina));
1141 hlen -= INADDR_LEN;
1142 cp += INADDR_LEN - 1;
1143 i -= INADDR_LEN;
1144 if (i < INADDR_LEN)
1145 break;
1146 (void)putchar('\n');
1147 }
1148 } else
1149 (void)printf("\t(truncated route)");
1150 break;
1151 case IPOPT_NOP:
1152 (void)printf("\nNOP");
1153 break;
1154 default:
1155 (void)printf("\nunknown option %x", *cp);
1156 break;
1157 }
1158 if (!(options & F_FLOOD)) {
1159 (void)putchar('\n');
1160 (void)fflush(stdout);
1161 }
1162}
1163
1164/*
1165 * in_cksum --
1166 * Checksum routine for Internet Protocol family headers (C Version)
1167 */
1168u_short
1169in_cksum(addr, len)
1170 u_short *addr;
1171 int len;
1172{
1173 int nleft, sum;
1174 u_short *w;
1175 union {
1176 u_short us;
1177 u_char uc[2];
1178 } last;
1179 u_short answer;
1180
1181 nleft = len;
1182 sum = 0;
1183 w = addr;
1184
1185 /*
1186 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1187 * sequential 16 bit words to it, and at the end, fold back all the
1188 * carry bits from the top 16 bits into the lower 16 bits.
1189 */
1190 while (nleft > 1) {
1191 sum += *w++;
1192 nleft -= 2;
1193 }
1194
1195 /* mop up an odd byte, if necessary */
1196 if (nleft == 1) {
1197 last.uc[0] = *(u_char *)w;
1198 last.uc[1] = 0;
1199 sum += last.us;
1200 }
1201
1202 /* add back carry outs from top 16 bits to low 16 bits */
1203 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1204 sum += (sum >> 16); /* add carry */
1205 answer = ~sum; /* truncate to 16 bits */
1206 return(answer);
1207}
1208
1209/*
1210 * tvsub --
1211 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1212 * be >= in.
1213 */
1214static void
1215tvsub(out, in)
1216 struct timeval *out, *in;
1217{
1218
1219 if ((out->tv_usec -= in->tv_usec) < 0) {
1220 --out->tv_sec;
1221 out->tv_usec += 1000000;
1222 }
1223 out->tv_sec -= in->tv_sec;
1224}
1225
1226/*
1227 * status --
1228 * Print out statistics when SIGINFO is received.
1229 */
1230
1231static void
1232status(sig)
1233 int sig __unused;
1234{
1235
1236 siginfo_p = 1;
1237}
1238
1239static void
1240check_status()
1241{
1242
1243 if (siginfo_p) {
1244 siginfo_p = 0;
1245 (void)fprintf(stderr,
1246 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
1247 nreceived, ntransmitted,
1248 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
1249 nreceived ? tmin : 0.0,
1250 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
1251 tmax);
1252 }
1253}
1254
1255/*
1256 * finish --
1257 * Print out statistics, and give up.
1258 */
1259static void
1260finish()
1261{
1262 struct termios ts;
1263
1264 (void)signal(SIGINT, SIG_IGN);
1265 (void)signal(SIGALRM, SIG_IGN);
1266 (void)putchar('\n');
1267 (void)fflush(stdout);
1268 (void)printf("--- %s ping statistics ---\n", hostname);
1269 (void)printf("%ld packets transmitted, ", ntransmitted);
1270 (void)printf("%ld packets received, ", nreceived);
1271 if (nrepeats)
1272 (void)printf("+%ld duplicates, ", nrepeats);
1273 if (ntransmitted) {
1274 if (nreceived > ntransmitted)
1275 (void)printf("-- somebody's printing up packets!");
1276 else
1277 (void)printf("%d%% packet loss",
1278 (int)(((ntransmitted - nreceived) * 100) /
1279 ntransmitted));
1280 }
1281 (void)putchar('\n');
1282 if (nreceived && timing) {
1283 double n = nreceived + nrepeats;
1284 double avg = tsum / n;
1285 double vari = tsumsq / n - avg * avg;
1286 (void)printf(
1287 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1288 tmin, avg, tmax, sqrt(vari));
1289 }
1290 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
1291 ts.c_lflag &= ~NOKERNINFO;
1292 tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
1293 }
1294
1295 if (nreceived)
1296 exit(0);
1297 else
1298 exit(2);
1299}
1300
1301#ifdef notdef
1302static char *ttab[] = {
1303 "Echo Reply", /* ip + seq + udata */
1304 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
1305 "Source Quench", /* IP */
1306 "Redirect", /* redirect type, gateway, + IP */
1307 "Echo",
1308 "Time Exceeded", /* transit, frag reassem + IP */
1309 "Parameter Problem", /* pointer + IP */
1310 "Timestamp", /* id + seq + three timestamps */
1311 "Timestamp Reply", /* " */
1312 "Info Request", /* id + sq */
1313 "Info Reply" /* " */
1314};
1315#endif
1316
1317/*
1318 * pr_icmph --
1319 * Print a descriptive string about an ICMP header.
1320 */
1321static void
1322pr_icmph(icp)
1323 struct icmp *icp;
1324{
1325
1326 switch(icp->icmp_type) {
1327 case ICMP_ECHOREPLY:
1328 (void)printf("Echo Reply\n");
1329 /* XXX ID + Seq + Data */
1330 break;
1331 case ICMP_UNREACH:
1332 switch(icp->icmp_code) {
1333 case ICMP_UNREACH_NET:
1334 (void)printf("Destination Net Unreachable\n");
1335 break;
1336 case ICMP_UNREACH_HOST:
1337 (void)printf("Destination Host Unreachable\n");
1338 break;
1339 case ICMP_UNREACH_PROTOCOL:
1340 (void)printf("Destination Protocol Unreachable\n");
1341 break;
1342 case ICMP_UNREACH_PORT:
1343 (void)printf("Destination Port Unreachable\n");
1344 break;
1345 case ICMP_UNREACH_NEEDFRAG:
1346 (void)printf("frag needed and DF set (MTU %d)\n",
1347 ntohs(icp->icmp_nextmtu));
1348 break;
1349 case ICMP_UNREACH_SRCFAIL:
1350 (void)printf("Source Route Failed\n");
1351 break;
1352 case ICMP_UNREACH_FILTER_PROHIB:
1353 (void)printf("Communication prohibited by filter\n");
1354 break;
1355 default:
1356 (void)printf("Dest Unreachable, Bad Code: %d\n",
1357 icp->icmp_code);
1358 break;
1359 }
1360 /* Print returned IP header information */
1361#ifndef icmp_data
1362 pr_retip(&icp->icmp_ip);
1363#else
1364 pr_retip((struct ip *)icp->icmp_data);
1365#endif
1366 break;
1367 case ICMP_SOURCEQUENCH:
1368 (void)printf("Source Quench\n");
1369#ifndef icmp_data
1370 pr_retip(&icp->icmp_ip);
1371#else
1372 pr_retip((struct ip *)icp->icmp_data);
1373#endif
1374 break;
1375 case ICMP_REDIRECT:
1376 switch(icp->icmp_code) {
1377 case ICMP_REDIRECT_NET:
1378 (void)printf("Redirect Network");
1379 break;
1380 case ICMP_REDIRECT_HOST:
1381 (void)printf("Redirect Host");
1382 break;
1383 case ICMP_REDIRECT_TOSNET:
1384 (void)printf("Redirect Type of Service and Network");
1385 break;
1386 case ICMP_REDIRECT_TOSHOST:
1387 (void)printf("Redirect Type of Service and Host");
1388 break;
1389 default:
1390 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1391 break;
1392 }
1393 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1394#ifndef icmp_data
1395 pr_retip(&icp->icmp_ip);
1396#else
1397 pr_retip((struct ip *)icp->icmp_data);
1398#endif
1399 break;
1400 case ICMP_ECHO:
1401 (void)printf("Echo Request\n");
1402 /* XXX ID + Seq + Data */
1403 break;
1404 case ICMP_TIMXCEED:
1405 switch(icp->icmp_code) {
1406 case ICMP_TIMXCEED_INTRANS:
1407 (void)printf("Time to live exceeded\n");
1408 break;
1409 case ICMP_TIMXCEED_REASS:
1410 (void)printf("Frag reassembly time exceeded\n");
1411 break;
1412 default:
1413 (void)printf("Time exceeded, Bad Code: %d\n",
1414 icp->icmp_code);
1415 break;
1416 }
1417#ifndef icmp_data
1418 pr_retip(&icp->icmp_ip);
1419#else
1420 pr_retip((struct ip *)icp->icmp_data);
1421#endif
1422 break;
1423 case ICMP_PARAMPROB:
1424 (void)printf("Parameter problem: pointer = 0x%02x\n",
1425 icp->icmp_hun.ih_pptr);
1426#ifndef icmp_data
1427 pr_retip(&icp->icmp_ip);
1428#else
1429 pr_retip((struct ip *)icp->icmp_data);
1430#endif
1431 break;
1432 case ICMP_TSTAMP:
1433 (void)printf("Timestamp\n");
1434 /* XXX ID + Seq + 3 timestamps */
1435 break;
1436 case ICMP_TSTAMPREPLY:
1437 (void)printf("Timestamp Reply\n");
1438 /* XXX ID + Seq + 3 timestamps */
1439 break;
1440 case ICMP_IREQ:
1441 (void)printf("Information Request\n");
1442 /* XXX ID + Seq */
1443 break;
1444 case ICMP_IREQREPLY:
1445 (void)printf("Information Reply\n");
1446 /* XXX ID + Seq */
1447 break;
1448 case ICMP_MASKREQ:
1449 (void)printf("Address Mask Request\n");
1450 break;
1451 case ICMP_MASKREPLY:
1452 (void)printf("Address Mask Reply\n");
1453 break;
1454 case ICMP_ROUTERADVERT:
1455 (void)printf("Router Advertisement\n");
1456 break;
1457 case ICMP_ROUTERSOLICIT:
1458 (void)printf("Router Solicitation\n");
1459 break;
1460 default:
1461 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1462 }
1463}
1464
1465/*
1466 * pr_iph --
1467 * Print an IP header with options.
1468 */
1469static void
1470pr_iph(ip)
1471 struct ip *ip;
1472{
1473 u_char *cp;
1474 int hlen;
1475
1476 hlen = ip->ip_hl << 2;
1477 cp = (u_char *)ip + 20; /* point to options */
1478
1479 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
1480 (void)printf(" %1x %1x %02x %04x %04x",
1481 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1482 ntohs(ip->ip_id));
1483 (void)printf(" %1lx %04lx",
1484 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1485 (u_long) ntohl(ip->ip_off) & 0x1fff);
1486 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1487 ntohs(ip->ip_sum));
1488 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1489 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1490 /* dump any option bytes */
1491 while (hlen-- > 20) {
1492 (void)printf("%02x", *cp++);
1493 }
1494 (void)putchar('\n');
1495}
1496
1497/*
1498 * pr_addr --
1499 * Return an ascii host address as a dotted quad and optionally with
1500 * a hostname.
1501 */
1502static char *
1503pr_addr(ina)
1504 struct in_addr ina;
1505{
1506 struct hostent *hp;
1507 static char buf[16 + 3 + MAXHOSTNAMELEN];
1508
1509 if ((options & F_NUMERIC) ||
1510 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1511 return inet_ntoa(ina);
1512 else
1513 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1514 inet_ntoa(ina));
1515 return(buf);
1516}
1517
1518/*
1519 * pr_retip --
1520 * Dump some info on a returned (via ICMP) IP packet.
1521 */
1522static void
1523pr_retip(ip)
1524 struct ip *ip;
1525{
1526 u_char *cp;
1527 int hlen;
1528
1529 pr_iph(ip);
1530 hlen = ip->ip_hl << 2;
1531 cp = (u_char *)ip + hlen;
1532
1533 if (ip->ip_p == 6)
1534 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1535 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1536 else if (ip->ip_p == 17)
1537 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1538 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1539}
1540
1541static char *
1542pr_ntime (n_time time)
1543{
1544 static char buf[10];
1545 int h, m, s;
1546
1547 s = ntohl(time) / 1000;
1548 h = s / 60 / 60;
1549 m = (s % (60 * 60)) / 60;
1550 s = (s % (60 * 60)) % 60;
1551
1552 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", h, m, s);
1553
1554 return (buf);
1555}
1556
1557static void
1558fill(bp, patp)
1559 char *bp, *patp;
1560{
1561 char *cp;
1562 int pat[16];
1563 u_int ii, jj, kk;
1564
1565 for (cp = patp; *cp; cp++) {
1566 if (!isxdigit(*cp))
1567 errx(EX_USAGE,
1568 "patterns must be specified as hex digits");
1569
1570 }
1571 ii = sscanf(patp,
1572 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1573 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1574 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1575 &pat[13], &pat[14], &pat[15]);
1576
1577 if (ii > 0)
1578 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
1579 for (jj = 0; jj < ii; ++jj)
1580 bp[jj + kk] = pat[jj];
1581 if (!(options & F_QUIET)) {
1582 (void)printf("PATTERN: 0x");
1583 for (jj = 0; jj < ii; ++jj)
1584 (void)printf("%02x", bp[jj] & 0xFF);
1585 (void)printf("\n");
1586 }
1587}
1588
1589#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
1590#define SECOPT " [-P policy]"
1591#else
1592#define SECOPT ""
1593#endif
1594static void
1595usage()
1596{
1597
1598 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n",
1599"usage: ping [-AaDdfnoQqRrv] [-c count] [-i wait] [-l preload] [-M mask | time]",
1600" [-m ttl]" SECOPT " [-p pattern] [-S src_addr] [-s packetsize]",
1601" [-t timeout] [-z tos] host",
1602" ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]",
1603" [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]",
1604" [-s packetsize] [-T ttl] [-t timeout] [-z tos] mcast-group");
1605 exit(EX_USAGE);
1606}
50
51/*
52 * P I N G . C
53 *
54 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
55 * measure round-trip-delays and packet loss across network paths.
56 *
57 * Author -
58 * Mike Muuss
59 * U. S. Army Ballistic Research Laboratory
60 * December, 1983
61 *
62 * Status -
63 * Public Domain. Distribution Unlimited.
64 * Bugs -
65 * More statistics could always be gathered.
66 * This program has to run SUID to ROOT to access the ICMP socket.
67 */
68
69#include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
70#include <sys/socket.h>
71#include <sys/sysctl.h>
72#include <sys/time.h>
73#include <sys/uio.h>
74
75#include <netinet/in.h>
76#include <netinet/in_systm.h>
77#include <netinet/ip.h>
78#include <netinet/ip_icmp.h>
79#include <netinet/ip_var.h>
80#include <arpa/inet.h>
81
82#ifdef IPSEC
83#include <netinet6/ipsec.h>
84#endif /*IPSEC*/
85
86#include <ctype.h>
87#include <err.h>
88#include <errno.h>
89#include <math.h>
90#include <netdb.h>
91#include <signal.h>
92#include <stdio.h>
93#include <stdlib.h>
94#include <string.h>
95#include <sysexits.h>
96#include <termios.h>
97#include <unistd.h>
98
99#define INADDR_LEN ((int)sizeof(in_addr_t))
100#define TIMEVAL_LEN ((int)sizeof(struct timeval))
101#define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN)
102#define TS_LEN (ICMP_TSLEN - ICMP_MINLEN)
103#define DEFDATALEN 56 /* default data length */
104#define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
105 /* runs out of buffer space */
106#define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
107#define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
108#define MINICMPLEN ICMP_MINLEN
109#define MAXWAIT 10 /* max seconds to wait for response */
110#define MAXALARM (60 * 60) /* max seconds for alarm timeout */
111#define MAXTOS 255
112
113#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
114#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
115#define SET(bit) (A(bit) |= B(bit))
116#define CLR(bit) (A(bit) &= (~B(bit)))
117#define TST(bit) (A(bit) & B(bit))
118
119/* various options */
120int options;
121#define F_FLOOD 0x0001
122#define F_INTERVAL 0x0002
123#define F_NUMERIC 0x0004
124#define F_PINGFILLED 0x0008
125#define F_QUIET 0x0010
126#define F_RROUTE 0x0020
127#define F_SO_DEBUG 0x0040
128#define F_SO_DONTROUTE 0x0080
129#define F_VERBOSE 0x0100
130#define F_QUIET2 0x0200
131#define F_NOLOOP 0x0400
132#define F_MTTL 0x0800
133#define F_MIF 0x1000
134#define F_AUDIBLE 0x2000
135#ifdef IPSEC
136#ifdef IPSEC_POLICY_IPSEC
137#define F_POLICY 0x4000
138#endif /*IPSEC_POLICY_IPSEC*/
139#endif /*IPSEC*/
140#define F_TTL 0x8000
141#define F_MISSED 0x10000
142#define F_ONCE 0x20000
143#define F_HDRINCL 0x40000
144#define F_MASK 0x80000
145#define F_TIME 0x100000
146
147/*
148 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
149 * number of received sequence numbers we can keep track of. Change 128
150 * to 8192 for complete accuracy...
151 */
152#define MAX_DUP_CHK (8 * 128)
153int mx_dup_ck = MAX_DUP_CHK;
154char rcvd_tbl[MAX_DUP_CHK / 8];
155
156struct sockaddr_in whereto; /* who to ping */
157int datalen = DEFDATALEN;
158int maxpayload;
159int s; /* socket file descriptor */
160u_char outpackhdr[IP_MAXPACKET], *outpack;
161char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
162char BSPACE = '\b'; /* characters written for flood */
163char DOT = '.';
164char *hostname;
165char *shostname;
166int ident; /* process id to identify our packets */
167int uid; /* cached uid for micro-optimization */
168u_char icmp_type = ICMP_ECHO;
169u_char icmp_type_rsp = ICMP_ECHOREPLY;
170int phdr_len = 0;
171
172/* counters */
173long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
174long npackets; /* max packets to transmit */
175long nreceived; /* # of packets we got back */
176long nrepeats; /* number of duplicates */
177long ntransmitted; /* sequence # for outbound packets = #sent */
178int interval = 1000; /* interval between packets, ms */
179
180/* timing */
181int timing; /* flag to do timing */
182double tmin = 999999999.0; /* minimum round trip time */
183double tmax = 0.0; /* maximum round trip time */
184double tsum = 0.0; /* sum of all times, for doing average */
185double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
186
187volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */
188int reset_kerninfo;
189volatile sig_atomic_t siginfo_p;
190
191static void fill(char *, char *);
192static u_short in_cksum(u_short *, int);
193static void check_status(void);
194static void finish(void) __dead2;
195static void pinger(void);
196static char *pr_addr(struct in_addr);
197static char *pr_ntime(n_time);
198static void pr_icmph(struct icmp *);
199static void pr_iph(struct ip *);
200static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
201static void pr_retip(struct ip *);
202static void status(int);
203static void stopit(int);
204static void tvsub(struct timeval *, struct timeval *);
205static void usage(void) __dead2;
206
207int
208main(argc, argv)
209 int argc;
210 char *const *argv;
211{
212 struct sockaddr_in from, sock_in;
213 struct in_addr ifaddr;
214 struct timeval last, intvl;
215 struct iovec iov;
216 struct ip *ip;
217 struct msghdr msg;
218 struct sigaction si_sa;
219 struct termios ts;
220 size_t sz;
221 u_char *datap, packet[IP_MAXPACKET];
222 char *ep, *source, *target, *payload;
223 struct hostent *hp;
224#ifdef IPSEC_POLICY_IPSEC
225 char *policy_in, *policy_out;
226#endif
227 struct sockaddr_in *to;
228 double t;
229 u_long alarmtimeout, ultmp;
230 int almost_done, ch, df, hold, i, mib[4], packlen, preload, sockerrno,
231 tos, ttl;
232 char ctrl[CMSG_SPACE(sizeof(struct timeval))];
233 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
234#ifdef IP_OPTIONS
235 char rspace[MAX_IPOPTLEN]; /* record route space */
236#endif
237 unsigned char loop, mttl;
238
239 payload = source = NULL;
240#ifdef IPSEC_POLICY_IPSEC
241 policy_in = policy_out = NULL;
242#endif
243
244 /*
245 * Do the stuff that we need root priv's for *first*, and
246 * then drop our setuid bit. Save error reporting for
247 * after arg parsing.
248 */
249 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
250 sockerrno = errno;
251
252 setuid(getuid());
253 uid = getuid();
254
255 alarmtimeout = df = preload = tos = 0;
256
257 outpack = outpackhdr + sizeof(struct ip);
258 while ((ch = getopt(argc, argv,
259 "Aac:DdfI:i:Ll:M:m:nop:QqRrS:s:T:t:vz:"
260#ifdef IPSEC
261#ifdef IPSEC_POLICY_IPSEC
262 "P:"
263#endif /*IPSEC_POLICY_IPSEC*/
264#endif /*IPSEC*/
265 )) != -1)
266 {
267 switch(ch) {
268 case 'A':
269 options |= F_MISSED;
270 break;
271 case 'a':
272 options |= F_AUDIBLE;
273 break;
274 case 'c':
275 ultmp = strtoul(optarg, &ep, 0);
276 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
277 errx(EX_USAGE,
278 "invalid count of packets to transmit: `%s'",
279 optarg);
280 npackets = ultmp;
281 break;
282 case 'D':
283 options |= F_HDRINCL;
284 df = 1;
285 break;
286 case 'd':
287 options |= F_SO_DEBUG;
288 break;
289 case 'f':
290 if (uid) {
291 errno = EPERM;
292 err(EX_NOPERM, "-f flag");
293 }
294 options |= F_FLOOD;
295 setbuf(stdout, (char *)NULL);
296 break;
297 case 'I': /* multicast interface */
298 if (inet_aton(optarg, &ifaddr) == 0)
299 errx(EX_USAGE,
300 "invalid multicast interface: `%s'",
301 optarg);
302 options |= F_MIF;
303 break;
304 case 'i': /* wait between sending packets */
305 t = strtod(optarg, &ep) * 1000.0;
306 if (*ep || ep == optarg || t > (double)INT_MAX)
307 errx(EX_USAGE, "invalid timing interval: `%s'",
308 optarg);
309 options |= F_INTERVAL;
310 interval = (int)t;
311 if (uid && interval < 1000) {
312 errno = EPERM;
313 err(EX_NOPERM, "-i interval too short");
314 }
315 break;
316 case 'L':
317 options |= F_NOLOOP;
318 loop = 0;
319 break;
320 case 'l':
321 ultmp = strtoul(optarg, &ep, 0);
322 if (*ep || ep == optarg || ultmp > INT_MAX)
323 errx(EX_USAGE,
324 "invalid preload value: `%s'", optarg);
325 if (uid) {
326 errno = EPERM;
327 err(EX_NOPERM, "-l flag");
328 }
329 preload = ultmp;
330 break;
331 case 'M':
332 switch(optarg[0]) {
333 case 'M':
334 case 'm':
335 options |= F_MASK;
336 break;
337 case 'T':
338 case 't':
339 options |= F_TIME;
340 break;
341 default:
342 errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
343 break;
344 }
345 break;
346 case 'm': /* TTL */
347 ultmp = strtoul(optarg, &ep, 0);
348 if (*ep || ep == optarg || ultmp > MAXTTL)
349 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
350 ttl = ultmp;
351 options |= F_TTL;
352 break;
353 case 'n':
354 options |= F_NUMERIC;
355 break;
356 case 'o':
357 options |= F_ONCE;
358 break;
359#ifdef IPSEC
360#ifdef IPSEC_POLICY_IPSEC
361 case 'P':
362 options |= F_POLICY;
363 if (!strncmp("in", optarg, 2))
364 policy_in = strdup(optarg);
365 else if (!strncmp("out", optarg, 3))
366 policy_out = strdup(optarg);
367 else
368 errx(1, "invalid security policy");
369 break;
370#endif /*IPSEC_POLICY_IPSEC*/
371#endif /*IPSEC*/
372 case 'p': /* fill buffer with user pattern */
373 options |= F_PINGFILLED;
374 payload = optarg;
375 break;
376 case 'Q':
377 options |= F_QUIET2;
378 break;
379 case 'q':
380 options |= F_QUIET;
381 break;
382 case 'R':
383 options |= F_RROUTE;
384 break;
385 case 'r':
386 options |= F_SO_DONTROUTE;
387 break;
388 case 'S':
389 source = optarg;
390 break;
391 case 's': /* size of packet to send */
392 ultmp = strtoul(optarg, &ep, 0);
393 if (*ep || ep == optarg)
394 errx(EX_USAGE, "invalid packet size: `%s'",
395 optarg);
396 if (uid != 0 && ultmp > DEFDATALEN) {
397 errno = EPERM;
398 err(EX_NOPERM,
399 "packet size too large: %lu > %u",
400 ultmp, DEFDATALEN);
401 }
402 datalen = ultmp;
403 break;
404 case 'T': /* multicast TTL */
405 ultmp = strtoul(optarg, &ep, 0);
406 if (*ep || ep == optarg || ultmp > MAXTTL)
407 errx(EX_USAGE, "invalid multicast TTL: `%s'",
408 optarg);
409 mttl = ultmp;
410 options |= F_MTTL;
411 break;
412 case 't':
413 alarmtimeout = strtoul(optarg, &ep, 0);
414 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
415 errx(EX_USAGE, "invalid timeout: `%s'",
416 optarg);
417 if (alarmtimeout > MAXALARM)
418 errx(EX_USAGE, "invalid timeout: `%s' > %d",
419 optarg, MAXALARM);
420 alarm((int)alarmtimeout);
421 break;
422 case 'v':
423 options |= F_VERBOSE;
424 break;
425 case 'z':
426 options |= F_HDRINCL;
427 ultmp = strtoul(optarg, &ep, 0);
428 if (*ep || ep == optarg || ultmp > MAXTOS)
429 errx(EX_USAGE, "invalid TOS: `%s'", optarg);
430 tos = ultmp;
431 break;
432 default:
433 usage();
434 }
435 }
436
437 if (argc - optind != 1)
438 usage();
439 target = argv[optind];
440
441 switch (options & (F_MASK|F_TIME)) {
442 case 0: break;
443 case F_MASK:
444 icmp_type = ICMP_MASKREQ;
445 icmp_type_rsp = ICMP_MASKREPLY;
446 phdr_len = MASK_LEN;
447 if (!(options & F_QUIET))
448 (void)printf("ICMP_MASKREQ\n");
449 break;
450 case F_TIME:
451 icmp_type = ICMP_TSTAMP;
452 icmp_type_rsp = ICMP_TSTAMPREPLY;
453 phdr_len = TS_LEN;
454 if (!(options & F_QUIET))
455 (void)printf("ICMP_TSTAMP\n");
456 break;
457 default:
458 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
459 break;
460 }
461 maxpayload = IP_MAXPACKET - sizeof(struct ip) - MINICMPLEN - phdr_len;
462 if (options & F_RROUTE)
463 maxpayload -= MAX_IPOPTLEN;
464 if (datalen > maxpayload)
465 errx(EX_USAGE, "packet size too large: %d > %d", datalen,
466 maxpayload);
467 datap = &outpack[MINICMPLEN + phdr_len + TIMEVAL_LEN];
468 if (options & F_PINGFILLED) {
469 fill((char *)datap, payload);
470 }
471 if (source) {
472 bzero((char *)&sock_in, sizeof(sock_in));
473 sock_in.sin_family = AF_INET;
474 if (inet_aton(source, &sock_in.sin_addr) != 0) {
475 shostname = source;
476 } else {
477 hp = gethostbyname2(source, AF_INET);
478 if (!hp)
479 errx(EX_NOHOST, "cannot resolve %s: %s",
480 source, hstrerror(h_errno));
481
482 sock_in.sin_len = sizeof sock_in;
483 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
484 hp->h_length < 0)
485 errx(1, "gethostbyname2: illegal address");
486 memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
487 sizeof(sock_in.sin_addr));
488 (void)strncpy(snamebuf, hp->h_name,
489 sizeof(snamebuf) - 1);
490 snamebuf[sizeof(snamebuf) - 1] = '\0';
491 shostname = snamebuf;
492 }
493 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
494 err(1, "bind");
495 }
496
497 bzero(&whereto, sizeof(whereto));
498 to = &whereto;
499 to->sin_family = AF_INET;
500 to->sin_len = sizeof *to;
501 if (inet_aton(target, &to->sin_addr) != 0) {
502 hostname = target;
503 } else {
504 hp = gethostbyname2(target, AF_INET);
505 if (!hp)
506 errx(EX_NOHOST, "cannot resolve %s: %s",
507 target, hstrerror(h_errno));
508
509 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
510 errx(1, "gethostbyname2 returned an illegal address");
511 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
512 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
513 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
514 hostname = hnamebuf;
515 }
516
517 if (options & F_FLOOD && options & F_INTERVAL)
518 errx(EX_USAGE, "-f and -i: incompatible options");
519
520 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
521 errx(EX_USAGE,
522 "-f flag cannot be used with multicast destination");
523 if (options & (F_MIF | F_NOLOOP | F_MTTL)
524 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
525 errx(EX_USAGE,
526 "-I, -L, -T flags cannot be used with unicast destination");
527
528 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
529 timing = 1;
530 packlen = MAXIPLEN + MAXICMPLEN + datalen;
531 packlen = packlen > IP_MAXPACKET ? IP_MAXPACKET : packlen;
532
533 if (!(options & F_PINGFILLED))
534 for (i = TIMEVAL_LEN; i < datalen; ++i)
535 *datap++ = i;
536
537 ident = getpid() & 0xFFFF;
538
539 if (s < 0) {
540 errno = sockerrno;
541 err(EX_OSERR, "socket");
542 }
543 hold = 1;
544 if (options & F_SO_DEBUG)
545 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
546 sizeof(hold));
547 if (options & F_SO_DONTROUTE)
548 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
549 sizeof(hold));
550#ifdef IPSEC
551#ifdef IPSEC_POLICY_IPSEC
552 if (options & F_POLICY) {
553 char *buf;
554 if (policy_in != NULL) {
555 buf = ipsec_set_policy(policy_in, strlen(policy_in));
556 if (buf == NULL)
557 errx(EX_CONFIG, "%s", ipsec_strerror());
558 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
559 buf, ipsec_get_policylen(buf)) < 0)
560 err(EX_CONFIG,
561 "ipsec policy cannot be configured");
562 free(buf);
563 }
564
565 if (policy_out != NULL) {
566 buf = ipsec_set_policy(policy_out, strlen(policy_out));
567 if (buf == NULL)
568 errx(EX_CONFIG, "%s", ipsec_strerror());
569 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
570 buf, ipsec_get_policylen(buf)) < 0)
571 err(EX_CONFIG,
572 "ipsec policy cannot be configured");
573 free(buf);
574 }
575 }
576#endif /*IPSEC_POLICY_IPSEC*/
577#endif /*IPSEC*/
578
579 if (options & F_HDRINCL) {
580 ip = (struct ip*)outpackhdr;
581 if (!(options & (F_TTL | F_MTTL))) {
582 mib[0] = CTL_NET;
583 mib[1] = PF_INET;
584 mib[2] = IPPROTO_IP;
585 mib[3] = IPCTL_DEFTTL;
586 sz = sizeof(ttl);
587 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
588 err(1, "sysctl(net.inet.ip.ttl)");
589 }
590 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
591 ip->ip_v = IPVERSION;
592 ip->ip_hl = sizeof(struct ip) >> 2;
593 ip->ip_tos = tos;
594 ip->ip_id = 0;
595 ip->ip_off = df ? IP_DF : 0;
596 ip->ip_ttl = ttl;
597 ip->ip_p = IPPROTO_ICMP;
598 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
599 ip->ip_dst = to->sin_addr;
600 }
601 /* record route option */
602 if (options & F_RROUTE) {
603#ifdef IP_OPTIONS
604 bzero(rspace, sizeof(rspace));
605 rspace[IPOPT_OPTVAL] = IPOPT_RR;
606 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
607 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
608 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
609 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
610 sizeof(rspace)) < 0)
611 err(EX_OSERR, "setsockopt IP_OPTIONS");
612#else
613 errx(EX_UNAVAILABLE,
614 "record route not available in this implementation");
615#endif /* IP_OPTIONS */
616 }
617
618 if (options & F_TTL) {
619 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
620 sizeof(ttl)) < 0) {
621 err(EX_OSERR, "setsockopt IP_TTL");
622 }
623 }
624 if (options & F_NOLOOP) {
625 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
626 sizeof(loop)) < 0) {
627 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
628 }
629 }
630 if (options & F_MTTL) {
631 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
632 sizeof(mttl)) < 0) {
633 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
634 }
635 }
636 if (options & F_MIF) {
637 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
638 sizeof(ifaddr)) < 0) {
639 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
640 }
641 }
642#ifdef SO_TIMESTAMP
643 { int on = 1;
644 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
645 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
646 }
647#endif
648
649 /*
650 * When pinging the broadcast address, you can get a lot of answers.
651 * Doing something so evil is useful if you are trying to stress the
652 * ethernet, or just want to fill the arp cache to get some stuff for
653 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
654 * or multicast pings if they wish.
655 */
656
657 /*
658 * XXX receive buffer needs undetermined space for mbuf overhead
659 * as well.
660 */
661 hold = IP_MAXPACKET + 128;
662 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
663 sizeof(hold));
664 if (uid == 0)
665 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
666 sizeof(hold));
667
668 if (to->sin_family == AF_INET) {
669 (void)printf("PING %s (%s)", hostname,
670 inet_ntoa(to->sin_addr));
671 if (source)
672 (void)printf(" from %s", shostname);
673 (void)printf(": %d data bytes\n", datalen);
674 } else
675 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
676
677 /*
678 * Use sigaction() instead of signal() to get unambiguous semantics,
679 * in particular with SA_RESTART not set.
680 */
681
682 sigemptyset(&si_sa.sa_mask);
683 si_sa.sa_flags = 0;
684
685 si_sa.sa_handler = stopit;
686 if (sigaction(SIGINT, &si_sa, 0) == -1) {
687 err(EX_OSERR, "sigaction SIGINT");
688 }
689
690 si_sa.sa_handler = status;
691 if (sigaction(SIGINFO, &si_sa, 0) == -1) {
692 err(EX_OSERR, "sigaction");
693 }
694
695 if (alarmtimeout > 0) {
696 si_sa.sa_handler = stopit;
697 if (sigaction(SIGALRM, &si_sa, 0) == -1)
698 err(EX_OSERR, "sigaction SIGALRM");
699 }
700
701 bzero(&msg, sizeof(msg));
702 msg.msg_name = (caddr_t)&from;
703 msg.msg_iov = &iov;
704 msg.msg_iovlen = 1;
705#ifdef SO_TIMESTAMP
706 msg.msg_control = (caddr_t)ctrl;
707#endif
708 iov.iov_base = packet;
709 iov.iov_len = packlen;
710
711 if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
712 reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
713 ts.c_lflag |= NOKERNINFO;
714 tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
715 }
716
717 if (preload == 0)
718 pinger(); /* send the first ping */
719 else {
720 if (npackets != 0 && preload > npackets)
721 preload = npackets;
722 while (preload--) /* fire off them quickies */
723 pinger();
724 }
725 (void)gettimeofday(&last, NULL);
726
727 if (options & F_FLOOD) {
728 intvl.tv_sec = 0;
729 intvl.tv_usec = 10000;
730 } else {
731 intvl.tv_sec = interval / 1000;
732 intvl.tv_usec = interval % 1000 * 1000;
733 }
734
735 almost_done = 0;
736 while (!finish_up) {
737 struct timeval now, timeout;
738 fd_set rfds;
739 int cc, n;
740
741 check_status();
742 if ((unsigned)s >= FD_SETSIZE)
743 errx(EX_OSERR, "descriptor too large");
744 FD_ZERO(&rfds);
745 FD_SET(s, &rfds);
746 (void)gettimeofday(&now, NULL);
747 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
748 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
749 while (timeout.tv_usec < 0) {
750 timeout.tv_usec += 1000000;
751 timeout.tv_sec--;
752 }
753 while (timeout.tv_usec >= 1000000) {
754 timeout.tv_usec -= 1000000;
755 timeout.tv_sec++;
756 }
757 if (timeout.tv_sec < 0)
758 timeout.tv_sec = timeout.tv_usec = 0;
759 n = select(s + 1, &rfds, NULL, NULL, &timeout);
760 if (n < 0)
761 continue; /* Must be EINTR. */
762 if (n == 1) {
763 struct timeval *tv = NULL;
764#ifdef SO_TIMESTAMP
765 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
766
767 msg.msg_controllen = sizeof(ctrl);
768#endif
769 msg.msg_namelen = sizeof(from);
770 if ((cc = recvmsg(s, &msg, 0)) < 0) {
771 if (errno == EINTR)
772 continue;
773 warn("recvmsg");
774 continue;
775 }
776#ifdef SO_TIMESTAMP
777 if (cmsg->cmsg_level == SOL_SOCKET &&
778 cmsg->cmsg_type == SCM_TIMESTAMP &&
779 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
780 /* Copy to avoid alignment problems: */
781 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
782 tv = &now;
783 }
784#endif
785 if (tv == NULL) {
786 (void)gettimeofday(&now, NULL);
787 tv = &now;
788 }
789 pr_pack((char *)packet, cc, &from, tv);
790 if ((options & F_ONCE && nreceived) ||
791 (npackets && nreceived >= npackets))
792 break;
793 }
794 if (n == 0 || options & F_FLOOD) {
795 if (!npackets || ntransmitted < npackets)
796 pinger();
797 else {
798 if (almost_done)
799 break;
800 almost_done = 1;
801 intvl.tv_usec = 0;
802 if (nreceived) {
803 intvl.tv_sec = 2 * tmax / 1000;
804 if (!intvl.tv_sec)
805 intvl.tv_sec = 1;
806 } else
807 intvl.tv_sec = MAXWAIT;
808 }
809 (void)gettimeofday(&last, NULL);
810 if (ntransmitted - nreceived - 1 > nmissedmax) {
811 nmissedmax = ntransmitted - nreceived - 1;
812 if (options & F_MISSED)
813 (void)write(STDOUT_FILENO, &BBELL, 1);
814 }
815 }
816 }
817 finish();
818 /* NOTREACHED */
819 exit(0); /* Make the compiler happy */
820}
821
822/*
823 * stopit --
824 * Set the global bit that causes the main loop to quit.
825 * Do NOT call finish() from here, since finish() does far too much
826 * to be called from a signal handler.
827 */
828void
829stopit(sig)
830 int sig __unused;
831{
832
833 finish_up = 1;
834}
835
836/*
837 * pinger --
838 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
839 * will be added on by the kernel. The ID field is our UNIX process ID,
840 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
841 * bytes of the data portion are used to hold a UNIX "timeval" struct in
842 * host byte-order, to compute the round-trip time.
843 */
844static void
845pinger(void)
846{
847 struct timeval now;
848 struct ip *ip;
849 struct icmp *icp;
850 int cc, i;
851 u_char *packet;
852
853 packet = outpack;
854 icp = (struct icmp *)outpack;
855 icp->icmp_type = icmp_type;
856 icp->icmp_code = 0;
857 icp->icmp_cksum = 0;
858 icp->icmp_seq = htons(ntransmitted);
859 icp->icmp_id = ident; /* ID */
860
861 CLR(ntransmitted % mx_dup_ck);
862
863 if ((options & F_TIME) || timing) {
864 (void)gettimeofday(&now, NULL);
865
866 if (options & F_TIME)
867 icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
868 * 1000 + now.tv_usec / 1000);
869 if (timing)
870 bcopy((void *)&now,
871 (void *)&outpack[MINICMPLEN + phdr_len],
872 sizeof(struct timeval));
873 }
874
875 cc = MINICMPLEN + phdr_len + datalen;
876
877 /* compute ICMP checksum here */
878 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
879
880 if (options & F_HDRINCL) {
881 cc += sizeof(struct ip);
882 ip = (struct ip *)outpackhdr;
883 ip->ip_len = cc;
884 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
885 packet = outpackhdr;
886 }
887 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
888 sizeof(whereto));
889
890 if (i < 0 || i != cc) {
891 if (i < 0) {
892 if (options & F_FLOOD && errno == ENOBUFS) {
893 usleep(FLOOD_BACKOFF);
894 return;
895 }
896 warn("sendto");
897 } else {
898 warn("%s: partial write: %d of %d bytes",
899 hostname, i, cc);
900 }
901 }
902 ntransmitted++;
903 if (!(options & F_QUIET) && options & F_FLOOD)
904 (void)write(STDOUT_FILENO, &DOT, 1);
905}
906
907/*
908 * pr_pack --
909 * Print out the packet, if it came from us. This logic is necessary
910 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
911 * which arrive ('tis only fair). This permits multiple copies of this
912 * program to be run without having intermingled output (or statistics!).
913 */
914static void
915pr_pack(buf, cc, from, tv)
916 char *buf;
917 int cc;
918 struct sockaddr_in *from;
919 struct timeval *tv;
920{
921 struct in_addr ina;
922 u_char *cp, *dp;
923 struct icmp *icp;
924 struct ip *ip;
925 const void *tp;
926 double triptime;
927 int dupflag, hlen, i, j, seq;
928 static int old_rrlen;
929 static char old_rr[MAX_IPOPTLEN];
930
931 /* Check the IP header */
932 ip = (struct ip *)buf;
933 hlen = ip->ip_hl << 2;
934 if (cc < hlen + ICMP_MINLEN) {
935 if (options & F_VERBOSE)
936 warn("packet too short (%d bytes) from %s", cc,
937 inet_ntoa(from->sin_addr));
938 return;
939 }
940
941 /* Now the ICMP part */
942 cc -= hlen;
943 icp = (struct icmp *)(buf + hlen);
944 if (icp->icmp_type == icmp_type_rsp) {
945 if (icp->icmp_id != ident)
946 return; /* 'Twas not our ECHO */
947 ++nreceived;
948 triptime = 0.0;
949 if (timing) {
950 struct timeval tv1;
951#ifndef icmp_data
952 tp = &icp->icmp_ip;
953#else
954 tp = icp->icmp_data;
955#endif
956 tp += phdr_len;
957
958 if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) {
959 /* Copy to avoid alignment problems: */
960 memcpy(&tv1, tp, sizeof(tv1));
961 tvsub(tv, &tv1);
962 triptime = ((double)tv->tv_sec) * 1000.0 +
963 ((double)tv->tv_usec) / 1000.0;
964 tsum += triptime;
965 tsumsq += triptime * triptime;
966 if (triptime < tmin)
967 tmin = triptime;
968 if (triptime > tmax)
969 tmax = triptime;
970 } else
971 timing = 0;
972 }
973
974 seq = ntohs(icp->icmp_seq);
975
976 if (TST(seq % mx_dup_ck)) {
977 ++nrepeats;
978 --nreceived;
979 dupflag = 1;
980 } else {
981 SET(seq % mx_dup_ck);
982 dupflag = 0;
983 }
984
985 if (options & F_QUIET)
986 return;
987
988 if (options & F_FLOOD)
989 (void)write(STDOUT_FILENO, &BSPACE, 1);
990 else {
991 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
992 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
993 seq);
994 (void)printf(" ttl=%d", ip->ip_ttl);
995 if (timing)
996 (void)printf(" time=%.3f ms", triptime);
997 if (dupflag)
998 (void)printf(" (DUP!)");
999 if (options & F_AUDIBLE)
1000 (void)write(STDOUT_FILENO, &BBELL, 1);
1001 if (options & F_MASK) {
1002 /* Just prentend this cast isn't ugly */
1003 (void)printf(" mask=%s",
1004 pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1005 }
1006 if (options & F_TIME) {
1007 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1008 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1009 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1010 }
1011 /* check the data */
1012 cp = (u_char*)&icp->icmp_data[phdr_len];
1013 dp = &outpack[MINICMPLEN + phdr_len];
1014 cc -= ICMP_MINLEN + phdr_len;
1015 i = 0;
1016 if (timing) { /* don't check variable timestamp */
1017 cp += TIMEVAL_LEN;
1018 dp += TIMEVAL_LEN;
1019 cc -= TIMEVAL_LEN;
1020 i += TIMEVAL_LEN;
1021 }
1022 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
1023 if (*cp != *dp) {
1024 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1025 i, *dp, *cp);
1026 (void)printf("\ncp:");
1027 cp = (u_char*)&icp->icmp_data[0];
1028 for (i = 0; i < datalen; ++i, ++cp) {
1029 if ((i % 32) == 8)
1030 (void)printf("\n\t");
1031 (void)printf("%x ", *cp);
1032 }
1033 (void)printf("\ndp:");
1034 cp = &outpack[MINICMPLEN];
1035 for (i = 0; i < datalen; ++i, ++cp) {
1036 if ((i % 32) == 8)
1037 (void)printf("\n\t");
1038 (void)printf("%x ", *cp);
1039 }
1040 break;
1041 }
1042 }
1043 }
1044 } else {
1045 /*
1046 * We've got something other than an ECHOREPLY.
1047 * See if it's a reply to something that we sent.
1048 * We can compare IP destination, protocol,
1049 * and ICMP type and ID.
1050 *
1051 * Only print all the error messages if we are running
1052 * as root to avoid leaking information not normally
1053 * available to those not running as root.
1054 */
1055#ifndef icmp_data
1056 struct ip *oip = &icp->icmp_ip;
1057#else
1058 struct ip *oip = (struct ip *)icp->icmp_data;
1059#endif
1060 struct icmp *oicmp = (struct icmp *)(oip + 1);
1061
1062 if (((options & F_VERBOSE) && uid == 0) ||
1063 (!(options & F_QUIET2) &&
1064 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1065 (oip->ip_p == IPPROTO_ICMP) &&
1066 (oicmp->icmp_type == ICMP_ECHO) &&
1067 (oicmp->icmp_id == ident))) {
1068 (void)printf("%d bytes from %s: ", cc,
1069 pr_addr(from->sin_addr));
1070 pr_icmph(icp);
1071 } else
1072 return;
1073 }
1074
1075 /* Display any IP options */
1076 cp = (u_char *)buf + sizeof(struct ip);
1077
1078 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1079 switch (*cp) {
1080 case IPOPT_EOL:
1081 hlen = 0;
1082 break;
1083 case IPOPT_LSRR:
1084 case IPOPT_SSRR:
1085 (void)printf(*cp == IPOPT_LSRR ?
1086 "\nLSRR: " : "\nSSRR: ");
1087 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1088 hlen -= 2;
1089 cp += 2;
1090 if (j >= INADDR_LEN &&
1091 j <= hlen - (int)sizeof(struct ip)) {
1092 for (;;) {
1093 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1094 if (ina.s_addr == 0)
1095 (void)printf("\t0.0.0.0");
1096 else
1097 (void)printf("\t%s",
1098 pr_addr(ina));
1099 hlen -= INADDR_LEN;
1100 cp += INADDR_LEN - 1;
1101 j -= INADDR_LEN;
1102 if (j < INADDR_LEN)
1103 break;
1104 (void)putchar('\n');
1105 }
1106 } else
1107 (void)printf("\t(truncated route)\n");
1108 break;
1109 case IPOPT_RR:
1110 j = cp[IPOPT_OLEN]; /* get length */
1111 i = cp[IPOPT_OFFSET]; /* and pointer */
1112 hlen -= 2;
1113 cp += 2;
1114 if (i > j)
1115 i = j;
1116 i = i - IPOPT_MINOFF + 1;
1117 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1118 old_rrlen = 0;
1119 continue;
1120 }
1121 if (i == old_rrlen
1122 && !bcmp((char *)cp, old_rr, i)
1123 && !(options & F_FLOOD)) {
1124 (void)printf("\t(same route)");
1125 hlen -= i;
1126 cp += i;
1127 break;
1128 }
1129 old_rrlen = i;
1130 bcopy((char *)cp, old_rr, i);
1131 (void)printf("\nRR: ");
1132 if (i >= INADDR_LEN &&
1133 i <= hlen - (int)sizeof(struct ip)) {
1134 for (;;) {
1135 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1136 if (ina.s_addr == 0)
1137 (void)printf("\t0.0.0.0");
1138 else
1139 (void)printf("\t%s",
1140 pr_addr(ina));
1141 hlen -= INADDR_LEN;
1142 cp += INADDR_LEN - 1;
1143 i -= INADDR_LEN;
1144 if (i < INADDR_LEN)
1145 break;
1146 (void)putchar('\n');
1147 }
1148 } else
1149 (void)printf("\t(truncated route)");
1150 break;
1151 case IPOPT_NOP:
1152 (void)printf("\nNOP");
1153 break;
1154 default:
1155 (void)printf("\nunknown option %x", *cp);
1156 break;
1157 }
1158 if (!(options & F_FLOOD)) {
1159 (void)putchar('\n');
1160 (void)fflush(stdout);
1161 }
1162}
1163
1164/*
1165 * in_cksum --
1166 * Checksum routine for Internet Protocol family headers (C Version)
1167 */
1168u_short
1169in_cksum(addr, len)
1170 u_short *addr;
1171 int len;
1172{
1173 int nleft, sum;
1174 u_short *w;
1175 union {
1176 u_short us;
1177 u_char uc[2];
1178 } last;
1179 u_short answer;
1180
1181 nleft = len;
1182 sum = 0;
1183 w = addr;
1184
1185 /*
1186 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1187 * sequential 16 bit words to it, and at the end, fold back all the
1188 * carry bits from the top 16 bits into the lower 16 bits.
1189 */
1190 while (nleft > 1) {
1191 sum += *w++;
1192 nleft -= 2;
1193 }
1194
1195 /* mop up an odd byte, if necessary */
1196 if (nleft == 1) {
1197 last.uc[0] = *(u_char *)w;
1198 last.uc[1] = 0;
1199 sum += last.us;
1200 }
1201
1202 /* add back carry outs from top 16 bits to low 16 bits */
1203 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1204 sum += (sum >> 16); /* add carry */
1205 answer = ~sum; /* truncate to 16 bits */
1206 return(answer);
1207}
1208
1209/*
1210 * tvsub --
1211 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1212 * be >= in.
1213 */
1214static void
1215tvsub(out, in)
1216 struct timeval *out, *in;
1217{
1218
1219 if ((out->tv_usec -= in->tv_usec) < 0) {
1220 --out->tv_sec;
1221 out->tv_usec += 1000000;
1222 }
1223 out->tv_sec -= in->tv_sec;
1224}
1225
1226/*
1227 * status --
1228 * Print out statistics when SIGINFO is received.
1229 */
1230
1231static void
1232status(sig)
1233 int sig __unused;
1234{
1235
1236 siginfo_p = 1;
1237}
1238
1239static void
1240check_status()
1241{
1242
1243 if (siginfo_p) {
1244 siginfo_p = 0;
1245 (void)fprintf(stderr,
1246 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
1247 nreceived, ntransmitted,
1248 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
1249 nreceived ? tmin : 0.0,
1250 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
1251 tmax);
1252 }
1253}
1254
1255/*
1256 * finish --
1257 * Print out statistics, and give up.
1258 */
1259static void
1260finish()
1261{
1262 struct termios ts;
1263
1264 (void)signal(SIGINT, SIG_IGN);
1265 (void)signal(SIGALRM, SIG_IGN);
1266 (void)putchar('\n');
1267 (void)fflush(stdout);
1268 (void)printf("--- %s ping statistics ---\n", hostname);
1269 (void)printf("%ld packets transmitted, ", ntransmitted);
1270 (void)printf("%ld packets received, ", nreceived);
1271 if (nrepeats)
1272 (void)printf("+%ld duplicates, ", nrepeats);
1273 if (ntransmitted) {
1274 if (nreceived > ntransmitted)
1275 (void)printf("-- somebody's printing up packets!");
1276 else
1277 (void)printf("%d%% packet loss",
1278 (int)(((ntransmitted - nreceived) * 100) /
1279 ntransmitted));
1280 }
1281 (void)putchar('\n');
1282 if (nreceived && timing) {
1283 double n = nreceived + nrepeats;
1284 double avg = tsum / n;
1285 double vari = tsumsq / n - avg * avg;
1286 (void)printf(
1287 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1288 tmin, avg, tmax, sqrt(vari));
1289 }
1290 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
1291 ts.c_lflag &= ~NOKERNINFO;
1292 tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
1293 }
1294
1295 if (nreceived)
1296 exit(0);
1297 else
1298 exit(2);
1299}
1300
1301#ifdef notdef
1302static char *ttab[] = {
1303 "Echo Reply", /* ip + seq + udata */
1304 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
1305 "Source Quench", /* IP */
1306 "Redirect", /* redirect type, gateway, + IP */
1307 "Echo",
1308 "Time Exceeded", /* transit, frag reassem + IP */
1309 "Parameter Problem", /* pointer + IP */
1310 "Timestamp", /* id + seq + three timestamps */
1311 "Timestamp Reply", /* " */
1312 "Info Request", /* id + sq */
1313 "Info Reply" /* " */
1314};
1315#endif
1316
1317/*
1318 * pr_icmph --
1319 * Print a descriptive string about an ICMP header.
1320 */
1321static void
1322pr_icmph(icp)
1323 struct icmp *icp;
1324{
1325
1326 switch(icp->icmp_type) {
1327 case ICMP_ECHOREPLY:
1328 (void)printf("Echo Reply\n");
1329 /* XXX ID + Seq + Data */
1330 break;
1331 case ICMP_UNREACH:
1332 switch(icp->icmp_code) {
1333 case ICMP_UNREACH_NET:
1334 (void)printf("Destination Net Unreachable\n");
1335 break;
1336 case ICMP_UNREACH_HOST:
1337 (void)printf("Destination Host Unreachable\n");
1338 break;
1339 case ICMP_UNREACH_PROTOCOL:
1340 (void)printf("Destination Protocol Unreachable\n");
1341 break;
1342 case ICMP_UNREACH_PORT:
1343 (void)printf("Destination Port Unreachable\n");
1344 break;
1345 case ICMP_UNREACH_NEEDFRAG:
1346 (void)printf("frag needed and DF set (MTU %d)\n",
1347 ntohs(icp->icmp_nextmtu));
1348 break;
1349 case ICMP_UNREACH_SRCFAIL:
1350 (void)printf("Source Route Failed\n");
1351 break;
1352 case ICMP_UNREACH_FILTER_PROHIB:
1353 (void)printf("Communication prohibited by filter\n");
1354 break;
1355 default:
1356 (void)printf("Dest Unreachable, Bad Code: %d\n",
1357 icp->icmp_code);
1358 break;
1359 }
1360 /* Print returned IP header information */
1361#ifndef icmp_data
1362 pr_retip(&icp->icmp_ip);
1363#else
1364 pr_retip((struct ip *)icp->icmp_data);
1365#endif
1366 break;
1367 case ICMP_SOURCEQUENCH:
1368 (void)printf("Source Quench\n");
1369#ifndef icmp_data
1370 pr_retip(&icp->icmp_ip);
1371#else
1372 pr_retip((struct ip *)icp->icmp_data);
1373#endif
1374 break;
1375 case ICMP_REDIRECT:
1376 switch(icp->icmp_code) {
1377 case ICMP_REDIRECT_NET:
1378 (void)printf("Redirect Network");
1379 break;
1380 case ICMP_REDIRECT_HOST:
1381 (void)printf("Redirect Host");
1382 break;
1383 case ICMP_REDIRECT_TOSNET:
1384 (void)printf("Redirect Type of Service and Network");
1385 break;
1386 case ICMP_REDIRECT_TOSHOST:
1387 (void)printf("Redirect Type of Service and Host");
1388 break;
1389 default:
1390 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1391 break;
1392 }
1393 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1394#ifndef icmp_data
1395 pr_retip(&icp->icmp_ip);
1396#else
1397 pr_retip((struct ip *)icp->icmp_data);
1398#endif
1399 break;
1400 case ICMP_ECHO:
1401 (void)printf("Echo Request\n");
1402 /* XXX ID + Seq + Data */
1403 break;
1404 case ICMP_TIMXCEED:
1405 switch(icp->icmp_code) {
1406 case ICMP_TIMXCEED_INTRANS:
1407 (void)printf("Time to live exceeded\n");
1408 break;
1409 case ICMP_TIMXCEED_REASS:
1410 (void)printf("Frag reassembly time exceeded\n");
1411 break;
1412 default:
1413 (void)printf("Time exceeded, Bad Code: %d\n",
1414 icp->icmp_code);
1415 break;
1416 }
1417#ifndef icmp_data
1418 pr_retip(&icp->icmp_ip);
1419#else
1420 pr_retip((struct ip *)icp->icmp_data);
1421#endif
1422 break;
1423 case ICMP_PARAMPROB:
1424 (void)printf("Parameter problem: pointer = 0x%02x\n",
1425 icp->icmp_hun.ih_pptr);
1426#ifndef icmp_data
1427 pr_retip(&icp->icmp_ip);
1428#else
1429 pr_retip((struct ip *)icp->icmp_data);
1430#endif
1431 break;
1432 case ICMP_TSTAMP:
1433 (void)printf("Timestamp\n");
1434 /* XXX ID + Seq + 3 timestamps */
1435 break;
1436 case ICMP_TSTAMPREPLY:
1437 (void)printf("Timestamp Reply\n");
1438 /* XXX ID + Seq + 3 timestamps */
1439 break;
1440 case ICMP_IREQ:
1441 (void)printf("Information Request\n");
1442 /* XXX ID + Seq */
1443 break;
1444 case ICMP_IREQREPLY:
1445 (void)printf("Information Reply\n");
1446 /* XXX ID + Seq */
1447 break;
1448 case ICMP_MASKREQ:
1449 (void)printf("Address Mask Request\n");
1450 break;
1451 case ICMP_MASKREPLY:
1452 (void)printf("Address Mask Reply\n");
1453 break;
1454 case ICMP_ROUTERADVERT:
1455 (void)printf("Router Advertisement\n");
1456 break;
1457 case ICMP_ROUTERSOLICIT:
1458 (void)printf("Router Solicitation\n");
1459 break;
1460 default:
1461 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1462 }
1463}
1464
1465/*
1466 * pr_iph --
1467 * Print an IP header with options.
1468 */
1469static void
1470pr_iph(ip)
1471 struct ip *ip;
1472{
1473 u_char *cp;
1474 int hlen;
1475
1476 hlen = ip->ip_hl << 2;
1477 cp = (u_char *)ip + 20; /* point to options */
1478
1479 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
1480 (void)printf(" %1x %1x %02x %04x %04x",
1481 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1482 ntohs(ip->ip_id));
1483 (void)printf(" %1lx %04lx",
1484 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1485 (u_long) ntohl(ip->ip_off) & 0x1fff);
1486 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1487 ntohs(ip->ip_sum));
1488 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1489 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1490 /* dump any option bytes */
1491 while (hlen-- > 20) {
1492 (void)printf("%02x", *cp++);
1493 }
1494 (void)putchar('\n');
1495}
1496
1497/*
1498 * pr_addr --
1499 * Return an ascii host address as a dotted quad and optionally with
1500 * a hostname.
1501 */
1502static char *
1503pr_addr(ina)
1504 struct in_addr ina;
1505{
1506 struct hostent *hp;
1507 static char buf[16 + 3 + MAXHOSTNAMELEN];
1508
1509 if ((options & F_NUMERIC) ||
1510 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1511 return inet_ntoa(ina);
1512 else
1513 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1514 inet_ntoa(ina));
1515 return(buf);
1516}
1517
1518/*
1519 * pr_retip --
1520 * Dump some info on a returned (via ICMP) IP packet.
1521 */
1522static void
1523pr_retip(ip)
1524 struct ip *ip;
1525{
1526 u_char *cp;
1527 int hlen;
1528
1529 pr_iph(ip);
1530 hlen = ip->ip_hl << 2;
1531 cp = (u_char *)ip + hlen;
1532
1533 if (ip->ip_p == 6)
1534 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1535 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1536 else if (ip->ip_p == 17)
1537 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1538 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1539}
1540
1541static char *
1542pr_ntime (n_time time)
1543{
1544 static char buf[10];
1545 int h, m, s;
1546
1547 s = ntohl(time) / 1000;
1548 h = s / 60 / 60;
1549 m = (s % (60 * 60)) / 60;
1550 s = (s % (60 * 60)) % 60;
1551
1552 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", h, m, s);
1553
1554 return (buf);
1555}
1556
1557static void
1558fill(bp, patp)
1559 char *bp, *patp;
1560{
1561 char *cp;
1562 int pat[16];
1563 u_int ii, jj, kk;
1564
1565 for (cp = patp; *cp; cp++) {
1566 if (!isxdigit(*cp))
1567 errx(EX_USAGE,
1568 "patterns must be specified as hex digits");
1569
1570 }
1571 ii = sscanf(patp,
1572 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1573 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1574 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1575 &pat[13], &pat[14], &pat[15]);
1576
1577 if (ii > 0)
1578 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
1579 for (jj = 0; jj < ii; ++jj)
1580 bp[jj + kk] = pat[jj];
1581 if (!(options & F_QUIET)) {
1582 (void)printf("PATTERN: 0x");
1583 for (jj = 0; jj < ii; ++jj)
1584 (void)printf("%02x", bp[jj] & 0xFF);
1585 (void)printf("\n");
1586 }
1587}
1588
1589#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
1590#define SECOPT " [-P policy]"
1591#else
1592#define SECOPT ""
1593#endif
1594static void
1595usage()
1596{
1597
1598 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n",
1599"usage: ping [-AaDdfnoQqRrv] [-c count] [-i wait] [-l preload] [-M mask | time]",
1600" [-m ttl]" SECOPT " [-p pattern] [-S src_addr] [-s packetsize]",
1601" [-t timeout] [-z tos] host",
1602" ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]",
1603" [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]",
1604" [-s packetsize] [-T ttl] [-t timeout] [-z tos] mcast-group");
1605 exit(EX_USAGE);
1606}