networking/interface.c: huke remaining big statics; use malloc for INET[6]_rresolve
[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->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->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);
177 int ping_main(int argc, char **argv)
178 {
179         len_and_sockaddr *lsa;
180 #if ENABLE_PING6
181         sa_family_t af = AF_UNSPEC;
182         while (++argv[0][0] == '-') {
183                 if (argv[0][1] == '4') {
184                         af = AF_INET;
185                         continue;
186                 }
187                 if (argv[0][1] == '6') {
188                         af = AF_INET6;
189                         continue;
190                 }
191                 bb_show_usage();
192         }
193 #else
194         argv++;
195 #endif
196
197         hostname = *argv;
198         if (!hostname)
199                 bb_show_usage();
200
201 #if ENABLE_PING6
202         lsa = xhost_and_af2sockaddr(hostname, 0, af);
203 #else
204         lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
205 #endif
206         /* Set timer _after_ DNS resolution */
207         signal(SIGALRM, noresp);
208         alarm(5); /* give the host 5000ms to respond */
209
210 #if ENABLE_PING6
211         if (lsa->sa.sa_family == AF_INET6)
212                 ping6(lsa);
213         else
214 #endif
215                 ping4(lsa);
216         printf("%s is alive!\n", hostname);
217         return EXIT_SUCCESS;
218 }
219
220
221 #else /* FEATURE_FANCY_PING */
222
223
224 /* full(er) version */
225
226 #define OPT_STRING ("qvc:s:I:4" USE_PING6("6"))
227 enum {
228         OPT_QUIET = 1 << 0,
229         OPT_VERBOSE = 1 << 1,
230         OPT_c = 1 << 2,
231         OPT_s = 1 << 3,
232         OPT_I = 1 << 4,
233         OPT_IPV4 = 1 << 5,
234         OPT_IPV6 = (1 << 6) * ENABLE_PING6,
235 };
236
237
238 struct globals {
239         int pingsock;
240         len_and_sockaddr *source_lsa;
241         unsigned datalen;
242         int if_index;
243         unsigned long ntransmitted, nreceived, nrepeats, pingcount;
244         uint16_t myid;
245         unsigned tmin, tmax; /* in us */
246         unsigned long long tsum; /* in us, sum of all times */
247         const char *hostname;
248         const char *dotted;
249         union {
250                 struct sockaddr sa;
251                 struct sockaddr_in sin;
252 #if ENABLE_PING6
253                 struct sockaddr_in6 sin6;
254 #endif
255         } pingaddr;
256         char rcvd_tbl[MAX_DUP_CHK / 8];
257 };
258 #define G (*(struct globals*)&bb_common_bufsiz1)
259 #define pingsock     (G.pingsock    )
260 #define source_lsa   (G.source_lsa  )
261 #define datalen      (G.datalen     )
262 #define if_index     (G.if_index    )
263 #define ntransmitted (G.ntransmitted)
264 #define nreceived    (G.nreceived   )
265 #define nrepeats     (G.nrepeats    )
266 #define pingcount    (G.pingcount   )
267 #define myid         (G.myid        )
268 #define tmin         (G.tmin        )
269 #define tmax         (G.tmax        )
270 #define tsum         (G.tsum        )
271 #define hostname     (G.hostname    )
272 #define dotted       (G.dotted      )
273 #define pingaddr     (G.pingaddr    )
274 #define rcvd_tbl     (G.rcvd_tbl    )
275 void BUG_ping_globals_too_big(void);
276 #define INIT_G() do { \
277         if (sizeof(G) > COMMON_BUFSIZE) \
278                 BUG_ping_globals_too_big(); \
279         pingsock = -1; \
280         tmin = UINT_MAX; \
281 } while (0)
282
283
284 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
285 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
286 #define SET(bit)        (A(bit) |= B(bit))
287 #define CLR(bit)        (A(bit) &= (~B(bit)))
288 #define TST(bit)        (A(bit) & B(bit))
289
290 /**************************************************************************/
291
292 static void pingstats(int junk ATTRIBUTE_UNUSED)
293 {
294         signal(SIGINT, SIG_IGN);
295
296         printf("\n--- %s ping statistics ---\n", hostname);
297         printf("%lu packets transmitted, ", ntransmitted);
298         printf("%lu packets received, ", nreceived);
299         if (nrepeats)
300                 printf("%lu duplicates, ", nrepeats);
301         if (ntransmitted)
302                 ntransmitted = (ntransmitted - nreceived) * 100 / ntransmitted;
303         printf("%lu%% packet loss\n", ntransmitted);
304         if (tmin != UINT_MAX) {
305                 unsigned tavg = tsum / (nreceived + nrepeats);
306                 printf("round-trip min/avg/max = %u.%03u/%u.%03u/%u.%03u ms\n",
307                         tmin / 1000, tmin % 1000,
308                         tavg / 1000, tavg % 1000,
309                         tmax / 1000, tmax % 1000);
310         }
311         exit(nreceived == 0); /* (nreceived == 0) is true (1) -- 'failure' */
312 }
313
314 static void sendping_tail(void (*sp)(int), const void *pkt, int size_pkt)
315 {
316         int sz;
317
318         CLR((uint16_t)ntransmitted % MAX_DUP_CHK);
319         ntransmitted++;
320
321         /* sizeof(pingaddr) can be larger than real sa size, but I think
322          * it doesn't matter */
323         sz = xsendto(pingsock, pkt, size_pkt, &pingaddr.sa, sizeof(pingaddr));
324         if (sz != size_pkt)
325                 bb_error_msg_and_die(bb_msg_write_error);
326
327         signal(SIGALRM, sp);
328         if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
329                 alarm(PINGINTERVAL);
330         } else { /* done, wait for the last ping to come back */
331                 /* todo, don't necessarily need to wait so long... */
332                 signal(SIGALRM, pingstats);
333                 alarm(MAXWAIT);
334         }
335 }
336
337 static void sendping4(int junk ATTRIBUTE_UNUSED)
338 {
339         /* +4 reserves a place for timestamp, which may end up sitting
340          * *after* packet. Saves one if() */
341         struct icmp *pkt = alloca(datalen + ICMP_MINLEN + 4);
342
343         pkt->icmp_type = ICMP_ECHO;
344         pkt->icmp_code = 0;
345         pkt->icmp_cksum = 0;
346         pkt->icmp_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
347         pkt->icmp_id = myid;
348
349         /* We don't do hton, because we will read it back on the same machine */
350         /*if (datalen >= 4)*/
351                 *(uint32_t*)&pkt->icmp_dun = monotonic_us();
352
353         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, datalen + ICMP_MINLEN);
354
355         sendping_tail(sendping4, pkt, datalen + ICMP_MINLEN);
356 }
357 #if ENABLE_PING6
358 static void sendping6(int junk ATTRIBUTE_UNUSED)
359 {
360         struct icmp6_hdr *pkt = alloca(datalen + sizeof(struct icmp6_hdr) + 4);
361
362         pkt->icmp6_type = ICMP6_ECHO_REQUEST;
363         pkt->icmp6_code = 0;
364         pkt->icmp6_cksum = 0;
365         pkt->icmp6_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
366         pkt->icmp6_id = myid;
367
368         /*if (datalen >= 4)*/
369                 *(uint32_t*)(&pkt->icmp6_data8[4]) = monotonic_us();
370
371         sendping_tail(sendping6, pkt, datalen + sizeof(struct icmp6_hdr));
372 }
373 #endif
374
375 static const char *icmp_type_name(int id)
376 {
377         switch (id) {
378         case ICMP_ECHOREPLY:      return "Echo Reply";
379         case ICMP_DEST_UNREACH:   return "Destination Unreachable";
380         case ICMP_SOURCE_QUENCH:  return "Source Quench";
381         case ICMP_REDIRECT:       return "Redirect (change route)";
382         case ICMP_ECHO:           return "Echo Request";
383         case ICMP_TIME_EXCEEDED:  return "Time Exceeded";
384         case ICMP_PARAMETERPROB:  return "Parameter Problem";
385         case ICMP_TIMESTAMP:      return "Timestamp Request";
386         case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
387         case ICMP_INFO_REQUEST:   return "Information Request";
388         case ICMP_INFO_REPLY:     return "Information Reply";
389         case ICMP_ADDRESS:        return "Address Mask Request";
390         case ICMP_ADDRESSREPLY:   return "Address Mask Reply";
391         default:                  return "unknown ICMP type";
392         }
393 }
394 #if ENABLE_PING6
395 /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
396  * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
397 #ifndef MLD_LISTENER_QUERY
398 # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
399 #endif
400 #ifndef MLD_LISTENER_REPORT
401 # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
402 #endif
403 #ifndef MLD_LISTENER_REDUCTION
404 # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
405 #endif
406 static const char *icmp6_type_name(int id)
407 {
408         switch (id) {
409         case ICMP6_DST_UNREACH:      return "Destination Unreachable";
410         case ICMP6_PACKET_TOO_BIG:   return "Packet too big";
411         case ICMP6_TIME_EXCEEDED:    return "Time Exceeded";
412         case ICMP6_PARAM_PROB:       return "Parameter Problem";
413         case ICMP6_ECHO_REPLY:       return "Echo Reply";
414         case ICMP6_ECHO_REQUEST:     return "Echo Request";
415         case MLD_LISTENER_QUERY:     return "Listener Query";
416         case MLD_LISTENER_REPORT:    return "Listener Report";
417         case MLD_LISTENER_REDUCTION: return "Listener Reduction";
418         default:                     return "unknown ICMP type";
419         }
420 }
421 #endif
422
423 static void unpack_tail(int sz, uint32_t *tp,
424                 const char *from_str,
425                 uint16_t recv_seq, int ttl)
426 {
427         const char *dupmsg = " (DUP!)";
428         unsigned triptime = triptime; /* for gcc */
429
430         ++nreceived;
431
432         if (tp) {
433                 /* (int32_t) cast is for hypothetical 64-bit unsigned */
434                 /* (doesn't hurt 32-bit real-world anyway) */
435                 triptime = (int32_t) ((uint32_t)monotonic_us() - *tp);
436                 tsum += triptime;
437                 if (triptime < tmin)
438                         tmin = triptime;
439                 if (triptime > tmax)
440                         tmax = triptime;
441         }
442
443         if (TST(recv_seq % MAX_DUP_CHK)) {
444                 ++nrepeats;
445                 --nreceived;
446         } else {
447                 SET(recv_seq % MAX_DUP_CHK);
448                 dupmsg += 7;
449         }
450
451         if (option_mask32 & OPT_QUIET)
452                 return;
453
454         printf("%d bytes from %s: seq=%u ttl=%d", sz,
455                 from_str, recv_seq, ttl);
456         if (tp)
457                 printf(" time=%u.%03u ms", triptime / 1000, triptime % 1000);
458         puts(dupmsg);
459         fflush(stdout);
460 }
461 static void unpack4(char *buf, int sz, struct sockaddr_in *from)
462 {
463         struct icmp *icmppkt;
464         struct iphdr *iphdr;
465         int hlen;
466
467         /* discard if too short */
468         if (sz < (datalen + ICMP_MINLEN))
469                 return;
470
471         /* check IP header */
472         iphdr = (struct iphdr *) buf;
473         hlen = iphdr->ihl << 2;
474         sz -= hlen;
475         icmppkt = (struct icmp *) (buf + hlen);
476         if (icmppkt->icmp_id != myid)
477                 return;                         /* not our ping */
478
479         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
480                 uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
481                 uint32_t *tp = NULL;
482
483                 if (sz >= ICMP_MINLEN + sizeof(uint32_t))
484                         tp = (uint32_t *) icmppkt->icmp_data;
485                 unpack_tail(sz, tp,
486                         inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
487                         recv_seq, iphdr->ttl);
488         } else if (icmppkt->icmp_type != ICMP_ECHO) {
489                 bb_error_msg("warning: got ICMP %d (%s)",
490                                 icmppkt->icmp_type,
491                                 icmp_type_name(icmppkt->icmp_type));
492         }
493 }
494 #if ENABLE_PING6
495 static void unpack6(char *packet, int sz, struct sockaddr_in6 *from, int hoplimit)
496 {
497         struct icmp6_hdr *icmppkt;
498         char buf[INET6_ADDRSTRLEN];
499
500         /* discard if too short */
501         if (sz < (datalen + sizeof(struct icmp6_hdr)))
502                 return;
503
504         icmppkt = (struct icmp6_hdr *) packet;
505         if (icmppkt->icmp6_id != myid)
506                 return;                         /* not our ping */
507
508         if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
509                 uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
510                 uint32_t *tp = NULL;
511
512                 if (sz >= sizeof(struct icmp6_hdr) + sizeof(uint32_t))
513                         tp = (uint32_t *) &icmppkt->icmp6_data8[4];
514                 unpack_tail(sz, tp,
515                         inet_ntop(AF_INET6, &pingaddr.sin6.sin6_addr,
516                                         buf, sizeof(buf)),
517                         recv_seq, hoplimit);
518         } else if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
519                 bb_error_msg("warning: got ICMP %d (%s)",
520                                 icmppkt->icmp6_type,
521                                 icmp6_type_name(icmppkt->icmp6_type));
522         }
523 }
524 #endif
525
526 static void ping4(len_and_sockaddr *lsa)
527 {
528         char packet[datalen + MAXIPLEN + MAXICMPLEN];
529         int sockopt;
530
531         pingsock = create_icmp_socket();
532         pingaddr.sin = lsa->sin;
533         if (source_lsa)
534                 xbind(pingsock, &lsa->sa, lsa->len);
535
536         /* enable broadcast pings */
537         setsockopt_broadcast(pingsock);
538
539         /* set recv buf for broadcast pings */
540         sockopt = 48 * 1024; /* explain why 48k? */
541         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
542
543         signal(SIGINT, pingstats);
544
545         /* start the ping's going ... */
546         sendping4(0);
547
548         /* listen for replies */
549         while (1) {
550                 struct sockaddr_in from;
551                 socklen_t fromlen = (socklen_t) sizeof(from);
552                 int c;
553
554                 c = recvfrom(pingsock, packet, sizeof(packet), 0,
555                                 (struct sockaddr *) &from, &fromlen);
556                 if (c < 0) {
557                         if (errno != EINTR)
558                                 bb_perror_msg("recvfrom");
559                         continue;
560                 }
561                 unpack4(packet, c, &from);
562                 if (pingcount > 0 && nreceived >= pingcount)
563                         break;
564         }
565 }
566 #if ENABLE_PING6
567 extern int BUG_bad_offsetof_icmp6_cksum(void);
568 static void ping6(len_and_sockaddr *lsa)
569 {
570         char packet[datalen + MAXIPLEN + MAXICMPLEN];
571         int sockopt;
572         struct msghdr msg;
573         struct sockaddr_in6 from;
574         struct iovec iov;
575         char control_buf[CMSG_SPACE(36)];
576
577         pingsock = create_icmp6_socket();
578         pingaddr.sin6 = lsa->sin6;
579         /* untested whether "-I addr" really works for IPv6: */
580         if (source_lsa)
581                 xbind(pingsock, &lsa->sa, lsa->len);
582
583 #ifdef ICMP6_FILTER
584         {
585                 struct icmp6_filter filt;
586                 if (!(option_mask32 & OPT_VERBOSE)) {
587                         ICMP6_FILTER_SETBLOCKALL(&filt);
588                         ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
589                 } else {
590                         ICMP6_FILTER_SETPASSALL(&filt);
591                 }
592                 if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
593                                            sizeof(filt)) < 0)
594                         bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
595         }
596 #endif /*ICMP6_FILTER*/
597
598         /* enable broadcast pings */
599         setsockopt_broadcast(pingsock);
600
601         /* set recv buf for broadcast pings */
602         sockopt = 48 * 1024; /* explain why 48k? */
603         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
604
605         sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
606         if (offsetof(struct icmp6_hdr, icmp6_cksum) != 2)
607                 BUG_bad_offsetof_icmp6_cksum();
608         setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
609
610         /* request ttl info to be returned in ancillary data */
611         setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, &const_int_1, sizeof(const_int_1));
612
613         if (if_index)
614                 pingaddr.sin6.sin6_scope_id = if_index;
615
616         signal(SIGINT, pingstats);
617
618         /* start the ping's going ... */
619         sendping6(0);
620
621         /* listen for replies */
622         msg.msg_name = &from;
623         msg.msg_namelen = sizeof(from);
624         msg.msg_iov = &iov;
625         msg.msg_iovlen = 1;
626         msg.msg_control = control_buf;
627         iov.iov_base = packet;
628         iov.iov_len = sizeof(packet);
629         while (1) {
630                 int c;
631                 struct cmsghdr *mp;
632                 int hoplimit = -1;
633                 msg.msg_controllen = sizeof(control_buf);
634
635                 c = recvmsg(pingsock, &msg, 0);
636                 if (c < 0) {
637                         if (errno != EINTR)
638                                 bb_perror_msg("recvfrom");
639                         continue;
640                 }
641                 for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
642                         if (mp->cmsg_level == SOL_IPV6
643                          && mp->cmsg_type == IPV6_HOPLIMIT
644                          /* don't check len - we trust the kernel: */
645                          /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
646                         ) {
647                                 hoplimit = *(int*)CMSG_DATA(mp);
648                         }
649                 }
650                 unpack6(packet, c, &from, hoplimit);
651                 if (pingcount > 0 && nreceived >= pingcount)
652                         break;
653         }
654 }
655 #endif
656
657 static void ping(len_and_sockaddr *lsa)
658 {
659         printf("PING %s (%s)", hostname, dotted);
660         if (source_lsa) {
661                 printf(" from %s",
662                         xmalloc_sockaddr2dotted_noport(&lsa->sa, lsa->len));
663         }
664         printf(": %d data bytes\n", datalen);
665
666 #if ENABLE_PING6
667         if (lsa->sa.sa_family == AF_INET6)
668                 ping6(lsa);
669         else
670 #endif
671                 ping4(lsa);
672 }
673
674 int ping_main(int argc, char **argv);
675 int ping_main(int argc, char **argv)
676 {
677         len_and_sockaddr *lsa;
678         char *opt_c, *opt_s, *opt_I;
679         USE_PING6(sa_family_t af = AF_UNSPEC;)
680
681         INIT_G();
682
683         datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
684
685         /* exactly one argument needed, -v and -q don't mix */
686         opt_complementary = "=1:q--v:v--q";
687         getopt32(argc, argv, OPT_STRING, &opt_c, &opt_s, &opt_I);
688         if (option_mask32 & OPT_c) pingcount = xatoul(opt_c); // -c
689         if (option_mask32 & OPT_s) datalen = xatou16(opt_s); // -s
690         if (option_mask32 & OPT_I) { // -I
691                 if_index = if_nametoindex(opt_I);
692                 if (!if_index) {
693                         /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
694                         /* (ping doesn't support source IPv6 addresses yet anyway) */
695                         source_lsa = xdotted2sockaddr(opt_I, 0);
696                 }
697         }
698         myid = (uint16_t) getpid();
699         hostname = argv[optind];
700 #if ENABLE_PING6
701         if (option_mask32 & OPT_IPV4)
702                 af = AF_INET;
703         if (option_mask32 & OPT_IPV6)
704                 af = AF_INET6;
705         lsa = xhost_and_af2sockaddr(hostname, 0, af);
706 #else
707         lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
708 #endif
709
710         if (source_lsa && source_lsa->sa.sa_family != lsa->sa.sa_family)
711                 /* leaking it here... */
712                 source_lsa = NULL;
713
714         dotted = xmalloc_sockaddr2dotted_noport(&lsa->sa, lsa->len);
715         ping(lsa);
716         pingstats(0);
717         return EXIT_SUCCESS;
718 }
719 #endif /* FEATURE_FANCY_PING */
720
721
722 #if ENABLE_PING6
723 int ping6_main(int argc, char **argv);
724 int ping6_main(int argc, char **argv)
725 {
726         argv[0] = (char*)"-6";
727         return ping_main(argc + 1, argv - 1);
728 }
729 #endif
730
731 /* from ping6.c:
732  * Copyright (c) 1989 The Regents of the University of California.
733  * All rights reserved.
734  *
735  * This code is derived from software contributed to Berkeley by
736  * Mike Muuss.
737  *
738  * Redistribution and use in source and binary forms, with or without
739  * modification, are permitted provided that the following conditions
740  * are met:
741  * 1. Redistributions of source code must retain the above copyright
742  *    notice, this list of conditions and the following disclaimer.
743  * 2. Redistributions in binary form must reproduce the above copyright
744  *    notice, this list of conditions and the following disclaimer in the
745  *    documentation and/or other materials provided with the distribution.
746  *
747  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
748  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
749  *
750  * 4. Neither the name of the University nor the names of its contributors
751  *    may be used to endorse or promote products derived from this software
752  *    without specific prior written permission.
753  *
754  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
755  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
756  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
757  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
758  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
759  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
760  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
761  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
762  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
763  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
764  * SUCH DAMAGE.
765  */