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