source: rtems-libbsd/freebsd/sbin/ping/ping.c @ e48f5465

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since e48f5465 was e48f5465, checked in by Sebastian Huber <sebastian.huber@…>, on 10/31/13 at 12:04:31

PING(8): Fix initialization and cleanup

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