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

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

Simplify getopt() to getopt_r() translation

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