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