9f83002a207893e41d13e288293b4eaf5ead7370
[oweals/busybox.git] / networking / ping.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * $Id: ping.c,v 1.14 2000/04/25 23:24:55 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                                 (int)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 char *icmp_type_name (int id)
266 {
267         switch (id) {
268         case ICMP_ECHOREPLY:            return "Echo Reply";
269         case ICMP_DEST_UNREACH:         return "Destination Unreachable";
270         case ICMP_SOURCE_QUENCH:        return "Source Quench";
271         case ICMP_REDIRECT:             return "Redirect (change route)";
272         case ICMP_ECHO:                         return "Echo Request";
273         case ICMP_TIME_EXCEEDED:        return "Time Exceeded";
274         case ICMP_PARAMETERPROB:        return "Parameter Problem";
275         case ICMP_TIMESTAMP:            return "Timestamp Request";
276         case ICMP_TIMESTAMPREPLY:       return "Timestamp Reply";
277         case ICMP_INFO_REQUEST:         return "Information Request";
278         case ICMP_INFO_REPLY:           return "Information Reply";
279         case ICMP_ADDRESS:                      return "Address Mask Request";
280         case ICMP_ADDRESSREPLY:         return "Address Mask Reply";
281         default:                                        return "unknown ICMP type";
282         }
283 }
284
285 static void unpack(char *buf, int sz, struct sockaddr_in *from)
286 {
287         struct icmp *icmppkt;
288         struct iphdr *iphdr;
289         struct timeval tv, *tp;
290         int hlen, dupflag;
291         unsigned long triptime;
292
293         gettimeofday(&tv, NULL);
294
295         /* check IP header */
296         iphdr = (struct iphdr *) buf;
297         hlen = iphdr->ihl << 2;
298         /* discard if too short */
299         if (sz < (DEFDATALEN + ICMP_MINLEN))
300                 return;
301
302         sz -= hlen;
303         icmppkt = (struct icmp *) (buf + hlen);
304
305         if (icmppkt->icmp_id != myid)
306             return;                             /* not our ping */
307
308         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
309             ++nreceived;
310                 tp = (struct timeval *) icmppkt->icmp_data;
311
312                 if ((tv.tv_usec -= tp->tv_usec) < 0) {
313                         --tv.tv_sec;
314                         tv.tv_usec += 1000000;
315                 }
316                 tv.tv_sec -= tp->tv_sec;
317
318                 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
319                 tsum += triptime;
320                 if (triptime < tmin)
321                         tmin = triptime;
322                 if (triptime > tmax)
323                         tmax = triptime;
324
325                 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
326                         ++nrepeats;
327                         --nreceived;
328                         dupflag = 1;
329                 } else {
330                         SET(icmppkt->icmp_seq % MAX_DUP_CHK);
331                         dupflag = 0;
332                 }
333
334                 if (options & O_QUIET)
335                         return;
336
337                 printf("%d bytes from %s: icmp_seq=%u", sz,
338                            inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
339                            icmppkt->icmp_seq);
340                 printf(" ttl=%d", iphdr->ttl);
341                 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
342                 if (dupflag)
343                         printf(" (DUP!)");
344                 printf("\n");
345         } else 
346                 if (icmppkt->icmp_type != ICMP_ECHO)
347                         fprintf(stderr,
348                                         "Warning: Got ICMP %d (%s)\n",
349                                         icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
350 }
351
352 static void ping(char *host)
353 {
354         struct protoent *proto;
355         struct hostent *h;
356         char buf[MAXHOSTNAMELEN];
357         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
358         int sockopt;
359
360         proto = getprotobyname("icmp");
361         /* if getprotobyname failed, just silently force 
362          * proto->p_proto to have the correct value for "icmp" */
363         if ((pingsock = socket(AF_INET, SOCK_RAW,
364                                                    (proto ? proto->p_proto : 1))) < 0) {        /* 1 == ICMP */
365                 if (errno == EPERM) {
366                         fprintf(stderr, "ping: permission denied. (are you root?)\n");
367                 } else {
368                         perror("ping");
369                 }
370                 exit(1);
371         }
372
373         /* drop root privs if running setuid */
374         setuid(getuid());
375
376         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
377
378         pingaddr.sin_family = AF_INET;
379         if (!(h = gethostbyname(host))) {
380                 fprintf(stderr, "ping: unknown host %s\n", host);
381                 exit(1);
382         }
383
384         if (h->h_addrtype != AF_INET) {
385                 fprintf(stderr,
386                                 "ping: unknown address type; only AF_INET is currently supported.\n");
387                 exit(1);
388         }
389
390         pingaddr.sin_family = AF_INET;  /* h->h_addrtype */
391         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
392         strncpy(buf, h->h_name, sizeof(buf) - 1);
393         hostname = buf;
394
395         /* enable broadcast pings */
396         sockopt = 1;
397         setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
398                            sizeof(sockopt));
399
400         /* set recv buf for broadcast pings */
401         sockopt = 48 * 1024;
402         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
403                            sizeof(sockopt));
404
405         printf("PING %s (%s): %d data bytes\n",
406                    hostname,
407                    inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
408                    DEFDATALEN);
409
410         signal(SIGINT, pingstats);
411
412         /* start the ping's going ... */
413         sendping(0);
414
415         /* listen for replies */
416         while (1) {
417                 struct sockaddr_in from;
418                 socklen_t fromlen = (socklen_t) sizeof(from);
419                 int c;
420
421                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
422                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
423                         if (errno == EINTR)
424                                 continue;
425                         perror("ping");
426                         continue;
427                 }
428                 unpack(packet, c, &from);
429                 if (pingcount > 0 && nreceived >= pingcount)
430                         break;
431         }
432         pingstats(0);
433 }
434
435 extern int ping_main(int argc, char **argv)
436 {
437         char *thisarg;
438
439         argc--;
440         argv++;
441         options = 0;
442         /* Parse any options */
443         while (argc >= 1 && **argv == '-') {
444                 thisarg = *argv;
445                 thisarg++;
446                 switch (*thisarg) {
447                 case 'q':
448                         options |= O_QUIET;
449                         break;
450                 case 'c':
451                         argc--;
452                         argv++;
453                         pingcount = atoi(*argv);
454                         break;
455                 default:
456                         usage(ping_usage);
457                 }
458                 argc--;
459                 argv++;
460         }
461         if (argc < 1)
462                 usage(ping_usage);
463
464         myid = getpid() & 0xFFFF;
465         ping(*argv);
466         exit(TRUE);
467 }
468 #endif
469
470 /*
471  * Copyright (c) 1989 The Regents of the University of California.
472  * All rights reserved.
473  *
474  * This code is derived from software contributed to Berkeley by
475  * Mike Muuss.
476  *
477  * Redistribution and use in source and binary forms, with or without
478  * modification, are permitted provided that the following conditions
479  * are met:
480  * 1. Redistributions of source code must retain the above copyright
481  *    notice, this list of conditions and the following disclaimer.
482  * 2. Redistributions in binary form must reproduce the above copyright
483  *    notice, this list of conditions and the following disclaimer in the
484  *    documentation and/or other materials provided with the distribution.
485  * 3. All advertising materials mentioning features or use of this software
486  *    must display the following acknowledgement:
487  *      This product includes software developed by the University of
488  *      California, Berkeley and its contributors.
489  * 4. Neither the name of the University nor the names of its contributors
490  *    may be used to endorse or promote products derived from this software
491  *    without specific prior written permission.
492  *
493  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
494  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
495  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
496  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
497  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
498  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
499  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
500  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
501  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
502  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
503  * SUCH DAMAGE.
504  */