More doc updates for BusyBox, with fixes to apps for bugs revealed
[oweals/busybox.git] / ping.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * $Id: ping.c,v 1.12 2000/04/13 18:49:43 erik Exp $
4  * Mini ping implementation for busybox
5  *
6  * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21  *
22  * This version of ping is adapted from the ping in netkit-base 0.10,
23  * which is:
24  *
25  * Copyright (c) 1989 The Regents of the University of California.
26  * All rights reserved.
27  *
28  * This code is derived from software contributed to Berkeley by
29  * Mike Muuss.
30  * 
31  * Original copyright notice is retained at the end of this file.
32  */
33
34 #include "internal.h"
35 #include <sys/param.h>
36 #include <sys/socket.h>
37 #include <sys/file.h>
38 #include <sys/time.h>
39 #include <sys/times.h>
40 #include <sys/signal.h>
41
42 #include <netinet/in.h>
43 #include <netinet/ip.h>
44 #include <netinet/ip_icmp.h>
45 #include <arpa/inet.h>
46 #include <netdb.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <errno.h>
50
51 #define DEFDATALEN      56
52 #define MAXIPLEN        60
53 #define MAXICMPLEN      76
54 #define MAXPACKET       65468
55 #define MAX_DUP_CHK     (8 * 128)
56 #define MAXWAIT         10
57 #define PINGINTERVAL    1               /* second */
58
59 #define O_QUIET         (1 << 0)
60
61 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
62 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
63 #define SET(bit)        (A(bit) |= B(bit))
64 #define CLR(bit)        (A(bit) &= (~B(bit)))
65 #define TST(bit)        (A(bit) & B(bit))
66
67 /* common routines */
68 static int in_cksum(unsigned short *buf, int sz)
69 {
70         int nleft = sz;
71         int sum = 0;
72         unsigned short *w = buf;
73         unsigned short ans = 0;
74
75         while (nleft > 1) {
76                 sum += *w++;
77                 nleft -= 2;
78         }
79
80         if (nleft == 1) {
81                 *(unsigned char *) (&ans) = *(unsigned char *) w;
82                 sum += ans;
83         }
84
85         sum = (sum >> 16) + (sum & 0xFFFF);
86         sum += (sum >> 16);
87         ans = ~sum;
88         return (ans);
89 }
90
91 /* simple version */
92 #ifdef BB_SIMPLE_PING
93 static const char *ping_usage = "ping host\n\n";
94
95 static char *hostname = NULL;
96
97 static void noresp(int ign)
98 {
99         printf("No response from %s\n", hostname);
100         exit(0);
101 }
102
103 static int ping(const char *host)
104 {
105         struct hostent *h;
106         struct sockaddr_in pingaddr;
107         struct icmp *pkt;
108         int pingsock, c;
109         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
110
111         if ((pingsock = socket(AF_INET, SOCK_RAW, 1)) < 0) {    /* 1 == ICMP */
112                 perror("ping");
113                 exit(1);
114         }
115
116         /* drop root privs if running setuid */
117         setuid(getuid());
118
119         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
120
121         pingaddr.sin_family = AF_INET;
122         if (!(h = gethostbyname(host))) {
123                 fprintf(stderr, "ping: unknown host %s\n", host);
124                 exit(1);
125         }
126         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
127         hostname = h->h_name;
128
129         pkt = (struct icmp *) packet;
130         memset(pkt, 0, sizeof(packet));
131         pkt->icmp_type = ICMP_ECHO;
132         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
133
134         c = sendto(pingsock, packet, sizeof(packet), 0,
135                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
136
137         if (c < 0 || c != sizeof(packet)) {
138                 if (c < 0)
139                         perror("ping");
140                 fprintf(stderr, "ping: write incomplete\n");
141                 exit(1);
142         }
143
144         signal(SIGALRM, noresp);
145         alarm(5);                                       /* give the host 5000ms to respond */
146         /* listen for replies */
147         while (1) {
148                 struct sockaddr_in from;
149                 size_t fromlen = sizeof(from);
150
151                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
152                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
153                         if (errno == EINTR)
154                                 continue;
155                         perror("ping");
156                         continue;
157                 }
158                 if (c >= 76) {                  /* ip + icmp */
159                         struct iphdr *iphdr = (struct iphdr *) packet;
160
161                         pkt = (struct icmp *) (packet + (iphdr->ihl << 2));     /* skip ip hdr */
162                         if (pkt->icmp_type == ICMP_ECHOREPLY)
163                                 break;
164                 }
165         }
166         printf("%s is alive!\n", hostname);
167         return (TRUE);
168 }
169
170 extern int ping_main(int argc, char **argv)
171 {
172         argc--;
173         argv++;
174         if (argc < 1)
175                 usage(ping_usage);
176         ping(*argv);
177         exit(TRUE);
178 }
179
180 #else
181 /* full(er) version */
182 static const char *ping_usage = "ping [OPTION]... host\n\n"
183         "Send ICMP ECHO_REQUEST packets to network hosts.\n\n"
184         "Options:\n"
185         "\t-c COUNT\tSend only COUNT pings.\n"
186         "\t-q\t\tQuiet mode, only displays output at start\n"
187         "\t\t\tand when finished.\n"; 
188
189 static char *hostname = NULL;
190 static struct sockaddr_in pingaddr;
191 static int pingsock = -1;
192
193 static long ntransmitted = 0, nreceived = 0, nrepeats = 0, pingcount = 0;
194 static int myid = 0, options = 0;
195 static unsigned long tmin = ULONG_MAX, tmax = 0, tsum = 0;
196 static char rcvd_tbl[MAX_DUP_CHK / 8];
197
198 static void sendping(int);
199 static void pingstats(int);
200 static void unpack(char *, int, struct sockaddr_in *);
201
202 static void ping(char *);
203
204 /**************************************************************************/
205
206 static void pingstats(int ign)
207 {
208         signal(SIGINT, SIG_IGN);
209
210         printf("\n--- %s ping statistics ---\n", hostname);
211         printf("%ld packets transmitted, ", ntransmitted);
212         printf("%ld packets received, ", nreceived);
213         if (nrepeats)
214                 printf("%ld duplicates, ", nrepeats);
215         if (ntransmitted)
216                 printf("%ld%% packet loss\n",
217                            (ntransmitted - nreceived) * 100 / ntransmitted);
218         if (nreceived)
219                 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
220                            tmin / 10, tmin % 10,
221                            (tsum / (nreceived + nrepeats)) / 10,
222                            (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
223         exit(0);
224 }
225
226 static void sendping(int ign)
227 {
228         struct icmp *pkt;
229         int i;
230         char packet[DEFDATALEN + 8];
231
232         pkt = (struct icmp *) packet;
233
234         pkt->icmp_type = ICMP_ECHO;
235         pkt->icmp_code = 0;
236         pkt->icmp_cksum = 0;
237         pkt->icmp_seq = ntransmitted++;
238         pkt->icmp_id = myid;
239         CLR(pkt->icmp_seq % MAX_DUP_CHK);
240
241         gettimeofday((struct timeval *) &packet[8], NULL);
242         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
243
244         i = sendto(pingsock, packet, sizeof(packet), 0,
245                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
246
247         if (i < 0 || i != sizeof(packet)) {
248                 if (i < 0)
249                         perror("ping");
250                 fprintf(stderr, "ping wrote %d chars; %d expected\n", i,
251                                 sizeof(packet));
252                 exit(1);
253         }
254
255         signal(SIGALRM, sendping);
256         if (pingcount == 0 || ntransmitted < pingcount) {       /* schedule next in 1s */
257                 alarm(PINGINTERVAL);
258         } else {                                        /* done, wait for the last ping to come back */
259                 /* todo, don't necessarily need to wait so long... */
260                 signal(SIGALRM, pingstats);
261                 alarm(MAXWAIT);
262         }
263 }
264
265 static void unpack(char *buf, int sz, struct sockaddr_in *from)
266 {
267         struct icmp *icmppkt;
268         struct iphdr *iphdr;
269         struct timeval tv, *tp;
270         int hlen, dupflag;
271         unsigned long triptime;
272
273         gettimeofday(&tv, NULL);
274
275         /* check IP header */
276         iphdr = (struct iphdr *) buf;
277         hlen = iphdr->ihl << 2;
278         /* discard if too short */
279         if (sz < (DEFDATALEN + ICMP_MINLEN))
280                 return;
281
282         sz -= hlen;
283         icmppkt = (struct icmp *) (buf + hlen);
284
285         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
286                 if (icmppkt->icmp_id != myid)
287                         return;                         /* not our ping */
288                 ++nreceived;
289                 tp = (struct timeval *) icmppkt->icmp_data;
290
291                 if ((tv.tv_usec -= tp->tv_usec) < 0) {
292                         --tv.tv_sec;
293                         tv.tv_usec += 1000000;
294                 }
295                 tv.tv_sec -= tp->tv_sec;
296
297                 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
298                 tsum += triptime;
299                 if (triptime < tmin)
300                         tmin = triptime;
301                 if (triptime > tmax)
302                         tmax = triptime;
303
304                 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
305                         ++nrepeats;
306                         --nreceived;
307                         dupflag = 1;
308                 } else {
309                         SET(icmppkt->icmp_seq % MAX_DUP_CHK);
310                         dupflag = 0;
311                 }
312
313                 if (options & O_QUIET)
314                         return;
315
316                 printf("%d bytes from %s: icmp_seq=%u", sz,
317                            inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
318                            icmppkt->icmp_seq);
319                 printf(" ttl=%d", iphdr->ttl);
320                 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
321                 if (dupflag)
322                         printf(" (DUP!)");
323                 printf("\n");
324         } else {
325                 fprintf(stderr,
326                                 "Warning: unknown ICMP packet received (not echo-reply)\n");
327         }
328 }
329
330 static void ping(char *host)
331 {
332         struct protoent *proto;
333         struct hostent *h;
334         char buf[MAXHOSTNAMELEN];
335         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
336         int sockopt;
337
338         proto = getprotobyname("icmp");
339         /* if getprotobyname failed, just silently force 
340          * proto->p_proto to have the correct value for "icmp" */
341         if ((pingsock = socket(AF_INET, SOCK_RAW,
342                                                    (proto ? proto->p_proto : 1))) < 0) {        /* 1 == ICMP */
343                 if (errno == EPERM) {
344                         fprintf(stderr, "ping: permission denied. (are you root?)\n");
345                 } else {
346                         perror("ping");
347                 }
348                 exit(1);
349         }
350
351         /* drop root privs if running setuid */
352         setuid(getuid());
353
354         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
355
356         pingaddr.sin_family = AF_INET;
357         if (!(h = gethostbyname(host))) {
358                 fprintf(stderr, "ping: unknown host %s\n", host);
359                 exit(1);
360         }
361
362         if (h->h_addrtype != AF_INET) {
363                 fprintf(stderr,
364                                 "ping: unknown address type; only AF_INET is currently supported.\n");
365                 exit(1);
366         }
367
368         pingaddr.sin_family = AF_INET;  /* h->h_addrtype */
369         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
370         strncpy(buf, h->h_name, sizeof(buf) - 1);
371         hostname = buf;
372
373         /* enable broadcast pings */
374         sockopt = 1;
375         setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
376                            sizeof(sockopt));
377
378         /* set recv buf for broadcast pings */
379         sockopt = 48 * 1024;
380         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
381                            sizeof(sockopt));
382
383         printf("PING %s (%s): %d data bytes\n",
384                    hostname,
385                    inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
386                    DEFDATALEN);
387
388         signal(SIGINT, pingstats);
389
390         /* start the ping's going ... */
391         sendping(0);
392
393         /* listen for replies */
394         while (1) {
395                 struct sockaddr_in from;
396                 size_t fromlen = sizeof(from);
397                 int c;
398
399                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
400                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
401                         if (errno == EINTR)
402                                 continue;
403                         perror("ping");
404                         continue;
405                 }
406                 unpack(packet, c, &from);
407                 if (pingcount > 0 && nreceived >= pingcount)
408                         break;
409         }
410         pingstats(0);
411 }
412
413 extern int ping_main(int argc, char **argv)
414 {
415         char *thisarg;
416
417         argc--;
418         argv++;
419         options = 0;
420         /* Parse any options */
421         while (argc >= 1 && **argv == '-') {
422                 thisarg = *argv;
423                 thisarg++;
424                 switch (*thisarg) {
425                 case 'q':
426                         options |= O_QUIET;
427                         break;
428                 case 'c':
429                         argc--;
430                         argv++;
431                         pingcount = atoi(*argv);
432                         break;
433                 default:
434                         usage(ping_usage);
435                 }
436                 argc--;
437                 argv++;
438         }
439         if (argc < 1)
440                 usage(ping_usage);
441
442         myid = getpid() & 0xFFFF;
443         ping(*argv);
444         exit(TRUE);
445 }
446 #endif
447
448 /*
449  * Copyright (c) 1989 The Regents of the University of California.
450  * All rights reserved.
451  *
452  * This code is derived from software contributed to Berkeley by
453  * Mike Muuss.
454  *
455  * Redistribution and use in source and binary forms, with or without
456  * modification, are permitted provided that the following conditions
457  * are met:
458  * 1. Redistributions of source code must retain the above copyright
459  *    notice, this list of conditions and the following disclaimer.
460  * 2. Redistributions in binary form must reproduce the above copyright
461  *    notice, this list of conditions and the following disclaimer in the
462  *    documentation and/or other materials provided with the distribution.
463  * 3. All advertising materials mentioning features or use of this software
464  *    must display the following acknowledgement:
465  *      This product includes software developed by the University of
466  *      California, Berkeley and its contributors.
467  * 4. Neither the name of the University nor the names of its contributors
468  *    may be used to endorse or promote products derived from this software
469  *    without specific prior written permission.
470  *
471  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
472  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
473  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
474  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
475  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
476  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
477  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
478  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
479  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
480  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
481  * SUCH DAMAGE.
482  */