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