]> git.saurik.com Git - apple/network_cmds.git/blame - ping.tproj/ping.c
network_cmds-543.270.1.tar.gz
[apple/network_cmds.git] / ping.tproj / ping.c
CommitLineData
9c859447 1/*
26c66ce9 2 * Copyright (c) 1999-2016 Apple Inc. All rights reserved.
9c859447
A
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
b7080c8e
A
28/*
29 * Copyright (c) 1989, 1993
30 * The Regents of the University of California. All rights reserved.
31 *
32 * This code is derived from software contributed to Berkeley by
33 * Mike Muuss.
34 *
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
37 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
b7080c8e
A
43 * 4. Neither the name of the University nor the names of its contributors
44 * may be used to endorse or promote products derived from this software
45 * without specific prior written permission.
46 *
47 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * SUCH DAMAGE.
58 */
59
342c141e
A
60#include <sys/cdefs.h>
61
2b484d24 62#ifndef lint
342c141e 63__unused static const char copyright[] =
2b484d24
A
64"@(#) Copyright (c) 1989, 1993\n\
65 The Regents of the University of California. All rights reserved.\n";
66#endif /* not lint */
67
b7080c8e
A
68/*
69 * P I N G . C
70 *
2b484d24 71 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
b7080c8e
A
72 * measure round-trip-delays and packet loss across network paths.
73 *
74 * Author -
75 * Mike Muuss
76 * U. S. Army Ballistic Research Laboratory
77 * December, 1983
78 *
79 * Status -
80 * Public Domain. Distribution Unlimited.
81 * Bugs -
82 * More statistics could always be gathered.
83 * This program has to run SUID to ROOT to access the ICMP socket.
84 */
85
2b484d24 86#include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
b7080c8e 87#include <sys/socket.h>
2b484d24 88#include <sys/sysctl.h>
b7080c8e 89#include <sys/time.h>
2b484d24 90#include <sys/uio.h>
b7080c8e 91
b7080c8e 92#include <netinet/in.h>
2b484d24 93#include <netinet/in_systm.h>
b7080c8e
A
94#include <netinet/ip.h>
95#include <netinet/ip_icmp.h>
96#include <netinet/ip_var.h>
2b484d24 97#include <arpa/inet.h>
9c859447 98#include <net/if.h>
2b484d24
A
99
100#ifdef IPSEC
101#include <netinet6/ipsec.h>
102#endif /*IPSEC*/
103
b7080c8e 104#include <ctype.h>
2b484d24 105#include <err.h>
b7080c8e 106#include <errno.h>
2b484d24
A
107#include <math.h>
108#include <netdb.h>
109#include <signal.h>
26c66ce9 110#include <stdbool.h>
2b484d24
A
111#include <stdio.h>
112#include <stdlib.h>
b7080c8e 113#include <string.h>
2b484d24
A
114#include <sysexits.h>
115#include <unistd.h>
fdfd5971 116#include <ifaddrs.h>
26c66ce9 117#include <getopt.h>
b7080c8e 118
2b484d24 119#define INADDR_LEN ((int)sizeof(in_addr_t))
9c859447 120#define TIMEVAL_LEN ((int)sizeof(struct tv32))
2b484d24
A
121#define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN)
122#define TS_LEN (ICMP_TSLEN - ICMP_MINLEN)
123#define DEFDATALEN 56 /* default data length */
124#define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
125 /* runs out of buffer space */
126#define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
127#define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
9c859447 128#define MAXWAIT 10000 /* max ms to wait for response */
2b484d24
A
129#define MAXALARM (60 * 60) /* max seconds for alarm timeout */
130#define MAXTOS 255
b7080c8e
A
131
132#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
133#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
134#define SET(bit) (A(bit) |= B(bit))
135#define CLR(bit) (A(bit) &= (~B(bit)))
136#define TST(bit) (A(bit) & B(bit))
137
9c859447
A
138struct tv32 {
139 u_int32_t tv32_sec;
140 u_int32_t tv32_usec;
141};
142
b7080c8e
A
143/* various options */
144int options;
2b484d24
A
145#define F_FLOOD 0x0001
146#define F_INTERVAL 0x0002
147#define F_NUMERIC 0x0004
148#define F_PINGFILLED 0x0008
149#define F_QUIET 0x0010
150#define F_RROUTE 0x0020
151#define F_SO_DEBUG 0x0040
152#define F_SO_DONTROUTE 0x0080
153#define F_VERBOSE 0x0100
154#define F_QUIET2 0x0200
155#define F_NOLOOP 0x0400
156#define F_MTTL 0x0800
157#define F_MIF 0x1000
158#define F_AUDIBLE 0x2000
159#ifdef IPSEC
160#ifdef IPSEC_POLICY_IPSEC
161#define F_POLICY 0x4000
162#endif /*IPSEC_POLICY_IPSEC*/
163#endif /*IPSEC*/
164#define F_TTL 0x8000
165#define F_MISSED 0x10000
166#define F_ONCE 0x20000
167#define F_HDRINCL 0x40000
168#define F_MASK 0x80000
169#define F_TIME 0x100000
9c859447
A
170#define F_SWEEP 0x200000
171#define F_WAITTIME 0x400000
26c66ce9
A
172#define F_CONNECT 0x800000
173#define F_PRTIME 0x1000000
b7080c8e
A
174
175/*
176 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
177 * number of received sequence numbers we can keep track of. Change 128
178 * to 8192 for complete accuracy...
179 */
180#define MAX_DUP_CHK (8 * 128)
181int mx_dup_ck = MAX_DUP_CHK;
182char rcvd_tbl[MAX_DUP_CHK / 8];
183
2b484d24 184struct sockaddr_in whereto; /* who to ping */
b7080c8e 185int datalen = DEFDATALEN;
2b484d24 186int maxpayload;
b7080c8e 187int s; /* socket file descriptor */
2b484d24
A
188u_char outpackhdr[IP_MAXPACKET], *outpack;
189char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
b7080c8e
A
190char BSPACE = '\b'; /* characters written for flood */
191char DOT = '.';
192char *hostname;
2b484d24 193char *shostname;
b7080c8e 194int ident; /* process id to identify our packets */
2b484d24
A
195int uid; /* cached uid for micro-optimization */
196u_char icmp_type = ICMP_ECHO;
197u_char icmp_type_rsp = ICMP_ECHOREPLY;
198int phdr_len = 0;
199int send_len;
9c859447
A
200char *boundif;
201unsigned int ifscope;
fdfd5971 202int nocell;
26c66ce9
A
203int use_sendmsg = 0;
204int use_recvmsg = 0;
7af5ce03 205int traffic_class = SO_TC_CTL; /* use control class, by default */
26c66ce9 206int net_service_type = -1;
fdfd5971 207int no_dup = 0;
b7080c8e
A
208
209/* counters */
2b484d24 210long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
b7080c8e
A
211long npackets; /* max packets to transmit */
212long nreceived; /* # of packets we got back */
213long nrepeats; /* number of duplicates */
214long ntransmitted; /* sequence # for outbound packets = #sent */
9c859447
A
215long snpackets; /* max packets to transmit in one sweep */
216long snreceived; /* # of packets we got back in this sweep */
217long sntransmitted; /* # of packets we sent in this sweep */
218int sweepmax; /* max value of payload in sweep */
219int sweepmin = 0; /* start value of payload in sweep */
220int sweepincr = 1; /* payload increment in sweep */
2b484d24 221int interval = 1000; /* interval between packets, ms */
9c859447
A
222int waittime = MAXWAIT; /* timeout for each packet */
223long nrcvtimeout = 0; /* # of packets we got back after waittime */
89c4ed63 224int icmp_len = 0; /* length of the ICMP header */
b7080c8e
A
225
226/* timing */
227int timing; /* flag to do timing */
228double tmin = 999999999.0; /* minimum round trip time */
229double tmax = 0.0; /* maximum round trip time */
230double tsum = 0.0; /* sum of all times, for doing average */
2b484d24
A
231double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
232
233volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */
234volatile sig_atomic_t siginfo_p;
235
236static void fill(char *, char *);
237static u_short in_cksum(u_short *, int);
238static void check_status(void);
239static void finish(void) __dead2;
240static void pinger(void);
241static char *pr_addr(struct in_addr);
242static char *pr_ntime(n_time);
243static void pr_icmph(struct icmp *);
244static void pr_iph(struct ip *);
fdfd5971 245static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *, int);
2b484d24
A
246static void pr_retip(struct ip *);
247static void status(int);
248static void stopit(int);
9dc66a05 249static void tvsub(struct timeval *, const struct timeval *);
26c66ce9
A
250static int str2sotc(const char *, bool *);
251static int str2netservicetype(const char *, bool *);
252static u_int8_t str2tos(const char *, bool *);
2b484d24
A
253static void usage(void) __dead2;
254
26c66ce9
A
255int32_t thiszone; /* seconds offset from gmt to local time */
256extern int32_t gmt2local(time_t);
257static void pr_currenttime(void);
258
259static int longopt_flag = 0;
260
261#define LOF_CONNECT 0x01
262#define LOF_PRTIME 0x02
263
264static const struct option longopts[] = {
265 { "apple-connect", no_argument, &longopt_flag, LOF_CONNECT },
266 { "apple-time", no_argument, &longopt_flag, LOF_PRTIME },
267 { NULL, 0, NULL, 0 }
268};
269
2b484d24 270int
9dc66a05 271main(int argc, char *const *argv)
b7080c8e 272{
2b484d24
A
273 struct sockaddr_in from, sock_in;
274 struct in_addr ifaddr;
275 struct timeval last, intvl;
276 struct iovec iov;
277 struct ip *ip;
278 struct msghdr msg;
279 struct sigaction si_sa;
280 size_t sz;
9dc66a05 281 u_char *datap, packet[IP_MAXPACKET] __attribute__((aligned(4)));
2b484d24 282 char *ep, *source, *target, *payload;
b7080c8e 283 struct hostent *hp;
2b484d24
A
284#ifdef IPSEC_POLICY_IPSEC
285 char *policy_in, *policy_out;
286#endif
b7080c8e 287 struct sockaddr_in *to;
2b484d24
A
288 double t;
289 u_long alarmtimeout, ultmp;
89c4ed63 290 int almost_done, ch, df, hold, i, mib[4], preload, sockerrno,
2b484d24 291 tos, ttl;
fdfd5971 292 char ctrl[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(int))];
2b484d24 293 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
b7080c8e 294#ifdef IP_OPTIONS
2b484d24
A
295 char rspace[MAX_IPOPTLEN]; /* record route space */
296#endif
297 unsigned char loop, mttl;
298
299 payload = source = NULL;
300#ifdef IPSEC_POLICY_IPSEC
301 policy_in = policy_out = NULL;
b7080c8e 302#endif
26c66ce9 303 bool valid;
b7080c8e 304
2b484d24
A
305 /*
306 * Do the stuff that we need root priv's for *first*, and
307 * then drop our setuid bit. Save error reporting for
308 * after arg parsing.
309 */
9c859447
A
310 if (getuid())
311 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
312 else
313 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
2b484d24
A
314 sockerrno = errno;
315
9dc66a05
A
316 if (setuid(getuid()) != 0)
317 err(EX_NOPERM, "setuid() failed");
2b484d24
A
318 uid = getuid();
319
320 alarmtimeout = df = preload = tos = 0;
321
322 outpack = outpackhdr + sizeof(struct ip);
26c66ce9
A
323 while ((ch = getopt_long(argc, argv,
324 "AaB:b:Cc:DdfG:g:h:I:i:k:K:Ll:M:m:noP:p:QqRrS:s:T:t:vW:z:",
325 longopts, NULL)) != -1)
2b484d24 326 {
b7080c8e 327 switch(ch) {
2b484d24
A
328 case 'A':
329 options |= F_MISSED;
330 break;
331 case 'a':
332 options |= F_AUDIBLE;
333 break;
9c859447 334 case 'B':
9c859447
A
335 case 'b':
336 boundif = optarg;
337 break;
fdfd5971
A
338 case 'C':
339 nocell++;
340 break;
b7080c8e 341 case 'c':
2b484d24
A
342 ultmp = strtoul(optarg, &ep, 0);
343 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
344 errx(EX_USAGE,
345 "invalid count of packets to transmit: `%s'",
346 optarg);
347 npackets = ultmp;
348 break;
349 case 'D':
350 options |= F_HDRINCL;
351 df = 1;
b7080c8e
A
352 break;
353 case 'd':
354 options |= F_SO_DEBUG;
355 break;
356 case 'f':
2b484d24
A
357 if (uid) {
358 errno = EPERM;
359 err(EX_NOPERM, "-f flag");
b7080c8e
A
360 }
361 options |= F_FLOOD;
362 setbuf(stdout, (char *)NULL);
363 break;
9c859447
A
364 case 'G': /* Maximum packet size for ping sweep */
365 ultmp = strtoul(optarg, &ep, 0);
366 if (*ep || ep == optarg)
367 errx(EX_USAGE, "invalid packet size: `%s'",
368 optarg);
369#ifndef __APPLE__
370 if (uid != 0 && ultmp > DEFDATALEN) {
371 errno = EPERM;
372 err(EX_NOPERM,
373 "packet size too large: %lu > %u",
374 ultmp, DEFDATALEN);
375 }
376#endif /* __APPLE__ */
377 options |= F_SWEEP;
378 sweepmax = ultmp;
379 break;
380 case 'g': /* Minimum packet size for ping sweep */
381 ultmp = strtoul(optarg, &ep, 0);
382 if (*ep || ep == optarg)
383 errx(EX_USAGE, "invalid packet size: `%s'",
384 optarg);
385#ifndef __APPLE__
386 if (uid != 0 && ultmp > DEFDATALEN) {
387 errno = EPERM;
388 err(EX_NOPERM,
389 "packet size too large: %lu > %u",
390 ultmp, DEFDATALEN);
391 }
392#endif /* __APPLE__ */
393 options |= F_SWEEP;
394 sweepmin = ultmp;
395 break;
396 case 'h': /* Packet size increment for ping sweep */
397 ultmp = strtoul(optarg, &ep, 0);
398 if (*ep || ep == optarg || ultmp < 1)
399 errx(EX_USAGE, "invalid increment size: `%s'",
400 optarg);
401#ifndef __APPLE__
402 if (uid != 0 && ultmp > DEFDATALEN) {
403 errno = EPERM;
404 err(EX_NOPERM,
405 "packet size too large: %lu > %u",
406 ultmp, DEFDATALEN);
407 }
408#endif /* __APPLE__ */
409 options |= F_SWEEP;
410 sweepincr = ultmp;
411 break;
2b484d24
A
412 case 'I': /* multicast interface */
413 if (inet_aton(optarg, &ifaddr) == 0)
414 errx(EX_USAGE,
415 "invalid multicast interface: `%s'",
416 optarg);
417 options |= F_MIF;
418 break;
b7080c8e 419 case 'i': /* wait between sending packets */
2b484d24
A
420 t = strtod(optarg, &ep) * 1000.0;
421 if (*ep || ep == optarg || t > (double)INT_MAX)
422 errx(EX_USAGE, "invalid timing interval: `%s'",
423 optarg);
b7080c8e 424 options |= F_INTERVAL;
2b484d24 425 interval = (int)t;
9dc66a05 426 if (uid && interval < 100) {
2b484d24
A
427 errno = EPERM;
428 err(EX_NOPERM, "-i interval too short");
429 }
430 break;
5902acfc 431 case 'k':
26c66ce9
A
432 if (strcasecmp(optarg, "sendmsg") == 0) {
433 use_sendmsg++;
434 break;
435 }
436 if (strcasecmp(optarg, "recvmsg") == 0) {
437 use_recvmsg++;
438 break;
439 }
440 traffic_class = str2sotc(optarg, &valid);
441 if (valid == false)
342c141e
A
442 errx(EX_USAGE, "bad traffic class: `%s'",
443 optarg);
5902acfc 444 break;
26c66ce9
A
445 case 'K':
446 if (strcasecmp(optarg, "sendmsg") == 0) {
447 use_sendmsg++;
448 break;
449 }
450 net_service_type = str2netservicetype(optarg, &valid);
451 if (valid == false)
452 errx(EX_USAGE, "bad network service type: `%s'",
453 optarg);
454 /* suppress default traffic class (-k can still be specified after -K) */
455 traffic_class = -1;
456 break;
2b484d24
A
457 case 'L':
458 options |= F_NOLOOP;
459 loop = 0;
b7080c8e
A
460 break;
461 case 'l':
2b484d24
A
462 ultmp = strtoul(optarg, &ep, 0);
463 if (*ep || ep == optarg || ultmp > INT_MAX)
464 errx(EX_USAGE,
465 "invalid preload value: `%s'", optarg);
466 if (uid) {
467 errno = EPERM;
468 err(EX_NOPERM, "-l flag");
b7080c8e 469 }
2b484d24
A
470 preload = ultmp;
471 break;
472 case 'M':
473 switch(optarg[0]) {
474 case 'M':
475 case 'm':
476 options |= F_MASK;
477 break;
478 case 'T':
479 case 't':
480 options |= F_TIME;
481 break;
482 default:
483 errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
484 break;
b7080c8e
A
485 }
486 break;
2b484d24
A
487 case 'm': /* TTL */
488 ultmp = strtoul(optarg, &ep, 0);
489 if (*ep || ep == optarg || ultmp > MAXTTL)
490 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
491 ttl = ultmp;
492 options |= F_TTL;
493 break;
b7080c8e
A
494 case 'n':
495 options |= F_NUMERIC;
496 break;
2b484d24
A
497 case 'o':
498 options |= F_ONCE;
499 break;
26c66ce9 500 case 'P':
2b484d24
A
501#ifdef IPSEC
502#ifdef IPSEC_POLICY_IPSEC
2b484d24
A
503 options |= F_POLICY;
504 if (!strncmp("in", optarg, 2))
505 policy_in = strdup(optarg);
506 else if (!strncmp("out", optarg, 3))
507 policy_out = strdup(optarg);
508 else
509 errx(1, "invalid security policy");
2b484d24
A
510#endif /*IPSEC_POLICY_IPSEC*/
511#endif /*IPSEC*/
26c66ce9 512 break;
b7080c8e
A
513 case 'p': /* fill buffer with user pattern */
514 options |= F_PINGFILLED;
2b484d24
A
515 payload = optarg;
516 break;
517 case 'Q':
518 options |= F_QUIET2;
519 break;
b7080c8e
A
520 case 'q':
521 options |= F_QUIET;
522 break;
523 case 'R':
524 options |= F_RROUTE;
525 break;
526 case 'r':
527 options |= F_SO_DONTROUTE;
528 break;
2b484d24
A
529 case 'S':
530 source = optarg;
531 break;
b7080c8e 532 case 's': /* size of packet to send */
2b484d24
A
533 ultmp = strtoul(optarg, &ep, 0);
534 if (*ep || ep == optarg)
535 errx(EX_USAGE, "invalid packet size: `%s'",
536 optarg);
537#ifndef __APPLE__
538 if (uid != 0 && ultmp > DEFDATALEN) {
539 errno = EPERM;
540 err(EX_NOPERM,
541 "packet size too large: %lu > %u",
542 ultmp, DEFDATALEN);
b7080c8e 543 }
9c859447 544#endif /* __APPLE__ */
2b484d24
A
545 datalen = ultmp;
546 break;
547 case 'T': /* multicast TTL */
548 ultmp = strtoul(optarg, &ep, 0);
549 if (*ep || ep == optarg || ultmp > MAXTTL)
550 errx(EX_USAGE, "invalid multicast TTL: `%s'",
551 optarg);
552 mttl = ultmp;
553 options |= F_MTTL;
554 break;
555 case 't':
556 alarmtimeout = strtoul(optarg, &ep, 0);
557 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
558 errx(EX_USAGE, "invalid timeout: `%s'",
559 optarg);
560 if (alarmtimeout > MAXALARM)
561 errx(EX_USAGE, "invalid timeout: `%s' > %d",
562 optarg, MAXALARM);
9c859447 563 alarm((unsigned int)alarmtimeout);
b7080c8e
A
564 break;
565 case 'v':
566 options |= F_VERBOSE;
567 break;
9c859447
A
568 case 'W': /* wait ms for answer */
569 t = strtod(optarg, &ep);
570 if (*ep || ep == optarg || t > (double)INT_MAX)
571 errx(EX_USAGE, "invalid timing interval: `%s'",
572 optarg);
573 options |= F_WAITTIME;
574 waittime = (int)t;
575 break;
2b484d24
A
576 case 'z':
577 options |= F_HDRINCL;
26c66ce9
A
578 tos = str2tos(optarg, &valid);
579 if (valid == false)
2b484d24 580 errx(EX_USAGE, "invalid TOS: `%s'", optarg);
26c66ce9
A
581 break;
582 case 0:
583 switch (longopt_flag) {
584 case LOF_CONNECT:
585 options |= F_CONNECT;
586 break;
587 case LOF_PRTIME:
588 options |= F_PRTIME;
589 thiszone = gmt2local(0);
590 break;
591 default:
592 break;
593 }
594 longopt_flag = 0;
2b484d24 595 break;
b7080c8e
A
596 default:
597 usage();
598 }
2b484d24 599 }
b7080c8e 600
9c859447
A
601 if (boundif != NULL && (ifscope = if_nametoindex(boundif)) == 0)
602 errx(1, "bad interface name");
603
2b484d24 604 if (argc - optind != 1)
b7080c8e 605 usage();
2b484d24
A
606 target = argv[optind];
607
608 switch (options & (F_MASK|F_TIME)) {
609 case 0: break;
610 case F_MASK:
611 icmp_type = ICMP_MASKREQ;
612 icmp_type_rsp = ICMP_MASKREPLY;
613 phdr_len = MASK_LEN;
614 if (!(options & F_QUIET))
615 (void)printf("ICMP_MASKREQ\n");
616 break;
617 case F_TIME:
618 icmp_type = ICMP_TSTAMP;
619 icmp_type_rsp = ICMP_TSTAMPREPLY;
620 phdr_len = TS_LEN;
621 if (!(options & F_QUIET))
622 (void)printf("ICMP_TSTAMP\n");
623 break;
624 default:
625 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
626 break;
627 }
628 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len;
629 if (options & F_RROUTE)
630 icmp_len += MAX_IPOPTLEN;
631 maxpayload = IP_MAXPACKET - icmp_len;
632 if (datalen > maxpayload)
633 errx(EX_USAGE, "packet size too large: %d > %d", datalen,
634 maxpayload);
635 send_len = icmp_len + datalen;
636 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN];
637 if (options & F_PINGFILLED) {
638 fill((char *)datap, payload);
639 }
640 if (source) {
641 bzero((char *)&sock_in, sizeof(sock_in));
642 sock_in.sin_family = AF_INET;
643 if (inet_aton(source, &sock_in.sin_addr) != 0) {
644 shostname = source;
645 } else {
646 hp = gethostbyname2(source, AF_INET);
647 if (!hp)
648 errx(EX_NOHOST, "cannot resolve %s: %s",
649 source, hstrerror(h_errno));
650
651 sock_in.sin_len = sizeof sock_in;
652 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
653 hp->h_length < 0)
654 errx(1, "gethostbyname2: illegal address");
655 memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
656 sizeof(sock_in.sin_addr));
657 (void)strncpy(snamebuf, hp->h_name,
658 sizeof(snamebuf) - 1);
659 snamebuf[sizeof(snamebuf) - 1] = '\0';
660 shostname = snamebuf;
661 }
662 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
26c66ce9
A
663#if (DEBUG || DEVELOPMENT)
664 options |= F_HDRINCL;
665#else
2b484d24 666 err(1, "bind");
26c66ce9 667#endif /* DEBUG || DEVELOPMENT */
2b484d24 668 }
b7080c8e 669
2b484d24
A
670 bzero(&whereto, sizeof(whereto));
671 to = &whereto;
b7080c8e 672 to->sin_family = AF_INET;
2b484d24
A
673 to->sin_len = sizeof *to;
674 if (inet_aton(target, &to->sin_addr) != 0) {
b7080c8e 675 hostname = target;
2b484d24
A
676 } else {
677 hp = gethostbyname2(target, AF_INET);
678 if (!hp)
679 errx(EX_NOHOST, "cannot resolve %s: %s",
680 target, hstrerror(h_errno));
681
682 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
683 errx(1, "gethostbyname2 returned an illegal address");
684 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
b7080c8e 685 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
2b484d24 686 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
b7080c8e
A
687 hostname = hnamebuf;
688 }
689
fdfd5971
A
690 do {
691 struct ifaddrs *ifa_list, *ifa;
692
693 if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr)) || whereto.sin_addr.s_addr == INADDR_BROADCAST) {
694 no_dup = 1;
695 break;
696 }
697
698 if (getifaddrs(&ifa_list) == -1)
699 break;
700 for (ifa = ifa_list; ifa; ifa = ifa->ifa_next) {
701 if (ifa->ifa_addr->sa_family != AF_INET)
702 continue;
703 if ((ifa->ifa_flags & IFF_BROADCAST) == 0 || ifa->ifa_broadaddr == NULL)
704 continue;
705 if (whereto.sin_addr.s_addr != ((struct sockaddr_in*)ifa->ifa_broadaddr)->sin_addr.s_addr)
706 continue;
707 no_dup = 1;
708 break;
709 }
710
711 freeifaddrs(ifa_list);
712 } while (0);
713
2b484d24
A
714 if (options & F_FLOOD && options & F_INTERVAL)
715 errx(EX_USAGE, "-f and -i: incompatible options");
b7080c8e 716
2b484d24
A
717 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
718 errx(EX_USAGE,
719 "-f flag cannot be used with multicast destination");
720 if (options & (F_MIF | F_NOLOOP | F_MTTL)
721 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
722 errx(EX_USAGE,
723 "-I, -L, -T flags cannot be used with unicast destination");
724
b7080c8e 725 if (!(options & F_PINGFILLED))
89c4ed63 726 for (i = TIMEVAL_LEN; i < MAX(datalen, sweepmax); ++i)
b7080c8e
A
727 *datap++ = i;
728
729 ident = getpid() & 0xFFFF;
730
2b484d24
A
731 if (s < 0) {
732 errno = sockerrno;
733 err(EX_OSERR, "socket");
b7080c8e
A
734 }
735 hold = 1;
9dc66a05
A
736 (void) setsockopt(s, SOL_SOCKET, SO_RECV_ANYIF, (char *)&hold,
737 sizeof(hold));
9c859447
A
738 if (ifscope != 0) {
739 if (setsockopt(s, IPPROTO_IP, IP_BOUND_IF,
740 (char *)&ifscope, sizeof (ifscope)) != 0)
741 err(EX_OSERR, "setsockopt(IP_BOUND_IF)");
742 }
fdfd5971
A
743 if (nocell) {
744 if (setsockopt(s, IPPROTO_IP, IP_NO_IFT_CELLULAR,
745 (char *)&nocell, sizeof (nocell)) != 0)
746 err(EX_OSERR, "setsockopt(IP_NO_IFT_CELLULAR)");
747 }
b7080c8e
A
748 if (options & F_SO_DEBUG)
749 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
750 sizeof(hold));
751 if (options & F_SO_DONTROUTE)
752 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
753 sizeof(hold));
26c66ce9
A
754 if (use_sendmsg == 0) {
755 if (net_service_type != -1)
756 if (setsockopt(s, SOL_SOCKET, SO_NET_SERVICE_TYPE,
757 (void *)&net_service_type, sizeof (net_service_type)) != 0)
758 warn("setsockopt(SO_NET_SERVICE_TYPE");
759 if (traffic_class != -1) {
760 if (setsockopt(s, SOL_SOCKET, SO_TRAFFIC_CLASS,
761 (void *)&traffic_class, sizeof (traffic_class)) != 0)
762 warn("setsockopt(SO_TRAFFIC_CLASS");
763
764 }
7af5ce03 765 }
26c66ce9 766 if (use_recvmsg > 0) {
fdfd5971 767 int on = 1;
7af5ce03
A
768 (void) setsockopt(s, SOL_SOCKET, SO_RECV_TRAFFIC_CLASS,
769 (void *)&on, sizeof (on));
5902acfc 770 }
2b484d24
A
771#ifdef IPSEC
772#ifdef IPSEC_POLICY_IPSEC
773 if (options & F_POLICY) {
774 char *buf;
775 if (policy_in != NULL) {
776 buf = ipsec_set_policy(policy_in, strlen(policy_in));
777 if (buf == NULL)
778 errx(EX_CONFIG, "%s", ipsec_strerror());
779 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
780 buf, ipsec_get_policylen(buf)) < 0)
781 err(EX_CONFIG,
782 "ipsec policy cannot be configured");
783 free(buf);
784 }
b7080c8e 785
2b484d24
A
786 if (policy_out != NULL) {
787 buf = ipsec_set_policy(policy_out, strlen(policy_out));
788 if (buf == NULL)
789 errx(EX_CONFIG, "%s", ipsec_strerror());
790 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
791 buf, ipsec_get_policylen(buf)) < 0)
792 err(EX_CONFIG,
793 "ipsec policy cannot be configured");
794 free(buf);
795 }
796 }
797#endif /*IPSEC_POLICY_IPSEC*/
798#endif /*IPSEC*/
799
800 if (options & F_HDRINCL) {
801 ip = (struct ip*)outpackhdr;
802 if (!(options & (F_TTL | F_MTTL))) {
803 mib[0] = CTL_NET;
804 mib[1] = PF_INET;
805 mib[2] = IPPROTO_IP;
806 mib[3] = IPCTL_DEFTTL;
807 sz = sizeof(ttl);
808 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
809 err(1, "sysctl(net.inet.ip.ttl)");
810 }
811 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
812 ip->ip_v = IPVERSION;
813 ip->ip_hl = sizeof(struct ip) >> 2;
814 ip->ip_tos = tos;
815 ip->ip_id = 0;
816 ip->ip_off = df ? IP_DF : 0;
817 ip->ip_ttl = ttl;
818 ip->ip_p = IPPROTO_ICMP;
819 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
820 ip->ip_dst = to->sin_addr;
821 }
b7080c8e
A
822 /* record route option */
823 if (options & F_RROUTE) {
824#ifdef IP_OPTIONS
2b484d24 825 bzero(rspace, sizeof(rspace));
b7080c8e 826 rspace[IPOPT_OPTVAL] = IPOPT_RR;
2b484d24 827 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
b7080c8e 828 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
2b484d24 829 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
b7080c8e 830 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
2b484d24
A
831 sizeof(rspace)) < 0)
832 err(EX_OSERR, "setsockopt IP_OPTIONS");
b7080c8e 833#else
2b484d24
A
834 errx(EX_UNAVAILABLE,
835 "record route not available in this implementation");
b7080c8e
A
836#endif /* IP_OPTIONS */
837 }
838
2b484d24
A
839 if (options & F_TTL) {
840 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
841 sizeof(ttl)) < 0) {
842 err(EX_OSERR, "setsockopt IP_TTL");
843 }
844 }
845 if (options & F_NOLOOP) {
846 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
847 sizeof(loop)) < 0) {
848 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
849 }
850 }
851 if (options & F_MTTL) {
852 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
853 sizeof(mttl)) < 0) {
854 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
855 }
856 }
857 if (options & F_MIF) {
858 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
859 sizeof(ifaddr)) < 0) {
860 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
861 }
862 }
863#ifdef SO_TIMESTAMP
864 { int on = 1;
865 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
866 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
867 }
868#endif
26c66ce9
A
869
870 if ((options & F_CONNECT)) {
871 if (connect(s, (struct sockaddr *)&whereto, sizeof whereto) == -1)
872 err(EX_OSERR, "connect");
873 }
874
9c859447
A
875 if (sweepmax) {
876 if (sweepmin >= sweepmax)
877 errx(EX_USAGE, "Maximum packet size must be greater than the minimum packet size");
878
879 if (datalen != DEFDATALEN)
880 errx(EX_USAGE, "Packet size and ping sweep are mutually exclusive");
881
882 if (npackets > 0) {
883 snpackets = npackets;
884 npackets = 0;
885 } else
886 snpackets = 1;
887 datalen = sweepmin;
888 send_len = icmp_len + sweepmin;
889 }
890 if (options & F_SWEEP && !sweepmax)
891 errx(EX_USAGE, "Maximum sweep size must be specified");
2b484d24 892
b7080c8e
A
893 /*
894 * When pinging the broadcast address, you can get a lot of answers.
895 * Doing something so evil is useful if you are trying to stress the
896 * ethernet, or just want to fill the arp cache to get some stuff for
2b484d24
A
897 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
898 * or multicast pings if they wish.
b7080c8e 899 */
b7080c8e 900
2b484d24
A
901 /*
902 * XXX receive buffer needs undetermined space for mbuf overhead
903 * as well.
904 */
905 hold = IP_MAXPACKET + 128;
906 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
907 sizeof(hold));
908 if (uid == 0)
909 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
910 sizeof(hold));
911
912 if (to->sin_family == AF_INET) {
913 (void)printf("PING %s (%s)", hostname,
914 inet_ntoa(to->sin_addr));
915 if (source)
916 (void)printf(" from %s", shostname);
9c859447
A
917 if (sweepmax)
918 (void)printf(": (%d ... %d) data bytes\n",
919 sweepmin, sweepmax);
920 else
921 (void)printf(": %d data bytes\n", datalen);
922
923 } else {
924 if (sweepmax)
925 (void)printf("PING %s: (%d ... %d) data bytes\n",
926 hostname, sweepmin, sweepmax);
927 else
928 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
929 }
b7080c8e 930
26c66ce9
A
931 /*
932 * rdar://25829310
933 *
934 * Clear blocked signals inherited from the parent
935 */
936 sigset_t newset;
937 sigemptyset(&newset);
938 if (sigprocmask(SIG_SETMASK, &newset, NULL) != 0)
939 err(EX_OSERR, "sigprocmask(newset)");
940
2b484d24
A
941 /*
942 * Use sigaction() instead of signal() to get unambiguous semantics,
943 * in particular with SA_RESTART not set.
944 */
945
946 sigemptyset(&si_sa.sa_mask);
947 si_sa.sa_flags = 0;
b7080c8e 948
2b484d24
A
949 si_sa.sa_handler = stopit;
950 if (sigaction(SIGINT, &si_sa, 0) == -1) {
951 err(EX_OSERR, "sigaction SIGINT");
952 }
9dc66a05
A
953 si_sa.sa_handler = stopit;
954 if (sigaction(SIGQUIT, &si_sa, 0) == -1) {
955 err(EX_OSERR, "sigaction SIGQUIT");
956 }
957
2b484d24
A
958 si_sa.sa_handler = status;
959 if (sigaction(SIGINFO, &si_sa, 0) == -1) {
9dc66a05 960 err(EX_OSERR, "sigaction SIGINFO");
2b484d24 961 }
b7080c8e 962
9dc66a05 963 if (alarmtimeout > 0) {
2b484d24
A
964 si_sa.sa_handler = stopit;
965 if (sigaction(SIGALRM, &si_sa, 0) == -1)
966 err(EX_OSERR, "sigaction SIGALRM");
9dc66a05 967 }
2b484d24
A
968
969 bzero(&msg, sizeof(msg));
970 msg.msg_name = (caddr_t)&from;
971 msg.msg_iov = &iov;
972 msg.msg_iovlen = 1;
973#ifdef SO_TIMESTAMP
974 msg.msg_control = (caddr_t)ctrl;
975#endif
976 iov.iov_base = packet;
977 iov.iov_len = IP_MAXPACKET;
b7080c8e 978
2b484d24
A
979 if (preload == 0)
980 pinger(); /* send the first ping */
981 else {
982 if (npackets != 0 && preload > npackets)
983 preload = npackets;
984 while (preload--) /* fire off them quickies */
b7080c8e 985 pinger();
2b484d24
A
986 }
987 (void)gettimeofday(&last, NULL);
988
989 if (options & F_FLOOD) {
990 intvl.tv_sec = 0;
991 intvl.tv_usec = 10000;
992 } else {
993 intvl.tv_sec = interval / 1000;
994 intvl.tv_usec = interval % 1000 * 1000;
995 }
996
997 almost_done = 0;
998 while (!finish_up) {
999 struct timeval now, timeout;
1000 fd_set rfds;
1001 int cc, n;
fdfd5971 1002 int tc = -1;
2b484d24
A
1003
1004 check_status();
1005 if ((unsigned)s >= FD_SETSIZE)
1006 errx(EX_OSERR, "descriptor too large");
1007 FD_ZERO(&rfds);
1008 FD_SET(s, &rfds);
1009 (void)gettimeofday(&now, NULL);
1010 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
1011 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
1012 while (timeout.tv_usec < 0) {
1013 timeout.tv_usec += 1000000;
1014 timeout.tv_sec--;
b7080c8e 1015 }
2b484d24
A
1016 while (timeout.tv_usec >= 1000000) {
1017 timeout.tv_usec -= 1000000;
1018 timeout.tv_sec++;
1019 }
1020 if (timeout.tv_sec < 0)
1021 timeout.tv_sec = timeout.tv_usec = 0;
1022 n = select(s + 1, &rfds, NULL, NULL, &timeout);
1023 if (n < 0)
1024 continue; /* Must be EINTR. */
1025 if (n == 1) {
1026 struct timeval *tv = NULL;
1027#ifdef SO_TIMESTAMP
26c66ce9 1028 struct cmsghdr *cmsg;
2b484d24
A
1029
1030 msg.msg_controllen = sizeof(ctrl);
1031#endif
1032 msg.msg_namelen = sizeof(from);
1033 if ((cc = recvmsg(s, &msg, 0)) < 0) {
1034 if (errno == EINTR)
1035 continue;
1036 warn("recvmsg");
b7080c8e 1037 continue;
2b484d24 1038 }
fdfd5971 1039 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
9dc66a05 1040#ifdef SO_TIMESTAMP
fdfd5971
A
1041 if (cmsg->cmsg_level == SOL_SOCKET &&
1042 cmsg->cmsg_type == SCM_TIMESTAMP &&
1043 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
1044 /* Copy to avoid alignment problems: */
1045 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
1046 tv = &now;
1047 }
9dc66a05 1048#endif
fdfd5971
A
1049 if (cmsg->cmsg_level == SOL_SOCKET &&
1050 cmsg->cmsg_type == SO_TRAFFIC_CLASS &&
1051 cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
1052 /* Copy to avoid alignment problems: */
1053 memcpy(&tc, CMSG_DATA(cmsg), sizeof(tc));
1054 }
2b484d24 1055 }
2b484d24
A
1056 if (tv == NULL) {
1057 (void)gettimeofday(&now, NULL);
1058 tv = &now;
1059 }
fdfd5971 1060 pr_pack((char *)packet, cc, &from, tv, tc);
2b484d24
A
1061 if ((options & F_ONCE && nreceived) ||
1062 (npackets && nreceived >= npackets))
1063 break;
1064 }
1065 if (n == 0 || options & F_FLOOD) {
9c859447 1066 if (sweepmax && sntransmitted == snpackets) {
9c859447
A
1067 datalen += sweepincr;
1068 if (datalen > sweepmax)
1069 break;
1070 send_len = icmp_len + datalen;
1071 sntransmitted = 0;
1072 }
2b484d24
A
1073 if (!npackets || ntransmitted < npackets)
1074 pinger();
1075 else {
1076 if (almost_done)
1077 break;
1078 almost_done = 1;
1079 intvl.tv_usec = 0;
1080 if (nreceived) {
1081 intvl.tv_sec = 2 * tmax / 1000;
1082 if (!intvl.tv_sec)
1083 intvl.tv_sec = 1;
9c859447
A
1084 } else {
1085 intvl.tv_sec = waittime / 1000;
1086 intvl.tv_usec = waittime % 1000 * 1000;
1087 }
2b484d24
A
1088 }
1089 (void)gettimeofday(&last, NULL);
1090 if (ntransmitted - nreceived - 1 > nmissedmax) {
1091 nmissedmax = ntransmitted - nreceived - 1;
1092 if (options & F_MISSED)
1093 (void)write(STDOUT_FILENO, &BBELL, 1);
89c4ed63
A
1094 if (!(options & F_QUIET)) {
1095 printf("Request timeout for icmp_seq %u\n",
1096 (uint16_t)(ntransmitted - 2));
1097 if (!(options & F_FLOOD))
1098 (void)fflush(stdout);
1099 }
2b484d24 1100 }
b7080c8e 1101 }
b7080c8e
A
1102 }
1103 finish();
1104 /* NOTREACHED */
2b484d24 1105 exit(0); /* Make the compiler happy */
b7080c8e
A
1106}
1107
1108/*
2b484d24
A
1109 * stopit --
1110 * Set the global bit that causes the main loop to quit.
1111 * Do NOT call finish() from here, since finish() does far too much
1112 * to be called from a signal handler.
b7080c8e
A
1113 */
1114void
9dc66a05 1115stopit(int sig __unused)
b7080c8e 1116{
b7080c8e 1117
2b484d24
A
1118 /*
1119 * When doing reverse DNS lookups, the finish_up flag might not
1120 * be noticed for a while. Just exit if we get a second SIGINT.
1121 */
1122 if (!(options & F_NUMERIC) && finish_up)
1123 _exit(nreceived ? 0 : 2);
1124 finish_up = 1;
b7080c8e
A
1125}
1126
1127/*
1128 * pinger --
1129 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1130 * will be added on by the kernel. The ID field is our UNIX process ID,
2b484d24
A
1131 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
1132 * bytes of the data portion are used to hold a UNIX "timeval" struct in
1133 * host byte-order, to compute the round-trip time.
b7080c8e 1134 */
2b484d24
A
1135static void
1136pinger(void)
b7080c8e 1137{
2b484d24 1138 struct timeval now;
9c859447 1139 struct tv32 tv32;
2b484d24
A
1140 struct ip *ip;
1141 struct icmp *icp;
1142 int cc, i;
1143 u_char *packet;
b7080c8e 1144
2b484d24 1145 packet = outpack;
b7080c8e 1146 icp = (struct icmp *)outpack;
2b484d24 1147 icp->icmp_type = icmp_type;
b7080c8e
A
1148 icp->icmp_code = 0;
1149 icp->icmp_cksum = 0;
2b484d24 1150 icp->icmp_seq = htons(ntransmitted);
b7080c8e
A
1151 icp->icmp_id = ident; /* ID */
1152
2b484d24 1153 CLR(ntransmitted % mx_dup_ck);
b7080c8e 1154
26c66ce9
A
1155 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
1156 timing = 1;
1157 else
1158 timing = 0;
1159
2b484d24
A
1160 if ((options & F_TIME) || timing) {
1161 (void)gettimeofday(&now, NULL);
b7080c8e 1162
9c859447
A
1163 tv32.tv32_sec = htonl(now.tv_sec);
1164 tv32.tv32_usec = htonl(now.tv_usec);
2b484d24
A
1165 if (options & F_TIME)
1166 icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
1167 * 1000 + now.tv_usec / 1000);
1168 if (timing)
9c859447 1169 bcopy((void *)&tv32,
2b484d24 1170 (void *)&outpack[ICMP_MINLEN + phdr_len],
9c859447 1171 sizeof(tv32));
2b484d24
A
1172 }
1173
1174 cc = ICMP_MINLEN + phdr_len + datalen;
b7080c8e
A
1175
1176 /* compute ICMP checksum here */
1177 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
1178
2b484d24
A
1179 if (options & F_HDRINCL) {
1180 cc += sizeof(struct ip);
1181 ip = (struct ip *)outpackhdr;
1182 ip->ip_len = cc;
1183 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
1184 packet = outpackhdr;
1185 }
26c66ce9 1186 if (use_sendmsg > 0) {
5902acfc
A
1187 struct msghdr msg;
1188 struct iovec iov;
26c66ce9 1189 char cmbuf[2 * CMSG_SPACE(sizeof(int))];
5902acfc
A
1190 struct cmsghdr *cm = (struct cmsghdr *)cmbuf;
1191
26c66ce9
A
1192 if ((options & F_CONNECT)) {
1193 msg.msg_name = NULL;
1194 msg.msg_namelen = 0;
1195 } else {
5902acfc
A
1196 msg.msg_name = &whereto;
1197 msg.msg_namelen = sizeof(whereto);
26c66ce9 1198 }
5902acfc
A
1199 iov.iov_base = packet;
1200 iov.iov_len = cc;
1201 msg.msg_iov = &iov;
1202 msg.msg_iovlen = 1;
1203
26c66ce9
A
1204 msg.msg_controllen = 0;
1205 msg.msg_control = NULL;
1206
1207 if (traffic_class >= 0) {
1208 cm->cmsg_len = CMSG_LEN(sizeof(int));
1209 cm->cmsg_level = SOL_SOCKET;
1210 cm->cmsg_type = SO_TRAFFIC_CLASS;
1211 *(int *)CMSG_DATA(cm) = traffic_class;
1212 msg.msg_controllen += CMSG_SPACE(sizeof(int));
1213 cm = (struct cmsghdr *)(((char *)cm) + CMSG_SPACE(sizeof(int)));
1214 }
1215 if (net_service_type >= 0) {
1216 cm->cmsg_len = CMSG_LEN(sizeof(int));
1217 cm->cmsg_level = SOL_SOCKET;
1218 cm->cmsg_type = SO_NET_SERVICE_TYPE;
1219 msg.msg_controllen += CMSG_SPACE(sizeof(int));
1220 *(int *)CMSG_DATA(cm) = net_service_type;
1221 }
1222 msg.msg_control = cmbuf;
5902acfc
A
1223
1224 msg.msg_flags = 0;
1225
1226 i = sendmsg(s, &msg, 0);
1227 } else {
26c66ce9
A
1228 if ((options & F_CONNECT)) {
1229 i = send(s, (char *)packet, cc, 0);
1230 } else {
5902acfc
A
1231 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
1232 sizeof(whereto));
1233 }
26c66ce9 1234 }
b7080c8e 1235 if (i < 0 || i != cc) {
2b484d24
A
1236 if (i < 0) {
1237 if (options & F_FLOOD && errno == ENOBUFS) {
1238 usleep(FLOOD_BACKOFF);
1239 return;
1240 }
1241 warn("sendto");
1242 } else {
1243 warn("%s: partial write: %d of %d bytes",
1244 hostname, i, cc);
1245 }
b7080c8e 1246 }
2b484d24 1247 ntransmitted++;
9c859447 1248 sntransmitted++;
b7080c8e
A
1249 if (!(options & F_QUIET) && options & F_FLOOD)
1250 (void)write(STDOUT_FILENO, &DOT, 1);
1251}
1252
1253/*
1254 * pr_pack --
1255 * Print out the packet, if it came from us. This logic is necessary
1256 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1257 * which arrive ('tis only fair). This permits multiple copies of this
1258 * program to be run without having intermingled output (or statistics!).
1259 */
2b484d24 1260static void
9dc66a05
A
1261pr_pack(char *buf, int cc, struct sockaddr_in *from, struct timeval *tv,
1262 int tc)
b7080c8e 1263{
2b484d24
A
1264 struct in_addr ina;
1265 u_char *cp, *dp;
1266 struct icmp *icp;
b7080c8e 1267 struct ip *ip;
2b484d24 1268 const void *tp;
b7080c8e 1269 double triptime;
2b484d24
A
1270 int dupflag, hlen, i, j, recv_len, seq;
1271 static int old_rrlen;
1272 static char old_rr[MAX_IPOPTLEN];
b7080c8e
A
1273
1274 /* Check the IP header */
1275 ip = (struct ip *)buf;
1276 hlen = ip->ip_hl << 2;
2b484d24 1277 recv_len = cc;
b7080c8e
A
1278 if (cc < hlen + ICMP_MINLEN) {
1279 if (options & F_VERBOSE)
2b484d24
A
1280 warn("packet too short (%d bytes) from %s", cc,
1281 inet_ntoa(from->sin_addr));
b7080c8e
A
1282 return;
1283 }
1284
1285 /* Now the ICMP part */
1286 cc -= hlen;
1287 icp = (struct icmp *)(buf + hlen);
2b484d24 1288 if (icp->icmp_type == icmp_type_rsp) {
b7080c8e
A
1289 if (icp->icmp_id != ident)
1290 return; /* 'Twas not our ECHO */
1291 ++nreceived;
2b484d24 1292 triptime = 0.0;
b7080c8e 1293 if (timing) {
2b484d24 1294 struct timeval tv1;
9c859447 1295 struct tv32 tv32;
b7080c8e 1296#ifndef icmp_data
2b484d24 1297 tp = &icp->icmp_ip;
b7080c8e 1298#else
2b484d24 1299 tp = icp->icmp_data;
b7080c8e 1300#endif
2b484d24
A
1301 tp = (const char *)tp + phdr_len;
1302
1303 if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) {
1304 /* Copy to avoid alignment problems: */
9c859447
A
1305 memcpy(&tv32, tp, sizeof(tv32));
1306 tv1.tv_sec = ntohl(tv32.tv32_sec);
1307 tv1.tv_usec = ntohl(tv32.tv32_usec);
2b484d24
A
1308 tvsub(tv, &tv1);
1309 triptime = ((double)tv->tv_sec) * 1000.0 +
1310 ((double)tv->tv_usec) / 1000.0;
1311 tsum += triptime;
1312 tsumsq += triptime * triptime;
1313 if (triptime < tmin)
1314 tmin = triptime;
1315 if (triptime > tmax)
1316 tmax = triptime;
1317 } else
1318 timing = 0;
b7080c8e
A
1319 }
1320
2b484d24
A
1321 seq = ntohs(icp->icmp_seq);
1322
1323 if (TST(seq % mx_dup_ck)) {
b7080c8e
A
1324 ++nrepeats;
1325 --nreceived;
1326 dupflag = 1;
1327 } else {
2b484d24 1328 SET(seq % mx_dup_ck);
b7080c8e
A
1329 dupflag = 0;
1330 }
1331
1332 if (options & F_QUIET)
1333 return;
9c859447
A
1334
1335 if (options & F_WAITTIME && triptime > waittime) {
1336 ++nrcvtimeout;
1337 return;
1338 }
b7080c8e
A
1339
1340 if (options & F_FLOOD)
1341 (void)write(STDOUT_FILENO, &BSPACE, 1);
1342 else {
89c4ed63
A
1343 int seq_sent_len = send_len;
1344 int seq_datalen = datalen;
1345
1346 if (sweepmax != 0) {
1347 /*
1348 * When sweeping take in account the length of that
1349 * was sent based on the sequence number
1350 */
1351 seq_datalen = sweepmin + (seq / snpackets) * sweepincr;
1352 seq_sent_len = icmp_len + seq_datalen;
1353 }
26c66ce9
A
1354 if (options & F_PRTIME)
1355 pr_currenttime();
b7080c8e
A
1356 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
1357 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
2b484d24 1358 seq);
b7080c8e
A
1359 (void)printf(" ttl=%d", ip->ip_ttl);
1360 if (timing)
2b484d24 1361 (void)printf(" time=%.3f ms", triptime);
fdfd5971
A
1362 if (tc != -1) {
1363 (void)printf(" tc=%d", tc);
1364 }
1365 if (dupflag && no_dup == 0) {
1366 (void)printf(" (DUP!)");
9c859447 1367 }
2b484d24
A
1368 if (options & F_AUDIBLE)
1369 (void)write(STDOUT_FILENO, &BBELL, 1);
1370 if (options & F_MASK) {
1371 /* Just prentend this cast isn't ugly */
1372 (void)printf(" mask=%s",
1373 pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1374 }
1375 if (options & F_TIME) {
1376 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1377 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1378 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1379 }
89c4ed63 1380 if (recv_len != seq_sent_len) {
2b484d24
A
1381 (void)printf(
1382 "\nwrong total length %d instead of %d",
89c4ed63 1383 recv_len, seq_sent_len);
2b484d24 1384 }
b7080c8e 1385 /* check the data */
2b484d24
A
1386 cp = (u_char*)&icp->icmp_data[phdr_len];
1387 dp = &outpack[ICMP_MINLEN + phdr_len];
1388 cc -= ICMP_MINLEN + phdr_len;
1389 i = 0;
1390 if (timing) { /* don't check variable timestamp */
1391 cp += TIMEVAL_LEN;
1392 dp += TIMEVAL_LEN;
1393 cc -= TIMEVAL_LEN;
1394 i += TIMEVAL_LEN;
1395 }
89c4ed63 1396 for (; i < seq_datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
b7080c8e
A
1397 if (*cp != *dp) {
1398 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1399 i, *dp, *cp);
2b484d24 1400 (void)printf("\ncp:");
b7080c8e 1401 cp = (u_char*)&icp->icmp_data[0];
89c4ed63
A
1402 for (i = 0; i < seq_datalen; ++i, ++cp) {
1403 if ((i % 16) == 0)
2b484d24
A
1404 (void)printf("\n\t");
1405 (void)printf("%2x ", *cp);
1406 }
1407 (void)printf("\ndp:");
1408 cp = &outpack[ICMP_MINLEN];
89c4ed63
A
1409 for (i = 0; i < seq_datalen; ++i, ++cp) {
1410 if ((i % 16) == 0)
b7080c8e 1411 (void)printf("\n\t");
2b484d24 1412 (void)printf("%2x ", *cp);
b7080c8e
A
1413 }
1414 break;
1415 }
1416 }
1417 }
1418 } else {
2b484d24
A
1419 /*
1420 * We've got something other than an ECHOREPLY.
1421 * See if it's a reply to something that we sent.
1422 * We can compare IP destination, protocol,
1423 * and ICMP type and ID.
1424 *
1425 * Only print all the error messages if we are running
1426 * as root to avoid leaking information not normally
1427 * available to those not running as root.
1428 */
1429#ifndef icmp_data
1430 struct ip *oip = &icp->icmp_ip;
1431#else
1432 struct ip *oip = (struct ip *)icp->icmp_data;
1433#endif
1434 struct icmp *oicmp = (struct icmp *)(oip + 1);
1435
1436 if (((options & F_VERBOSE) && uid == 0) ||
1437 (!(options & F_QUIET2) &&
1438 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1439 (oip->ip_p == IPPROTO_ICMP) &&
1440 (oicmp->icmp_type == ICMP_ECHO) &&
1441 (oicmp->icmp_id == ident))) {
26c66ce9
A
1442 if (options & F_PRTIME)
1443 pr_currenttime();
2b484d24
A
1444 (void)printf("%d bytes from %s: ", cc,
1445 pr_addr(from->sin_addr));
1446 pr_icmph(icp);
1447 } else
1448 return;
b7080c8e
A
1449 }
1450
1451 /* Display any IP options */
1452 cp = (u_char *)buf + sizeof(struct ip);
1453
1454 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1455 switch (*cp) {
1456 case IPOPT_EOL:
1457 hlen = 0;
1458 break;
1459 case IPOPT_LSRR:
2b484d24
A
1460 case IPOPT_SSRR:
1461 (void)printf(*cp == IPOPT_LSRR ?
1462 "\nLSRR: " : "\nSSRR: ");
1463 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
b7080c8e 1464 hlen -= 2;
2b484d24
A
1465 cp += 2;
1466 if (j >= INADDR_LEN &&
1467 j <= hlen - (int)sizeof(struct ip)) {
b7080c8e 1468 for (;;) {
2b484d24
A
1469 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1470 if (ina.s_addr == 0)
b7080c8e 1471 (void)printf("\t0.0.0.0");
2b484d24
A
1472 else
1473 (void)printf("\t%s",
1474 pr_addr(ina));
1475 hlen -= INADDR_LEN;
1476 cp += INADDR_LEN - 1;
1477 j -= INADDR_LEN;
1478 if (j < INADDR_LEN)
1479 break;
1480 (void)putchar('\n');
1481 }
1482 } else
1483 (void)printf("\t(truncated route)\n");
b7080c8e
A
1484 break;
1485 case IPOPT_RR:
2b484d24
A
1486 j = cp[IPOPT_OLEN]; /* get length */
1487 i = cp[IPOPT_OFFSET]; /* and pointer */
b7080c8e 1488 hlen -= 2;
2b484d24 1489 cp += 2;
b7080c8e
A
1490 if (i > j)
1491 i = j;
2b484d24
A
1492 i = i - IPOPT_MINOFF + 1;
1493 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1494 old_rrlen = 0;
b7080c8e 1495 continue;
2b484d24 1496 }
b7080c8e 1497 if (i == old_rrlen
2b484d24 1498 && !bcmp((char *)cp, old_rr, i)
b7080c8e
A
1499 && !(options & F_FLOOD)) {
1500 (void)printf("\t(same route)");
b7080c8e
A
1501 hlen -= i;
1502 cp += i;
1503 break;
1504 }
2b484d24
A
1505 old_rrlen = i;
1506 bcopy((char *)cp, old_rr, i);
b7080c8e 1507 (void)printf("\nRR: ");
2b484d24
A
1508 if (i >= INADDR_LEN &&
1509 i <= hlen - (int)sizeof(struct ip)) {
1510 for (;;) {
1511 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1512 if (ina.s_addr == 0)
1513 (void)printf("\t0.0.0.0");
1514 else
1515 (void)printf("\t%s",
1516 pr_addr(ina));
1517 hlen -= INADDR_LEN;
1518 cp += INADDR_LEN - 1;
1519 i -= INADDR_LEN;
1520 if (i < INADDR_LEN)
1521 break;
1522 (void)putchar('\n');
b7080c8e 1523 }
2b484d24
A
1524 } else
1525 (void)printf("\t(truncated route)");
b7080c8e
A
1526 break;
1527 case IPOPT_NOP:
1528 (void)printf("\nNOP");
1529 break;
1530 default:
1531 (void)printf("\nunknown option %x", *cp);
1532 break;
1533 }
1534 if (!(options & F_FLOOD)) {
1535 (void)putchar('\n');
1536 (void)fflush(stdout);
1537 }
1538}
1539
1540/*
1541 * in_cksum --
1542 * Checksum routine for Internet Protocol family headers (C Version)
1543 */
2b484d24 1544u_short
9dc66a05 1545in_cksum(u_short *addr, int len)
b7080c8e 1546{
2b484d24
A
1547 int nleft, sum;
1548 u_short *w;
1549 union {
1550 u_short us;
1551 u_char uc[2];
1552 } last;
1553 u_short answer;
1554
1555 nleft = len;
1556 sum = 0;
1557 w = addr;
b7080c8e
A
1558
1559 /*
1560 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1561 * sequential 16 bit words to it, and at the end, fold back all the
1562 * carry bits from the top 16 bits into the lower 16 bits.
1563 */
1564 while (nleft > 1) {
1565 sum += *w++;
1566 nleft -= 2;
1567 }
1568
1569 /* mop up an odd byte, if necessary */
1570 if (nleft == 1) {
2b484d24
A
1571 last.uc[0] = *(u_char *)w;
1572 last.uc[1] = 0;
1573 sum += last.us;
b7080c8e
A
1574 }
1575
1576 /* add back carry outs from top 16 bits to low 16 bits */
1577 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1578 sum += (sum >> 16); /* add carry */
1579 answer = ~sum; /* truncate to 16 bits */
1580 return(answer);
1581}
1582
1583/*
1584 * tvsub --
1585 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1586 * be >= in.
1587 */
2b484d24 1588static void
9dc66a05 1589tvsub(struct timeval *out, const struct timeval *in)
b7080c8e 1590{
2b484d24 1591
b7080c8e
A
1592 if ((out->tv_usec -= in->tv_usec) < 0) {
1593 --out->tv_sec;
1594 out->tv_usec += 1000000;
1595 }
1596 out->tv_sec -= in->tv_sec;
1597}
1598
2b484d24
A
1599/*
1600 * status --
1601 * Print out statistics when SIGINFO is received.
1602 */
1603
1604static void
9dc66a05 1605status(int sig __unused)
2b484d24
A
1606{
1607
1608 siginfo_p = 1;
1609}
1610
1611static void
9dc66a05 1612check_status(void)
2b484d24
A
1613{
1614
1615 if (siginfo_p) {
1616 siginfo_p = 0;
9c859447 1617 (void)fprintf(stderr, "\r%ld/%ld packets received (%.1f%%)",
2b484d24
A
1618 nreceived, ntransmitted,
1619 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0);
1620 if (nreceived && timing)
1621 (void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max",
1622 tmin, tsum / (nreceived + nrepeats), tmax);
1623 (void)fprintf(stderr, "\n");
1624 }
1625}
1626
b7080c8e
A
1627/*
1628 * finish --
1629 * Print out statistics, and give up.
1630 */
2b484d24 1631static void
9dc66a05 1632finish(void)
b7080c8e 1633{
b7080c8e
A
1634
1635 (void)signal(SIGINT, SIG_IGN);
2b484d24 1636 (void)signal(SIGALRM, SIG_IGN);
b7080c8e
A
1637 (void)putchar('\n');
1638 (void)fflush(stdout);
1639 (void)printf("--- %s ping statistics ---\n", hostname);
1640 (void)printf("%ld packets transmitted, ", ntransmitted);
1641 (void)printf("%ld packets received, ", nreceived);
1642 if (nrepeats)
1643 (void)printf("+%ld duplicates, ", nrepeats);
2b484d24 1644 if (ntransmitted) {
b7080c8e
A
1645 if (nreceived > ntransmitted)
1646 (void)printf("-- somebody's printing up packets!");
1647 else
9c859447
A
1648 (void)printf("%.1f%% packet loss",
1649 ((ntransmitted - nreceived) * 100.0) /
1650 ntransmitted);
2b484d24 1651 }
9c859447
A
1652 if (nrcvtimeout)
1653 (void)printf(", %ld packets out of wait time", nrcvtimeout);
b7080c8e
A
1654 (void)putchar('\n');
1655 if (nreceived && timing) {
2b484d24
A
1656 double n = nreceived + nrepeats;
1657 double avg = tsum / n;
1658 double vari = tsumsq / n - avg * avg;
1659 (void)printf(
1660 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1661 tmin, avg, tmax, sqrt(vari));
b7080c8e 1662 }
2b484d24
A
1663
1664 if (nreceived)
1665 exit(0);
1666 else
1667 exit(2);
b7080c8e
A
1668}
1669
1670#ifdef notdef
1671static char *ttab[] = {
1672 "Echo Reply", /* ip + seq + udata */
1673 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
1674 "Source Quench", /* IP */
1675 "Redirect", /* redirect type, gateway, + IP */
1676 "Echo",
1677 "Time Exceeded", /* transit, frag reassem + IP */
1678 "Parameter Problem", /* pointer + IP */
1679 "Timestamp", /* id + seq + three timestamps */
1680 "Timestamp Reply", /* " */
1681 "Info Request", /* id + sq */
1682 "Info Reply" /* " */
1683};
1684#endif
1685
1686/*
1687 * pr_icmph --
1688 * Print a descriptive string about an ICMP header.
1689 */
2b484d24 1690static void
9dc66a05 1691pr_icmph(struct icmp *icp)
b7080c8e 1692{
2b484d24 1693
b7080c8e
A
1694 switch(icp->icmp_type) {
1695 case ICMP_ECHOREPLY:
1696 (void)printf("Echo Reply\n");
1697 /* XXX ID + Seq + Data */
1698 break;
1699 case ICMP_UNREACH:
1700 switch(icp->icmp_code) {
1701 case ICMP_UNREACH_NET:
1702 (void)printf("Destination Net Unreachable\n");
1703 break;
1704 case ICMP_UNREACH_HOST:
1705 (void)printf("Destination Host Unreachable\n");
1706 break;
1707 case ICMP_UNREACH_PROTOCOL:
1708 (void)printf("Destination Protocol Unreachable\n");
1709 break;
1710 case ICMP_UNREACH_PORT:
1711 (void)printf("Destination Port Unreachable\n");
1712 break;
1713 case ICMP_UNREACH_NEEDFRAG:
2b484d24
A
1714 (void)printf("frag needed and DF set (MTU %d)\n",
1715 ntohs(icp->icmp_nextmtu));
b7080c8e
A
1716 break;
1717 case ICMP_UNREACH_SRCFAIL:
1718 (void)printf("Source Route Failed\n");
1719 break;
2b484d24
A
1720 case ICMP_UNREACH_FILTER_PROHIB:
1721 (void)printf("Communication prohibited by filter\n");
1722 break;
b7080c8e
A
1723 default:
1724 (void)printf("Dest Unreachable, Bad Code: %d\n",
1725 icp->icmp_code);
1726 break;
1727 }
1728 /* Print returned IP header information */
1729#ifndef icmp_data
1730 pr_retip(&icp->icmp_ip);
1731#else
1732 pr_retip((struct ip *)icp->icmp_data);
1733#endif
1734 break;
1735 case ICMP_SOURCEQUENCH:
1736 (void)printf("Source Quench\n");
1737#ifndef icmp_data
1738 pr_retip(&icp->icmp_ip);
1739#else
1740 pr_retip((struct ip *)icp->icmp_data);
1741#endif
1742 break;
1743 case ICMP_REDIRECT:
1744 switch(icp->icmp_code) {
1745 case ICMP_REDIRECT_NET:
1746 (void)printf("Redirect Network");
1747 break;
1748 case ICMP_REDIRECT_HOST:
1749 (void)printf("Redirect Host");
1750 break;
1751 case ICMP_REDIRECT_TOSNET:
1752 (void)printf("Redirect Type of Service and Network");
1753 break;
1754 case ICMP_REDIRECT_TOSHOST:
1755 (void)printf("Redirect Type of Service and Host");
1756 break;
1757 default:
1758 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1759 break;
1760 }
2b484d24 1761 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
b7080c8e
A
1762#ifndef icmp_data
1763 pr_retip(&icp->icmp_ip);
1764#else
1765 pr_retip((struct ip *)icp->icmp_data);
1766#endif
1767 break;
1768 case ICMP_ECHO:
1769 (void)printf("Echo Request\n");
1770 /* XXX ID + Seq + Data */
1771 break;
1772 case ICMP_TIMXCEED:
1773 switch(icp->icmp_code) {
1774 case ICMP_TIMXCEED_INTRANS:
1775 (void)printf("Time to live exceeded\n");
1776 break;
1777 case ICMP_TIMXCEED_REASS:
1778 (void)printf("Frag reassembly time exceeded\n");
1779 break;
1780 default:
1781 (void)printf("Time exceeded, Bad Code: %d\n",
1782 icp->icmp_code);
1783 break;
1784 }
1785#ifndef icmp_data
1786 pr_retip(&icp->icmp_ip);
1787#else
1788 pr_retip((struct ip *)icp->icmp_data);
1789#endif
1790 break;
1791 case ICMP_PARAMPROB:
1792 (void)printf("Parameter problem: pointer = 0x%02x\n",
1793 icp->icmp_hun.ih_pptr);
1794#ifndef icmp_data
1795 pr_retip(&icp->icmp_ip);
1796#else
1797 pr_retip((struct ip *)icp->icmp_data);
1798#endif
1799 break;
1800 case ICMP_TSTAMP:
1801 (void)printf("Timestamp\n");
1802 /* XXX ID + Seq + 3 timestamps */
1803 break;
1804 case ICMP_TSTAMPREPLY:
1805 (void)printf("Timestamp Reply\n");
1806 /* XXX ID + Seq + 3 timestamps */
1807 break;
1808 case ICMP_IREQ:
1809 (void)printf("Information Request\n");
1810 /* XXX ID + Seq */
1811 break;
1812 case ICMP_IREQREPLY:
1813 (void)printf("Information Reply\n");
1814 /* XXX ID + Seq */
1815 break;
b7080c8e
A
1816 case ICMP_MASKREQ:
1817 (void)printf("Address Mask Request\n");
1818 break;
b7080c8e
A
1819 case ICMP_MASKREPLY:
1820 (void)printf("Address Mask Reply\n");
1821 break;
2b484d24
A
1822 case ICMP_ROUTERADVERT:
1823 (void)printf("Router Advertisement\n");
1824 break;
1825 case ICMP_ROUTERSOLICIT:
1826 (void)printf("Router Solicitation\n");
1827 break;
b7080c8e
A
1828 default:
1829 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1830 }
1831}
1832
1833/*
1834 * pr_iph --
1835 * Print an IP header with options.
1836 */
2b484d24 1837static void
9dc66a05 1838pr_iph(struct ip *ip)
b7080c8e 1839{
b7080c8e 1840 u_char *cp;
2b484d24 1841 int hlen;
b7080c8e
A
1842
1843 hlen = ip->ip_hl << 2;
1844 cp = (u_char *)ip + 20; /* point to options */
1845
2b484d24 1846 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
b7080c8e 1847 (void)printf(" %1x %1x %02x %04x %04x",
2b484d24
A
1848 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1849 ntohs(ip->ip_id));
1850 (void)printf(" %1lx %04lx",
1851 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1852 (u_long) ntohl(ip->ip_off) & 0x1fff);
1853 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1854 ntohs(ip->ip_sum));
b7080c8e
A
1855 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1856 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
2b484d24 1857 /* dump any option bytes */
b7080c8e
A
1858 while (hlen-- > 20) {
1859 (void)printf("%02x", *cp++);
1860 }
1861 (void)putchar('\n');
1862}
1863
1864/*
1865 * pr_addr --
1866 * Return an ascii host address as a dotted quad and optionally with
1867 * a hostname.
1868 */
2b484d24 1869static char *
9dc66a05 1870pr_addr(struct in_addr ina)
b7080c8e
A
1871{
1872 struct hostent *hp;
2b484d24 1873 static char buf[16 + 3 + MAXHOSTNAMELEN];
b7080c8e
A
1874
1875 if ((options & F_NUMERIC) ||
2b484d24
A
1876 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1877 return inet_ntoa(ina);
b7080c8e 1878 else
2b484d24
A
1879 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1880 inet_ntoa(ina));
b7080c8e
A
1881 return(buf);
1882}
1883
1884/*
1885 * pr_retip --
1886 * Dump some info on a returned (via ICMP) IP packet.
1887 */
2b484d24 1888static void
9dc66a05 1889pr_retip(struct ip *ip)
b7080c8e 1890{
b7080c8e 1891 u_char *cp;
2b484d24 1892 int hlen;
b7080c8e
A
1893
1894 pr_iph(ip);
1895 hlen = ip->ip_hl << 2;
1896 cp = (u_char *)ip + hlen;
1897
1898 if (ip->ip_p == 6)
1899 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1900 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1901 else if (ip->ip_p == 17)
1902 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1903 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1904}
1905
2b484d24 1906static char *
9dc66a05 1907pr_ntime(n_time timestamp)
2b484d24
A
1908{
1909 static char buf[10];
1910 int hour, min, sec;
1911
1912 sec = ntohl(timestamp) / 1000;
1913 hour = sec / 60 / 60;
1914 min = (sec % (60 * 60)) / 60;
1915 sec = (sec % (60 * 60)) % 60;
1916
1917 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1918
1919 return (buf);
1920}
1921
1922static void
9dc66a05 1923fill(char *bp, char *patp)
b7080c8e 1924{
b7080c8e 1925 char *cp;
2b484d24
A
1926 int pat[16];
1927 u_int ii, jj, kk;
b7080c8e 1928
2b484d24
A
1929 for (cp = patp; *cp; cp++) {
1930 if (!isxdigit(*cp))
1931 errx(EX_USAGE,
1932 "patterns must be specified as hex digits");
1933
1934 }
b7080c8e
A
1935 ii = sscanf(patp,
1936 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1937 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1938 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1939 &pat[13], &pat[14], &pat[15]);
1940
1941 if (ii > 0)
2b484d24 1942 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
b7080c8e
A
1943 for (jj = 0; jj < ii; ++jj)
1944 bp[jj + kk] = pat[jj];
1945 if (!(options & F_QUIET)) {
1946 (void)printf("PATTERN: 0x");
1947 for (jj = 0; jj < ii; ++jj)
1948 (void)printf("%02x", bp[jj] & 0xFF);
1949 (void)printf("\n");
1950 }
1951}
1952
26c66ce9
A
1953int
1954str2sotc(const char *str, bool *valid)
342c141e 1955{
26c66ce9 1956 int sotc = -1;
342c141e
A
1957 char *endptr;
1958
26c66ce9
A
1959 *valid = true;
1960
342c141e 1961 if (str == NULL || *str == '\0')
26c66ce9 1962 *valid = false;
342c141e
A
1963 else if (strcasecmp(str, "BK_SYS") == 0)
1964 return SO_TC_BK_SYS;
1965 else if (strcasecmp(str, "BK") == 0)
1966 return SO_TC_BK;
1967 else if (strcasecmp(str, "BE") == 0)
1968 return SO_TC_BE;
1969 else if (strcasecmp(str, "RD") == 0)
1970 return SO_TC_RD;
1971 else if (strcasecmp(str, "OAM") == 0)
1972 return SO_TC_OAM;
1973 else if (strcasecmp(str, "AV") == 0)
1974 return SO_TC_AV;
1975 else if (strcasecmp(str, "RV") == 0)
1976 return SO_TC_RV;
1977 else if (strcasecmp(str, "VI") == 0)
1978 return SO_TC_VI;
1979 else if (strcasecmp(str, "VO") == 0)
1980 return SO_TC_VO;
1981 else if (strcasecmp(str, "CTL") == 0)
1982 return SO_TC_CTL;
1983 else {
26c66ce9 1984 sotc = (int)strtol(str, &endptr, 0);
342c141e 1985 if (*endptr != '\0')
26c66ce9
A
1986 *valid = false;
1987 }
1988 return (sotc);
1989}
1990
1991int
1992str2netservicetype(const char *str, bool *valid)
1993{
1994 int svc = -1;
1995 char *endptr;
1996
1997 *valid = true;
1998
1999 if (str == NULL || *str == '\0')
2000 *valid = false;
2001 else if (strcasecmp(str, "BK") == 0)
2002 return NET_SERVICE_TYPE_BK;
2003 else if (strcasecmp(str, "BE") == 0)
2004 return NET_SERVICE_TYPE_BE;
2005 else if (strcasecmp(str, "VI") == 0)
2006 return NET_SERVICE_TYPE_VI;
2007 else if (strcasecmp(str, "SIG") == 0)
2008 return NET_SERVICE_TYPE_SIG;
2009 else if (strcasecmp(str, "VO") == 0)
2010 return NET_SERVICE_TYPE_VO;
2011 else if (strcasecmp(str, "RV") == 0)
2012 return NET_SERVICE_TYPE_RV;
2013 else if (strcasecmp(str, "AV") == 0)
2014 return NET_SERVICE_TYPE_AV;
2015 else if (strcasecmp(str, "OAM") == 0)
2016 return NET_SERVICE_TYPE_OAM;
2017 else if (strcasecmp(str, "RD") == 0)
2018 return NET_SERVICE_TYPE_RD;
2019 else {
2020 svc = (int)strtol(str, &endptr, 0);
2021 if (*endptr != '\0')
2022 *valid = false;
342c141e
A
2023 }
2024 return (svc);
2025}
2026
26c66ce9
A
2027u_int8_t
2028str2tos(const char *str, bool *valid)
2029{
2030 u_int8_t dscp = -1;
2031 char *endptr;
2032
2033 *valid = true;
2034
2035 if (str == NULL || *str == '\0')
2036 *valid = false;
2037 else if (strcasecmp(str, "DF") == 0)
2038 dscp = _DSCP_DF;
2039 else if (strcasecmp(str, "EF") == 0)
2040 dscp = _DSCP_EF;
2041 else if (strcasecmp(str, "VA") == 0)
2042 dscp = _DSCP_VA;
2043
2044 else if (strcasecmp(str, "CS0") == 0)
2045 dscp = _DSCP_CS0;
2046 else if (strcasecmp(str, "CS1") == 0)
2047 dscp = _DSCP_CS1;
2048 else if (strcasecmp(str, "CS2") == 0)
2049 dscp = _DSCP_CS2;
2050 else if (strcasecmp(str, "CS3") == 0)
2051 dscp = _DSCP_CS3;
2052 else if (strcasecmp(str, "CS4") == 0)
2053 dscp = _DSCP_CS4;
2054 else if (strcasecmp(str, "CS5") == 0)
2055 dscp = _DSCP_CS5;
2056 else if (strcasecmp(str, "CS6") == 0)
2057 dscp = _DSCP_CS6;
2058 else if (strcasecmp(str, "CS7") == 0)
2059 dscp = _DSCP_CS7;
2060
2061 else if (strcasecmp(str, "AF11") == 0)
2062 dscp = _DSCP_AF11;
2063 else if (strcasecmp(str, "AF12") == 0)
2064 dscp = _DSCP_AF12;
2065 else if (strcasecmp(str, "AF13") == 0)
2066 dscp = _DSCP_AF13;
2067 else if (strcasecmp(str, "AF21") == 0)
2068 dscp = _DSCP_AF21;
2069 else if (strcasecmp(str, "AF22") == 0)
2070 dscp = _DSCP_AF22;
2071 else if (strcasecmp(str, "AF23") == 0)
2072 dscp = _DSCP_AF23;
2073 else if (strcasecmp(str, "AF31") == 0)
2074 dscp = _DSCP_AF31;
2075 else if (strcasecmp(str, "AF32") == 0)
2076 dscp = _DSCP_AF32;
2077 else if (strcasecmp(str, "AF33") == 0)
2078 dscp = _DSCP_AF33;
2079 else if (strcasecmp(str, "AF41") == 0)
2080 dscp = _DSCP_AF41;
2081 else if (strcasecmp(str, "AF42") == 0)
2082 dscp = _DSCP_AF42;
2083 else if (strcasecmp(str, "AF43") == 0)
2084 dscp = _DSCP_AF43;
2085
2086 else {
2087 unsigned long val = strtoul(str, &endptr, 0);
2088 if (*endptr != '\0' || val > 255)
2089 *valid = false;
2090 else
2091 return ((u_int8_t)val);
2092 }
2093 /* DSCP occupies the 6 upper bits of the TOS field */
2094 return (dscp << 2);
2095}
2096
2097void
2098pr_currenttime(void)
2099{
2100 int s;
2101 struct timeval tv;
2102
2103 gettimeofday(&tv, NULL);
2104
2105 s = (tv.tv_sec + thiszone) % 86400;
2106 printf("%02d:%02d:%02d.%06u ", s / 3600, (s % 3600) / 60, s % 60,
2107 (u_int32_t)tv.tv_usec);
2108}
2109
2b484d24
A
2110#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
2111#define SECOPT " [-P policy]"
2112#else
2113#define SECOPT ""
2114#endif
2115static void
9dc66a05 2116usage(void)
b7080c8e 2117{
2b484d24 2118
342c141e 2119 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
26c66ce9
A
2120"usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize]",
2121" [-g sweepminsize] [-h sweepincrsize] [-i wait]",
342c141e 2122" [-l preload] [-M mask | time] [-m ttl]" SECOPT " [-p pattern]",
26c66ce9
A
2123" [-S src_addr] [-s packetsize] [-t timeout][-W waittime]",
2124" [-z tos] host",
2125" ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait]",
2126" [-l preload] [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]",
9c859447
A
2127" [-s packetsize] [-T ttl] [-t timeout] [-W waittime]",
2128" [-z tos] mcast-group");
26c66ce9
A
2129 (void)fprintf(stderr, "Apple specific options (to be specified before mcast-group or host like all options)\n");
2130 (void)fprintf(stderr, " -b boundif # bind the socket to the interface\n");
2131 (void)fprintf(stderr, " -k traffic_class # set traffic class socket option\n");
2132 (void)fprintf(stderr, " -K net_service_type # set traffic class socket options\n");
2133 (void)fprintf(stderr, " -apple-connect # call connect(2) in the socket\n");
2134 (void)fprintf(stderr, " -apple-time # display current time\n");
2b484d24 2135 exit(EX_USAGE);
b7080c8e 2136}