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

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

PING(8): Use local scope for global variables

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