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

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

PING(8): Delete unused variable

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