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