source: rtems-libbsd/freebsd-userspace/commands/sbin/ping/ping.c @ 234dfb8

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 234dfb8 was 234dfb8, checked in by Joel Sherrill <joel.sherrill@…>, on 09/01/12 at 00:33:20

ping/ping6: Use getopt_r and make main unique for RTEMS

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