Fix broken link
[oweals/busybox.git] / networking / ping.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * $Id: ping.c,v 1.48 2002/02/01 16:54:00 kraai 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 CONFIG_FEATURE_FANCY_PING
178
179 static void ping(const char *host)
180 {
181         struct hostent *h;
182         struct sockaddr_in pingaddr;
183         struct icmp *pkt;
184         int pingsock, c;
185         char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
186
187         void noresp(int ign)
188         {
189                 printf("No response from %s\n", h->h_name);
190                 exit(0);
191         }
192
193         pingsock = create_icmp_socket();
194
195         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
196
197         pingaddr.sin_family = AF_INET;
198         h = xgethostbyname(host);
199         memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
200
201         pkt = (struct icmp *) packet;
202         memset(pkt, 0, sizeof(packet));
203         pkt->icmp_type = ICMP_ECHO;
204         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
205
206         c = sendto(pingsock, packet, sizeof(packet), 0,
207                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
208
209         if (c < 0 || c != sizeof(packet))
210                 perror_msg_and_die("sendto");
211
212         signal(SIGALRM, noresp);
213         alarm(5);                                       /* give the host 5000ms to respond */
214         /* listen for replies */
215         while (1) {
216                 struct sockaddr_in from;
217                 size_t fromlen = sizeof(from);
218
219                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
220                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
221                         if (errno == EINTR)
222                                 continue;
223                         perror_msg("recvfrom");
224                         continue;
225                 }
226                 if (c >= 76) {                  /* ip + icmp */
227                         struct iphdr *iphdr = (struct iphdr *) packet;
228
229                         pkt = (struct icmp *) (packet + (iphdr->ihl << 2));     /* skip ip hdr */
230                         if (pkt->icmp_type == ICMP_ECHOREPLY)
231                                 break;
232                 }
233         }
234         printf("%s is alive!\n", h->h_name);
235         return;
236 }
237
238 extern int ping_main(int argc, char **argv)
239 {
240         argc--;
241         argv++;
242         if (argc < 1)
243                 show_usage();
244         ping(*argv);
245         return EXIT_SUCCESS;
246 }
247
248 #else /* ! CONFIG_FEATURE_FANCY_PING */
249 /* full(er) version */
250 static struct sockaddr_in pingaddr;
251 static int pingsock = -1;
252 static int datalen; /* intentionally uninitialized to work around gcc bug */
253
254 static long ntransmitted, nreceived, nrepeats, pingcount;
255 static int myid, options;
256 static unsigned long tmin = ULONG_MAX, tmax, tsum;
257 static char rcvd_tbl[MAX_DUP_CHK / 8];
258
259 struct hostent *hostent;
260
261 static void sendping(int);
262 static void pingstats(int);
263 static void unpack(char *, int, struct sockaddr_in *);
264
265 /**************************************************************************/
266
267 static void pingstats(int junk)
268 {
269         int status;
270
271         signal(SIGINT, SIG_IGN);
272
273         printf("\n--- %s ping statistics ---\n", hostent->h_name);
274         printf("%ld packets transmitted, ", ntransmitted);
275         printf("%ld packets received, ", nreceived);
276         if (nrepeats)
277                 printf("%ld duplicates, ", nrepeats);
278         if (ntransmitted)
279                 printf("%ld%% packet loss\n",
280                            (ntransmitted - nreceived) * 100 / ntransmitted);
281         if (nreceived)
282                 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
283                            tmin / 10, tmin % 10,
284                            (tsum / (nreceived + nrepeats)) / 10,
285                            (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
286         if (nreceived != 0)
287                 status = EXIT_SUCCESS;
288         else
289                 status = EXIT_FAILURE;
290         exit(status);
291 }
292
293 static void sendping(int junk)
294 {
295         struct icmp *pkt;
296         int i;
297         char packet[datalen + 8];
298
299         pkt = (struct icmp *) packet;
300
301         pkt->icmp_type = ICMP_ECHO;
302         pkt->icmp_code = 0;
303         pkt->icmp_cksum = 0;
304         pkt->icmp_seq = ntransmitted++;
305         pkt->icmp_id = myid;
306         CLR(pkt->icmp_seq % MAX_DUP_CHK);
307
308         gettimeofday((struct timeval *) &packet[8], NULL);
309         pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
310
311         i = sendto(pingsock, packet, sizeof(packet), 0,
312                            (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
313
314         if (i < 0)
315                 perror_msg_and_die("sendto");
316         else if ((size_t)i != sizeof(packet))
317                 error_msg_and_die("ping wrote %d chars; %d expected", i,
318                            (int)sizeof(packet));
319
320         signal(SIGALRM, sendping);
321         if (pingcount == 0 || ntransmitted < pingcount) {       /* schedule next in 1s */
322                 alarm(PINGINTERVAL);
323         } else {                                        /* done, wait for the last ping to come back */
324                 /* todo, don't necessarily need to wait so long... */
325                 signal(SIGALRM, pingstats);
326                 alarm(MAXWAIT);
327         }
328 }
329
330 static char *icmp_type_name (int id)
331 {
332         switch (id) {
333         case ICMP_ECHOREPLY:            return "Echo Reply";
334         case ICMP_DEST_UNREACH:         return "Destination Unreachable";
335         case ICMP_SOURCE_QUENCH:        return "Source Quench";
336         case ICMP_REDIRECT:             return "Redirect (change route)";
337         case ICMP_ECHO:                         return "Echo Request";
338         case ICMP_TIME_EXCEEDED:        return "Time Exceeded";
339         case ICMP_PARAMETERPROB:        return "Parameter Problem";
340         case ICMP_TIMESTAMP:            return "Timestamp Request";
341         case ICMP_TIMESTAMPREPLY:       return "Timestamp Reply";
342         case ICMP_INFO_REQUEST:         return "Information Request";
343         case ICMP_INFO_REPLY:           return "Information Reply";
344         case ICMP_ADDRESS:                      return "Address Mask Request";
345         case ICMP_ADDRESSREPLY:         return "Address Mask Reply";
346         default:                                        return "unknown ICMP type";
347         }
348 }
349
350 static void unpack(char *buf, int sz, struct sockaddr_in *from)
351 {
352         struct icmp *icmppkt;
353         struct iphdr *iphdr;
354         struct timeval tv, *tp;
355         int hlen, dupflag;
356         unsigned long triptime;
357
358         gettimeofday(&tv, NULL);
359
360         /* check IP header */
361         iphdr = (struct iphdr *) buf;
362         hlen = iphdr->ihl << 2;
363         /* discard if too short */
364         if (sz < (datalen + ICMP_MINLEN))
365                 return;
366
367         sz -= hlen;
368         icmppkt = (struct icmp *) (buf + hlen);
369
370         if (icmppkt->icmp_id != myid)
371             return;                             /* not our ping */
372
373         if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
374             ++nreceived;
375                 tp = (struct timeval *) icmppkt->icmp_data;
376
377                 if ((tv.tv_usec -= tp->tv_usec) < 0) {
378                         --tv.tv_sec;
379                         tv.tv_usec += 1000000;
380                 }
381                 tv.tv_sec -= tp->tv_sec;
382
383                 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
384                 tsum += triptime;
385                 if (triptime < tmin)
386                         tmin = triptime;
387                 if (triptime > tmax)
388                         tmax = triptime;
389
390                 if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
391                         ++nrepeats;
392                         --nreceived;
393                         dupflag = 1;
394                 } else {
395                         SET(icmppkt->icmp_seq % MAX_DUP_CHK);
396                         dupflag = 0;
397                 }
398
399                 if (options & O_QUIET)
400                         return;
401
402                 printf("%d bytes from %s: icmp_seq=%u", sz,
403                            inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
404                            icmppkt->icmp_seq);
405                 printf(" ttl=%d", iphdr->ttl);
406                 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
407                 if (dupflag)
408                         printf(" (DUP!)");
409                 printf("\n");
410         } else 
411                 if (icmppkt->icmp_type != ICMP_ECHO)
412                         error_msg("Warning: Got ICMP %d (%s)",
413                                         icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
414 }
415
416 static void ping(const char *host)
417 {
418         char packet[datalen + MAXIPLEN + MAXICMPLEN];
419         int sockopt;
420
421         pingsock = create_icmp_socket();
422
423         memset(&pingaddr, 0, sizeof(struct sockaddr_in));
424
425         pingaddr.sin_family = AF_INET;
426         hostent = xgethostbyname(host);
427         if (hostent->h_addrtype != AF_INET)
428                 error_msg_and_die("unknown address type; only AF_INET is currently supported.");
429
430         memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
431
432         /* enable broadcast pings */
433         sockopt = 1;
434         setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
435                            sizeof(sockopt));
436
437         /* set recv buf for broadcast pings */
438         sockopt = 48 * 1024;
439         setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
440                            sizeof(sockopt));
441
442         printf("PING %s (%s): %d data bytes\n",
443                    hostent->h_name,
444                    inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
445                    datalen);
446
447         signal(SIGINT, pingstats);
448
449         /* start the ping's going ... */
450         sendping(0);
451
452         /* listen for replies */
453         while (1) {
454                 struct sockaddr_in from;
455                 socklen_t fromlen = (socklen_t) sizeof(from);
456                 int c;
457
458                 if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
459                                                   (struct sockaddr *) &from, &fromlen)) < 0) {
460                         if (errno == EINTR)
461                                 continue;
462                         perror_msg("recvfrom");
463                         continue;
464                 }
465                 unpack(packet, c, &from);
466                 if (pingcount > 0 && nreceived >= pingcount)
467                         break;
468         }
469         pingstats(0);
470 }
471
472 extern int ping_main(int argc, char **argv)
473 {
474         char *thisarg;
475
476         datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
477
478         argc--;
479         argv++;
480         options = 0;
481         /* Parse any options */
482         while (argc >= 1 && **argv == '-') {
483                 thisarg = *argv;
484                 thisarg++;
485                 switch (*thisarg) {
486                 case 'q':
487                         options |= O_QUIET;
488                         break;
489                 case 'c':
490                         if (--argc <= 0)
491                                 show_usage();
492                         argv++;
493                         pingcount = atoi(*argv);
494                         break;
495                 case 's':
496                         if (--argc <= 0)
497                                 show_usage();
498                         argv++;
499                         datalen = atoi(*argv);
500                         break;
501                 default:
502                         show_usage();
503                 }
504                 argc--;
505                 argv++;
506         }
507         if (argc < 1)
508                 show_usage();
509
510         myid = getpid() & 0xFFFF;
511         ping(*argv);
512         return EXIT_SUCCESS;
513 }
514 #endif /* ! CONFIG_FEATURE_FANCY_PING */
515
516 /*
517  * Copyright (c) 1989 The Regents of the University of California.
518  * All rights reserved.
519  *
520  * This code is derived from software contributed to Berkeley by
521  * Mike Muuss.
522  *
523  * Redistribution and use in source and binary forms, with or without
524  * modification, are permitted provided that the following conditions
525  * are met:
526  * 1. Redistributions of source code must retain the above copyright
527  *    notice, this list of conditions and the following disclaimer.
528  * 2. Redistributions in binary form must reproduce the above copyright
529  *    notice, this list of conditions and the following disclaimer in the
530  *    documentation and/or other materials provided with the distribution.
531  *
532  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change 
533  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change> 
534  *
535  * 4. Neither the name of the University nor the names of its contributors
536  *    may be used to endorse or promote products derived from this software
537  *    without specific prior written permission.
538  *
539  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
540  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
541  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
542  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
543  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
544  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
545  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
546  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
547  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
548  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
549  * SUCH DAMAGE.
550  */