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