2006-03-21 Shaun Jackman <sjackman@gmail.com>: Include signal.h instead of sys...
[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 <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 enum {
37         DEFDATALEN = 56,
38         MAXIPLEN = 60,
39         MAXICMPLEN = 76,
40         MAXPACKET = 65468,
41         MAX_DUP_CHK = (8 * 128),
42         MAXWAIT = 10,
43         PINGINTERVAL = 1                /* second */
44 };
45
46 #define O_QUIET         (1 << 0)
47
48 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
49 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
50 #define SET(bit)        (A(bit) |= B(bit))
51 #define CLR(bit)        (A(bit) &= (~B(bit)))
52 #define TST(bit)        (A(bit) & B(bit))
53
54 static void ping(const char *host);
55
56 /* common routines */
57 static int in_cksum(unsigned short *buf, int sz)
58 {
59         int nleft = sz;
60         int sum = 0;
61         unsigned short *w = buf;
62         unsigned short ans = 0;
63
64         while (nleft > 1) {
65                 sum += *w++;
66                 nleft -= 2;
67         }
68
69         if (nleft == 1) {
70                 *(unsigned char *) (&ans) = *(unsigned char *) w;
71                 sum += ans;
72         }
73
74         sum = (sum >> 16) + (sum & 0xFFFF);
75         sum += (sum >> 16);
76         ans = ~sum;
77         return (ans);
78 }
79
80 /* simple version */
81 #ifndef CONFIG_FEATURE_FANCY_PING
82 static char *hostname = NULL;
83 static void noresp(int ign)
84 {
85         printf("No response from %s\n", hostname);
86         exit(EXIT_FAILURE);
87 }
88
89 static void ping(const char *host)
90 {
91         struct hostent *h;
92         struct sockaddr_in pingaddr;
93         struct icmp *pkt;
94         int pingsock, c;
95         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
96
97         pingsock = create_icmp_socket();
98
99         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
100
101         pingaddr.sin_family = AF_INET;
102         h = xgethostbyname(host);
103         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
104         hostname = h->h_name;
105
106         pkt = (struct icmp *) packet;
107         memset(pkt, 0, sizeof(packet));
108         pkt->icmp_type = ICMP_ECHO;
109         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
110
111         c = sendto(pingsock, packet, sizeof(packet), 0,
112                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
113
114         if (c < 0 || c != sizeof(packet))
115                 bb_perror_msg_and_die("sendto");
116
117         signal(SIGALRM, noresp);
118         alarm(5);                                       /* give the host 5000ms to respond */
119         /* listen for replies */
120         while (1) {
121                 struct sockaddr_in from;
122                 socklen_t fromlen = sizeof(from);
123
124                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
125                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
126                         if (errno == EINTR)
127                                 continue;
128                         bb_perror_msg("recvfrom");
129                         continue;
130                 }
131                 if (c >= 76) {                  /* ip + icmp */
132                         struct iphdr *iphdr = (struct iphdr *) packet;
133
134                         pkt = (struct icmp *) (packet + (iphdr->ihl << 2));     /* skip ip hdr */
135                         if (pkt->icmp_type == ICMP_ECHOREPLY)
136                                 break;
137                 }
138         }
139         printf("%s is alive!\n", hostname);
140         return;
141 }
142
143 int ping_main(int argc, char **argv)
144 {
145         argc--;
146         argv++;
147         if (argc < 1)
148                 bb_show_usage();
149         ping(*argv);
150         return EXIT_SUCCESS;
151 }
152
153 #else /* ! CONFIG_FEATURE_FANCY_PING */
154 /* full(er) version */
155 static struct sockaddr_in pingaddr;
156 static int pingsock = -1;
157 static int datalen; /* intentionally uninitialized to work around gcc bug */
158
159 static long ntransmitted, nreceived, nrepeats, pingcount;
160 static int myid, options;
161 static unsigned long tmin = ULONG_MAX, tmax, tsum;
162 static char rcvd_tbl[MAX_DUP_CHK / 8];
163
164 #ifndef CONFIG_FEATURE_FANCY_PING6
165 static
166 #endif
167         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 + sizeof(struct icmp)];
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         /* check IP header */
269         iphdr = (struct iphdr *) buf;
270         hlen = iphdr->ihl << 2;
271         /* discard if too short */
272         if (sz < (datalen + ICMP_MINLEN))
273                 return;
274
275         sz -= hlen;
276         icmppkt = (struct icmp *) (buf + hlen);
277
278         if (icmppkt->icmp_id != myid)
279             return;                             /* not our ping */
280
281         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
282                 u_int16_t recv_seq = ntohs(icmppkt->icmp_seq);
283             ++nreceived;
284                 tp = (struct timeval *) icmppkt->icmp_data;
285
286                 if ((tv.tv_usec -= tp->tv_usec) < 0) {
287                         --tv.tv_sec;
288                         tv.tv_usec += 1000000;
289                 }
290                 tv.tv_sec -= tp->tv_sec;
291
292                 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
293                 tsum += triptime;
294                 if (triptime < tmin)
295                         tmin = triptime;
296                 if (triptime > tmax)
297                         tmax = triptime;
298
299                 if (TST(recv_seq % MAX_DUP_CHK)) {
300                         ++nrepeats;
301                         --nreceived;
302                         dupflag = 1;
303                 } else {
304                         SET(recv_seq % MAX_DUP_CHK);
305                         dupflag = 0;
306                 }
307
308                 if (options & O_QUIET)
309                         return;
310
311                 printf("%d bytes from %s: icmp_seq=%u", sz,
312                            inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
313                            recv_seq);
314                 printf(" ttl=%d", iphdr->ttl);
315                 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
316                 if (dupflag)
317                         printf(" (DUP!)");
318                 printf("\n");
319         } else
320                 if (icmppkt->icmp_type != ICMP_ECHO)
321                         bb_error_msg("Warning: Got ICMP %d (%s)",
322                                         icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
323         fflush(stdout);
324 }
325
326 static void ping(const char *host)
327 {
328         char packet[datalen + MAXIPLEN + MAXICMPLEN];
329         int sockopt;
330
331         pingsock = create_icmp_socket();
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         sockopt = 1;
344         setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
345                            sizeof(sockopt));
346
347         /* set recv buf for broadcast pings */
348         sockopt = 48 * 1024;
349         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
350                            sizeof(sockopt));
351
352         printf("PING %s (%s): %d data bytes\n",
353                    hostent->h_name,
354                    inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
355                    datalen);
356
357         signal(SIGINT, pingstats);
358
359         /* start the ping's going ... */
360         sendping(0);
361
362         /* listen for replies */
363         while (1) {
364                 struct sockaddr_in from;
365                 socklen_t fromlen = (socklen_t) sizeof(from);
366                 int c;
367
368                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
369                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
370                         if (errno == EINTR)
371                                 continue;
372                         bb_perror_msg("recvfrom");
373                         continue;
374                 }
375                 unpack(packet, c, &from);
376                 if (pingcount > 0 && nreceived >= pingcount)
377                         break;
378         }
379         pingstats(0);
380 }
381
382 int ping_main(int argc, char **argv)
383 {
384         char *thisarg;
385
386         datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
387
388         argc--;
389         argv++;
390         options = 0;
391         /* Parse any options */
392         while (argc >= 1 && **argv == '-') {
393                 thisarg = *argv;
394                 thisarg++;
395                 switch (*thisarg) {
396                 case 'q':
397                         options |= O_QUIET;
398                         break;
399                 case 'c':
400                         if (--argc <= 0)
401                                 bb_show_usage();
402                         argv++;
403                         pingcount = atoi(*argv);
404                         break;
405                 case 's':
406                         if (--argc <= 0)
407                                 bb_show_usage();
408                         argv++;
409                         datalen = atoi(*argv);
410                         break;
411                 default:
412                         bb_show_usage();
413                 }
414                 argc--;
415                 argv++;
416         }
417         if (argc < 1)
418                 bb_show_usage();
419
420         myid = getpid() & 0xFFFF;
421         ping(*argv);
422         return EXIT_SUCCESS;
423 }
424 #endif /* ! CONFIG_FEATURE_FANCY_PING */