source: trunk/mindi-busybox/networking/ping6.c @ 904

Last change on this file since 904 was 904, checked in by bruno, 13 years ago

merge -r890:902 $SVN_M/branches/stable

File size: 14.2 KB
Line 
1/* vi: set sw=4 ts=4: */
2/*
3 * $Id: ping6.c,v 1.6 2004/03/15 08:28:48 andersen Exp $
4 * Mini ping implementation for busybox
5 *
6 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 *
22 * This version of ping is adapted from the ping in netkit-base 0.10,
23 * which is:
24 *
25 * Copyright (c) 1989 The Regents of the University of California.
26 * All rights reserved.
27 *
28 * This code is derived from software contributed to Berkeley by
29 * Mike Muuss.
30 *
31 * Original copyright notice is retained at the end of this file.
32 *
33 * This version is an adaptation of ping.c from busybox.
34 * The code was modified by Bart Visscher <magick@linux-fan.com>
35 */
36
37#include <sys/param.h>
38#include <sys/socket.h>
39#include <sys/file.h>
40#include <sys/times.h>
41#include <signal.h>
42
43#include <netinet/in.h>
44#include <netinet/ip6.h>
45#include <netinet/icmp6.h>
46#include <arpa/inet.h>
47#include <net/if.h>
48#include <netdb.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <errno.h>
52#include <unistd.h>
53#include <string.h>
54#include <stdlib.h>
55#include <stddef.h>             /* offsetof */
56#include "busybox.h"
57
58enum {
59    DEFDATALEN = 56,
60    MAXIPLEN = 60,
61    MAXICMPLEN = 76,
62    MAXPACKET = 65468,
63    MAX_DUP_CHK = (8 * 128),
64    MAXWAIT = 10,
65    PINGINTERVAL = 1        /* second */
66};
67
68#define O_QUIET         (1 << 0)
69#define O_VERBOSE       (1 << 1)
70
71#define A(bit)      rcvd_tbl[(bit)>>3]  /* identify byte in array */
72#define B(bit)      (1 << ((bit) & 0x07))   /* identify bit in byte */
73#define SET(bit)    (A(bit) |= B(bit))
74#define CLR(bit)    (A(bit) &= (~B(bit)))
75#define TST(bit)    (A(bit) & B(bit))
76
77static void ping(const char *host);
78
79/* simple version */
80#ifndef CONFIG_FEATURE_FANCY_PING6
81static struct hostent *h;
82
83void noresp(int ign)
84{
85    printf("No response from %s\n", h->h_name);
86    exit(EXIT_FAILURE);
87}
88
89static void ping(const char *host)
90{
91    struct sockaddr_in6 pingaddr;
92    struct icmp6_hdr *pkt;
93    int pingsock, c;
94    int sockopt;
95    char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
96
97    pingsock = create_icmp6_socket();
98
99    memset(&pingaddr, 0, sizeof(struct sockaddr_in));
100
101    pingaddr.sin6_family = AF_INET6;
102    h = xgethostbyname2(host, AF_INET6);
103    memcpy(&pingaddr.sin6_addr, h->h_addr, sizeof(pingaddr.sin6_addr));
104
105    pkt = (struct icmp6_hdr *) packet;
106    memset(pkt, 0, sizeof(packet));
107    pkt->icmp6_type = ICMP6_ECHO_REQUEST;
108
109    sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
110    setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, (char *) &sockopt,
111               sizeof(sockopt));
112
113    c = sendto(pingsock, packet, DEFDATALEN + sizeof (struct icmp6_hdr), 0,
114               (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in6));
115
116    if (c < 0 || c != sizeof(packet))
117        bb_perror_msg_and_die("sendto");
118
119    signal(SIGALRM, noresp);
120    alarm(5);                   /* give the host 5000ms to respond */
121    /* listen for replies */
122    while (1) {
123        struct sockaddr_in6 from;
124        size_t fromlen = sizeof(from);
125
126        if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
127                          (struct sockaddr *) &from, &fromlen)) < 0) {
128            if (errno == EINTR)
129                continue;
130            bb_perror_msg("recvfrom");
131            continue;
132        }
133        if (c >= 8) {           /* icmp6_hdr */
134            pkt = (struct icmp6_hdr *) packet;
135            if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
136                break;
137        }
138    }
139    printf("%s is alive!\n", h->h_name);
140    return;
141}
142
143int ping6_main(int argc, char **argv)
144{
145    argc--;
146    argv++;
147    if (argc < 1)
148        bb_show_usage();
149    ping(*argv);
150    return EXIT_SUCCESS;
151}
152
153#else /* ! CONFIG_FEATURE_FANCY_PING6 */
154/* full(er) version */
155static struct sockaddr_in6 pingaddr;
156static int pingsock = -1;
157static int datalen; /* intentionally uninitialized to work around gcc bug */
158static char* ifname;
159
160static long ntransmitted, nreceived, nrepeats, pingcount;
161static int myid, options;
162static unsigned long tmin = ULONG_MAX, tmax, tsum;
163static char rcvd_tbl[MAX_DUP_CHK / 8];
164
165# ifdef CONFIG_FEATURE_FANCY_PING
166extern
167# endif
168    struct hostent *hostent;
169
170static void sendping(int);
171static void pingstats(int);
172static void unpack(char *, int, struct sockaddr_in6 *, int);
173
174/**************************************************************************/
175
176static void pingstats(int junk)
177{
178    int status;
179
180    signal(SIGINT, SIG_IGN);
181
182    printf("\n--- %s ping statistics ---\n", hostent->h_name);
183    printf("%ld packets transmitted, ", ntransmitted);
184    printf("%ld packets received, ", nreceived);
185    if (nrepeats)
186        printf("%ld duplicates, ", nrepeats);
187    if (ntransmitted)
188        printf("%ld%% packet loss\n",
189               (ntransmitted - nreceived) * 100 / ntransmitted);
190    if (nreceived)
191        printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
192               tmin / 10, tmin % 10,
193               (tsum / (nreceived + nrepeats)) / 10,
194               (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
195    if (nreceived != 0)
196        status = EXIT_SUCCESS;
197    else
198        status = EXIT_FAILURE;
199    exit(status);
200}
201
202static void sendping(int junk)
203{
204    struct icmp6_hdr *pkt;
205    int i;
206    char packet[datalen + sizeof (struct icmp6_hdr)];
207
208    pkt = (struct icmp6_hdr *) packet;
209
210    pkt->icmp6_type = ICMP6_ECHO_REQUEST;
211    pkt->icmp6_code = 0;
212    pkt->icmp6_cksum = 0;
213    pkt->icmp6_seq = SWAP_BE16(ntransmitted++);
214    pkt->icmp6_id = myid;
215    CLR(pkt->icmp6_seq % MAX_DUP_CHK);
216
217    gettimeofday((struct timeval *) &pkt->icmp6_data8[4], NULL);
218
219    i = sendto(pingsock, packet, sizeof(packet), 0,
220               (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in6));
221
222    if (i < 0)
223        bb_perror_msg_and_die("sendto");
224    else if ((size_t)i != sizeof(packet))
225        bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
226               (int)sizeof(packet));
227
228    signal(SIGALRM, sendping);
229    if (pingcount == 0 || ntransmitted < pingcount) {   /* schedule next in 1s */
230        alarm(PINGINTERVAL);
231    } else {                    /* done, wait for the last ping to come back */
232        /* todo, don't necessarily need to wait so long... */
233        signal(SIGALRM, pingstats);
234        alarm(MAXWAIT);
235    }
236}
237
238/* RFC3542 changed some definitions from RFC2292 for no good reason, whee !
239 * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
240#ifndef MLD_LISTENER_QUERY
241# define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
242#endif
243#ifndef MLD_LISTENER_REPORT
244# define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
245#endif
246#ifndef MLD_LISTENER_REDUCTION
247# define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
248#endif
249static char *icmp6_type_name (int id)
250{
251    switch (id) {
252    case ICMP6_DST_UNREACH:             return "Destination Unreachable";
253    case ICMP6_PACKET_TOO_BIG:          return "Packet too big";
254    case ICMP6_TIME_EXCEEDED:           return "Time Exceeded";
255    case ICMP6_PARAM_PROB:              return "Parameter Problem";
256    case ICMP6_ECHO_REPLY:              return "Echo Reply";
257    case ICMP6_ECHO_REQUEST:            return "Echo Request";
258    case MLD_LISTENER_QUERY:            return "Listener Query";
259    case MLD_LISTENER_REPORT:           return "Listener Report";
260    case MLD_LISTENER_REDUCTION:        return "Listener Reduction";
261    default:                            return "unknown ICMP type";
262    }
263}
264
265static void unpack(char *packet, int sz, struct sockaddr_in6 *from, int hoplimit)
266{
267    struct icmp6_hdr *icmppkt;
268    struct timeval tv, *tp;
269    int dupflag;
270    unsigned long triptime;
271    char buf[INET6_ADDRSTRLEN];
272
273    gettimeofday(&tv, NULL);
274
275    /* discard if too short */
276    if (sz < (datalen + sizeof(struct icmp6_hdr)))
277        return;
278
279    icmppkt = (struct icmp6_hdr *) packet;
280
281    if (icmppkt->icmp6_id != myid)
282        return;             /* not our ping */
283
284    if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
285        ++nreceived;
286        tp = (struct timeval *) &icmppkt->icmp6_data8[4];
287
288        if ((tv.tv_usec -= tp->tv_usec) < 0) {
289            --tv.tv_sec;
290            tv.tv_usec += 1000000;
291        }
292        tv.tv_sec -= tp->tv_sec;
293
294        triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
295        tsum += triptime;
296        if (triptime < tmin)
297            tmin = triptime;
298        if (triptime > tmax)
299            tmax = triptime;
300
301        if (TST(icmppkt->icmp6_seq % MAX_DUP_CHK)) {
302            ++nrepeats;
303            --nreceived;
304            dupflag = 1;
305        } else {
306            SET(icmppkt->icmp6_seq % MAX_DUP_CHK);
307            dupflag = 0;
308        }
309
310        if (options & O_QUIET)
311            return;
312
313        printf("%d bytes from %s: icmp6_seq=%u", sz,
314               inet_ntop(AF_INET6, &pingaddr.sin6_addr,
315                         buf, sizeof(buf)),
316               icmppkt->icmp6_seq);
317        printf(" ttl=%d time=%lu.%lu ms", hoplimit,
318               triptime / 10, triptime % 10);
319        if (dupflag)
320            printf(" (DUP!)");
321        printf("\n");
322    } else
323        if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST)
324            bb_error_msg("Warning: Got ICMP %d (%s)",
325                    icmppkt->icmp6_type, icmp6_type_name (icmppkt->icmp6_type));
326}
327
328static void ping(const char *host)
329{
330    char packet[datalen + MAXIPLEN + MAXICMPLEN];
331    char buf[INET6_ADDRSTRLEN];
332    int sockopt;
333    struct msghdr msg;
334    struct sockaddr_in6 from;
335    struct iovec iov;
336    char control_buf[CMSG_SPACE(36)];
337
338    pingsock = create_icmp6_socket();
339
340    memset(&pingaddr, 0, sizeof(struct sockaddr_in));
341
342    pingaddr.sin6_family = AF_INET6;
343    hostent = xgethostbyname2(host, AF_INET6);
344    if (hostent->h_addrtype != AF_INET6)
345        bb_error_msg_and_die("unknown address type; only AF_INET6 is currently supported.");
346
347    memcpy(&pingaddr.sin6_addr, hostent->h_addr, sizeof(pingaddr.sin6_addr));
348
349#ifdef ICMP6_FILTER
350    {
351        struct icmp6_filter filt;
352        if (!(options & O_VERBOSE)) {
353            ICMP6_FILTER_SETBLOCKALL(&filt);
354#if 0
355            if ((options & F_FQDN) || (options & F_FQDNOLD) ||
356                (options & F_NODEADDR) || (options & F_SUPTYPES))
357                ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt);
358            else
359#endif
360                ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
361        } else {
362            ICMP6_FILTER_SETPASSALL(&filt);
363        }
364        if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
365                       sizeof(filt)) < 0)
366            bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
367    }
368#endif /*ICMP6_FILTER*/
369
370    /* enable broadcast pings */
371    sockopt = 1;
372    setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
373               sizeof(sockopt));
374
375    /* set recv buf for broadcast pings */
376    sockopt = 48 * 1024;
377    setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
378               sizeof(sockopt));
379
380    sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
381    setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, (char *) &sockopt,
382               sizeof(sockopt));
383
384    sockopt = 1;
385    setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, (char *) &sockopt,
386               sizeof(sockopt));
387
388    if (ifname) {
389        if ((pingaddr.sin6_scope_id = if_nametoindex(ifname)) == 0)
390            bb_error_msg_and_die("%s: invalid interface name", ifname);
391    }
392
393    printf("PING %s (%s): %d data bytes\n",
394               hostent->h_name,
395               inet_ntop(AF_INET6, &pingaddr.sin6_addr,
396                         buf, sizeof(buf)),
397           datalen);
398
399    signal(SIGINT, pingstats);
400
401    /* start the ping's going ... */
402    sendping(0);
403
404    /* listen for replies */
405    msg.msg_name=&from;
406    msg.msg_namelen=sizeof(from);
407    msg.msg_iov=&iov;
408    msg.msg_iovlen=1;
409    msg.msg_control=control_buf;
410    iov.iov_base=packet;
411    iov.iov_len=sizeof(packet);
412    while (1) {
413        int c;
414        struct cmsghdr *cmsgptr = NULL;
415        int hoplimit=-1;
416        msg.msg_controllen=sizeof(control_buf);
417
418        if ((c = recvmsg(pingsock, &msg, 0)) < 0) {
419            if (errno == EINTR)
420                continue;
421            bb_perror_msg("recvfrom");
422            continue;
423        }
424        for (cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
425             cmsgptr = CMSG_NXTHDR(&msg, cmsgptr)) {
426            if (cmsgptr->cmsg_level == SOL_IPV6 &&
427                cmsgptr->cmsg_type == IPV6_HOPLIMIT ) {
428                hoplimit=*(int*)CMSG_DATA(cmsgptr);
429            }
430        }
431        unpack(packet, c, &from, hoplimit);
432        if (pingcount > 0 && nreceived >= pingcount)
433            break;
434    }
435    pingstats(0);
436}
437
438int ping6_main(int argc, char **argv)
439{
440    char *thisarg;
441
442    datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
443
444    argc--;
445    argv++;
446    options = 0;
447    /* Parse any options */
448    while (argc >= 1 && **argv == '-') {
449        thisarg = *argv;
450        thisarg++;
451        switch (*thisarg) {
452        case 'v':
453            options &= ~O_QUIET;
454            options |= O_VERBOSE;
455            break;
456        case 'q':
457            options &= ~O_VERBOSE;
458            options |= O_QUIET;
459            break;
460        case 'c':
461            if (--argc <= 0)
462                    bb_show_usage();
463            argv++;
464            pingcount = atoi(*argv);
465            break;
466        case 's':
467            if (--argc <= 0)
468                    bb_show_usage();
469            argv++;
470            datalen = atoi(*argv);
471            break;
472        case 'I':
473            if (--argc <= 0)
474                    bb_show_usage();
475            argv++;
476            ifname = *argv;
477            break;
478        default:
479            bb_show_usage();
480        }
481        argc--;
482        argv++;
483    }
484    if (argc < 1)
485        bb_show_usage();
486
487    myid = getpid() & 0xFFFF;
488    ping(*argv);
489    return EXIT_SUCCESS;
490}
491#endif /* ! CONFIG_FEATURE_FANCY_PING6 */
492
493/*
494 * Copyright (c) 1989 The Regents of the University of California.
495 * All rights reserved.
496 *
497 * This code is derived from software contributed to Berkeley by
498 * Mike Muuss.
499 *
500 * Redistribution and use in source and binary forms, with or without
501 * modification, are permitted provided that the following conditions
502 * are met:
503 * 1. Redistributions of source code must retain the above copyright
504 *    notice, this list of conditions and the following disclaimer.
505 * 2. Redistributions in binary form must reproduce the above copyright
506 *    notice, this list of conditions and the following disclaimer in the
507 *    documentation and/or other materials provided with the distribution.
508 *
509 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
510 *      ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
511 *
512 * 4. Neither the name of the University nor the names of its contributors
513 *    may be used to endorse or promote products derived from this software
514 *    without specific prior written permission.
515 *
516 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
517 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
518 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
519 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
520 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
521 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
522 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
523 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
524 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
525 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
526 * SUCH DAMAGE.
527 */
Note: See TracBrowser for help on using the repository browser.