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