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