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