Patch from vodz:
[platform/upstream/busybox.git] / networking / ping.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * $Id: ping.c,v 1.44 2001/07/12 20:26:31 andersen 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 <sys/param.h>
35 #include <sys/socket.h>
36 #include <sys/file.h>
37 #include <sys/time.h>
38 #include <sys/times.h>
39 #include <sys/signal.h>
40
41 #include <netinet/in.h>
42 #include <netinet/ip.h>
43 #include <netinet/ip_icmp.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <errno.h>
49 #include <unistd.h>
50 #include <string.h>
51 #include <stdlib.h>
52 #include "busybox.h"
53
54
55 /* It turns out that libc5 doesn't have proper icmp support
56  * built into it header files, so we have to supplement it */
57 #if __GNU_LIBRARY__ < 5
58 static const int ICMP_MINLEN = 8;                               /* abs minimum */
59
60 struct icmp_ra_addr
61 {
62   u_int32_t ira_addr;
63   u_int32_t ira_preference;
64 };
65
66
67 struct icmp
68 {
69   u_int8_t  icmp_type;  /* type of message, see below */
70   u_int8_t  icmp_code;  /* type sub code */
71   u_int16_t icmp_cksum; /* ones complement checksum of struct */
72   union
73   {
74     u_char ih_pptr;             /* ICMP_PARAMPROB */
75     struct in_addr ih_gwaddr;   /* gateway address */
76     struct ih_idseq             /* echo datagram */
77     {
78       u_int16_t icd_id;
79       u_int16_t icd_seq;
80     } ih_idseq;
81     u_int32_t ih_void;
82
83     /* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */
84     struct ih_pmtu
85     {
86       u_int16_t ipm_void;
87       u_int16_t ipm_nextmtu;
88     } ih_pmtu;
89
90     struct ih_rtradv
91     {
92       u_int8_t irt_num_addrs;
93       u_int8_t irt_wpa;
94       u_int16_t irt_lifetime;
95     } ih_rtradv;
96   } icmp_hun;
97 #define icmp_pptr       icmp_hun.ih_pptr
98 #define icmp_gwaddr     icmp_hun.ih_gwaddr
99 #define icmp_id         icmp_hun.ih_idseq.icd_id
100 #define icmp_seq        icmp_hun.ih_idseq.icd_seq
101 #define icmp_void       icmp_hun.ih_void
102 #define icmp_pmvoid     icmp_hun.ih_pmtu.ipm_void
103 #define icmp_nextmtu    icmp_hun.ih_pmtu.ipm_nextmtu
104 #define icmp_num_addrs  icmp_hun.ih_rtradv.irt_num_addrs
105 #define icmp_wpa        icmp_hun.ih_rtradv.irt_wpa
106 #define icmp_lifetime   icmp_hun.ih_rtradv.irt_lifetime
107   union
108   {
109     struct
110     {
111       u_int32_t its_otime;
112       u_int32_t its_rtime;
113       u_int32_t its_ttime;
114     } id_ts;
115     struct
116     {
117       struct ip idi_ip;
118       /* options and then 64 bits of data */
119     } id_ip;
120     struct icmp_ra_addr id_radv;
121     u_int32_t   id_mask;
122     u_int8_t    id_data[1];
123   } icmp_dun;
124 #define icmp_otime      icmp_dun.id_ts.its_otime
125 #define icmp_rtime      icmp_dun.id_ts.its_rtime
126 #define icmp_ttime      icmp_dun.id_ts.its_ttime
127 #define icmp_ip         icmp_dun.id_ip.idi_ip
128 #define icmp_radv       icmp_dun.id_radv
129 #define icmp_mask       icmp_dun.id_mask
130 #define icmp_data       icmp_dun.id_data
131 };
132 #endif
133
134 static const int DEFDATALEN = 56;
135 static const int MAXIPLEN = 60;
136 static const int MAXICMPLEN = 76;
137 static const int MAXPACKET = 65468;
138 #define MAX_DUP_CHK     (8 * 128)
139 static const int MAXWAIT = 10;
140 static const int PINGINTERVAL = 1;              /* second */
141
142 #define O_QUIET         (1 << 0)
143
144 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
145 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
146 #define SET(bit)        (A(bit) |= B(bit))
147 #define CLR(bit)        (A(bit) &= (~B(bit)))
148 #define TST(bit)        (A(bit) & B(bit))
149
150 static void ping(const char *host);
151
152 /* common routines */
153 static int in_cksum(unsigned short *buf, int sz)
154 {
155         int nleft = sz;
156         int sum = 0;
157         unsigned short *w = buf;
158         unsigned short ans = 0;
159
160         while (nleft > 1) {
161                 sum += *w++;
162                 nleft -= 2;
163         }
164
165         if (nleft == 1) {
166                 *(unsigned char *) (&ans) = *(unsigned char *) w;
167                 sum += ans;
168         }
169
170         sum = (sum >> 16) + (sum & 0xFFFF);
171         sum += (sum >> 16);
172         ans = ~sum;
173         return (ans);
174 }
175
176 /* simple version */
177 #ifndef BB_FEATURE_FANCY_PING
178 static char *hostname = NULL;
179
180 static void noresp(int ign)
181 {
182         printf("No response from %s\n", hostname);
183         exit(0);
184 }
185
186 static void ping(const char *host)
187 {
188         struct hostent *h;
189         struct sockaddr_in pingaddr;
190         struct icmp *pkt;
191         int pingsock, c;
192         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
193
194         pingsock = create_raw_socket();
195
196         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
197
198         pingaddr.sin_family = AF_INET;
199         h = xgethostbyname(host);
200         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
201         hostname = h->h_name;
202
203         pkt = (struct icmp *) packet;
204         memset(pkt, 0, sizeof(packet));
205         pkt->icmp_type = ICMP_ECHO;
206         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
207
208         c = sendto(pingsock, packet, sizeof(packet), 0,
209                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
210
211         if (c < 0 || c != sizeof(packet))
212                 perror_msg_and_die("sendto");
213
214         signal(SIGALRM, noresp);
215         alarm(5);                                       /* give the host 5000ms to respond */
216         /* listen for replies */
217         while (1) {
218                 struct sockaddr_in from;
219                 size_t fromlen = sizeof(from);
220
221                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
222                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
223                         if (errno == EINTR)
224                                 continue;
225                         perror_msg("recvfrom");
226                         continue;
227                 }
228                 if (c >= 76) {                  /* ip + icmp */
229                         struct iphdr *iphdr = (struct iphdr *) packet;
230
231                         pkt = (struct icmp *) (packet + (iphdr->ihl << 2));     /* skip ip hdr */
232                         if (pkt->icmp_type == ICMP_ECHOREPLY)
233                                 break;
234                 }
235         }
236         printf("%s is alive!\n", hostname);
237         return;
238 }
239
240 extern int ping_main(int argc, char **argv)
241 {
242         argc--;
243         argv++;
244         if (argc < 1)
245                 show_usage();
246         ping(*argv);
247         return EXIT_SUCCESS;
248 }
249
250 #else /* ! BB_FEATURE_FANCY_PING */
251 /* full(er) version */
252 static char *hostname = NULL;
253 static struct sockaddr_in pingaddr;
254 static int pingsock = -1;
255 static int datalen; /* intentionally uninitialized to work around gcc bug */
256
257 static long ntransmitted = 0, nreceived = 0, nrepeats = 0, pingcount = 0;
258 static int myid = 0, options = 0;
259 static unsigned long tmin = ULONG_MAX, tmax = 0, tsum = 0;
260 static char rcvd_tbl[MAX_DUP_CHK / 8];
261
262 static void sendping(int);
263 static void pingstats(int);
264 static void unpack(char *, int, struct sockaddr_in *);
265
266 /**************************************************************************/
267
268 static void pingstats(int junk)
269 {
270         int status;
271
272         signal(SIGINT, SIG_IGN);
273
274         printf("\n--- %s ping statistics ---\n", hostname);
275         printf("%ld packets transmitted, ", ntransmitted);
276         printf("%ld packets received, ", nreceived);
277         if (nrepeats)
278                 printf("%ld duplicates, ", nrepeats);
279         if (ntransmitted)
280                 printf("%ld%% packet loss\n",
281                            (ntransmitted - nreceived) * 100 / ntransmitted);
282         if (nreceived)
283                 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
284                            tmin / 10, tmin % 10,
285                            (tsum / (nreceived + nrepeats)) / 10,
286                            (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
287         if (nreceived != 0)
288                 status = EXIT_SUCCESS;
289         else
290                 status = EXIT_FAILURE;
291         exit(status);
292 }
293
294 static void sendping(int junk)
295 {
296         struct icmp *pkt;
297         int i;
298         char packet[datalen + 8];
299
300         pkt = (struct icmp *) packet;
301
302         pkt->icmp_type = ICMP_ECHO;
303         pkt->icmp_code = 0;
304         pkt->icmp_cksum = 0;
305         pkt->icmp_seq = ntransmitted++;
306         pkt->icmp_id = myid;
307         CLR(pkt->icmp_seq % MAX_DUP_CHK);
308
309         gettimeofday((struct timeval *) &packet[8], NULL);
310         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
311
312         i = sendto(pingsock, packet, sizeof(packet), 0,
313                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
314
315         if (i < 0)
316                 perror_msg_and_die("sendto");
317         else if ((size_t)i != sizeof(packet))
318                 error_msg_and_die("ping wrote %d chars; %d expected", i,
319                            (int)sizeof(packet));
320
321         signal(SIGALRM, sendping);
322         if (pingcount == 0 || ntransmitted < pingcount) {       /* schedule next in 1s */
323                 alarm(PINGINTERVAL);
324         } else {                                        /* done, wait for the last ping to come back */
325                 /* todo, don't necessarily need to wait so long... */
326                 signal(SIGALRM, pingstats);
327                 alarm(MAXWAIT);
328         }
329 }
330
331 static char *icmp_type_name (int id)
332 {
333         switch (id) {
334         case ICMP_ECHOREPLY:            return "Echo Reply";
335         case ICMP_DEST_UNREACH:         return "Destination Unreachable";
336         case ICMP_SOURCE_QUENCH:        return "Source Quench";
337         case ICMP_REDIRECT:             return "Redirect (change route)";
338         case ICMP_ECHO:                         return "Echo Request";
339         case ICMP_TIME_EXCEEDED:        return "Time Exceeded";
340         case ICMP_PARAMETERPROB:        return "Parameter Problem";
341         case ICMP_TIMESTAMP:            return "Timestamp Request";
342         case ICMP_TIMESTAMPREPLY:       return "Timestamp Reply";
343         case ICMP_INFO_REQUEST:         return "Information Request";
344         case ICMP_INFO_REPLY:           return "Information Reply";
345         case ICMP_ADDRESS:                      return "Address Mask Request";
346         case ICMP_ADDRESSREPLY:         return "Address Mask Reply";
347         default:                                        return "unknown ICMP type";
348         }
349 }
350
351 static void unpack(char *buf, int sz, struct sockaddr_in *from)
352 {
353         struct icmp *icmppkt;
354         struct iphdr *iphdr;
355         struct timeval tv, *tp;
356         int hlen, dupflag;
357         unsigned long triptime;
358
359         gettimeofday(&tv, NULL);
360
361         /* check IP header */
362         iphdr = (struct iphdr *) buf;
363         hlen = iphdr->ihl << 2;
364         /* discard if too short */
365         if (sz < (datalen + ICMP_MINLEN))
366                 return;
367
368         sz -= hlen;
369         icmppkt = (struct icmp *) (buf + hlen);
370
371         if (icmppkt->icmp_id != myid)
372             return;                             /* not our ping */
373
374         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
375             ++nreceived;
376                 tp = (struct timeval *) icmppkt->icmp_data;
377
378                 if ((tv.tv_usec -= tp->tv_usec) < 0) {
379                         --tv.tv_sec;
380                         tv.tv_usec += 1000000;
381                 }
382                 tv.tv_sec -= tp->tv_sec;
383
384                 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
385                 tsum += triptime;
386                 if (triptime < tmin)
387                         tmin = triptime;
388                 if (triptime > tmax)
389                         tmax = triptime;
390
391                 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
392                         ++nrepeats;
393                         --nreceived;
394                         dupflag = 1;
395                 } else {
396                         SET(icmppkt->icmp_seq % MAX_DUP_CHK);
397                         dupflag = 0;
398                 }
399
400                 if (options & O_QUIET)
401                         return;
402
403                 printf("%d bytes from %s: icmp_seq=%u", sz,
404                            inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
405                            icmppkt->icmp_seq);
406                 printf(" ttl=%d", iphdr->ttl);
407                 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
408                 if (dupflag)
409                         printf(" (DUP!)");
410                 printf("\n");
411         } else 
412                 if (icmppkt->icmp_type != ICMP_ECHO)
413                         error_msg("Warning: Got ICMP %d (%s)",
414                                         icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
415 }
416
417 static void ping(const char *host)
418 {
419         struct protoent *proto;
420         struct hostent *h;
421         char buf[MAXHOSTNAMELEN];
422         char packet[datalen + MAXIPLEN + MAXICMPLEN];
423         int sockopt;
424
425         proto = getprotobyname("icmp");
426         /* if getprotobyname failed, just silently force 
427          * proto->p_proto to have the correct value for "icmp" */
428         if ((pingsock = socket(AF_INET, SOCK_RAW,
429                                                    (proto ? proto->p_proto : 1))) < 0) {        /* 1 == ICMP */
430                 if (errno == EPERM)
431                         error_msg_and_die("permission denied. (are you root?)");
432                 else
433                         perror_msg_and_die(can_not_create_raw_socket);
434         }
435
436         /* drop root privs if running setuid */
437         setuid(getuid());
438
439         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
440
441         pingaddr.sin_family = AF_INET;
442         h = xgethostbyname(host);
443         if (h->h_addrtype != AF_INET)
444                 error_msg_and_die("unknown address type; only AF_INET is currently supported.");
445
446         pingaddr.sin_family = AF_INET;  /* h->h_addrtype */
447         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
448         strncpy(buf, h->h_name, sizeof(buf) - 1);
449         hostname = buf;
450
451         /* enable broadcast pings */
452         sockopt = 1;
453         setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
454                            sizeof(sockopt));
455
456         /* set recv buf for broadcast pings */
457         sockopt = 48 * 1024;
458         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
459                            sizeof(sockopt));
460
461         printf("PING %s (%s): %d data bytes\n",
462                    hostname,
463                    inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
464                    datalen);
465
466         signal(SIGINT, pingstats);
467
468         /* start the ping's going ... */
469         sendping(0);
470
471         /* listen for replies */
472         while (1) {
473                 struct sockaddr_in from;
474                 socklen_t fromlen = (socklen_t) sizeof(from);
475                 int c;
476
477                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
478                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
479                         if (errno == EINTR)
480                                 continue;
481                         perror_msg("recvfrom");
482                         continue;
483                 }
484                 unpack(packet, c, &from);
485                 if (pingcount > 0 && nreceived >= pingcount)
486                         break;
487         }
488         pingstats(0);
489 }
490
491 extern int ping_main(int argc, char **argv)
492 {
493         char *thisarg;
494
495         datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
496
497         argc--;
498         argv++;
499         options = 0;
500         /* Parse any options */
501         while (argc >= 1 && **argv == '-') {
502                 thisarg = *argv;
503                 thisarg++;
504                 switch (*thisarg) {
505                 case 'q':
506                         options |= O_QUIET;
507                         break;
508                 case 'c':
509                         if (--argc <= 0)
510                                 show_usage();
511                         argv++;
512                         pingcount = atoi(*argv);
513                         break;
514                 case 's':
515                         if (--argc <= 0)
516                                 show_usage();
517                         argv++;
518                         datalen = atoi(*argv);
519                         break;
520                 default:
521                         show_usage();
522                 }
523                 argc--;
524                 argv++;
525         }
526         if (argc < 1)
527                 show_usage();
528
529         myid = getpid() & 0xFFFF;
530         ping(*argv);
531         return EXIT_SUCCESS;
532 }
533 #endif /* ! BB_FEATURE_FANCY_PING */
534
535 /*
536  * Copyright (c) 1989 The Regents of the University of California.
537  * All rights reserved.
538  *
539  * This code is derived from software contributed to Berkeley by
540  * Mike Muuss.
541  *
542  * Redistribution and use in source and binary forms, with or without
543  * modification, are permitted provided that the following conditions
544  * are met:
545  * 1. Redistributions of source code must retain the above copyright
546  *    notice, this list of conditions and the following disclaimer.
547  * 2. Redistributions in binary form must reproduce the above copyright
548  *    notice, this list of conditions and the following disclaimer in the
549  *    documentation and/or other materials provided with the distribution.
550  *
551  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change 
552  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change> 
553  *
554  * 4. Neither the name of the University nor the names of its contributors
555  *    may be used to endorse or promote products derived from this software
556  *    without specific prior written permission.
557  *
558  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
559  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
560  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
561  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
562  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
563  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
564  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
565  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
566  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
567  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
568  * SUCH DAMAGE.
569  */