Consolidate #include <sys/time.h> so libbb.h does it.
[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
35 enum {
36         DEFDATALEN = 56,
37         MAXIPLEN = 60,
38         MAXICMPLEN = 76,
39         MAXPACKET = 65468,
40         MAX_DUP_CHK = (8 * 128),
41         MAXWAIT = 10,
42         PINGINTERVAL = 1                /* second */
43 };
44
45 #define O_QUIET         (1 << 0)
46
47 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
48 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
49 #define SET(bit)        (A(bit) |= B(bit))
50 #define CLR(bit)        (A(bit) &= (~B(bit)))
51 #define TST(bit)        (A(bit) & B(bit))
52
53 static void ping(const char *host);
54
55 /* common routines */
56 static int in_cksum(unsigned short *buf, int sz)
57 {
58         int nleft = sz;
59         int sum = 0;
60         unsigned short *w = buf;
61         unsigned short ans = 0;
62
63         while (nleft > 1) {
64                 sum += *w++;
65                 nleft -= 2;
66         }
67
68         if (nleft == 1) {
69                 *(unsigned char *) (&ans) = *(unsigned char *) w;
70                 sum += ans;
71         }
72
73         sum = (sum >> 16) + (sum & 0xFFFF);
74         sum += (sum >> 16);
75         ans = ~sum;
76         return (ans);
77 }
78
79 /* simple version */
80 #ifndef CONFIG_FEATURE_FANCY_PING
81 static char *hostname = NULL;
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 || c != sizeof(packet))
114                 bb_perror_msg_and_die("sendto");
115
116         signal(SIGALRM, noresp);
117         alarm(5);                                       /* give the host 5000ms to respond */
118         /* listen for replies */
119         while (1) {
120                 struct sockaddr_in from;
121                 socklen_t fromlen = sizeof(from);
122
123                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
124                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
125                         if (errno == EINTR)
126                                 continue;
127                         bb_perror_msg("recvfrom");
128                         continue;
129                 }
130                 if (c >= 76) {                  /* ip + icmp */
131                         struct iphdr *iphdr = (struct iphdr *) packet;
132
133                         pkt = (struct icmp *) (packet + (iphdr->ihl << 2));     /* skip ip hdr */
134                         if (pkt->icmp_type == ICMP_ECHOREPLY)
135                                 break;
136                 }
137         }
138         printf("%s is alive!\n", hostname);
139         return;
140 }
141
142 int ping_main(int argc, char **argv)
143 {
144         argc--;
145         argv++;
146         if (argc < 1)
147                 bb_show_usage();
148         ping(*argv);
149         return EXIT_SUCCESS;
150 }
151
152 #else /* ! CONFIG_FEATURE_FANCY_PING */
153 /* full(er) version */
154 static struct sockaddr_in pingaddr;
155 static int pingsock = -1;
156 static int datalen; /* intentionally uninitialized to work around gcc bug */
157
158 static long ntransmitted, nreceived, nrepeats, pingcount;
159 static int myid, options;
160 static unsigned long tmin = ULONG_MAX, tmax, tsum;
161 static char rcvd_tbl[MAX_DUP_CHK / 8];
162
163 #ifndef CONFIG_FEATURE_FANCY_PING6
164 static
165 #endif
166         struct hostent *hostent;
167
168 static void sendping(int);
169 static void pingstats(int);
170 static void unpack(char *, int, struct sockaddr_in *);
171
172 /**************************************************************************/
173
174 static void pingstats(int junk)
175 {
176         int status;
177
178         signal(SIGINT, SIG_IGN);
179
180         printf("\n--- %s ping statistics ---\n", hostent->h_name);
181         printf("%ld packets transmitted, ", ntransmitted);
182         printf("%ld packets received, ", nreceived);
183         if (nrepeats)
184                 printf("%ld duplicates, ", nrepeats);
185         if (ntransmitted)
186                 printf("%ld%% packet loss\n",
187                            (ntransmitted - nreceived) * 100 / ntransmitted);
188         if (nreceived)
189                 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
190                            tmin / 10, tmin % 10,
191                            (tsum / (nreceived + nrepeats)) / 10,
192                            (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
193         if (nreceived != 0)
194                 status = EXIT_SUCCESS;
195         else
196                 status = EXIT_FAILURE;
197         exit(status);
198 }
199
200 static void sendping(int junk)
201 {
202         struct icmp *pkt;
203         int i;
204         char packet[datalen + ICMP_MINLEN];
205
206         pkt = (struct icmp *) packet;
207
208         pkt->icmp_type = ICMP_ECHO;
209         pkt->icmp_code = 0;
210         pkt->icmp_cksum = 0;
211         pkt->icmp_seq = htons(ntransmitted++);
212         pkt->icmp_id = myid;
213         CLR(ntohs(pkt->icmp_seq) % MAX_DUP_CHK);
214
215         gettimeofday((struct timeval *) &pkt->icmp_dun, NULL);
216         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
217
218         i = sendto(pingsock, packet, sizeof(packet), 0,
219                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
220
221         if (i < 0)
222                 bb_perror_msg_and_die("sendto");
223         else if ((size_t)i != sizeof(packet))
224                 bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
225                            (int)sizeof(packet));
226
227         signal(SIGALRM, sendping);
228         if (pingcount == 0 || ntransmitted < pingcount) {       /* schedule next in 1s */
229                 alarm(PINGINTERVAL);
230         } else {                                        /* done, wait for the last ping to come back */
231                 /* todo, don't necessarily need to wait so long... */
232                 signal(SIGALRM, pingstats);
233                 alarm(MAXWAIT);
234         }
235 }
236
237 static char *icmp_type_name (int id)
238 {
239         switch (id) {
240         case ICMP_ECHOREPLY:            return "Echo Reply";
241         case ICMP_DEST_UNREACH:         return "Destination Unreachable";
242         case ICMP_SOURCE_QUENCH:        return "Source Quench";
243         case ICMP_REDIRECT:                     return "Redirect (change route)";
244         case ICMP_ECHO:                         return "Echo Request";
245         case ICMP_TIME_EXCEEDED:        return "Time Exceeded";
246         case ICMP_PARAMETERPROB:        return "Parameter Problem";
247         case ICMP_TIMESTAMP:            return "Timestamp Request";
248         case ICMP_TIMESTAMPREPLY:       return "Timestamp Reply";
249         case ICMP_INFO_REQUEST:         return "Information Request";
250         case ICMP_INFO_REPLY:           return "Information Reply";
251         case ICMP_ADDRESS:                      return "Address Mask Request";
252         case ICMP_ADDRESSREPLY:         return "Address Mask Reply";
253         default:                                        return "unknown ICMP type";
254         }
255 }
256
257 static void unpack(char *buf, int sz, struct sockaddr_in *from)
258 {
259         struct icmp *icmppkt;
260         struct iphdr *iphdr;
261         struct timeval tv, *tp;
262         int hlen, dupflag;
263         unsigned long triptime;
264
265         gettimeofday(&tv, NULL);
266
267         /* check IP header */
268         iphdr = (struct iphdr *) buf;
269         hlen = iphdr->ihl << 2;
270         /* discard if too short */
271         if (sz < (datalen + ICMP_MINLEN))
272                 return;
273
274         sz -= hlen;
275         icmppkt = (struct icmp *) (buf + hlen);
276
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         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
333
334         pingaddr.sin_family = AF_INET;
335         hostent = xgethostbyname(host);
336         if (hostent->h_addrtype != AF_INET)
337                 bb_error_msg_and_die("unknown address type; only AF_INET is currently supported.");
338
339         memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
340
341         /* enable broadcast pings */
342         sockopt = 1;
343         setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
344                            sizeof(sockopt));
345
346         /* set recv buf for broadcast pings */
347         sockopt = 48 * 1024;
348         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
349                            sizeof(sockopt));
350
351         printf("PING %s (%s): %d data bytes\n",
352                    hostent->h_name,
353                    inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
354                    datalen);
355
356         signal(SIGINT, pingstats);
357
358         /* start the ping's going ... */
359         sendping(0);
360
361         /* listen for replies */
362         while (1) {
363                 struct sockaddr_in from;
364                 socklen_t fromlen = (socklen_t) sizeof(from);
365                 int c;
366
367                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
368                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
369                         if (errno == EINTR)
370                                 continue;
371                         bb_perror_msg("recvfrom");
372                         continue;
373                 }
374                 unpack(packet, c, &from);
375                 if (pingcount > 0 && nreceived >= pingcount)
376                         break;
377         }
378         pingstats(0);
379 }
380
381 int ping_main(int argc, char **argv)
382 {
383         char *thisarg;
384
385         datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
386
387         argc--;
388         argv++;
389         options = 0;
390         /* Parse any options */
391         while (argc >= 1 && **argv == '-') {
392                 thisarg = *argv;
393                 thisarg++;
394                 switch (*thisarg) {
395                 case 'q':
396                         options |= O_QUIET;
397                         break;
398                 case 'c':
399                         if (--argc <= 0)
400                                 bb_show_usage();
401                         argv++;
402                         pingcount = atoi(*argv);
403                         break;
404                 case 's':
405                         if (--argc <= 0)
406                                 bb_show_usage();
407                         argv++;
408                         datalen = atoi(*argv);
409                         break;
410                 default:
411                         bb_show_usage();
412                 }
413                 argc--;
414                 argv++;
415         }
416         if (argc < 1)
417                 bb_show_usage();
418
419         myid = getpid() & 0xFFFF;
420         ping(*argv);
421         return EXIT_SUCCESS;
422 }
423 #endif /* ! CONFIG_FEATURE_FANCY_PING */