]> git.saurik.com Git - apple/network_cmds.git/blame - ping.tproj/ping.c
network_cmds-596.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));
e0b07f2d
A
657 (void)strlcpy(snamebuf, hp->h_name,
658 sizeof(snamebuf));
2b484d24
A
659 shostname = snamebuf;
660 }
661 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1)
26c66ce9
A
662#if (DEBUG || DEVELOPMENT)
663 options |= F_HDRINCL;
664#else
2b484d24 665 err(1, "bind");
26c66ce9 666#endif /* DEBUG || DEVELOPMENT */
2b484d24 667 }
b7080c8e 668
2b484d24
A
669 bzero(&whereto, sizeof(whereto));
670 to = &whereto;
b7080c8e 671 to->sin_family = AF_INET;
2b484d24
A
672 to->sin_len = sizeof *to;
673 if (inet_aton(target, &to->sin_addr) != 0) {
b7080c8e 674 hostname = target;
2b484d24
A
675 } else {
676 hp = gethostbyname2(target, AF_INET);
677 if (!hp)
678 errx(EX_NOHOST, "cannot resolve %s: %s",
679 target, hstrerror(h_errno));
680
681 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
682 errx(1, "gethostbyname2 returned an illegal address");
683 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
e0b07f2d 684 (void)strlcpy(hnamebuf, hp->h_name, sizeof(hnamebuf));
b7080c8e
A
685 hostname = hnamebuf;
686 }
687
fdfd5971
A
688 do {
689 struct ifaddrs *ifa_list, *ifa;
690
691 if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr)) || whereto.sin_addr.s_addr == INADDR_BROADCAST) {
692 no_dup = 1;
693 break;
694 }
695
696 if (getifaddrs(&ifa_list) == -1)
697 break;
698 for (ifa = ifa_list; ifa; ifa = ifa->ifa_next) {
699 if (ifa->ifa_addr->sa_family != AF_INET)
700 continue;
701 if ((ifa->ifa_flags & IFF_BROADCAST) == 0 || ifa->ifa_broadaddr == NULL)
702 continue;
703 if (whereto.sin_addr.s_addr != ((struct sockaddr_in*)ifa->ifa_broadaddr)->sin_addr.s_addr)
704 continue;
705 no_dup = 1;
706 break;
707 }
708
709 freeifaddrs(ifa_list);
710 } while (0);
711
2b484d24
A
712 if (options & F_FLOOD && options & F_INTERVAL)
713 errx(EX_USAGE, "-f and -i: incompatible options");
b7080c8e 714
2b484d24
A
715 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
716 errx(EX_USAGE,
717 "-f flag cannot be used with multicast destination");
718 if (options & (F_MIF | F_NOLOOP | F_MTTL)
719 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
720 errx(EX_USAGE,
721 "-I, -L, -T flags cannot be used with unicast destination");
722
b7080c8e 723 if (!(options & F_PINGFILLED))
89c4ed63 724 for (i = TIMEVAL_LEN; i < MAX(datalen, sweepmax); ++i)
b7080c8e
A
725 *datap++ = i;
726
727 ident = getpid() & 0xFFFF;
728
2b484d24
A
729 if (s < 0) {
730 errno = sockerrno;
731 err(EX_OSERR, "socket");
b7080c8e
A
732 }
733 hold = 1;
9dc66a05
A
734 (void) setsockopt(s, SOL_SOCKET, SO_RECV_ANYIF, (char *)&hold,
735 sizeof(hold));
9c859447
A
736 if (ifscope != 0) {
737 if (setsockopt(s, IPPROTO_IP, IP_BOUND_IF,
738 (char *)&ifscope, sizeof (ifscope)) != 0)
739 err(EX_OSERR, "setsockopt(IP_BOUND_IF)");
740 }
fdfd5971
A
741 if (nocell) {
742 if (setsockopt(s, IPPROTO_IP, IP_NO_IFT_CELLULAR,
743 (char *)&nocell, sizeof (nocell)) != 0)
744 err(EX_OSERR, "setsockopt(IP_NO_IFT_CELLULAR)");
745 }
b7080c8e
A
746 if (options & F_SO_DEBUG)
747 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
748 sizeof(hold));
749 if (options & F_SO_DONTROUTE)
750 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
751 sizeof(hold));
26c66ce9
A
752 if (use_sendmsg == 0) {
753 if (net_service_type != -1)
754 if (setsockopt(s, SOL_SOCKET, SO_NET_SERVICE_TYPE,
755 (void *)&net_service_type, sizeof (net_service_type)) != 0)
756 warn("setsockopt(SO_NET_SERVICE_TYPE");
757 if (traffic_class != -1) {
758 if (setsockopt(s, SOL_SOCKET, SO_TRAFFIC_CLASS,
759 (void *)&traffic_class, sizeof (traffic_class)) != 0)
760 warn("setsockopt(SO_TRAFFIC_CLASS");
761
762 }
7af5ce03 763 }
26c66ce9 764 if (use_recvmsg > 0) {
fdfd5971 765 int on = 1;
7af5ce03
A
766 (void) setsockopt(s, SOL_SOCKET, SO_RECV_TRAFFIC_CLASS,
767 (void *)&on, sizeof (on));
5902acfc 768 }
2b484d24
A
769#ifdef IPSEC
770#ifdef IPSEC_POLICY_IPSEC
771 if (options & F_POLICY) {
772 char *buf;
773 if (policy_in != NULL) {
774 buf = ipsec_set_policy(policy_in, strlen(policy_in));
775 if (buf == NULL)
776 errx(EX_CONFIG, "%s", ipsec_strerror());
777 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
778 buf, ipsec_get_policylen(buf)) < 0)
779 err(EX_CONFIG,
780 "ipsec policy cannot be configured");
781 free(buf);
782 }
b7080c8e 783
2b484d24
A
784 if (policy_out != NULL) {
785 buf = ipsec_set_policy(policy_out, strlen(policy_out));
786 if (buf == NULL)
787 errx(EX_CONFIG, "%s", ipsec_strerror());
788 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
789 buf, ipsec_get_policylen(buf)) < 0)
790 err(EX_CONFIG,
791 "ipsec policy cannot be configured");
792 free(buf);
793 }
794 }
795#endif /*IPSEC_POLICY_IPSEC*/
796#endif /*IPSEC*/
797
798 if (options & F_HDRINCL) {
799 ip = (struct ip*)outpackhdr;
800 if (!(options & (F_TTL | F_MTTL))) {
801 mib[0] = CTL_NET;
802 mib[1] = PF_INET;
803 mib[2] = IPPROTO_IP;
804 mib[3] = IPCTL_DEFTTL;
805 sz = sizeof(ttl);
806 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
807 err(1, "sysctl(net.inet.ip.ttl)");
808 }
809 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
810 ip->ip_v = IPVERSION;
811 ip->ip_hl = sizeof(struct ip) >> 2;
812 ip->ip_tos = tos;
813 ip->ip_id = 0;
814 ip->ip_off = df ? IP_DF : 0;
815 ip->ip_ttl = ttl;
816 ip->ip_p = IPPROTO_ICMP;
817 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
818 ip->ip_dst = to->sin_addr;
819 }
b7080c8e
A
820 /* record route option */
821 if (options & F_RROUTE) {
822#ifdef IP_OPTIONS
2b484d24 823 bzero(rspace, sizeof(rspace));
b7080c8e 824 rspace[IPOPT_OPTVAL] = IPOPT_RR;
2b484d24 825 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
b7080c8e 826 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
2b484d24 827 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
b7080c8e 828 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
2b484d24
A
829 sizeof(rspace)) < 0)
830 err(EX_OSERR, "setsockopt IP_OPTIONS");
b7080c8e 831#else
2b484d24
A
832 errx(EX_UNAVAILABLE,
833 "record route not available in this implementation");
b7080c8e
A
834#endif /* IP_OPTIONS */
835 }
836
2b484d24
A
837 if (options & F_TTL) {
838 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
839 sizeof(ttl)) < 0) {
840 err(EX_OSERR, "setsockopt IP_TTL");
841 }
842 }
843 if (options & F_NOLOOP) {
844 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
845 sizeof(loop)) < 0) {
846 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
847 }
848 }
849 if (options & F_MTTL) {
850 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
851 sizeof(mttl)) < 0) {
852 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
853 }
854 }
855 if (options & F_MIF) {
856 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
857 sizeof(ifaddr)) < 0) {
858 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
859 }
860 }
861#ifdef SO_TIMESTAMP
862 { int on = 1;
863 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
864 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
865 }
866#endif
26c66ce9
A
867
868 if ((options & F_CONNECT)) {
869 if (connect(s, (struct sockaddr *)&whereto, sizeof whereto) == -1)
870 err(EX_OSERR, "connect");
871 }
872
9c859447
A
873 if (sweepmax) {
874 if (sweepmin >= sweepmax)
875 errx(EX_USAGE, "Maximum packet size must be greater than the minimum packet size");
876
877 if (datalen != DEFDATALEN)
878 errx(EX_USAGE, "Packet size and ping sweep are mutually exclusive");
879
880 if (npackets > 0) {
881 snpackets = npackets;
882 npackets = 0;
883 } else
884 snpackets = 1;
885 datalen = sweepmin;
886 send_len = icmp_len + sweepmin;
887 }
888 if (options & F_SWEEP && !sweepmax)
889 errx(EX_USAGE, "Maximum sweep size must be specified");
2b484d24 890
b7080c8e
A
891 /*
892 * When pinging the broadcast address, you can get a lot of answers.
893 * Doing something so evil is useful if you are trying to stress the
894 * ethernet, or just want to fill the arp cache to get some stuff for
2b484d24
A
895 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
896 * or multicast pings if they wish.
b7080c8e 897 */
b7080c8e 898
2b484d24
A
899 /*
900 * XXX receive buffer needs undetermined space for mbuf overhead
901 * as well.
902 */
903 hold = IP_MAXPACKET + 128;
904 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
905 sizeof(hold));
906 if (uid == 0)
907 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
908 sizeof(hold));
909
910 if (to->sin_family == AF_INET) {
911 (void)printf("PING %s (%s)", hostname,
912 inet_ntoa(to->sin_addr));
913 if (source)
914 (void)printf(" from %s", shostname);
9c859447
A
915 if (sweepmax)
916 (void)printf(": (%d ... %d) data bytes\n",
917 sweepmin, sweepmax);
918 else
919 (void)printf(": %d data bytes\n", datalen);
920
921 } else {
922 if (sweepmax)
923 (void)printf("PING %s: (%d ... %d) data bytes\n",
924 hostname, sweepmin, sweepmax);
925 else
926 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
927 }
b7080c8e 928
26c66ce9
A
929 /*
930 * rdar://25829310
931 *
932 * Clear blocked signals inherited from the parent
933 */
934 sigset_t newset;
935 sigemptyset(&newset);
936 if (sigprocmask(SIG_SETMASK, &newset, NULL) != 0)
937 err(EX_OSERR, "sigprocmask(newset)");
938
2b484d24
A
939 /*
940 * Use sigaction() instead of signal() to get unambiguous semantics,
941 * in particular with SA_RESTART not set.
942 */
943
944 sigemptyset(&si_sa.sa_mask);
945 si_sa.sa_flags = 0;
b7080c8e 946
2b484d24
A
947 si_sa.sa_handler = stopit;
948 if (sigaction(SIGINT, &si_sa, 0) == -1) {
949 err(EX_OSERR, "sigaction SIGINT");
950 }
9dc66a05
A
951 si_sa.sa_handler = stopit;
952 if (sigaction(SIGQUIT, &si_sa, 0) == -1) {
953 err(EX_OSERR, "sigaction SIGQUIT");
954 }
955
2b484d24
A
956 si_sa.sa_handler = status;
957 if (sigaction(SIGINFO, &si_sa, 0) == -1) {
9dc66a05 958 err(EX_OSERR, "sigaction SIGINFO");
2b484d24 959 }
b7080c8e 960
9dc66a05 961 if (alarmtimeout > 0) {
2b484d24
A
962 si_sa.sa_handler = stopit;
963 if (sigaction(SIGALRM, &si_sa, 0) == -1)
964 err(EX_OSERR, "sigaction SIGALRM");
9dc66a05 965 }
2b484d24
A
966
967 bzero(&msg, sizeof(msg));
968 msg.msg_name = (caddr_t)&from;
969 msg.msg_iov = &iov;
970 msg.msg_iovlen = 1;
971#ifdef SO_TIMESTAMP
972 msg.msg_control = (caddr_t)ctrl;
973#endif
974 iov.iov_base = packet;
975 iov.iov_len = IP_MAXPACKET;
b7080c8e 976
2b484d24
A
977 if (preload == 0)
978 pinger(); /* send the first ping */
979 else {
980 if (npackets != 0 && preload > npackets)
981 preload = npackets;
982 while (preload--) /* fire off them quickies */
b7080c8e 983 pinger();
2b484d24
A
984 }
985 (void)gettimeofday(&last, NULL);
986
987 if (options & F_FLOOD) {
988 intvl.tv_sec = 0;
989 intvl.tv_usec = 10000;
990 } else {
991 intvl.tv_sec = interval / 1000;
992 intvl.tv_usec = interval % 1000 * 1000;
993 }
994
995 almost_done = 0;
996 while (!finish_up) {
997 struct timeval now, timeout;
998 fd_set rfds;
999 int cc, n;
fdfd5971 1000 int tc = -1;
2b484d24
A
1001
1002 check_status();
1003 if ((unsigned)s >= FD_SETSIZE)
1004 errx(EX_OSERR, "descriptor too large");
1005 FD_ZERO(&rfds);
1006 FD_SET(s, &rfds);
1007 (void)gettimeofday(&now, NULL);
1008 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
1009 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
1010 while (timeout.tv_usec < 0) {
1011 timeout.tv_usec += 1000000;
1012 timeout.tv_sec--;
b7080c8e 1013 }
2b484d24
A
1014 while (timeout.tv_usec >= 1000000) {
1015 timeout.tv_usec -= 1000000;
1016 timeout.tv_sec++;
1017 }
1018 if (timeout.tv_sec < 0)
1019 timeout.tv_sec = timeout.tv_usec = 0;
1020 n = select(s + 1, &rfds, NULL, NULL, &timeout);
1021 if (n < 0)
1022 continue; /* Must be EINTR. */
1023 if (n == 1) {
1024 struct timeval *tv = NULL;
1025#ifdef SO_TIMESTAMP
26c66ce9 1026 struct cmsghdr *cmsg;
2b484d24
A
1027
1028 msg.msg_controllen = sizeof(ctrl);
1029#endif
1030 msg.msg_namelen = sizeof(from);
1031 if ((cc = recvmsg(s, &msg, 0)) < 0) {
1032 if (errno == EINTR)
1033 continue;
1034 warn("recvmsg");
b7080c8e 1035 continue;
2b484d24 1036 }
fdfd5971 1037 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
9dc66a05 1038#ifdef SO_TIMESTAMP
fdfd5971
A
1039 if (cmsg->cmsg_level == SOL_SOCKET &&
1040 cmsg->cmsg_type == SCM_TIMESTAMP &&
1041 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
1042 /* Copy to avoid alignment problems: */
1043 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
1044 tv = &now;
1045 }
9dc66a05 1046#endif
fdfd5971
A
1047 if (cmsg->cmsg_level == SOL_SOCKET &&
1048 cmsg->cmsg_type == SO_TRAFFIC_CLASS &&
1049 cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
1050 /* Copy to avoid alignment problems: */
1051 memcpy(&tc, CMSG_DATA(cmsg), sizeof(tc));
1052 }
2b484d24 1053 }
2b484d24
A
1054 if (tv == NULL) {
1055 (void)gettimeofday(&now, NULL);
1056 tv = &now;
1057 }
fdfd5971 1058 pr_pack((char *)packet, cc, &from, tv, tc);
2b484d24
A
1059 if ((options & F_ONCE && nreceived) ||
1060 (npackets && nreceived >= npackets))
1061 break;
1062 }
1063 if (n == 0 || options & F_FLOOD) {
9c859447 1064 if (sweepmax && sntransmitted == snpackets) {
9c859447
A
1065 datalen += sweepincr;
1066 if (datalen > sweepmax)
1067 break;
1068 send_len = icmp_len + datalen;
1069 sntransmitted = 0;
1070 }
2b484d24
A
1071 if (!npackets || ntransmitted < npackets)
1072 pinger();
1073 else {
1074 if (almost_done)
1075 break;
1076 almost_done = 1;
1077 intvl.tv_usec = 0;
1078 if (nreceived) {
1079 intvl.tv_sec = 2 * tmax / 1000;
1080 if (!intvl.tv_sec)
1081 intvl.tv_sec = 1;
9c859447
A
1082 } else {
1083 intvl.tv_sec = waittime / 1000;
1084 intvl.tv_usec = waittime % 1000 * 1000;
1085 }
2b484d24
A
1086 }
1087 (void)gettimeofday(&last, NULL);
1088 if (ntransmitted - nreceived - 1 > nmissedmax) {
1089 nmissedmax = ntransmitted - nreceived - 1;
1090 if (options & F_MISSED)
1091 (void)write(STDOUT_FILENO, &BBELL, 1);
89c4ed63
A
1092 if (!(options & F_QUIET)) {
1093 printf("Request timeout for icmp_seq %u\n",
1094 (uint16_t)(ntransmitted - 2));
1095 if (!(options & F_FLOOD))
1096 (void)fflush(stdout);
1097 }
2b484d24 1098 }
b7080c8e 1099 }
b7080c8e
A
1100 }
1101 finish();
1102 /* NOTREACHED */
2b484d24 1103 exit(0); /* Make the compiler happy */
b7080c8e
A
1104}
1105
1106/*
2b484d24
A
1107 * stopit --
1108 * Set the global bit that causes the main loop to quit.
1109 * Do NOT call finish() from here, since finish() does far too much
1110 * to be called from a signal handler.
b7080c8e
A
1111 */
1112void
9dc66a05 1113stopit(int sig __unused)
b7080c8e 1114{
b7080c8e 1115
2b484d24
A
1116 /*
1117 * When doing reverse DNS lookups, the finish_up flag might not
1118 * be noticed for a while. Just exit if we get a second SIGINT.
1119 */
1120 if (!(options & F_NUMERIC) && finish_up)
1121 _exit(nreceived ? 0 : 2);
1122 finish_up = 1;
b7080c8e
A
1123}
1124
1125/*
1126 * pinger --
1127 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1128 * will be added on by the kernel. The ID field is our UNIX process ID,
2b484d24
A
1129 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
1130 * bytes of the data portion are used to hold a UNIX "timeval" struct in
1131 * host byte-order, to compute the round-trip time.
b7080c8e 1132 */
2b484d24
A
1133static void
1134pinger(void)
b7080c8e 1135{
2b484d24 1136 struct timeval now;
9c859447 1137 struct tv32 tv32;
2b484d24
A
1138 struct ip *ip;
1139 struct icmp *icp;
1140 int cc, i;
1141 u_char *packet;
b7080c8e 1142
2b484d24 1143 packet = outpack;
b7080c8e 1144 icp = (struct icmp *)outpack;
2b484d24 1145 icp->icmp_type = icmp_type;
b7080c8e
A
1146 icp->icmp_code = 0;
1147 icp->icmp_cksum = 0;
2b484d24 1148 icp->icmp_seq = htons(ntransmitted);
b7080c8e
A
1149 icp->icmp_id = ident; /* ID */
1150
2b484d24 1151 CLR(ntransmitted % mx_dup_ck);
b7080c8e 1152
26c66ce9
A
1153 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
1154 timing = 1;
1155 else
1156 timing = 0;
1157
2b484d24
A
1158 if ((options & F_TIME) || timing) {
1159 (void)gettimeofday(&now, NULL);
b7080c8e 1160
9c859447
A
1161 tv32.tv32_sec = htonl(now.tv_sec);
1162 tv32.tv32_usec = htonl(now.tv_usec);
2b484d24
A
1163 if (options & F_TIME)
1164 icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
1165 * 1000 + now.tv_usec / 1000);
1166 if (timing)
9c859447 1167 bcopy((void *)&tv32,
2b484d24 1168 (void *)&outpack[ICMP_MINLEN + phdr_len],
9c859447 1169 sizeof(tv32));
2b484d24
A
1170 }
1171
1172 cc = ICMP_MINLEN + phdr_len + datalen;
b7080c8e
A
1173
1174 /* compute ICMP checksum here */
1175 icp->icmp_cksum = in_cksum((u_short *)icp, cc);
1176
2b484d24
A
1177 if (options & F_HDRINCL) {
1178 cc += sizeof(struct ip);
1179 ip = (struct ip *)outpackhdr;
1180 ip->ip_len = cc;
1181 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
1182 packet = outpackhdr;
1183 }
26c66ce9 1184 if (use_sendmsg > 0) {
5902acfc
A
1185 struct msghdr msg;
1186 struct iovec iov;
26c66ce9 1187 char cmbuf[2 * CMSG_SPACE(sizeof(int))];
5902acfc
A
1188 struct cmsghdr *cm = (struct cmsghdr *)cmbuf;
1189
26c66ce9
A
1190 if ((options & F_CONNECT)) {
1191 msg.msg_name = NULL;
1192 msg.msg_namelen = 0;
1193 } else {
5902acfc
A
1194 msg.msg_name = &whereto;
1195 msg.msg_namelen = sizeof(whereto);
26c66ce9 1196 }
5902acfc
A
1197 iov.iov_base = packet;
1198 iov.iov_len = cc;
1199 msg.msg_iov = &iov;
1200 msg.msg_iovlen = 1;
1201
26c66ce9
A
1202 msg.msg_controllen = 0;
1203 msg.msg_control = NULL;
1204
1205 if (traffic_class >= 0) {
1206 cm->cmsg_len = CMSG_LEN(sizeof(int));
1207 cm->cmsg_level = SOL_SOCKET;
1208 cm->cmsg_type = SO_TRAFFIC_CLASS;
1209 *(int *)CMSG_DATA(cm) = traffic_class;
1210 msg.msg_controllen += CMSG_SPACE(sizeof(int));
1211 cm = (struct cmsghdr *)(((char *)cm) + CMSG_SPACE(sizeof(int)));
1212 }
1213 if (net_service_type >= 0) {
1214 cm->cmsg_len = CMSG_LEN(sizeof(int));
1215 cm->cmsg_level = SOL_SOCKET;
1216 cm->cmsg_type = SO_NET_SERVICE_TYPE;
1217 msg.msg_controllen += CMSG_SPACE(sizeof(int));
1218 *(int *)CMSG_DATA(cm) = net_service_type;
1219 }
1220 msg.msg_control = cmbuf;
5902acfc
A
1221
1222 msg.msg_flags = 0;
1223
1224 i = sendmsg(s, &msg, 0);
1225 } else {
26c66ce9
A
1226 if ((options & F_CONNECT)) {
1227 i = send(s, (char *)packet, cc, 0);
1228 } else {
5902acfc
A
1229 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
1230 sizeof(whereto));
1231 }
26c66ce9 1232 }
b7080c8e 1233 if (i < 0 || i != cc) {
2b484d24
A
1234 if (i < 0) {
1235 if (options & F_FLOOD && errno == ENOBUFS) {
1236 usleep(FLOOD_BACKOFF);
1237 return;
1238 }
1239 warn("sendto");
1240 } else {
1241 warn("%s: partial write: %d of %d bytes",
1242 hostname, i, cc);
1243 }
b7080c8e 1244 }
2b484d24 1245 ntransmitted++;
9c859447 1246 sntransmitted++;
b7080c8e
A
1247 if (!(options & F_QUIET) && options & F_FLOOD)
1248 (void)write(STDOUT_FILENO, &DOT, 1);
1249}
1250
1251/*
1252 * pr_pack --
1253 * Print out the packet, if it came from us. This logic is necessary
1254 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1255 * which arrive ('tis only fair). This permits multiple copies of this
1256 * program to be run without having intermingled output (or statistics!).
1257 */
2b484d24 1258static void
9dc66a05
A
1259pr_pack(char *buf, int cc, struct sockaddr_in *from, struct timeval *tv,
1260 int tc)
b7080c8e 1261{
2b484d24
A
1262 struct in_addr ina;
1263 u_char *cp, *dp;
1264 struct icmp *icp;
b7080c8e 1265 struct ip *ip;
2b484d24 1266 const void *tp;
b7080c8e 1267 double triptime;
2b484d24
A
1268 int dupflag, hlen, i, j, recv_len, seq;
1269 static int old_rrlen;
1270 static char old_rr[MAX_IPOPTLEN];
b7080c8e
A
1271
1272 /* Check the IP header */
1273 ip = (struct ip *)buf;
1274 hlen = ip->ip_hl << 2;
2b484d24 1275 recv_len = cc;
b7080c8e
A
1276 if (cc < hlen + ICMP_MINLEN) {
1277 if (options & F_VERBOSE)
2b484d24
A
1278 warn("packet too short (%d bytes) from %s", cc,
1279 inet_ntoa(from->sin_addr));
b7080c8e
A
1280 return;
1281 }
1282
1283 /* Now the ICMP part */
1284 cc -= hlen;
1285 icp = (struct icmp *)(buf + hlen);
2b484d24 1286 if (icp->icmp_type == icmp_type_rsp) {
b7080c8e
A
1287 if (icp->icmp_id != ident)
1288 return; /* 'Twas not our ECHO */
1289 ++nreceived;
2b484d24 1290 triptime = 0.0;
b7080c8e 1291 if (timing) {
2b484d24 1292 struct timeval tv1;
9c859447 1293 struct tv32 tv32;
b7080c8e 1294#ifndef icmp_data
2b484d24 1295 tp = &icp->icmp_ip;
b7080c8e 1296#else
2b484d24 1297 tp = icp->icmp_data;
b7080c8e 1298#endif
2b484d24
A
1299 tp = (const char *)tp + phdr_len;
1300
1301 if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) {
1302 /* Copy to avoid alignment problems: */
9c859447
A
1303 memcpy(&tv32, tp, sizeof(tv32));
1304 tv1.tv_sec = ntohl(tv32.tv32_sec);
1305 tv1.tv_usec = ntohl(tv32.tv32_usec);
2b484d24
A
1306 tvsub(tv, &tv1);
1307 triptime = ((double)tv->tv_sec) * 1000.0 +
1308 ((double)tv->tv_usec) / 1000.0;
1309 tsum += triptime;
1310 tsumsq += triptime * triptime;
1311 if (triptime < tmin)
1312 tmin = triptime;
1313 if (triptime > tmax)
1314 tmax = triptime;
1315 } else
1316 timing = 0;
b7080c8e
A
1317 }
1318
2b484d24
A
1319 seq = ntohs(icp->icmp_seq);
1320
1321 if (TST(seq % mx_dup_ck)) {
b7080c8e
A
1322 ++nrepeats;
1323 --nreceived;
1324 dupflag = 1;
1325 } else {
2b484d24 1326 SET(seq % mx_dup_ck);
b7080c8e
A
1327 dupflag = 0;
1328 }
1329
1330 if (options & F_QUIET)
1331 return;
9c859447
A
1332
1333 if (options & F_WAITTIME && triptime > waittime) {
1334 ++nrcvtimeout;
1335 return;
1336 }
b7080c8e
A
1337
1338 if (options & F_FLOOD)
1339 (void)write(STDOUT_FILENO, &BSPACE, 1);
1340 else {
89c4ed63
A
1341 int seq_sent_len = send_len;
1342 int seq_datalen = datalen;
1343
1344 if (sweepmax != 0) {
1345 /*
1346 * When sweeping take in account the length of that
1347 * was sent based on the sequence number
1348 */
1349 seq_datalen = sweepmin + (seq / snpackets) * sweepincr;
1350 seq_sent_len = icmp_len + seq_datalen;
1351 }
26c66ce9
A
1352 if (options & F_PRTIME)
1353 pr_currenttime();
b7080c8e
A
1354 (void)printf("%d bytes from %s: icmp_seq=%u", cc,
1355 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
2b484d24 1356 seq);
b7080c8e
A
1357 (void)printf(" ttl=%d", ip->ip_ttl);
1358 if (timing)
2b484d24 1359 (void)printf(" time=%.3f ms", triptime);
fdfd5971
A
1360 if (tc != -1) {
1361 (void)printf(" tc=%d", tc);
1362 }
1363 if (dupflag && no_dup == 0) {
1364 (void)printf(" (DUP!)");
9c859447 1365 }
2b484d24
A
1366 if (options & F_AUDIBLE)
1367 (void)write(STDOUT_FILENO, &BBELL, 1);
1368 if (options & F_MASK) {
1369 /* Just prentend this cast isn't ugly */
1370 (void)printf(" mask=%s",
1371 pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1372 }
1373 if (options & F_TIME) {
1374 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1375 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1376 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1377 }
89c4ed63 1378 if (recv_len != seq_sent_len) {
2b484d24
A
1379 (void)printf(
1380 "\nwrong total length %d instead of %d",
89c4ed63 1381 recv_len, seq_sent_len);
2b484d24 1382 }
b7080c8e 1383 /* check the data */
2b484d24
A
1384 cp = (u_char*)&icp->icmp_data[phdr_len];
1385 dp = &outpack[ICMP_MINLEN + phdr_len];
1386 cc -= ICMP_MINLEN + phdr_len;
1387 i = 0;
1388 if (timing) { /* don't check variable timestamp */
1389 cp += TIMEVAL_LEN;
1390 dp += TIMEVAL_LEN;
1391 cc -= TIMEVAL_LEN;
1392 i += TIMEVAL_LEN;
1393 }
89c4ed63 1394 for (; i < seq_datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
b7080c8e
A
1395 if (*cp != *dp) {
1396 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1397 i, *dp, *cp);
2b484d24 1398 (void)printf("\ncp:");
b7080c8e 1399 cp = (u_char*)&icp->icmp_data[0];
89c4ed63
A
1400 for (i = 0; i < seq_datalen; ++i, ++cp) {
1401 if ((i % 16) == 0)
2b484d24
A
1402 (void)printf("\n\t");
1403 (void)printf("%2x ", *cp);
1404 }
1405 (void)printf("\ndp:");
1406 cp = &outpack[ICMP_MINLEN];
89c4ed63
A
1407 for (i = 0; i < seq_datalen; ++i, ++cp) {
1408 if ((i % 16) == 0)
b7080c8e 1409 (void)printf("\n\t");
2b484d24 1410 (void)printf("%2x ", *cp);
b7080c8e
A
1411 }
1412 break;
1413 }
1414 }
1415 }
1416 } else {
2b484d24
A
1417 /*
1418 * We've got something other than an ECHOREPLY.
1419 * See if it's a reply to something that we sent.
1420 * We can compare IP destination, protocol,
1421 * and ICMP type and ID.
1422 *
1423 * Only print all the error messages if we are running
1424 * as root to avoid leaking information not normally
1425 * available to those not running as root.
1426 */
1427#ifndef icmp_data
1428 struct ip *oip = &icp->icmp_ip;
1429#else
1430 struct ip *oip = (struct ip *)icp->icmp_data;
1431#endif
1432 struct icmp *oicmp = (struct icmp *)(oip + 1);
1433
1434 if (((options & F_VERBOSE) && uid == 0) ||
1435 (!(options & F_QUIET2) &&
1436 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1437 (oip->ip_p == IPPROTO_ICMP) &&
1438 (oicmp->icmp_type == ICMP_ECHO) &&
1439 (oicmp->icmp_id == ident))) {
26c66ce9
A
1440 if (options & F_PRTIME)
1441 pr_currenttime();
2b484d24
A
1442 (void)printf("%d bytes from %s: ", cc,
1443 pr_addr(from->sin_addr));
1444 pr_icmph(icp);
1445 } else
1446 return;
b7080c8e
A
1447 }
1448
1449 /* Display any IP options */
1450 cp = (u_char *)buf + sizeof(struct ip);
1451
1452 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1453 switch (*cp) {
1454 case IPOPT_EOL:
1455 hlen = 0;
1456 break;
1457 case IPOPT_LSRR:
2b484d24
A
1458 case IPOPT_SSRR:
1459 (void)printf(*cp == IPOPT_LSRR ?
1460 "\nLSRR: " : "\nSSRR: ");
1461 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
b7080c8e 1462 hlen -= 2;
2b484d24
A
1463 cp += 2;
1464 if (j >= INADDR_LEN &&
1465 j <= hlen - (int)sizeof(struct ip)) {
b7080c8e 1466 for (;;) {
2b484d24
A
1467 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1468 if (ina.s_addr == 0)
b7080c8e 1469 (void)printf("\t0.0.0.0");
2b484d24
A
1470 else
1471 (void)printf("\t%s",
1472 pr_addr(ina));
1473 hlen -= INADDR_LEN;
1474 cp += INADDR_LEN - 1;
1475 j -= INADDR_LEN;
1476 if (j < INADDR_LEN)
1477 break;
1478 (void)putchar('\n');
1479 }
1480 } else
1481 (void)printf("\t(truncated route)\n");
b7080c8e
A
1482 break;
1483 case IPOPT_RR:
2b484d24
A
1484 j = cp[IPOPT_OLEN]; /* get length */
1485 i = cp[IPOPT_OFFSET]; /* and pointer */
b7080c8e 1486 hlen -= 2;
2b484d24 1487 cp += 2;
b7080c8e
A
1488 if (i > j)
1489 i = j;
2b484d24
A
1490 i = i - IPOPT_MINOFF + 1;
1491 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1492 old_rrlen = 0;
b7080c8e 1493 continue;
2b484d24 1494 }
b7080c8e 1495 if (i == old_rrlen
2b484d24 1496 && !bcmp((char *)cp, old_rr, i)
b7080c8e
A
1497 && !(options & F_FLOOD)) {
1498 (void)printf("\t(same route)");
b7080c8e
A
1499 hlen -= i;
1500 cp += i;
1501 break;
1502 }
2b484d24
A
1503 old_rrlen = i;
1504 bcopy((char *)cp, old_rr, i);
b7080c8e 1505 (void)printf("\nRR: ");
2b484d24
A
1506 if (i >= INADDR_LEN &&
1507 i <= hlen - (int)sizeof(struct ip)) {
1508 for (;;) {
1509 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1510 if (ina.s_addr == 0)
1511 (void)printf("\t0.0.0.0");
1512 else
1513 (void)printf("\t%s",
1514 pr_addr(ina));
1515 hlen -= INADDR_LEN;
1516 cp += INADDR_LEN - 1;
1517 i -= INADDR_LEN;
1518 if (i < INADDR_LEN)
1519 break;
1520 (void)putchar('\n');
b7080c8e 1521 }
2b484d24
A
1522 } else
1523 (void)printf("\t(truncated route)");
b7080c8e
A
1524 break;
1525 case IPOPT_NOP:
1526 (void)printf("\nNOP");
1527 break;
1528 default:
1529 (void)printf("\nunknown option %x", *cp);
1530 break;
1531 }
1532 if (!(options & F_FLOOD)) {
1533 (void)putchar('\n');
1534 (void)fflush(stdout);
1535 }
1536}
1537
1538/*
1539 * in_cksum --
1540 * Checksum routine for Internet Protocol family headers (C Version)
1541 */
2b484d24 1542u_short
9dc66a05 1543in_cksum(u_short *addr, int len)
b7080c8e 1544{
2b484d24
A
1545 int nleft, sum;
1546 u_short *w;
1547 union {
1548 u_short us;
1549 u_char uc[2];
1550 } last;
1551 u_short answer;
1552
1553 nleft = len;
1554 sum = 0;
1555 w = addr;
b7080c8e
A
1556
1557 /*
1558 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1559 * sequential 16 bit words to it, and at the end, fold back all the
1560 * carry bits from the top 16 bits into the lower 16 bits.
1561 */
1562 while (nleft > 1) {
1563 sum += *w++;
1564 nleft -= 2;
1565 }
1566
1567 /* mop up an odd byte, if necessary */
1568 if (nleft == 1) {
2b484d24
A
1569 last.uc[0] = *(u_char *)w;
1570 last.uc[1] = 0;
1571 sum += last.us;
b7080c8e
A
1572 }
1573
1574 /* add back carry outs from top 16 bits to low 16 bits */
1575 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1576 sum += (sum >> 16); /* add carry */
1577 answer = ~sum; /* truncate to 16 bits */
1578 return(answer);
1579}
1580
1581/*
1582 * tvsub --
1583 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1584 * be >= in.
1585 */
2b484d24 1586static void
9dc66a05 1587tvsub(struct timeval *out, const struct timeval *in)
b7080c8e 1588{
2b484d24 1589
b7080c8e
A
1590 if ((out->tv_usec -= in->tv_usec) < 0) {
1591 --out->tv_sec;
1592 out->tv_usec += 1000000;
1593 }
1594 out->tv_sec -= in->tv_sec;
1595}
1596
2b484d24
A
1597/*
1598 * status --
1599 * Print out statistics when SIGINFO is received.
1600 */
1601
1602static void
9dc66a05 1603status(int sig __unused)
2b484d24
A
1604{
1605
1606 siginfo_p = 1;
1607}
1608
1609static void
9dc66a05 1610check_status(void)
2b484d24
A
1611{
1612
1613 if (siginfo_p) {
1614 siginfo_p = 0;
9c859447 1615 (void)fprintf(stderr, "\r%ld/%ld packets received (%.1f%%)",
2b484d24
A
1616 nreceived, ntransmitted,
1617 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0);
1618 if (nreceived && timing)
1619 (void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max",
1620 tmin, tsum / (nreceived + nrepeats), tmax);
1621 (void)fprintf(stderr, "\n");
1622 }
1623}
1624
b7080c8e
A
1625/*
1626 * finish --
1627 * Print out statistics, and give up.
1628 */
2b484d24 1629static void
9dc66a05 1630finish(void)
b7080c8e 1631{
b7080c8e
A
1632
1633 (void)signal(SIGINT, SIG_IGN);
2b484d24 1634 (void)signal(SIGALRM, SIG_IGN);
b7080c8e
A
1635 (void)putchar('\n');
1636 (void)fflush(stdout);
1637 (void)printf("--- %s ping statistics ---\n", hostname);
1638 (void)printf("%ld packets transmitted, ", ntransmitted);
1639 (void)printf("%ld packets received, ", nreceived);
1640 if (nrepeats)
1641 (void)printf("+%ld duplicates, ", nrepeats);
2b484d24 1642 if (ntransmitted) {
b7080c8e
A
1643 if (nreceived > ntransmitted)
1644 (void)printf("-- somebody's printing up packets!");
1645 else
9c859447
A
1646 (void)printf("%.1f%% packet loss",
1647 ((ntransmitted - nreceived) * 100.0) /
1648 ntransmitted);
2b484d24 1649 }
9c859447
A
1650 if (nrcvtimeout)
1651 (void)printf(", %ld packets out of wait time", nrcvtimeout);
b7080c8e
A
1652 (void)putchar('\n');
1653 if (nreceived && timing) {
2b484d24
A
1654 double n = nreceived + nrepeats;
1655 double avg = tsum / n;
1656 double vari = tsumsq / n - avg * avg;
1657 (void)printf(
1658 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1659 tmin, avg, tmax, sqrt(vari));
b7080c8e 1660 }
2b484d24
A
1661
1662 if (nreceived)
1663 exit(0);
1664 else
1665 exit(2);
b7080c8e
A
1666}
1667
1668#ifdef notdef
1669static char *ttab[] = {
1670 "Echo Reply", /* ip + seq + udata */
1671 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
1672 "Source Quench", /* IP */
1673 "Redirect", /* redirect type, gateway, + IP */
1674 "Echo",
1675 "Time Exceeded", /* transit, frag reassem + IP */
1676 "Parameter Problem", /* pointer + IP */
1677 "Timestamp", /* id + seq + three timestamps */
1678 "Timestamp Reply", /* " */
1679 "Info Request", /* id + sq */
1680 "Info Reply" /* " */
1681};
1682#endif
1683
1684/*
1685 * pr_icmph --
1686 * Print a descriptive string about an ICMP header.
1687 */
2b484d24 1688static void
9dc66a05 1689pr_icmph(struct icmp *icp)
b7080c8e 1690{
2b484d24 1691
b7080c8e
A
1692 switch(icp->icmp_type) {
1693 case ICMP_ECHOREPLY:
1694 (void)printf("Echo Reply\n");
1695 /* XXX ID + Seq + Data */
1696 break;
1697 case ICMP_UNREACH:
1698 switch(icp->icmp_code) {
1699 case ICMP_UNREACH_NET:
1700 (void)printf("Destination Net Unreachable\n");
1701 break;
1702 case ICMP_UNREACH_HOST:
1703 (void)printf("Destination Host Unreachable\n");
1704 break;
1705 case ICMP_UNREACH_PROTOCOL:
1706 (void)printf("Destination Protocol Unreachable\n");
1707 break;
1708 case ICMP_UNREACH_PORT:
1709 (void)printf("Destination Port Unreachable\n");
1710 break;
1711 case ICMP_UNREACH_NEEDFRAG:
2b484d24
A
1712 (void)printf("frag needed and DF set (MTU %d)\n",
1713 ntohs(icp->icmp_nextmtu));
b7080c8e
A
1714 break;
1715 case ICMP_UNREACH_SRCFAIL:
1716 (void)printf("Source Route Failed\n");
1717 break;
2b484d24
A
1718 case ICMP_UNREACH_FILTER_PROHIB:
1719 (void)printf("Communication prohibited by filter\n");
1720 break;
b7080c8e
A
1721 default:
1722 (void)printf("Dest Unreachable, Bad Code: %d\n",
1723 icp->icmp_code);
1724 break;
1725 }
1726 /* Print returned IP header information */
1727#ifndef icmp_data
1728 pr_retip(&icp->icmp_ip);
1729#else
1730 pr_retip((struct ip *)icp->icmp_data);
1731#endif
1732 break;
1733 case ICMP_SOURCEQUENCH:
1734 (void)printf("Source Quench\n");
1735#ifndef icmp_data
1736 pr_retip(&icp->icmp_ip);
1737#else
1738 pr_retip((struct ip *)icp->icmp_data);
1739#endif
1740 break;
1741 case ICMP_REDIRECT:
1742 switch(icp->icmp_code) {
1743 case ICMP_REDIRECT_NET:
1744 (void)printf("Redirect Network");
1745 break;
1746 case ICMP_REDIRECT_HOST:
1747 (void)printf("Redirect Host");
1748 break;
1749 case ICMP_REDIRECT_TOSNET:
1750 (void)printf("Redirect Type of Service and Network");
1751 break;
1752 case ICMP_REDIRECT_TOSHOST:
1753 (void)printf("Redirect Type of Service and Host");
1754 break;
1755 default:
1756 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1757 break;
1758 }
2b484d24 1759 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
b7080c8e
A
1760#ifndef icmp_data
1761 pr_retip(&icp->icmp_ip);
1762#else
1763 pr_retip((struct ip *)icp->icmp_data);
1764#endif
1765 break;
1766 case ICMP_ECHO:
1767 (void)printf("Echo Request\n");
1768 /* XXX ID + Seq + Data */
1769 break;
1770 case ICMP_TIMXCEED:
1771 switch(icp->icmp_code) {
1772 case ICMP_TIMXCEED_INTRANS:
1773 (void)printf("Time to live exceeded\n");
1774 break;
1775 case ICMP_TIMXCEED_REASS:
1776 (void)printf("Frag reassembly time exceeded\n");
1777 break;
1778 default:
1779 (void)printf("Time exceeded, Bad Code: %d\n",
1780 icp->icmp_code);
1781 break;
1782 }
1783#ifndef icmp_data
1784 pr_retip(&icp->icmp_ip);
1785#else
1786 pr_retip((struct ip *)icp->icmp_data);
1787#endif
1788 break;
1789 case ICMP_PARAMPROB:
1790 (void)printf("Parameter problem: pointer = 0x%02x\n",
1791 icp->icmp_hun.ih_pptr);
1792#ifndef icmp_data
1793 pr_retip(&icp->icmp_ip);
1794#else
1795 pr_retip((struct ip *)icp->icmp_data);
1796#endif
1797 break;
1798 case ICMP_TSTAMP:
1799 (void)printf("Timestamp\n");
1800 /* XXX ID + Seq + 3 timestamps */
1801 break;
1802 case ICMP_TSTAMPREPLY:
1803 (void)printf("Timestamp Reply\n");
1804 /* XXX ID + Seq + 3 timestamps */
1805 break;
1806 case ICMP_IREQ:
1807 (void)printf("Information Request\n");
1808 /* XXX ID + Seq */
1809 break;
1810 case ICMP_IREQREPLY:
1811 (void)printf("Information Reply\n");
1812 /* XXX ID + Seq */
1813 break;
b7080c8e
A
1814 case ICMP_MASKREQ:
1815 (void)printf("Address Mask Request\n");
1816 break;
b7080c8e
A
1817 case ICMP_MASKREPLY:
1818 (void)printf("Address Mask Reply\n");
1819 break;
2b484d24
A
1820 case ICMP_ROUTERADVERT:
1821 (void)printf("Router Advertisement\n");
1822 break;
1823 case ICMP_ROUTERSOLICIT:
1824 (void)printf("Router Solicitation\n");
1825 break;
b7080c8e
A
1826 default:
1827 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1828 }
1829}
1830
1831/*
1832 * pr_iph --
1833 * Print an IP header with options.
1834 */
2b484d24 1835static void
9dc66a05 1836pr_iph(struct ip *ip)
b7080c8e 1837{
b7080c8e 1838 u_char *cp;
2b484d24 1839 int hlen;
b7080c8e
A
1840
1841 hlen = ip->ip_hl << 2;
1842 cp = (u_char *)ip + 20; /* point to options */
1843
2b484d24 1844 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n");
b7080c8e 1845 (void)printf(" %1x %1x %02x %04x %04x",
2b484d24
A
1846 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1847 ntohs(ip->ip_id));
1848 (void)printf(" %1lx %04lx",
1849 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1850 (u_long) ntohl(ip->ip_off) & 0x1fff);
1851 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1852 ntohs(ip->ip_sum));
b7080c8e
A
1853 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1854 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
2b484d24 1855 /* dump any option bytes */
b7080c8e
A
1856 while (hlen-- > 20) {
1857 (void)printf("%02x", *cp++);
1858 }
1859 (void)putchar('\n');
1860}
1861
1862/*
1863 * pr_addr --
1864 * Return an ascii host address as a dotted quad and optionally with
1865 * a hostname.
1866 */
2b484d24 1867static char *
9dc66a05 1868pr_addr(struct in_addr ina)
b7080c8e
A
1869{
1870 struct hostent *hp;
2b484d24 1871 static char buf[16 + 3 + MAXHOSTNAMELEN];
b7080c8e
A
1872
1873 if ((options & F_NUMERIC) ||
2b484d24
A
1874 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1875 return inet_ntoa(ina);
b7080c8e 1876 else
2b484d24
A
1877 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1878 inet_ntoa(ina));
b7080c8e
A
1879 return(buf);
1880}
1881
1882/*
1883 * pr_retip --
1884 * Dump some info on a returned (via ICMP) IP packet.
1885 */
2b484d24 1886static void
9dc66a05 1887pr_retip(struct ip *ip)
b7080c8e 1888{
b7080c8e 1889 u_char *cp;
2b484d24 1890 int hlen;
b7080c8e
A
1891
1892 pr_iph(ip);
1893 hlen = ip->ip_hl << 2;
1894 cp = (u_char *)ip + hlen;
1895
1896 if (ip->ip_p == 6)
1897 (void)printf("TCP: from port %u, to port %u (decimal)\n",
1898 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1899 else if (ip->ip_p == 17)
1900 (void)printf("UDP: from port %u, to port %u (decimal)\n",
1901 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1902}
1903
2b484d24 1904static char *
9dc66a05 1905pr_ntime(n_time timestamp)
2b484d24
A
1906{
1907 static char buf[10];
1908 int hour, min, sec;
1909
1910 sec = ntohl(timestamp) / 1000;
1911 hour = sec / 60 / 60;
1912 min = (sec % (60 * 60)) / 60;
1913 sec = (sec % (60 * 60)) % 60;
1914
1915 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1916
1917 return (buf);
1918}
1919
1920static void
9dc66a05 1921fill(char *bp, char *patp)
b7080c8e 1922{
b7080c8e 1923 char *cp;
2b484d24
A
1924 int pat[16];
1925 u_int ii, jj, kk;
b7080c8e 1926
2b484d24
A
1927 for (cp = patp; *cp; cp++) {
1928 if (!isxdigit(*cp))
1929 errx(EX_USAGE,
1930 "patterns must be specified as hex digits");
1931
1932 }
b7080c8e
A
1933 ii = sscanf(patp,
1934 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1935 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1936 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1937 &pat[13], &pat[14], &pat[15]);
1938
1939 if (ii > 0)
2b484d24 1940 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
b7080c8e
A
1941 for (jj = 0; jj < ii; ++jj)
1942 bp[jj + kk] = pat[jj];
1943 if (!(options & F_QUIET)) {
1944 (void)printf("PATTERN: 0x");
1945 for (jj = 0; jj < ii; ++jj)
1946 (void)printf("%02x", bp[jj] & 0xFF);
1947 (void)printf("\n");
1948 }
1949}
1950
26c66ce9
A
1951int
1952str2sotc(const char *str, bool *valid)
342c141e 1953{
26c66ce9 1954 int sotc = -1;
342c141e
A
1955 char *endptr;
1956
26c66ce9
A
1957 *valid = true;
1958
342c141e 1959 if (str == NULL || *str == '\0')
26c66ce9 1960 *valid = false;
342c141e
A
1961 else if (strcasecmp(str, "BK_SYS") == 0)
1962 return SO_TC_BK_SYS;
1963 else if (strcasecmp(str, "BK") == 0)
1964 return SO_TC_BK;
1965 else if (strcasecmp(str, "BE") == 0)
1966 return SO_TC_BE;
1967 else if (strcasecmp(str, "RD") == 0)
1968 return SO_TC_RD;
1969 else if (strcasecmp(str, "OAM") == 0)
1970 return SO_TC_OAM;
1971 else if (strcasecmp(str, "AV") == 0)
1972 return SO_TC_AV;
1973 else if (strcasecmp(str, "RV") == 0)
1974 return SO_TC_RV;
1975 else if (strcasecmp(str, "VI") == 0)
1976 return SO_TC_VI;
1977 else if (strcasecmp(str, "VO") == 0)
1978 return SO_TC_VO;
1979 else if (strcasecmp(str, "CTL") == 0)
1980 return SO_TC_CTL;
1981 else {
26c66ce9 1982 sotc = (int)strtol(str, &endptr, 0);
342c141e 1983 if (*endptr != '\0')
26c66ce9
A
1984 *valid = false;
1985 }
1986 return (sotc);
1987}
1988
1989int
1990str2netservicetype(const char *str, bool *valid)
1991{
1992 int svc = -1;
1993 char *endptr;
1994
1995 *valid = true;
1996
1997 if (str == NULL || *str == '\0')
1998 *valid = false;
1999 else if (strcasecmp(str, "BK") == 0)
2000 return NET_SERVICE_TYPE_BK;
2001 else if (strcasecmp(str, "BE") == 0)
2002 return NET_SERVICE_TYPE_BE;
2003 else if (strcasecmp(str, "VI") == 0)
2004 return NET_SERVICE_TYPE_VI;
2005 else if (strcasecmp(str, "SIG") == 0)
2006 return NET_SERVICE_TYPE_SIG;
2007 else if (strcasecmp(str, "VO") == 0)
2008 return NET_SERVICE_TYPE_VO;
2009 else if (strcasecmp(str, "RV") == 0)
2010 return NET_SERVICE_TYPE_RV;
2011 else if (strcasecmp(str, "AV") == 0)
2012 return NET_SERVICE_TYPE_AV;
2013 else if (strcasecmp(str, "OAM") == 0)
2014 return NET_SERVICE_TYPE_OAM;
2015 else if (strcasecmp(str, "RD") == 0)
2016 return NET_SERVICE_TYPE_RD;
2017 else {
2018 svc = (int)strtol(str, &endptr, 0);
2019 if (*endptr != '\0')
2020 *valid = false;
342c141e
A
2021 }
2022 return (svc);
2023}
2024
26c66ce9
A
2025u_int8_t
2026str2tos(const char *str, bool *valid)
2027{
2028 u_int8_t dscp = -1;
2029 char *endptr;
2030
2031 *valid = true;
2032
2033 if (str == NULL || *str == '\0')
2034 *valid = false;
2035 else if (strcasecmp(str, "DF") == 0)
2036 dscp = _DSCP_DF;
2037 else if (strcasecmp(str, "EF") == 0)
2038 dscp = _DSCP_EF;
2039 else if (strcasecmp(str, "VA") == 0)
2040 dscp = _DSCP_VA;
2041
2042 else if (strcasecmp(str, "CS0") == 0)
2043 dscp = _DSCP_CS0;
2044 else if (strcasecmp(str, "CS1") == 0)
2045 dscp = _DSCP_CS1;
2046 else if (strcasecmp(str, "CS2") == 0)
2047 dscp = _DSCP_CS2;
2048 else if (strcasecmp(str, "CS3") == 0)
2049 dscp = _DSCP_CS3;
2050 else if (strcasecmp(str, "CS4") == 0)
2051 dscp = _DSCP_CS4;
2052 else if (strcasecmp(str, "CS5") == 0)
2053 dscp = _DSCP_CS5;
2054 else if (strcasecmp(str, "CS6") == 0)
2055 dscp = _DSCP_CS6;
2056 else if (strcasecmp(str, "CS7") == 0)
2057 dscp = _DSCP_CS7;
2058
2059 else if (strcasecmp(str, "AF11") == 0)
2060 dscp = _DSCP_AF11;
2061 else if (strcasecmp(str, "AF12") == 0)
2062 dscp = _DSCP_AF12;
2063 else if (strcasecmp(str, "AF13") == 0)
2064 dscp = _DSCP_AF13;
2065 else if (strcasecmp(str, "AF21") == 0)
2066 dscp = _DSCP_AF21;
2067 else if (strcasecmp(str, "AF22") == 0)
2068 dscp = _DSCP_AF22;
2069 else if (strcasecmp(str, "AF23") == 0)
2070 dscp = _DSCP_AF23;
2071 else if (strcasecmp(str, "AF31") == 0)
2072 dscp = _DSCP_AF31;
2073 else if (strcasecmp(str, "AF32") == 0)
2074 dscp = _DSCP_AF32;
2075 else if (strcasecmp(str, "AF33") == 0)
2076 dscp = _DSCP_AF33;
2077 else if (strcasecmp(str, "AF41") == 0)
2078 dscp = _DSCP_AF41;
2079 else if (strcasecmp(str, "AF42") == 0)
2080 dscp = _DSCP_AF42;
2081 else if (strcasecmp(str, "AF43") == 0)
2082 dscp = _DSCP_AF43;
2083
2084 else {
2085 unsigned long val = strtoul(str, &endptr, 0);
2086 if (*endptr != '\0' || val > 255)
2087 *valid = false;
2088 else
2089 return ((u_int8_t)val);
2090 }
2091 /* DSCP occupies the 6 upper bits of the TOS field */
2092 return (dscp << 2);
2093}
2094
2095void
2096pr_currenttime(void)
2097{
2098 int s;
2099 struct timeval tv;
2100
2101 gettimeofday(&tv, NULL);
2102
2103 s = (tv.tv_sec + thiszone) % 86400;
2104 printf("%02d:%02d:%02d.%06u ", s / 3600, (s % 3600) / 60, s % 60,
2105 (u_int32_t)tv.tv_usec);
2106}
2107
2b484d24
A
2108#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
2109#define SECOPT " [-P policy]"
2110#else
2111#define SECOPT ""
2112#endif
2113static void
9dc66a05 2114usage(void)
b7080c8e 2115{
2b484d24 2116
342c141e 2117 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
26c66ce9
A
2118"usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize]",
2119" [-g sweepminsize] [-h sweepincrsize] [-i wait]",
342c141e 2120" [-l preload] [-M mask | time] [-m ttl]" SECOPT " [-p pattern]",
26c66ce9
A
2121" [-S src_addr] [-s packetsize] [-t timeout][-W waittime]",
2122" [-z tos] host",
2123" ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait]",
2124" [-l preload] [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]",
9c859447
A
2125" [-s packetsize] [-T ttl] [-t timeout] [-W waittime]",
2126" [-z tos] mcast-group");
26c66ce9
A
2127 (void)fprintf(stderr, "Apple specific options (to be specified before mcast-group or host like all options)\n");
2128 (void)fprintf(stderr, " -b boundif # bind the socket to the interface\n");
2129 (void)fprintf(stderr, " -k traffic_class # set traffic class socket option\n");
2130 (void)fprintf(stderr, " -K net_service_type # set traffic class socket options\n");
2131 (void)fprintf(stderr, " -apple-connect # call connect(2) in the socket\n");
2132 (void)fprintf(stderr, " -apple-time # display current time\n");
2b484d24 2133 exit(EX_USAGE);
b7080c8e 2134}