udhcp,ipcalc: simple code shrink (Nico Erfurth <masta AT perlgolf.de>)
[oweals/busybox.git] / networking / ping.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini ping implementation for busybox
4  *
5  * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
6  *
7  * Adapted from the ping in netkit-base 0.10:
8  * Copyright (c) 1989 The Regents of the University of California.
9  * All rights reserved.
10  *
11  * This code is derived from software contributed to Berkeley by
12  * Mike Muuss.
13  *
14  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
15  */
16 /* from ping6.c:
17  * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
18  *
19  * This version of ping is adapted from the ping in netkit-base 0.10,
20  * which is:
21  *
22  * Original copyright notice is retained at the end of this file.
23  *
24  * This version is an adaptation of ping.c from busybox.
25  * The code was modified by Bart Visscher <magick@linux-fan.com>
26  */
27
28 #include <net/if.h>
29 #include <netinet/ip_icmp.h>
30 #include "libbb.h"
31
32 #if ENABLE_PING6
33 #include <netinet/icmp6.h>
34 /* I see RENUMBERED constants in bits/in.h - !!?
35  * What a fuck is going on with libc? Is it a glibc joke? */
36 #ifdef IPV6_2292HOPLIMIT
37 #undef IPV6_HOPLIMIT
38 #define IPV6_HOPLIMIT IPV6_2292HOPLIMIT
39 #endif
40 #endif
41
42 enum {
43         DEFDATALEN = 56,
44         MAXIPLEN = 60,
45         MAXICMPLEN = 76,
46         MAXPACKET = 65468,
47         MAX_DUP_CHK = (8 * 128),
48         MAXWAIT = 10,
49         PINGINTERVAL = 1, /* 1 second */
50 };
51
52 /* common routines */
53
54 static int in_cksum(unsigned short *buf, int sz)
55 {
56         int nleft = sz;
57         int sum = 0;
58         unsigned short *w = buf;
59         unsigned short ans = 0;
60
61         while (nleft > 1) {
62                 sum += *w++;
63                 nleft -= 2;
64         }
65
66         if (nleft == 1) {
67                 *(unsigned char *) (&ans) = *(unsigned char *) w;
68                 sum += ans;
69         }
70
71         sum = (sum >> 16) + (sum & 0xFFFF);
72         sum += (sum >> 16);
73         ans = ~sum;
74         return ans;
75 }
76
77 #if !ENABLE_FEATURE_FANCY_PING
78
79 /* simple version */
80
81 static char *hostname;
82
83 static void noresp(int ign ATTRIBUTE_UNUSED)
84 {
85         printf("No response from %s\n", hostname);
86         exit(EXIT_FAILURE);
87 }
88
89 static void ping4(len_and_sockaddr *lsa)
90 {
91         struct sockaddr_in pingaddr;
92         struct icmp *pkt;
93         int pingsock, c;
94         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
95
96         pingsock = create_icmp_socket();
97         pingaddr = lsa->u.sin;
98
99         pkt = (struct icmp *) packet;
100         memset(pkt, 0, sizeof(packet));
101         pkt->icmp_type = ICMP_ECHO;
102         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
103
104         c = xsendto(pingsock, packet, DEFDATALEN + ICMP_MINLEN,
105                            (struct sockaddr *) &pingaddr, sizeof(pingaddr));
106
107         /* listen for replies */
108         while (1) {
109                 struct sockaddr_in from;
110                 socklen_t fromlen = sizeof(from);
111
112                 c = recvfrom(pingsock, packet, sizeof(packet), 0,
113                                 (struct sockaddr *) &from, &fromlen);
114                 if (c < 0) {
115                         if (errno != EINTR)
116                                 bb_perror_msg("recvfrom");
117                         continue;
118                 }
119                 if (c >= 76) {                  /* ip + icmp */
120                         struct iphdr *iphdr = (struct iphdr *) packet;
121
122                         pkt = (struct icmp *) (packet + (iphdr->ihl << 2));     /* skip ip hdr */
123                         if (pkt->icmp_type == ICMP_ECHOREPLY)
124                                 break;
125                 }
126         }
127         if (ENABLE_FEATURE_CLEAN_UP)
128                 close(pingsock);
129 }
130
131 #if ENABLE_PING6
132 static void ping6(len_and_sockaddr *lsa)
133 {
134         struct sockaddr_in6 pingaddr;
135         struct icmp6_hdr *pkt;
136         int pingsock, c;
137         int sockopt;
138         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
139
140         pingsock = create_icmp6_socket();
141         pingaddr = lsa->u.sin6;
142
143         pkt = (struct icmp6_hdr *) packet;
144         memset(pkt, 0, sizeof(packet));
145         pkt->icmp6_type = ICMP6_ECHO_REQUEST;
146
147         sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
148         setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
149
150         c = xsendto(pingsock, packet, DEFDATALEN + sizeof (struct icmp6_hdr),
151                            (struct sockaddr *) &pingaddr, sizeof(pingaddr));
152
153         /* listen for replies */
154         while (1) {
155                 struct sockaddr_in6 from;
156                 socklen_t fromlen = sizeof(from);
157
158                 c = recvfrom(pingsock, packet, sizeof(packet), 0,
159                                 (struct sockaddr *) &from, &fromlen);
160                 if (c < 0) {
161                         if (errno != EINTR)
162                                 bb_perror_msg("recvfrom");
163                         continue;
164                 }
165                 if (c >= 8) {                   /* icmp6_hdr */
166                         pkt = (struct icmp6_hdr *) packet;
167                         if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
168                                 break;
169                 }
170         }
171         if (ENABLE_FEATURE_CLEAN_UP)
172                 close(pingsock);
173 }
174 #endif
175
176 int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
177 int ping_main(int argc ATTRIBUTE_UNUSED, char **argv)
178 {
179         len_and_sockaddr *lsa;
180 #if ENABLE_PING6
181         sa_family_t af = AF_UNSPEC;
182
183         while ((++argv)[0] && argv[0][0] == '-') {
184                 if (argv[0][1] == '4') {
185                         af = AF_INET;
186                         continue;
187                 }
188                 if (argv[0][1] == '6') {
189                         af = AF_INET6;
190                         continue;
191                 }
192                 bb_show_usage();
193         }
194 #else
195         argv++;
196 #endif
197
198         hostname = *argv;
199         if (!hostname)
200                 bb_show_usage();
201
202 #if ENABLE_PING6
203         lsa = xhost_and_af2sockaddr(hostname, 0, af);
204 #else
205         lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
206 #endif
207         /* Set timer _after_ DNS resolution */
208         signal(SIGALRM, noresp);
209         alarm(5); /* give the host 5000ms to respond */
210
211 #if ENABLE_PING6
212         if (lsa->u.sa.sa_family == AF_INET6)
213                 ping6(lsa);
214         else
215 #endif
216                 ping4(lsa);
217         printf("%s is alive!\n", hostname);
218         return EXIT_SUCCESS;
219 }
220
221
222 #else /* FEATURE_FANCY_PING */
223
224
225 /* full(er) version */
226
227 #define OPT_STRING ("qvc:s:w:W:I:4" USE_PING6("6"))
228 enum {
229         OPT_QUIET = 1 << 0,
230         OPT_VERBOSE = 1 << 1,
231         OPT_c = 1 << 2,
232         OPT_s = 1 << 3,
233         OPT_w = 1 << 4,
234         OPT_W = 1 << 5,
235         OPT_I = 1 << 6,
236         OPT_IPV4 = 1 << 7,
237         OPT_IPV6 = (1 << 8) * ENABLE_PING6,
238 };
239
240
241 struct globals {
242         int pingsock;
243         int if_index;
244         char *opt_I;
245         len_and_sockaddr *source_lsa;
246         unsigned datalen;
247         unsigned long ntransmitted, nreceived, nrepeats, pingcount;
248         uint16_t myid;
249         unsigned tmin, tmax; /* in us */
250         unsigned long long tsum; /* in us, sum of all times */
251         unsigned deadline;
252         unsigned timeout;
253         unsigned total_secs;
254         const char *hostname;
255         const char *dotted;
256         union {
257                 struct sockaddr sa;
258                 struct sockaddr_in sin;
259 #if ENABLE_PING6
260                 struct sockaddr_in6 sin6;
261 #endif
262         } pingaddr;
263         char rcvd_tbl[MAX_DUP_CHK / 8];
264 };
265 #define G (*(struct globals*)&bb_common_bufsiz1)
266 #define pingsock     (G.pingsock    )
267 #define if_index     (G.if_index    )
268 #define source_lsa   (G.source_lsa  )
269 #define opt_I        (G.opt_I       )
270 #define datalen      (G.datalen     )
271 #define ntransmitted (G.ntransmitted)
272 #define nreceived    (G.nreceived   )
273 #define nrepeats     (G.nrepeats    )
274 #define pingcount    (G.pingcount   )
275 #define myid         (G.myid        )
276 #define tmin         (G.tmin        )
277 #define tmax         (G.tmax        )
278 #define tsum         (G.tsum        )
279 #define deadline     (G.deadline    )
280 #define timeout      (G.timeout     )
281 #define total_secs   (G.total_secs  )
282 #define hostname     (G.hostname    )
283 #define dotted       (G.dotted      )
284 #define pingaddr     (G.pingaddr    )
285 #define rcvd_tbl     (G.rcvd_tbl    )
286 void BUG_ping_globals_too_big(void);
287 #define INIT_G() do { \
288         if (sizeof(G) > COMMON_BUFSIZE) \
289                 BUG_ping_globals_too_big(); \
290         pingsock = -1; \
291         datalen = DEFDATALEN; \
292         timeout = MAXWAIT; \
293         tmin = UINT_MAX; \
294 } while (0)
295
296
297 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
298 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
299 #define SET(bit)        (A(bit) |= B(bit))
300 #define CLR(bit)        (A(bit) &= (~B(bit)))
301 #define TST(bit)        (A(bit) & B(bit))
302
303 /**************************************************************************/
304
305 static void print_stats_and_exit(int junk) ATTRIBUTE_NORETURN;
306 static void print_stats_and_exit(int junk ATTRIBUTE_UNUSED)
307 {
308         signal(SIGINT, SIG_IGN);
309
310         printf("\n--- %s ping statistics ---\n", hostname);
311         printf("%lu packets transmitted, ", ntransmitted);
312         printf("%lu packets received, ", nreceived);
313         if (nrepeats)
314                 printf("%lu duplicates, ", nrepeats);
315         if (ntransmitted)
316                 ntransmitted = (ntransmitted - nreceived) * 100 / ntransmitted;
317         printf("%lu%% packet loss\n", ntransmitted);
318         if (tmin != UINT_MAX) {
319                 unsigned tavg = tsum / (nreceived + nrepeats);
320                 printf("round-trip min/avg/max = %u.%03u/%u.%03u/%u.%03u ms\n",
321                         tmin / 1000, tmin % 1000,
322                         tavg / 1000, tavg % 1000,
323                         tmax / 1000, tmax % 1000);
324         }
325         /* if condition is true, exit with 1 -- 'failure' */
326         exit(nreceived == 0 || (deadline && nreceived < pingcount));
327 }
328
329 static void sendping_tail(void (*sp)(int), const void *pkt, int size_pkt)
330 {
331         int sz;
332
333         CLR((uint16_t)ntransmitted % MAX_DUP_CHK);
334         ntransmitted++;
335
336         /* sizeof(pingaddr) can be larger than real sa size, but I think
337          * it doesn't matter */
338         sz = xsendto(pingsock, pkt, size_pkt, &pingaddr.sa, sizeof(pingaddr));
339         if (sz != size_pkt)
340                 bb_error_msg_and_die(bb_msg_write_error);
341
342         if (pingcount == 0 || deadline || ntransmitted < pingcount) {
343                 /* Didn't send all pings yet - schedule next in 1s */
344                 signal(SIGALRM, sp);
345                 if (deadline) {
346                         total_secs += PINGINTERVAL;
347                         if (total_secs >= deadline)
348                                 signal(SIGALRM, print_stats_and_exit);
349                 }
350                 alarm(PINGINTERVAL);
351         } else { /* -c NN, and all NN are sent (and no deadline) */
352                 /* Wait for the last ping to come back.
353                  * -W timeout: wait for a response in seconds.
354                  * Affects only timeout in absense of any responses,
355                  * otherwise ping waits for two RTTs. */
356                 unsigned expire = timeout;
357
358                 if (nreceived) {
359                         /* approx. 2*tmax, in seconds (2 RTT) */
360                         expire = tmax / (512*1024);
361                         if (expire == 0)
362                                 expire = 1;
363                 }
364                 signal(SIGALRM, print_stats_and_exit);
365                 alarm(expire);
366         }
367 }
368
369 static void sendping4(int junk ATTRIBUTE_UNUSED)
370 {
371         /* +4 reserves a place for timestamp, which may end up sitting
372          * *after* packet. Saves one if() */
373         struct icmp *pkt = alloca(datalen + ICMP_MINLEN + 4);
374
375         pkt->icmp_type = ICMP_ECHO;
376         pkt->icmp_code = 0;
377         pkt->icmp_cksum = 0;
378         pkt->icmp_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
379         pkt->icmp_id = myid;
380
381         /* We don't do hton, because we will read it back on the same machine */
382         /*if (datalen >= 4)*/
383                 *(uint32_t*)&pkt->icmp_dun = monotonic_us();
384
385         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, datalen + ICMP_MINLEN);
386
387         sendping_tail(sendping4, pkt, datalen + ICMP_MINLEN);
388 }
389 #if ENABLE_PING6
390 static void sendping6(int junk ATTRIBUTE_UNUSED)
391 {
392         struct icmp6_hdr *pkt = alloca(datalen + sizeof(struct icmp6_hdr) + 4);
393
394         pkt->icmp6_type = ICMP6_ECHO_REQUEST;
395         pkt->icmp6_code = 0;
396         pkt->icmp6_cksum = 0;
397         pkt->icmp6_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
398         pkt->icmp6_id = myid;
399
400         /*if (datalen >= 4)*/
401                 *(uint32_t*)(&pkt->icmp6_data8[4]) = monotonic_us();
402
403         sendping_tail(sendping6, pkt, datalen + sizeof(struct icmp6_hdr));
404 }
405 #endif
406
407 static const char *icmp_type_name(int id)
408 {
409         switch (id) {
410         case ICMP_ECHOREPLY:      return "Echo Reply";
411         case ICMP_DEST_UNREACH:   return "Destination Unreachable";
412         case ICMP_SOURCE_QUENCH:  return "Source Quench";
413         case ICMP_REDIRECT:       return "Redirect (change route)";
414         case ICMP_ECHO:           return "Echo Request";
415         case ICMP_TIME_EXCEEDED:  return "Time Exceeded";
416         case ICMP_PARAMETERPROB:  return "Parameter Problem";
417         case ICMP_TIMESTAMP:      return "Timestamp Request";
418         case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
419         case ICMP_INFO_REQUEST:   return "Information Request";
420         case ICMP_INFO_REPLY:     return "Information Reply";
421         case ICMP_ADDRESS:        return "Address Mask Request";
422         case ICMP_ADDRESSREPLY:   return "Address Mask Reply";
423         default:                  return "unknown ICMP type";
424         }
425 }
426 #if ENABLE_PING6
427 /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
428  * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
429 #ifndef MLD_LISTENER_QUERY
430 # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
431 #endif
432 #ifndef MLD_LISTENER_REPORT
433 # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
434 #endif
435 #ifndef MLD_LISTENER_REDUCTION
436 # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
437 #endif
438 static const char *icmp6_type_name(int id)
439 {
440         switch (id) {
441         case ICMP6_DST_UNREACH:      return "Destination Unreachable";
442         case ICMP6_PACKET_TOO_BIG:   return "Packet too big";
443         case ICMP6_TIME_EXCEEDED:    return "Time Exceeded";
444         case ICMP6_PARAM_PROB:       return "Parameter Problem";
445         case ICMP6_ECHO_REPLY:       return "Echo Reply";
446         case ICMP6_ECHO_REQUEST:     return "Echo Request";
447         case MLD_LISTENER_QUERY:     return "Listener Query";
448         case MLD_LISTENER_REPORT:    return "Listener Report";
449         case MLD_LISTENER_REDUCTION: return "Listener Reduction";
450         default:                     return "unknown ICMP type";
451         }
452 }
453 #endif
454
455 static void unpack_tail(int sz, uint32_t *tp,
456                 const char *from_str,
457                 uint16_t recv_seq, int ttl)
458 {
459         const char *dupmsg = " (DUP!)";
460         unsigned triptime = triptime; /* for gcc */
461
462         ++nreceived;
463
464         if (tp) {
465                 /* (int32_t) cast is for hypothetical 64-bit unsigned */
466                 /* (doesn't hurt 32-bit real-world anyway) */
467                 triptime = (int32_t) ((uint32_t)monotonic_us() - *tp);
468                 tsum += triptime;
469                 if (triptime < tmin)
470                         tmin = triptime;
471                 if (triptime > tmax)
472                         tmax = triptime;
473         }
474
475         if (TST(recv_seq % MAX_DUP_CHK)) {
476                 ++nrepeats;
477                 --nreceived;
478         } else {
479                 SET(recv_seq % MAX_DUP_CHK);
480                 dupmsg += 7;
481         }
482
483         if (option_mask32 & OPT_QUIET)
484                 return;
485
486         printf("%d bytes from %s: seq=%u ttl=%d", sz,
487                 from_str, recv_seq, ttl);
488         if (tp)
489                 printf(" time=%u.%03u ms", triptime / 1000, triptime % 1000);
490         puts(dupmsg);
491         fflush(stdout);
492 }
493 static void unpack4(char *buf, int sz, struct sockaddr_in *from)
494 {
495         struct icmp *icmppkt;
496         struct iphdr *iphdr;
497         int hlen;
498
499         /* discard if too short */
500         if (sz < (datalen + ICMP_MINLEN))
501                 return;
502
503         /* check IP header */
504         iphdr = (struct iphdr *) buf;
505         hlen = iphdr->ihl << 2;
506         sz -= hlen;
507         icmppkt = (struct icmp *) (buf + hlen);
508         if (icmppkt->icmp_id != myid)
509                 return;                         /* not our ping */
510
511         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
512                 uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
513                 uint32_t *tp = NULL;
514
515                 if (sz >= ICMP_MINLEN + sizeof(uint32_t))
516                         tp = (uint32_t *) icmppkt->icmp_data;
517                 unpack_tail(sz, tp,
518                         inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
519                         recv_seq, iphdr->ttl);
520         } else if (icmppkt->icmp_type != ICMP_ECHO) {
521                 bb_error_msg("warning: got ICMP %d (%s)",
522                                 icmppkt->icmp_type,
523                                 icmp_type_name(icmppkt->icmp_type));
524         }
525 }
526 #if ENABLE_PING6
527 static void unpack6(char *packet, int sz, /*struct sockaddr_in6 *from,*/ int hoplimit)
528 {
529         struct icmp6_hdr *icmppkt;
530         char buf[INET6_ADDRSTRLEN];
531
532         /* discard if too short */
533         if (sz < (datalen + sizeof(struct icmp6_hdr)))
534                 return;
535
536         icmppkt = (struct icmp6_hdr *) packet;
537         if (icmppkt->icmp6_id != myid)
538                 return;                         /* not our ping */
539
540         if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
541                 uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
542                 uint32_t *tp = NULL;
543
544                 if (sz >= sizeof(struct icmp6_hdr) + sizeof(uint32_t))
545                         tp = (uint32_t *) &icmppkt->icmp6_data8[4];
546                 unpack_tail(sz, tp,
547                         inet_ntop(AF_INET6, &pingaddr.sin6.sin6_addr,
548                                         buf, sizeof(buf)),
549                         recv_seq, hoplimit);
550         } else if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
551                 bb_error_msg("warning: got ICMP %d (%s)",
552                                 icmppkt->icmp6_type,
553                                 icmp6_type_name(icmppkt->icmp6_type));
554         }
555 }
556 #endif
557
558 static void ping4(len_and_sockaddr *lsa)
559 {
560         char packet[datalen + MAXIPLEN + MAXICMPLEN];
561         int sockopt;
562
563         pingsock = create_icmp_socket();
564         pingaddr.sin = lsa->u.sin;
565         if (source_lsa) {
566                 if (setsockopt(pingsock, IPPROTO_IP, IP_MULTICAST_IF,
567                                 &source_lsa->u.sa, source_lsa->len))
568                         bb_error_msg_and_die("can't set multicast source interface");
569                 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
570         }
571         if (opt_I)
572                 setsockopt(pingsock, SOL_SOCKET, SO_BINDTODEVICE, opt_I, strlen(opt_I) + 1);
573
574         /* enable broadcast pings */
575         setsockopt_broadcast(pingsock);
576
577         /* set recv buf for broadcast pings */
578         sockopt = 48 * 1024; /* explain why 48k? */
579         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
580
581         signal(SIGINT, print_stats_and_exit);
582
583         /* start the ping's going ... */
584         sendping4(0);
585
586         /* listen for replies */
587         while (1) {
588                 struct sockaddr_in from;
589                 socklen_t fromlen = (socklen_t) sizeof(from);
590                 int c;
591
592                 c = recvfrom(pingsock, packet, sizeof(packet), 0,
593                                 (struct sockaddr *) &from, &fromlen);
594                 if (c < 0) {
595                         if (errno != EINTR)
596                                 bb_perror_msg("recvfrom");
597                         continue;
598                 }
599                 unpack4(packet, c, &from);
600                 if (pingcount && nreceived >= pingcount)
601                         break;
602         }
603 }
604 #if ENABLE_PING6
605 extern int BUG_bad_offsetof_icmp6_cksum(void);
606 static void ping6(len_and_sockaddr *lsa)
607 {
608         char packet[datalen + MAXIPLEN + MAXICMPLEN];
609         int sockopt;
610         struct msghdr msg;
611         struct sockaddr_in6 from;
612         struct iovec iov;
613         char control_buf[CMSG_SPACE(36)];
614
615         pingsock = create_icmp6_socket();
616         pingaddr.sin6 = lsa->u.sin6;
617         /* untested whether "-I addr" really works for IPv6: */
618         if (source_lsa)
619                 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
620         if (opt_I)
621                 setsockopt(pingsock, SOL_SOCKET, SO_BINDTODEVICE, opt_I, strlen(opt_I) + 1);
622
623 #ifdef ICMP6_FILTER
624         {
625                 struct icmp6_filter filt;
626                 if (!(option_mask32 & OPT_VERBOSE)) {
627                         ICMP6_FILTER_SETBLOCKALL(&filt);
628                         ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
629                 } else {
630                         ICMP6_FILTER_SETPASSALL(&filt);
631                 }
632                 if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
633                                            sizeof(filt)) < 0)
634                         bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
635         }
636 #endif /*ICMP6_FILTER*/
637
638         /* enable broadcast pings */
639         setsockopt_broadcast(pingsock);
640
641         /* set recv buf for broadcast pings */
642         sockopt = 48 * 1024; /* explain why 48k? */
643         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
644
645         sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
646         if (offsetof(struct icmp6_hdr, icmp6_cksum) != 2)
647                 BUG_bad_offsetof_icmp6_cksum();
648         setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
649
650         /* request ttl info to be returned in ancillary data */
651         setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, &const_int_1, sizeof(const_int_1));
652
653         if (if_index)
654                 pingaddr.sin6.sin6_scope_id = if_index;
655
656         signal(SIGINT, print_stats_and_exit);
657
658         /* start the ping's going ... */
659         sendping6(0);
660
661         /* listen for replies */
662         msg.msg_name = &from;
663         msg.msg_namelen = sizeof(from);
664         msg.msg_iov = &iov;
665         msg.msg_iovlen = 1;
666         msg.msg_control = control_buf;
667         iov.iov_base = packet;
668         iov.iov_len = sizeof(packet);
669         while (1) {
670                 int c;
671                 struct cmsghdr *mp;
672                 int hoplimit = -1;
673                 msg.msg_controllen = sizeof(control_buf);
674
675                 c = recvmsg(pingsock, &msg, 0);
676                 if (c < 0) {
677                         if (errno != EINTR)
678                                 bb_perror_msg("recvfrom");
679                         continue;
680                 }
681                 for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
682                         if (mp->cmsg_level == SOL_IPV6
683                          && mp->cmsg_type == IPV6_HOPLIMIT
684                          /* don't check len - we trust the kernel: */
685                          /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
686                         ) {
687                                 hoplimit = *(int*)CMSG_DATA(mp);
688                         }
689                 }
690                 unpack6(packet, c, /*&from,*/ hoplimit);
691                 if (pingcount && nreceived >= pingcount)
692                         break;
693         }
694 }
695 #endif
696
697 static void ping(len_and_sockaddr *lsa)
698 {
699         printf("PING %s (%s)", hostname, dotted);
700         if (source_lsa) {
701                 printf(" from %s",
702                         xmalloc_sockaddr2dotted_noport(&source_lsa->u.sa));
703         }
704         printf(": %d data bytes\n", datalen);
705
706 #if ENABLE_PING6
707         if (lsa->u.sa.sa_family == AF_INET6)
708                 ping6(lsa);
709         else
710 #endif
711                 ping4(lsa);
712 }
713
714 int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
715 int ping_main(int argc ATTRIBUTE_UNUSED, char **argv)
716 {
717         len_and_sockaddr *lsa;
718         char *opt_c, *opt_s;
719         USE_PING6(sa_family_t af = AF_UNSPEC;)
720
721         INIT_G();
722
723         /* exactly one argument needed; -v and -q don't mix; -w NUM, -W NUM */
724         opt_complementary = "=1:q--v:v--q:w+:W+";
725         getopt32(argv, OPT_STRING, &opt_c, &opt_s, &deadline, &timeout, &opt_I);
726         if (option_mask32 & OPT_c)
727                 pingcount = xatoul(opt_c); // -c
728         if (option_mask32 & OPT_s)
729                 datalen = xatou16(opt_s); // -s
730         if (option_mask32 & OPT_I) { // -I
731                 if_index = if_nametoindex(opt_I);
732                 if (!if_index) {
733                         /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
734                         source_lsa = xdotted2sockaddr(opt_I, 0);
735                         opt_I = NULL; /* don't try to bind to device later */
736                 }
737         }
738         myid = (uint16_t) getpid();
739         hostname = argv[optind];
740 #if ENABLE_PING6
741         if (option_mask32 & OPT_IPV4)
742                 af = AF_INET;
743         if (option_mask32 & OPT_IPV6)
744                 af = AF_INET6;
745         lsa = xhost_and_af2sockaddr(hostname, 0, af);
746 #else
747         lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
748 #endif
749
750         if (source_lsa && source_lsa->u.sa.sa_family != lsa->u.sa.sa_family)
751                 /* leaking it here... */
752                 source_lsa = NULL;
753
754         dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
755         ping(lsa);
756         print_stats_and_exit(0);
757         /*return EXIT_SUCCESS;*/
758 }
759 #endif /* FEATURE_FANCY_PING */
760
761
762 #if ENABLE_PING6
763 int ping6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
764 int ping6_main(int argc, char **argv)
765 {
766         argv[0] = (char*)"-6";
767         return ping_main(argc + 1, argv - 1);
768 }
769 #endif
770
771 /* from ping6.c:
772  * Copyright (c) 1989 The Regents of the University of California.
773  * All rights reserved.
774  *
775  * This code is derived from software contributed to Berkeley by
776  * Mike Muuss.
777  *
778  * Redistribution and use in source and binary forms, with or without
779  * modification, are permitted provided that the following conditions
780  * are met:
781  * 1. Redistributions of source code must retain the above copyright
782  *    notice, this list of conditions and the following disclaimer.
783  * 2. Redistributions in binary form must reproduce the above copyright
784  *    notice, this list of conditions and the following disclaimer in the
785  *    documentation and/or other materials provided with the distribution.
786  *
787  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
788  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
789  *
790  * 4. Neither the name of the University nor the names of its contributors
791  *    may be used to endorse or promote products derived from this software
792  *    without specific prior written permission.
793  *
794  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
795  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
796  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
797  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
798  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
799  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
800  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
801  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
802  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
803  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
804  * SUCH DAMAGE.
805  */