Complie libbb/duration.c if ping[6] is selected
[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 source tree.
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 //config:config PING
28 //config:       bool "ping (9.5 kb)"
29 //config:       default y
30 //config:       select PLATFORM_LINUX
31 //config:       help
32 //config:       ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to
33 //config:       elicit an ICMP ECHO_RESPONSE from a host or gateway.
34 //config:
35 //config:config PING6
36 //config:       bool "ping6 (10 kb)"
37 //config:       default y
38 //config:       depends on FEATURE_IPV6
39 //config:       help
40 //config:       Alias to "ping -6".
41 //config:
42 //config:config FEATURE_FANCY_PING
43 //config:       bool "Enable fancy ping output"
44 //config:       default y
45 //config:       depends on PING || PING6
46 //config:       help
47 //config:       With this option off, ping will say "HOST is alive!"
48 //config:       or terminate with SIGALRM in 5 seconds otherwise.
49 //config:       No command-line options will be recognized.
50
51 /* Needs socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), therefore BB_SUID_MAYBE: */
52 //applet:IF_PING(APPLET(ping, BB_DIR_BIN, BB_SUID_MAYBE))
53 //applet:IF_PING6(APPLET(ping6, BB_DIR_BIN, BB_SUID_MAYBE))
54
55 //kbuild:lib-$(CONFIG_PING)  += ping.o
56 //kbuild:lib-$(CONFIG_PING6) += ping.o
57
58 //usage:#if !ENABLE_FEATURE_FANCY_PING
59 //usage:# define ping_trivial_usage
60 //usage:       "HOST"
61 //usage:# define ping_full_usage "\n\n"
62 //usage:       "Send ICMP ECHO_REQUEST packets to network hosts"
63 //usage:# define ping6_trivial_usage
64 //usage:       "HOST"
65 //usage:# define ping6_full_usage "\n\n"
66 //usage:       "Send ICMP ECHO_REQUEST packets to network hosts"
67 //usage:#else
68 //usage:# define ping_trivial_usage
69 //usage:       "[OPTIONS] HOST"
70 //usage:# define ping_full_usage "\n\n"
71 //usage:       "Send ICMP ECHO_REQUEST packets to network hosts\n"
72 //usage:        IF_PING6(
73 //usage:     "\n        -4,-6           Force IP or IPv6 name resolution"
74 //usage:        )
75 //usage:     "\n        -c CNT          Send only CNT pings"
76 //usage:     "\n        -s SIZE         Send SIZE data bytes in packets (default 56)"
77 //usage:     "\n        -i SECS         Interval"
78 //usage:     "\n        -A              Ping as soon as reply is recevied"
79 //usage:     "\n        -t TTL          Set TTL"
80 //usage:     "\n        -I IFACE/IP     Source interface or IP address"
81 //usage:     "\n        -W SEC          Seconds to wait for the first response (default 10)"
82 //usage:     "\n                        (after all -c CNT packets are sent)"
83 //usage:     "\n        -w SEC          Seconds until ping exits (default:infinite)"
84 //usage:     "\n                        (can exit earlier with -c CNT)"
85 //usage:     "\n        -q              Quiet, only display output at start"
86 //usage:     "\n                        and when finished"
87 //usage:     "\n        -p HEXBYTE      Pattern to use for payload"
88 //usage:
89 //usage:# define ping6_trivial_usage
90 //usage:       "[OPTIONS] HOST"
91 //usage:# define ping6_full_usage "\n\n"
92 //usage:       "Send ICMP ECHO_REQUEST packets to network hosts\n"
93 //usage:     "\n        -c CNT          Send only CNT pings"
94 //usage:     "\n        -s SIZE         Send SIZE data bytes in packets (default 56)"
95 //usage:     "\n        -i SECS         Interval"
96 //usage:     "\n        -A              Ping as soon as reply is recevied"
97 //usage:     "\n        -I IFACE/IP     Source interface or IP address"
98 //usage:     "\n        -q              Quiet, only display output at start"
99 //usage:     "\n                        and when finished"
100 //usage:     "\n        -p HEXBYTE      Pattern to use for payload"
101 //usage:
102 //usage:#endif
103 //usage:
104 //usage:#define ping_example_usage
105 //usage:       "$ ping localhost\n"
106 //usage:       "PING slag (127.0.0.1): 56 data bytes\n"
107 //usage:       "64 bytes from 127.0.0.1: icmp_seq=0 ttl=255 time=20.1 ms\n"
108 //usage:       "\n"
109 //usage:       "--- debian ping statistics ---\n"
110 //usage:       "1 packets transmitted, 1 packets received, 0% packet loss\n"
111 //usage:       "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
112 //usage:#define ping6_example_usage
113 //usage:       "$ ping6 ip6-localhost\n"
114 //usage:       "PING ip6-localhost (::1): 56 data bytes\n"
115 //usage:       "64 bytes from ::1: icmp6_seq=0 ttl=64 time=20.1 ms\n"
116 //usage:       "\n"
117 //usage:       "--- ip6-localhost ping statistics ---\n"
118 //usage:       "1 packets transmitted, 1 packets received, 0% packet loss\n"
119 //usage:       "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
120
121 #include <net/if.h>
122 #include <netinet/ip_icmp.h>
123 #include "libbb.h"
124 #include "common_bufsiz.h"
125
126 #ifdef __BIONIC__
127 /* should be in netinet/ip_icmp.h */
128 # define ICMP_DEST_UNREACH    3  /* Destination Unreachable  */
129 # define ICMP_SOURCE_QUENCH   4  /* Source Quench    */
130 # define ICMP_REDIRECT        5  /* Redirect (change route)  */
131 # define ICMP_ECHO            8  /* Echo Request      */
132 # define ICMP_TIME_EXCEEDED  11  /* Time Exceeded    */
133 # define ICMP_PARAMETERPROB  12  /* Parameter Problem    */
134 # define ICMP_TIMESTAMP      13  /* Timestamp Request    */
135 # define ICMP_TIMESTAMPREPLY 14  /* Timestamp Reply    */
136 # define ICMP_INFO_REQUEST   15  /* Information Request    */
137 # define ICMP_INFO_REPLY     16  /* Information Reply    */
138 # define ICMP_ADDRESS        17  /* Address Mask Request    */
139 # define ICMP_ADDRESSREPLY   18  /* Address Mask Reply    */
140 #endif
141
142 /* Some operating systems, like GNU/Hurd, don't define SOL_RAW, but do have
143  * IPPROTO_RAW. Since the IPPROTO definitions are also valid to use for
144  * setsockopt (and take the same value as their corresponding SOL definitions,
145  * if they exist), we can just fall back on IPPROTO_RAW. */
146 #ifndef SOL_RAW
147 # define SOL_RAW IPPROTO_RAW
148 #endif
149
150 #if ENABLE_PING6
151 # include <netinet/icmp6.h>
152 /* I see RENUMBERED constants in bits/in.h - !!?
153  * What a fuck is going on with libc? Is it a glibc joke? */
154 # ifdef IPV6_2292HOPLIMIT
155 #  undef IPV6_HOPLIMIT
156 #  define IPV6_HOPLIMIT IPV6_2292HOPLIMIT
157 # endif
158 #endif
159
160 enum {
161         DEFDATALEN = 56,
162         MAXIPLEN = 60,
163         MAXICMPLEN = 76,
164         MAX_DUP_CHK = (8 * 128),
165         MAXWAIT = 10,
166         PINGINTERVAL = 1, /* 1 second */
167         pingsock = 0,
168 };
169
170 static void
171 #if ENABLE_PING6
172 create_icmp_socket(len_and_sockaddr *lsa)
173 #else
174 create_icmp_socket(void)
175 #define create_icmp_socket(lsa) create_icmp_socket()
176 #endif
177 {
178         int sock;
179 #if ENABLE_PING6
180         if (lsa->u.sa.sa_family == AF_INET6)
181                 sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
182         else
183 #endif
184                 sock = socket(AF_INET, SOCK_RAW, 1); /* 1 == ICMP */
185         if (sock < 0) {
186                 if (errno == EPERM)
187                         bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
188                 bb_perror_msg_and_die(bb_msg_can_not_create_raw_socket);
189         }
190
191         xmove_fd(sock, pingsock);
192 }
193
194 #if !ENABLE_FEATURE_FANCY_PING
195
196 /* Simple version */
197
198 struct globals {
199         char *hostname;
200         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
201         uint16_t myid;
202 } FIX_ALIASING;
203 #define G (*(struct globals*)bb_common_bufsiz1)
204 #define INIT_G() do { setup_common_bufsiz(); } while (0)
205
206 static void noresp(int ign UNUSED_PARAM)
207 {
208         printf("No response from %s\n", G.hostname);
209         exit(EXIT_FAILURE);
210 }
211
212 static void ping4(len_and_sockaddr *lsa)
213 {
214         struct icmp *pkt;
215         int c;
216
217         pkt = (struct icmp *) G.packet;
218         /*memset(pkt, 0, sizeof(G.packet)); already is */
219         pkt->icmp_type = ICMP_ECHO;
220         pkt->icmp_id = G.myid;
221         pkt->icmp_cksum = inet_cksum((uint16_t *) pkt, sizeof(G.packet));
222
223         xsendto(pingsock, G.packet, DEFDATALEN + ICMP_MINLEN, &lsa->u.sa, lsa->len);
224
225         /* listen for replies */
226         while (1) {
227 #if 0
228                 struct sockaddr_in from;
229                 socklen_t fromlen = sizeof(from);
230
231                 c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
232                                 (struct sockaddr *) &from, &fromlen);
233 #else
234                 c = recv(pingsock, G.packet, sizeof(G.packet), 0);
235 #endif
236                 if (c < 0) {
237                         if (errno != EINTR)
238                                 bb_perror_msg("recvfrom");
239                         continue;
240                 }
241                 if (c >= 76) {                  /* ip + icmp */
242                         struct iphdr *iphdr = (struct iphdr *) G.packet;
243
244                         pkt = (struct icmp *) (G.packet + (iphdr->ihl << 2));   /* skip ip hdr */
245                         if (pkt->icmp_id != G.myid)
246                                 continue; /* not our ping */
247                         if (pkt->icmp_type == ICMP_ECHOREPLY)
248                                 break;
249                 }
250         }
251 }
252
253 #if ENABLE_PING6
254 static void ping6(len_and_sockaddr *lsa)
255 {
256         struct icmp6_hdr *pkt;
257         int c;
258         int sockopt;
259
260         pkt = (struct icmp6_hdr *) G.packet;
261         /*memset(pkt, 0, sizeof(G.packet)); already is */
262         pkt->icmp6_type = ICMP6_ECHO_REQUEST;
263         pkt->icmp6_id = G.myid;
264
265         sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
266         setsockopt_int(pingsock, SOL_RAW, IPV6_CHECKSUM, sockopt);
267
268         xsendto(pingsock, G.packet, DEFDATALEN + sizeof(struct icmp6_hdr), &lsa->u.sa, lsa->len);
269
270         /* listen for replies */
271         while (1) {
272 #if 0
273                 struct sockaddr_in6 from;
274                 socklen_t fromlen = sizeof(from);
275
276                 c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
277                                 (struct sockaddr *) &from, &fromlen);
278 #else
279                 c = recv(pingsock, G.packet, sizeof(G.packet), 0);
280 #endif
281                 if (c < 0) {
282                         if (errno != EINTR)
283                                 bb_perror_msg("recvfrom");
284                         continue;
285                 }
286                 if (c >= ICMP_MINLEN) { /* icmp6_hdr */
287                         if (pkt->icmp6_id != G.myid)
288                                 continue; /* not our ping */
289                         if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
290                                 break;
291                 }
292         }
293 }
294 #endif
295
296 #if !ENABLE_PING6
297 # define common_ping_main(af, argv) common_ping_main(argv)
298 #endif
299 static int common_ping_main(sa_family_t af, char **argv)
300 {
301         len_and_sockaddr *lsa;
302
303         INIT_G();
304
305 #if ENABLE_PING6
306         while ((++argv)[0] && argv[0][0] == '-') {
307                 if (argv[0][1] == '4') {
308                         af = AF_INET;
309                         continue;
310                 }
311                 if (argv[0][1] == '6') {
312                         af = AF_INET6;
313                         continue;
314                 }
315                 bb_show_usage();
316         }
317 #else
318         argv++;
319 #endif
320
321         G.hostname = *argv;
322         if (!G.hostname)
323                 bb_show_usage();
324
325 #if ENABLE_PING6
326         lsa = xhost_and_af2sockaddr(G.hostname, 0, af);
327 #else
328         lsa = xhost_and_af2sockaddr(G.hostname, 0, AF_INET);
329 #endif
330         /* Set timer _after_ DNS resolution */
331         signal(SIGALRM, noresp);
332         alarm(5); /* give the host 5000ms to respond */
333
334         create_icmp_socket(lsa);
335         G.myid = (uint16_t) getpid();
336 #if ENABLE_PING6
337         if (lsa->u.sa.sa_family == AF_INET6)
338                 ping6(lsa);
339         else
340 #endif
341                 ping4(lsa);
342         if (ENABLE_FEATURE_CLEAN_UP)
343                 close(pingsock);
344         printf("%s is alive!\n", G.hostname);
345         return EXIT_SUCCESS;
346 }
347
348
349 #else /* FEATURE_FANCY_PING */
350
351
352 /* Full(er) version */
353
354 /* -c NUM, -t NUM, -w NUM, -W NUM */
355 #define OPT_STRING "qvAc:+s:t:+w:+W:+I:np:i:4"IF_PING6("6")
356 enum {
357         OPT_QUIET = 1 << 0,
358         OPT_VERBOSE = 1 << 1,
359         OPT_A = 1 << 2,
360         OPT_c = 1 << 3,
361         OPT_s = 1 << 4,
362         OPT_t = 1 << 5,
363         OPT_w = 1 << 6,
364         OPT_W = 1 << 7,
365         OPT_I = 1 << 8,
366         /*OPT_n = 1 << 9, - ignored */
367         OPT_p = 1 << 10,
368         OPT_i = 1 << 11,
369         OPT_IPV4 = 1 << 12,
370         OPT_IPV6 = (1 << 13) * ENABLE_PING6,
371 };
372
373
374 struct globals {
375         int if_index;
376         char *str_I;
377         len_and_sockaddr *source_lsa;
378         unsigned datalen;
379         unsigned pingcount; /* must be int-sized */
380         unsigned opt_ttl;
381         unsigned long ntransmitted, nreceived, nrepeats;
382         uint16_t myid;
383         uint8_t pattern;
384         unsigned tmin, tmax; /* in us */
385         unsigned long long tsum; /* in us, sum of all times */
386         unsigned cur_us; /* low word only, we don't need more */
387         unsigned deadline_us;
388         unsigned interval_us;
389         unsigned timeout;
390         unsigned sizeof_rcv_packet;
391         char *rcv_packet; /* [datalen + MAXIPLEN + MAXICMPLEN] */
392         void *snd_packet; /* [datalen + ipv4/ipv6_const] */
393         const char *hostname;
394         const char *dotted;
395         union {
396                 struct sockaddr sa;
397                 struct sockaddr_in sin;
398 #if ENABLE_PING6
399                 struct sockaddr_in6 sin6;
400 #endif
401         } pingaddr;
402         unsigned char rcvd_tbl[MAX_DUP_CHK / 8];
403 } FIX_ALIASING;
404 #define G (*(struct globals*)bb_common_bufsiz1)
405 #define if_index     (G.if_index    )
406 #define source_lsa   (G.source_lsa  )
407 #define str_I        (G.str_I       )
408 #define datalen      (G.datalen     )
409 #define pingcount    (G.pingcount   )
410 #define opt_ttl      (G.opt_ttl     )
411 #define myid         (G.myid        )
412 #define tmin         (G.tmin        )
413 #define tmax         (G.tmax        )
414 #define tsum         (G.tsum        )
415 #define timeout      (G.timeout     )
416 #define hostname     (G.hostname    )
417 #define dotted       (G.dotted      )
418 #define pingaddr     (G.pingaddr    )
419 #define rcvd_tbl     (G.rcvd_tbl    )
420 #define INIT_G() do { \
421         setup_common_bufsiz(); \
422         BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
423         datalen = DEFDATALEN; \
424         timeout = MAXWAIT; \
425         tmin = UINT_MAX; \
426 } while (0)
427
428
429 #define BYTE(bit)       rcvd_tbl[(bit)>>3]
430 #define MASK(bit)       (1 << ((bit) & 7))
431 #define SET(bit)        (BYTE(bit) |= MASK(bit))
432 #define CLR(bit)        (BYTE(bit) &= (~MASK(bit)))
433 #define TST(bit)        (BYTE(bit) & MASK(bit))
434
435 static void print_stats_and_exit(int junk) NORETURN;
436 static void print_stats_and_exit(int junk UNUSED_PARAM)
437 {
438         unsigned long ul;
439         unsigned long nrecv;
440
441         signal(SIGINT, SIG_IGN);
442
443         nrecv = G.nreceived;
444         printf("\n--- %s ping statistics ---\n"
445                 "%lu packets transmitted, "
446                 "%lu packets received, ",
447                 hostname, G.ntransmitted, nrecv
448         );
449         if (G.nrepeats)
450                 printf("%lu duplicates, ", G.nrepeats);
451         ul = G.ntransmitted;
452         if (ul != 0)
453                 ul = (ul - nrecv) * 100 / ul;
454         printf("%lu%% packet loss\n", ul);
455         if (tmin != UINT_MAX) {
456                 unsigned tavg = tsum / (nrecv + G.nrepeats);
457                 printf("round-trip min/avg/max = %u.%03u/%u.%03u/%u.%03u ms\n",
458                         tmin / 1000, tmin % 1000,
459                         tavg / 1000, tavg % 1000,
460                         tmax / 1000, tmax % 1000);
461         }
462         /* if condition is true, exit with 1 -- 'failure' */
463         exit(nrecv == 0 || (G.deadline_us && nrecv < pingcount));
464 }
465
466 static void sendping_tail(void (*sp)(int), int size_pkt)
467 {
468         int sz;
469
470         CLR((uint16_t)G.ntransmitted % MAX_DUP_CHK);
471         G.ntransmitted++;
472
473         size_pkt += datalen;
474
475         if (G.deadline_us) {
476                 unsigned n = G.cur_us - G.deadline_us;
477                 if ((int)n >= 0)
478                         print_stats_and_exit(0);
479         }
480
481         /* sizeof(pingaddr) can be larger than real sa size, but I think
482          * it doesn't matter */
483         sz = xsendto(pingsock, G.snd_packet, size_pkt, &pingaddr.sa, sizeof(pingaddr));
484         if (sz != size_pkt)
485                 bb_error_msg_and_die(bb_msg_write_error);
486
487         if (pingcount == 0 || G.ntransmitted < pingcount) {
488                 /* Didn't send all pings yet - schedule next in 1s */
489                 signal(SIGALRM, sp);
490                 ualarm(G.interval_us, 0);
491         } else { /* -c NN, and all NN are sent */
492                 /* Wait for the last ping to come back.
493                  * -W timeout: wait for a response in seconds.
494                  * Affects only timeout in absence of any responses,
495                  * otherwise ping waits for two RTTs. */
496                 unsigned expire = timeout;
497
498                 if (G.nreceived) {
499                         /* approx. 2*tmax, in seconds (2 RTT) */
500                         expire = tmax / (512*1024);
501                         if (expire == 0)
502                                 expire = 1;
503                 }
504                 signal(SIGALRM, print_stats_and_exit);
505                 alarm(expire);
506         }
507 }
508
509 static void sendping4(int junk UNUSED_PARAM)
510 {
511         struct icmp *pkt = G.snd_packet;
512
513         memset(pkt, G.pattern, datalen + ICMP_MINLEN + 4);
514         pkt->icmp_type = ICMP_ECHO;
515         /*pkt->icmp_code = 0;*/
516         pkt->icmp_cksum = 0; /* cksum is calculated with this field set to 0 */
517         pkt->icmp_seq = htons(G.ntransmitted); /* don't ++ here, it can be a macro */
518         pkt->icmp_id = myid;
519
520         /* If datalen < 4, we store timestamp _past_ the packet,
521          * but it's ok - we allocated 4 extra bytes in xzalloc() just in case.
522          */
523         /*if (datalen >= 4)*/
524                 /* No hton: we'll read it back on the same machine */
525                 *(uint32_t*)&pkt->icmp_dun = G.cur_us = monotonic_us();
526
527         pkt->icmp_cksum = inet_cksum((uint16_t *) pkt, datalen + ICMP_MINLEN);
528
529         sendping_tail(sendping4, ICMP_MINLEN);
530 }
531 #if ENABLE_PING6
532 static void sendping6(int junk UNUSED_PARAM)
533 {
534         struct icmp6_hdr *pkt = G.snd_packet;
535
536         memset(pkt, G.pattern, datalen + sizeof(struct icmp6_hdr) + 4);
537         pkt->icmp6_type = ICMP6_ECHO_REQUEST;
538         /*pkt->icmp6_code = 0;*/
539         /*pkt->icmp6_cksum = 0;*/
540         pkt->icmp6_seq = htons(G.ntransmitted); /* don't ++ here, it can be a macro */
541         pkt->icmp6_id = myid;
542
543         /*if (datalen >= 4)*/
544                 *(bb__aliased_uint32_t*)(&pkt->icmp6_data8[4]) = G.cur_us = monotonic_us();
545
546         //TODO? pkt->icmp_cksum = inet_cksum(...);
547
548         sendping_tail(sendping6, sizeof(struct icmp6_hdr));
549 }
550 #endif
551
552 static const char *icmp_type_name(int id)
553 {
554         switch (id) {
555         case ICMP_ECHOREPLY:      return "Echo Reply";
556         case ICMP_DEST_UNREACH:   return "Destination Unreachable";
557         case ICMP_SOURCE_QUENCH:  return "Source Quench";
558         case ICMP_REDIRECT:       return "Redirect (change route)";
559         case ICMP_ECHO:           return "Echo Request";
560         case ICMP_TIME_EXCEEDED:  return "Time Exceeded";
561         case ICMP_PARAMETERPROB:  return "Parameter Problem";
562         case ICMP_TIMESTAMP:      return "Timestamp Request";
563         case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
564         case ICMP_INFO_REQUEST:   return "Information Request";
565         case ICMP_INFO_REPLY:     return "Information Reply";
566         case ICMP_ADDRESS:        return "Address Mask Request";
567         case ICMP_ADDRESSREPLY:   return "Address Mask Reply";
568         default:                  return "unknown ICMP type";
569         }
570 }
571 #if ENABLE_PING6
572 /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
573  * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
574 #ifndef MLD_LISTENER_QUERY
575 # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
576 #endif
577 #ifndef MLD_LISTENER_REPORT
578 # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
579 #endif
580 #ifndef MLD_LISTENER_REDUCTION
581 # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
582 #endif
583 static const char *icmp6_type_name(int id)
584 {
585         switch (id) {
586         case ICMP6_DST_UNREACH:      return "Destination Unreachable";
587         case ICMP6_PACKET_TOO_BIG:   return "Packet too big";
588         case ICMP6_TIME_EXCEEDED:    return "Time Exceeded";
589         case ICMP6_PARAM_PROB:       return "Parameter Problem";
590         case ICMP6_ECHO_REPLY:       return "Echo Reply";
591         case ICMP6_ECHO_REQUEST:     return "Echo Request";
592         case MLD_LISTENER_QUERY:     return "Listener Query";
593         case MLD_LISTENER_REPORT:    return "Listener Report";
594         case MLD_LISTENER_REDUCTION: return "Listener Reduction";
595         default:                     return "unknown ICMP type";
596         }
597 }
598 #endif
599
600 static void unpack_tail(int sz, uint32_t *tp,
601                 const char *from_str,
602                 uint16_t recv_seq, int ttl)
603 {
604         unsigned char *b, m;
605         const char *dupmsg = " (DUP!)";
606         unsigned triptime = triptime; /* for gcc */
607
608         if (tp) {
609                 /* (int32_t) cast is for hypothetical 64-bit unsigned */
610                 /* (doesn't hurt 32-bit real-world anyway) */
611                 triptime = (int32_t) ((uint32_t)monotonic_us() - *tp);
612                 tsum += triptime;
613                 if (triptime < tmin)
614                         tmin = triptime;
615                 if (triptime > tmax)
616                         tmax = triptime;
617         }
618
619         b = &BYTE(recv_seq % MAX_DUP_CHK);
620         m = MASK(recv_seq % MAX_DUP_CHK);
621         /*if TST(recv_seq % MAX_DUP_CHK):*/
622         if (*b & m) {
623                 ++G.nrepeats;
624         } else {
625                 /*SET(recv_seq % MAX_DUP_CHK):*/
626                 *b |= m;
627                 ++G.nreceived;
628                 dupmsg += 7;
629         }
630
631         if (option_mask32 & OPT_QUIET)
632                 return;
633
634         printf("%d bytes from %s: seq=%u ttl=%d", sz,
635                 from_str, recv_seq, ttl);
636         if (tp)
637                 printf(" time=%u.%03u ms", triptime / 1000, triptime % 1000);
638         puts(dupmsg);
639         fflush_all();
640 }
641 static int unpack4(char *buf, int sz, struct sockaddr_in *from)
642 {
643         struct icmp *icmppkt;
644         struct iphdr *iphdr;
645         int hlen;
646
647         /* discard if too short */
648         if (sz < (datalen + ICMP_MINLEN))
649                 return 0;
650
651         /* check IP header */
652         iphdr = (struct iphdr *) buf;
653         hlen = iphdr->ihl << 2;
654         sz -= hlen;
655         icmppkt = (struct icmp *) (buf + hlen);
656         if (icmppkt->icmp_id != myid)
657                 return 0;                               /* not our ping */
658
659         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
660                 uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
661                 uint32_t *tp = NULL;
662
663                 if (sz >= ICMP_MINLEN + sizeof(uint32_t))
664                         tp = (uint32_t *) icmppkt->icmp_data;
665                 unpack_tail(sz, tp,
666                         inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
667                         recv_seq, iphdr->ttl);
668                 return 1;
669         }
670         if (icmppkt->icmp_type != ICMP_ECHO) {
671                 bb_error_msg("warning: got ICMP %d (%s)",
672                                 icmppkt->icmp_type,
673                                 icmp_type_name(icmppkt->icmp_type));
674         }
675         return 0;
676 }
677 #if ENABLE_PING6
678 static int unpack6(char *packet, int sz, struct sockaddr_in6 *from, int hoplimit)
679 {
680         struct icmp6_hdr *icmppkt;
681         char buf[INET6_ADDRSTRLEN];
682
683         /* discard if too short */
684         if (sz < (datalen + sizeof(struct icmp6_hdr)))
685                 return 0;
686
687         icmppkt = (struct icmp6_hdr *) packet;
688         if (icmppkt->icmp6_id != myid)
689                 return 0;                               /* not our ping */
690
691         if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
692                 uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
693                 uint32_t *tp = NULL;
694
695                 if (sz >= sizeof(struct icmp6_hdr) + sizeof(uint32_t))
696                         tp = (uint32_t *) &icmppkt->icmp6_data8[4];
697                 unpack_tail(sz, tp,
698                         inet_ntop(AF_INET6, &from->sin6_addr,
699                                         buf, sizeof(buf)),
700                         recv_seq, hoplimit);
701                 return 1;
702         }
703         if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
704                 bb_error_msg("warning: got ICMP %d (%s)",
705                                 icmppkt->icmp6_type,
706                                 icmp6_type_name(icmppkt->icmp6_type));
707         }
708         return 0;
709 }
710 #endif
711
712 static void ping4(len_and_sockaddr *lsa)
713 {
714         int sockopt;
715
716         pingaddr.sin = lsa->u.sin;
717         if (source_lsa) {
718                 if (setsockopt(pingsock, IPPROTO_IP, IP_MULTICAST_IF,
719                                 &source_lsa->u.sa, source_lsa->len))
720                         bb_error_msg_and_die("can't set multicast source interface");
721                 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
722         }
723
724         /* enable broadcast pings */
725         setsockopt_broadcast(pingsock);
726
727         /* set recv buf (needed if we can get lots of responses: flood ping,
728          * broadcast ping etc) */
729         sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
730         setsockopt_SOL_SOCKET_int(pingsock, SO_RCVBUF, sockopt);
731
732         if (opt_ttl != 0) {
733                 setsockopt_int(pingsock, IPPROTO_IP, IP_TTL, opt_ttl);
734                 /* above doesn't affect packets sent to bcast IP, so... */
735                 setsockopt_int(pingsock, IPPROTO_IP, IP_MULTICAST_TTL, opt_ttl);
736         }
737
738         signal(SIGINT, print_stats_and_exit);
739
740         /* start the ping's going ... */
741  send_ping:
742         sendping4(0);
743
744         /* listen for replies */
745         while (1) {
746                 struct sockaddr_in from;
747                 socklen_t fromlen = (socklen_t) sizeof(from);
748                 int c;
749
750                 c = recvfrom(pingsock, G.rcv_packet, G.sizeof_rcv_packet, 0,
751                                 (struct sockaddr *) &from, &fromlen);
752                 if (c < 0) {
753                         if (errno != EINTR)
754                                 bb_perror_msg("recvfrom");
755                         continue;
756                 }
757                 c = unpack4(G.rcv_packet, c, &from);
758                 if (pingcount && G.nreceived >= pingcount)
759                         break;
760                 if (c && (option_mask32 & OPT_A)) {
761                         goto send_ping;
762                 }
763         }
764 }
765 #if ENABLE_PING6
766 static void ping6(len_and_sockaddr *lsa)
767 {
768         int sockopt;
769         struct msghdr msg;
770         struct sockaddr_in6 from;
771         struct iovec iov;
772         char control_buf[CMSG_SPACE(36)];
773
774         pingaddr.sin6 = lsa->u.sin6;
775         if (source_lsa)
776                 xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
777
778 #ifdef ICMP6_FILTER
779         {
780                 struct icmp6_filter filt;
781                 if (!(option_mask32 & OPT_VERBOSE)) {
782                         ICMP6_FILTER_SETBLOCKALL(&filt);
783                         ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
784                 } else {
785                         ICMP6_FILTER_SETPASSALL(&filt);
786                 }
787                 if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
788                                         sizeof(filt)) < 0)
789                         bb_error_msg_and_die("setsockopt(%s)", "ICMP6_FILTER");
790         }
791 #endif /*ICMP6_FILTER*/
792
793         /* enable broadcast pings */
794         setsockopt_broadcast(pingsock);
795
796         /* set recv buf (needed if we can get lots of responses: flood ping,
797          * broadcast ping etc) */
798         sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
799         setsockopt_SOL_SOCKET_int(pingsock, SO_RCVBUF, sockopt);
800
801         sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
802         BUILD_BUG_ON(offsetof(struct icmp6_hdr, icmp6_cksum) != 2);
803         setsockopt_int(pingsock, SOL_RAW, IPV6_CHECKSUM, sockopt);
804
805         /* request ttl info to be returned in ancillary data */
806         setsockopt_1(pingsock, SOL_IPV6, IPV6_HOPLIMIT);
807
808         if (if_index)
809                 pingaddr.sin6.sin6_scope_id = if_index;
810
811         signal(SIGINT, print_stats_and_exit);
812
813         msg.msg_name = &from;
814         msg.msg_namelen = sizeof(from);
815         msg.msg_iov = &iov;
816         msg.msg_iovlen = 1;
817         msg.msg_control = control_buf;
818         iov.iov_base = G.rcv_packet;
819         iov.iov_len = G.sizeof_rcv_packet;
820
821         /* start the ping's going ... */
822  send_ping:
823         sendping6(0);
824
825         /* listen for replies */
826         while (1) {
827                 int c;
828                 struct cmsghdr *mp;
829                 int hoplimit = -1;
830
831                 msg.msg_controllen = sizeof(control_buf);
832                 c = recvmsg(pingsock, &msg, 0);
833                 if (c < 0) {
834                         if (errno != EINTR)
835                                 bb_perror_msg("recvfrom");
836                         continue;
837                 }
838                 for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
839                         if (mp->cmsg_level == SOL_IPV6
840                          && mp->cmsg_type == IPV6_HOPLIMIT
841                          /* don't check len - we trust the kernel: */
842                          /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
843                         ) {
844                                 /*hoplimit = *(int*)CMSG_DATA(mp); - unaligned access */
845                                 move_from_unaligned_int(hoplimit, CMSG_DATA(mp));
846                         }
847                 }
848                 c = unpack6(G.rcv_packet, c, &from, hoplimit);
849                 if (pingcount && G.nreceived >= pingcount)
850                         break;
851                 if (c && (option_mask32 & OPT_A)) {
852                         goto send_ping;
853                 }
854         }
855 }
856 #endif
857
858 static void ping(len_and_sockaddr *lsa)
859 {
860         printf("PING %s (%s)", hostname, dotted);
861         if (source_lsa) {
862                 printf(" from %s",
863                         xmalloc_sockaddr2dotted_noport(&source_lsa->u.sa));
864         }
865         printf(": %d data bytes\n", datalen);
866
867         create_icmp_socket(lsa);
868         /* untested whether "-I addr" really works for IPv6: */
869         if (str_I)
870                 setsockopt_bindtodevice(pingsock, str_I);
871
872         G.sizeof_rcv_packet = datalen + MAXIPLEN + MAXICMPLEN;
873         G.rcv_packet = xzalloc(G.sizeof_rcv_packet);
874 #if ENABLE_PING6
875         if (lsa->u.sa.sa_family == AF_INET6) {
876                 /* +4 reserves a place for timestamp, which may end up sitting
877                  * _after_ packet. Saves one if() - see sendping4/6() */
878                 G.snd_packet = xzalloc(datalen + sizeof(struct icmp6_hdr) + 4);
879                 ping6(lsa);
880         } else
881 #endif
882         {
883                 G.snd_packet = xzalloc(datalen + ICMP_MINLEN + 4);
884                 ping4(lsa);
885         }
886 }
887
888 static int common_ping_main(int opt, char **argv)
889 {
890         len_and_sockaddr *lsa;
891         char *str_s, *str_p;
892         char *str_i = (char*)"1";
893         duration_t interval;
894
895         INIT_G();
896
897         opt |= getopt32(argv, "^"
898                         OPT_STRING
899                         /* exactly one arg; -v and -q don't mix */
900                         "\0" "=1:q--v:v--q",
901                         &pingcount, &str_s, &opt_ttl, &G.deadline_us, &timeout, &str_I, &str_p, &str_i
902         );
903         if (opt & OPT_s)
904                 datalen = xatou16(str_s); // -s
905         if (opt & OPT_I) { // -I
906                 if_index = if_nametoindex(str_I);
907                 if (!if_index) {
908                         /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
909                         source_lsa = xdotted2sockaddr(str_I, 0);
910                         str_I = NULL; /* don't try to bind to device later */
911                 }
912         }
913         if (opt & OPT_p)
914                 G.pattern = xstrtou_range(str_p, 16, 0, 255);
915         if (G.deadline_us) {
916                 unsigned d = G.deadline_us < INT_MAX/1000000 ? G.deadline_us : INT_MAX/1000000;
917                 G.deadline_us = 1 | ((d * 1000000) + monotonic_us());
918         }
919         interval = parse_duration_str(str_i);
920         if (interval > INT_MAX/1000000)
921                 interval = INT_MAX/1000000;
922         G.interval_us = interval * 1000000;
923
924         myid = (uint16_t) getpid();
925         hostname = argv[optind];
926 #if ENABLE_PING6
927         {
928                 sa_family_t af = AF_UNSPEC;
929                 if (opt & OPT_IPV4)
930                         af = AF_INET;
931                 if (opt & OPT_IPV6)
932                         af = AF_INET6;
933                 lsa = xhost_and_af2sockaddr(hostname, 0, af);
934         }
935 #else
936         lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
937 #endif
938
939         if (source_lsa && source_lsa->u.sa.sa_family != lsa->u.sa.sa_family)
940                 /* leaking it here... */
941                 source_lsa = NULL;
942
943         dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
944         ping(lsa);
945         print_stats_and_exit(0);
946         /*return EXIT_SUCCESS;*/
947 }
948 #endif /* FEATURE_FANCY_PING */
949
950
951 #if ENABLE_PING
952 int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
953 int ping_main(int argc UNUSED_PARAM, char **argv)
954 {
955 # if !ENABLE_FEATURE_FANCY_PING
956         return common_ping_main(AF_UNSPEC, argv);
957 # else
958         return common_ping_main(0, argv);
959 # endif
960 }
961 #endif
962
963 #if ENABLE_PING6
964 int ping6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
965 int ping6_main(int argc UNUSED_PARAM, char **argv)
966 {
967 # if !ENABLE_FEATURE_FANCY_PING
968         return common_ping_main(AF_INET6, argv);
969 # else
970         return common_ping_main(OPT_IPV6, argv);
971 # endif
972 }
973 #endif
974
975 /* from ping6.c:
976  * Copyright (c) 1989 The Regents of the University of California.
977  * All rights reserved.
978  *
979  * This code is derived from software contributed to Berkeley by
980  * Mike Muuss.
981  *
982  * Redistribution and use in source and binary forms, with or without
983  * modification, are permitted provided that the following conditions
984  * are met:
985  * 1. Redistributions of source code must retain the above copyright
986  *    notice, this list of conditions and the following disclaimer.
987  * 2. Redistributions in binary form must reproduce the above copyright
988  *    notice, this list of conditions and the following disclaimer in the
989  *    documentation and/or other materials provided with the distribution.
990  *
991  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
992  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
993  *
994  * 4. Neither the name of the University nor the names of its contributors
995  *    may be used to endorse or promote products derived from this software
996  *    without specific prior written permission.
997  *
998  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
999  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1000  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1001  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1002  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1003  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1004  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1005  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1006  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1007  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1008  * SUCH DAMAGE.
1009  */