ping6: fix sequence numbers (missed ntoh) and ttl display.
[oweals/busybox.git] / networking / ping.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * $Id: ping.c,v 1.56 2004/03/15 08:28:48 andersen Exp $
4  * Mini ping implementation for busybox
5  *
6  * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
7  *
8  * Adapted from the ping in netkit-base 0.10:
9  * Copyright (c) 1989 The Regents of the University of California.
10  * Derived from software contributed to Berkeley by Mike Muuss.
11  *
12  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
13  */
14
15 //#include <netinet/in.h>
16 //#include <netinet/ip.h>
17 #include <netinet/ip_icmp.h>
18 //#include <arpa/inet.h>
19 //#include <netdb.h>
20 #include "busybox.h"
21
22 enum {
23         DEFDATALEN = 56,
24         MAXIPLEN = 60,
25         MAXICMPLEN = 76,
26         MAXPACKET = 65468,
27         MAX_DUP_CHK = (8 * 128),
28         MAXWAIT = 10,
29         PINGINTERVAL = 1                /* second */
30 };
31
32 static void ping(const char *host);
33
34 /* common routines */
35
36 static int in_cksum(unsigned short *buf, int sz)
37 {
38         int nleft = sz;
39         int sum = 0;
40         unsigned short *w = buf;
41         unsigned short ans = 0;
42
43         while (nleft > 1) {
44                 sum += *w++;
45                 nleft -= 2;
46         }
47
48         if (nleft == 1) {
49                 *(unsigned char *) (&ans) = *(unsigned char *) w;
50                 sum += ans;
51         }
52
53         sum = (sum >> 16) + (sum & 0xFFFF);
54         sum += (sum >> 16);
55         ans = ~sum;
56         return ans;
57 }
58
59 #ifndef CONFIG_FEATURE_FANCY_PING
60
61 /* simple version */
62
63 static char *hostname;
64
65 static void noresp(int ign)
66 {
67         printf("No response from %s\n", hostname);
68         exit(EXIT_FAILURE);
69 }
70
71 static void ping(const char *host)
72 {
73         struct hostent *h;
74         struct sockaddr_in pingaddr;
75         struct icmp *pkt;
76         int pingsock, c;
77         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
78
79         pingsock = create_icmp_socket();
80
81         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
82
83         pingaddr.sin_family = AF_INET;
84         h = xgethostbyname(host);
85         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
86         hostname = h->h_name;
87
88         pkt = (struct icmp *) packet;
89         memset(pkt, 0, sizeof(packet));
90         pkt->icmp_type = ICMP_ECHO;
91         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
92
93         c = sendto(pingsock, packet, DEFDATALEN + ICMP_MINLEN, 0,
94                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
95
96         if (c < 0) {
97                 if (ENABLE_FEATURE_CLEAN_UP) close(pingsock);
98                 bb_perror_msg_and_die("sendto");
99         }
100
101         signal(SIGALRM, noresp);
102         alarm(5);                                       /* give the host 5000ms to respond */
103         /* listen for replies */
104         while (1) {
105                 struct sockaddr_in from;
106                 socklen_t fromlen = sizeof(from);
107
108                 c = recvfrom(pingsock, packet, sizeof(packet), 0,
109                                 (struct sockaddr *) &from, &fromlen);
110                 if (c < 0) {
111                         if (errno != EINTR)
112                                 bb_perror_msg("recvfrom");
113                         continue;
114                 }
115                 if (c >= 76) {                  /* ip + icmp */
116                         struct iphdr *iphdr = (struct iphdr *) packet;
117
118                         pkt = (struct icmp *) (packet + (iphdr->ihl << 2));     /* skip ip hdr */
119                         if (pkt->icmp_type == ICMP_ECHOREPLY)
120                                 break;
121                 }
122         }
123         if (ENABLE_FEATURE_CLEAN_UP) close(pingsock);
124         printf("%s is alive!\n", hostname);
125 }
126
127 int ping_main(int argc, char **argv)
128 {
129         argc--;
130         argv++;
131         if (argc < 1)
132                 bb_show_usage();
133         ping(*argv);
134         return EXIT_SUCCESS;
135 }
136
137 #else /* ! CONFIG_FEATURE_FANCY_PING */
138
139 /* full(er) version */
140
141 #define OPT_STRING "qc:s:I:"
142 enum {
143         OPT_QUIET = 1 << 0,
144 };
145
146 static struct sockaddr_in pingaddr;
147 static struct sockaddr_in sourceaddr;
148 static int pingsock = -1;
149 static unsigned datalen; /* intentionally uninitialized to work around gcc bug */
150
151 static unsigned long ntransmitted, nreceived, nrepeats, pingcount;
152 static int myid;
153 static unsigned long tmin = ULONG_MAX, tmax, tsum;
154 static char rcvd_tbl[MAX_DUP_CHK / 8];
155
156 static struct hostent *hostent;
157
158 static void sendping(int);
159 static void pingstats(int);
160 static void unpack(char *, int, struct sockaddr_in *);
161
162 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
163 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
164 #define SET(bit)        (A(bit) |= B(bit))
165 #define CLR(bit)        (A(bit) &= (~B(bit)))
166 #define TST(bit)        (A(bit) & B(bit))
167
168 /**************************************************************************/
169
170 static void pingstats(int junk)
171 {
172         int status;
173
174         signal(SIGINT, SIG_IGN);
175
176         printf("\n--- %s ping statistics ---\n", hostent->h_name);
177         printf("%lu packets transmitted, ", ntransmitted);
178         printf("%lu packets received, ", nreceived);
179         if (nrepeats)
180                 printf("%lu duplicates, ", nrepeats);
181         if (ntransmitted)
182                 printf("%lu%% packet loss\n",
183                            (ntransmitted - nreceived) * 100 / ntransmitted);
184         if (nreceived)
185                 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
186                            tmin / 10, tmin % 10,
187                            (tsum / (nreceived + nrepeats)) / 10,
188                            (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
189         if (nreceived != 0)
190                 status = EXIT_SUCCESS;
191         else
192                 status = EXIT_FAILURE;
193         exit(status);
194 }
195
196 static void sendping(int junk)
197 {
198         struct icmp *pkt;
199         int i;
200         char packet[datalen + ICMP_MINLEN];
201
202         pkt = (struct icmp *) packet;
203
204         pkt->icmp_type = ICMP_ECHO;
205         pkt->icmp_code = 0;
206         pkt->icmp_cksum = 0;
207         pkt->icmp_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
208         pkt->icmp_id = myid;
209         CLR(ntohs(pkt->icmp_seq) % MAX_DUP_CHK);
210         ntransmitted++;
211
212         gettimeofday((struct timeval *) &pkt->icmp_dun, NULL);
213         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
214
215         i = sendto(pingsock, packet, sizeof(packet), 0,
216                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
217
218         if (i < 0)
219                 bb_perror_msg_and_die("sendto");
220         if ((size_t)i != sizeof(packet))
221                 bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
222                            (int)sizeof(packet));
223
224         signal(SIGALRM, sendping);
225         if (pingcount == 0 || ntransmitted < pingcount) {       /* schedule next in 1s */
226                 alarm(PINGINTERVAL);
227         } else {                                        /* done, wait for the last ping to come back */
228                 /* todo, don't necessarily need to wait so long... */
229                 signal(SIGALRM, pingstats);
230                 alarm(MAXWAIT);
231         }
232 }
233
234 static char *icmp_type_name(int id)
235 {
236         switch (id) {
237         case ICMP_ECHOREPLY:            return "Echo Reply";
238         case ICMP_DEST_UNREACH:         return "Destination Unreachable";
239         case ICMP_SOURCE_QUENCH:        return "Source Quench";
240         case ICMP_REDIRECT:                     return "Redirect (change route)";
241         case ICMP_ECHO:                         return "Echo Request";
242         case ICMP_TIME_EXCEEDED:        return "Time Exceeded";
243         case ICMP_PARAMETERPROB:        return "Parameter Problem";
244         case ICMP_TIMESTAMP:            return "Timestamp Request";
245         case ICMP_TIMESTAMPREPLY:       return "Timestamp Reply";
246         case ICMP_INFO_REQUEST:         return "Information Request";
247         case ICMP_INFO_REPLY:           return "Information Reply";
248         case ICMP_ADDRESS:                      return "Address Mask Request";
249         case ICMP_ADDRESSREPLY:         return "Address Mask Reply";
250         default:                                        return "unknown ICMP type";
251         }
252 }
253
254 static void unpack(char *buf, int sz, struct sockaddr_in *from)
255 {
256         struct icmp *icmppkt;
257         struct iphdr *iphdr;
258         struct timeval tv, *tp;
259         int hlen, dupflag;
260         unsigned long triptime;
261
262         gettimeofday(&tv, NULL);
263
264         /* discard if too short */
265         if (sz < (datalen + ICMP_MINLEN))
266                 return;
267
268         /* check IP header */
269         iphdr = (struct iphdr *) buf;
270         hlen = iphdr->ihl << 2;
271         sz -= hlen;
272         icmppkt = (struct icmp *) (buf + hlen);
273         if (icmppkt->icmp_id != myid)
274                 return;                         /* not our ping */
275
276         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
277                 u_int16_t recv_seq = ntohs(icmppkt->icmp_seq);
278                 ++nreceived;
279                 tp = (struct timeval *) icmppkt->icmp_data;
280
281                 if ((tv.tv_usec -= tp->tv_usec) < 0) {
282                         --tv.tv_sec;
283                         tv.tv_usec += 1000000;
284                 }
285                 tv.tv_sec -= tp->tv_sec;
286
287                 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
288                 tsum += triptime;
289                 if (triptime < tmin)
290                         tmin = triptime;
291                 if (triptime > tmax)
292                         tmax = triptime;
293
294                 if (TST(recv_seq % MAX_DUP_CHK)) {
295                         ++nrepeats;
296                         --nreceived;
297                         dupflag = 1;
298                 } else {
299                         SET(recv_seq % MAX_DUP_CHK);
300                         dupflag = 0;
301                 }
302
303                 if (option_mask32 & OPT_QUIET)
304                         return;
305
306                 printf("%d bytes from %s: icmp_seq=%u", sz,
307                            inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
308                            recv_seq);
309                 printf(" ttl=%d", iphdr->ttl);
310                 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
311                 if (dupflag)
312                         printf(" (DUP!)");
313                 puts("");
314         } else
315                 if (icmppkt->icmp_type != ICMP_ECHO)
316                         bb_error_msg("warning: got ICMP %d (%s)",
317                                         icmppkt->icmp_type,
318                                         icmp_type_name(icmppkt->icmp_type));
319         fflush(stdout);
320 }
321
322 static void ping(const char *host)
323 {
324         char packet[datalen + MAXIPLEN + MAXICMPLEN];
325         int sockopt;
326
327         pingsock = create_icmp_socket();
328
329         if (sourceaddr.sin_addr.s_addr) {
330                 xbind(pingsock, (struct sockaddr*)&sourceaddr, sizeof(sourceaddr));
331         }
332
333         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
334
335         pingaddr.sin_family = AF_INET;
336         hostent = xgethostbyname(host);
337         if (hostent->h_addrtype != AF_INET)
338                 bb_error_msg_and_die("unknown address type; only AF_INET is currently supported");
339
340         memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
341
342         /* enable broadcast pings */
343         setsockopt_broadcast(pingsock);
344
345         /* set recv buf for broadcast pings */
346         sockopt = 48 * 1024;
347         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
348                            sizeof(sockopt));
349
350         printf("PING %s (%s)",
351                         hostent->h_name,
352                         inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr));
353         if (sourceaddr.sin_addr.s_addr) {
354                 printf(" from %s",
355                         inet_ntoa(*(struct in_addr *) &sourceaddr.sin_addr.s_addr));
356         }
357         printf(": %d data bytes\n", datalen);
358
359         signal(SIGINT, pingstats);
360
361         /* start the ping's going ... */
362         sendping(0);
363
364         /* listen for replies */
365         while (1) {
366                 struct sockaddr_in from;
367                 socklen_t fromlen = (socklen_t) sizeof(from);
368                 int c;
369
370                 c = recvfrom(pingsock, packet, sizeof(packet), 0,
371                                 (struct sockaddr *) &from, &fromlen);
372                 if (c < 0) {
373                         if (errno != EINTR)
374                                 bb_perror_msg("recvfrom");
375                         continue;
376                 }
377                 unpack(packet, c, &from);
378                 if (pingcount > 0 && nreceived >= pingcount)
379                         break;
380         }
381         pingstats(0);
382 }
383
384 /* TODO: consolidate ether-wake.c, dnsd.c, ifupdown.c, nslookup.c
385  * versions of below thing. BTW we have far too many "%u.%u.%u.%u" too...
386 */
387 static int parse_nipquad(const char *str, struct sockaddr_in* addr)
388 {
389         char dummy;
390         unsigned i1, i2, i3, i4;
391         if (sscanf(str, "%u.%u.%u.%u%c",
392                            &i1, &i2, &i3, &i4, &dummy) == 4
393         && ( (i1|i2|i3|i4) <= 0xff )
394         ) {
395                 uint8_t* ptr = (uint8_t*)&addr->sin_addr;
396                 ptr[0] = i1;
397                 ptr[1] = i2;
398                 ptr[2] = i3;
399                 ptr[3] = i4;
400                 return 0;
401         }
402         return 1; /* error */
403 }
404
405 int ping_main(int argc, char **argv)
406 {
407         char *opt_c, *opt_s, *opt_I;
408
409         datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
410
411         /* exactly one argument needed */
412         opt_complementary = "=1";
413         getopt32(argc, argv, OPT_STRING, &opt_c, &opt_s, &opt_I);
414         if (option_mask32 & 2) pingcount = xatoul(opt_c); // -c
415         if (option_mask32 & 4) datalen = xatou16(opt_s); // -s
416         if (option_mask32 & 8) { // -I
417 /* TODO: ping6 accepts iface too:
418                 if_index = if_nametoindex(*argv);
419                 if (!if_index) ...
420 make it true for ping. */
421                 if (parse_nipquad(opt_I, &sourceaddr))
422                         bb_show_usage();
423         }
424
425         myid = (int16_t) getpid();
426         ping(argv[optind]);
427         return EXIT_SUCCESS;
428 }
429 #endif /* ! CONFIG_FEATURE_FANCY_PING */