source: rtems/cpukit/libmisc/shell/main_ping.c @ 56ed56a6

4.115
Last change on this file since 56ed56a6 was 56ed56a6, checked in by Chris Johns <chrisj@…>, on 10/03/14 at 22:55:12

libmisc/shell: Remove the need for -lm when linking from the ping command.

Remove the use of sqrt and so the need to link to -lm.
Clean up some warnings.

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