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