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

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

PING(8): Fix isxdigit() usage

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