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

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since efb82b8 was b4d6afd, checked in by Sebastian Huber <sebastian.huber@…>, on 11/12/13 at 08:40:54

commands: Use REQUIRE_ORDER option processing

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