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