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