source: rtems/cpukit/libmisc/shell/main_ping.c @ a8fa078

4.115
Last change on this file since a8fa078 was a8fa078, checked in by Chris Johns <chrisj@…>, on 09/14/14 at 22:00:18

shell: Add a ping command.

The ping code is taken from a recent FreeBSD release. Some options have been
tested, other not tested or do not work. This could be due to the age of
our TCP/IP stack.

This version of ping will not work if more than 64 file descriptors are
open at once because the select FD size is 64 as set in newlib.

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