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