1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Mike Muuss.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * P I N G . C
37 *
38 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
39 * measure round-trip-delays and packet loss across network paths.
40 *
41 * Author -
42 * Mike Muuss
43 * U. S. Army Ballistic Research Laboratory
44 * December, 1983
45 *
46 * Status -
47 * Public Domain. Distribution Unlimited.
48 * Bugs -
49 * More statistics could always be gathered.
50 * This program has to run SUID to ROOT to access the ICMP socket.
51 */
52
53 #include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
54 #ifndef __HAIKU__
55 #include <sys/capsicum.h>
56 #endif
57 #include <sys/socket.h>
58 #ifndef __HAIKU__
59 #include <sys/sysctl.h>
60 #endif
61 #include <sys/time.h>
62 #include <sys/uio.h>
63
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/ip.h>
67 #include <netinet/ip_icmp.h>
68 #include <netinet/ip_var.h>
69 #include <arpa/inet.h>
70
71 #ifndef __HAIKU__
72 #include <libcasper.h>
73 #include <casper/cap_dns.h>
74 #endif
75
76 #ifdef IPSEC
77 #include <netipsec/ipsec.h>
78 #endif /*IPSEC*/
79
80 #ifndef __HAIKU__
81 #include <capsicum_helpers.h>
82 #endif
83 #include <ctype.h>
84 #include <err.h>
85 #include <errno.h>
86 #include <netdb.h>
87 #include <stddef.h>
88 #include <signal.h>
89 #include <stdio.h>
90 #include <stdlib.h>
91 #include <string.h>
92 #include <sysexits.h>
93 #include <time.h>
94 #include <unistd.h>
95
96 #include "main.h"
97 #include "ping.h"
98 #include "utils.h"
99
100 #define INADDR_LEN ((int)sizeof(in_addr_t))
101 #define TIMEVAL_LEN ((int)sizeof(struct tv32))
102 #define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN)
103 #define TS_LEN (ICMP_TSLEN - ICMP_MINLEN)
104 #define DEFDATALEN 56 /* default data length */
105 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
106 /* runs out of buffer space */
107 #define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
108 #define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
109 #define MAXWAIT 10000 /* max ms to wait for response */
110 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */
111 #define MAXTOS 255
112
113 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
114 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
115 #define SET(bit) (A(bit) |= B(bit))
116 #define CLR(bit) (A(bit) &= (~B(bit)))
117 #define TST(bit) (A(bit) & B(bit))
118
119 struct tv32 {
120 int32_t tv32_sec;
121 int32_t tv32_nsec;
122 };
123
124 /* various options */
125 #define F_FLOOD 0x0001
126 #define F_INTERVAL 0x0002
127 #define F_PINGFILLED 0x0008
128 #define F_QUIET 0x0010
129 #define F_RROUTE 0x0020
130 #define F_SO_DEBUG 0x0040
131 #define F_SO_DONTROUTE 0x0080
132 #define F_VERBOSE 0x0100
133 #define F_QUIET2 0x0200
134 #define F_NOLOOP 0x0400
135 #define F_MTTL 0x0800
136 #define F_MIF 0x1000
137 #define F_AUDIBLE 0x2000
138 #ifdef IPSEC
139 #ifdef IPSEC_POLICY_IPSEC
140 #define F_POLICY 0x4000
141 #endif /*IPSEC_POLICY_IPSEC*/
142 #endif /*IPSEC*/
143 #define F_TTL 0x8000
144 #define F_MISSED 0x10000
145 #define F_ONCE 0x20000
146 #define F_HDRINCL 0x40000
147 #define F_MASK 0x80000
148 #define F_TIME 0x100000
149 #define F_SWEEP 0x200000
150 #define F_WAITTIME 0x400000
151 #define F_IP_VLAN_PCP 0x800000
152 #define F_DOT 0x1000000
153
154 /*
155 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
156 * number of received sequence numbers we can keep track of. Change 128
157 * to 8192 for complete accuracy...
158 */
159 #define MAX_DUP_CHK (8 * 128)
160 static int mx_dup_ck = MAX_DUP_CHK;
161 static char rcvd_tbl[MAX_DUP_CHK / 8];
162
163 static struct sockaddr_in whereto; /* who to ping */
164 static int datalen = DEFDATALEN;
165 static int maxpayload;
166 static int ssend; /* send socket file descriptor */
167 static int srecv; /* receive socket file descriptor */
168 static u_char outpackhdr[IP_MAXPACKET], *outpack;
169 static char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
170 static char BSPACE = '\b'; /* characters written for flood */
171 static const char *DOT = ".";
172 static size_t DOTlen = 1;
173 static size_t DOTidx = 0;
174 static char *shostname;
175 static int ident; /* process id to identify our packets */
176 static int uid; /* cached uid for micro-optimization */
177 static u_char icmp_type = ICMP_ECHO;
178 static u_char icmp_type_rsp = ICMP_ECHOREPLY;
179 static int phdr_len = 0;
180 static int send_len;
181
182 /* counters */
183 static long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
184 static long npackets; /* max packets to transmit */
185 static long snpackets; /* max packets to transmit in one sweep */
186 static long sntransmitted; /* # of packets we sent in this sweep */
187 static int sweepmax; /* max value of payload in sweep */
188 static int sweepmin = 0; /* start value of payload in sweep */
189 static int sweepincr = 1; /* payload increment in sweep */
190 static int interval = 1000; /* interval between packets, ms */
191 static int waittime = MAXWAIT; /* timeout for each packet */
192
193 #ifndef __HAIKU__
194 static cap_channel_t *capdns;
195 #endif
196
197 static void fill(char *, char *);
198 #ifndef __HAIKU__
199 static cap_channel_t *capdns_setup(void);
200 #endif
201 static void pinger(void);
202 static char *pr_addr(struct in_addr);
203 static char *pr_ntime(n_time);
204 static void pr_icmph(struct icmp *, struct ip *, const u_char *const);
205 static void pr_iph(struct ip *, const u_char *);
206 static void pr_pack(char *, ssize_t, struct sockaddr_in *, struct timespec *);
207
208 int
ping(int argc,char * const * argv)209 ping(int argc, char *const *argv)
210 {
211 struct sockaddr_in from, sock_in;
212 struct in_addr ifaddr;
213 struct timespec last, intvl;
214 struct iovec iov;
215 struct msghdr msg;
216 struct sigaction si_sa;
217 size_t sz;
218 #ifdef __HAIKU__
219 #define __aligned(x) __attribute__((__aligned__(x)))
220 #endif
221 u_char *datap, packet[IP_MAXPACKET] __aligned(4);
222 const char *errstr;
223 char *ep, *source, *target, *payload;
224 struct hostent *hp;
225 #ifdef IPSEC_POLICY_IPSEC
226 char *policy_in, *policy_out;
227 #endif
228 struct sockaddr_in *to;
229 double t;
230 u_long alarmtimeout;
231 long long ltmp;
232 int almost_done, ch, df, hold, i, icmp_len, mib[4], preload;
233 int ssend_errno, srecv_errno, tos, ttl, pcp;
234 char ctrl[CMSG_SPACE(sizeof(struct timespec))];
235 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
236 #ifdef IP_OPTIONS
237 char rspace[MAX_IPOPTLEN]; /* record route space */
238 #endif
239 unsigned char loop, mttl;
240
241 payload = source = NULL;
242 #ifdef IPSEC_POLICY_IPSEC
243 policy_in = policy_out = NULL;
244 #endif
245 #ifndef __HAIKU__
246 cap_rights_t rights;
247 #endif
248
249 /*
250 * Do the stuff that we need root priv's for *first*, and
251 * then drop our setuid bit. Save error reporting for
252 * after arg parsing.
253 *
254 * Historicaly ping was using one socket 's' for sending and for
255 * receiving. After capsicum(4) related changes we use two
256 * sockets. It was done for special ping use case - when user
257 * issue ping on multicast or broadcast address replies come
258 * from different addresses, not from the address we
259 * connect(2)'ed to, and send socket do not receive those
260 * packets.
261 */
262 ssend = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
263 ssend_errno = errno;
264 srecv = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
265 srecv_errno = errno;
266
267 if (setuid(getuid()) != 0)
268 err(EX_NOPERM, "setuid() failed");
269 uid = getuid();
270
271 if (ssend < 0) {
272 errno = ssend_errno;
273 err(EX_OSERR, "ssend socket");
274 }
275
276 if (srecv < 0) {
277 errno = srecv_errno;
278 err(EX_OSERR, "srecv socket");
279 }
280
281 alarmtimeout = df = preload = tos = pcp = 0;
282
283 outpack = outpackhdr + sizeof(struct ip);
284 while ((ch = getopt(argc, argv, PING4OPTS)) != -1) {
285 switch(ch) {
286 case '.':
287 options |= F_DOT;
288 if (optarg != NULL) {
289 DOT = optarg;
290 DOTlen = strlen(optarg);
291 }
292 break;
293 case '4':
294 /* This option is processed in main(). */
295 break;
296 case 'A':
297 options |= F_MISSED;
298 break;
299 case 'a':
300 options |= F_AUDIBLE;
301 break;
302 case 'C':
303 #ifndef __HAIKU__
304 options |= F_IP_VLAN_PCP;
305 ltmp = strtonum(optarg, -1, 7, &errstr);
306 if (errstr != NULL)
307 errx(EX_USAGE, "invalid PCP: `%s'", optarg);
308 pcp = ltmp;
309 #else
310 errx(EX_UNAVAILABLE, "VLAN PCP not available");
311 #endif
312 break;
313 case 'c':
314 ltmp = strtonum(optarg, 1, LONG_MAX, &errstr);
315 if (errstr != NULL)
316 errx(EX_USAGE,
317 "invalid count of packets to transmit: `%s'",
318 optarg);
319 npackets = (long)ltmp;
320 break;
321 case 'D':
322 options |= F_HDRINCL;
323 df = 1;
324 break;
325 case 'd':
326 options |= F_SO_DEBUG;
327 break;
328 case 'f':
329 if (uid) {
330 errno = EPERM;
331 err(EX_NOPERM, "-f flag");
332 }
333 options |= F_FLOOD;
334 options |= F_DOT;
335 setbuf(stdout, (char *)NULL);
336 break;
337 case 'G': /* Maximum packet size for ping sweep */
338 ltmp = strtonum(optarg, 1, INT_MAX, &errstr);
339 if (errstr != NULL) {
340 errx(EX_USAGE, "invalid packet size: `%s'",
341 optarg);
342 }
343 sweepmax = (int)ltmp;
344 if (uid != 0 && sweepmax > DEFDATALEN) {
345 errc(EX_NOPERM, EPERM,
346 "packet size too large: %d > %u",
347 sweepmax, DEFDATALEN);
348 }
349 options |= F_SWEEP;
350 break;
351 case 'g': /* Minimum packet size for ping sweep */
352 ltmp = strtonum(optarg, 1, INT_MAX, &errstr);
353 if (errstr != NULL) {
354 errx(EX_USAGE, "invalid packet size: `%s'",
355 optarg);
356 }
357 sweepmin = (int)ltmp;
358 if (uid != 0 && sweepmin > DEFDATALEN) {
359 errc(EX_NOPERM, EPERM,
360 "packet size too large: %d > %u",
361 sweepmin, DEFDATALEN);
362 }
363 options |= F_SWEEP;
364 break;
365 case 'H':
366 options |= F_HOSTNAME;
367 break;
368 case 'h': /* Packet size increment for ping sweep */
369 ltmp = strtonum(optarg, 1, INT_MAX, &errstr);
370 if (errstr != NULL) {
371 errx(EX_USAGE, "invalid packet size: `%s'",
372 optarg);
373 }
374 sweepincr = (int)ltmp;
375 if (uid != 0 && sweepincr > DEFDATALEN) {
376 errc(EX_NOPERM, EPERM,
377 "packet size too large: %d > %u",
378 sweepincr, DEFDATALEN);
379 }
380 options |= F_SWEEP;
381 break;
382 case 'I': /* multicast interface */
383 if (inet_aton(optarg, &ifaddr) == 0)
384 errx(EX_USAGE,
385 "invalid multicast interface: `%s'",
386 optarg);
387 options |= F_MIF;
388 break;
389 case 'i': /* wait between sending packets */
390 t = strtod(optarg, &ep) * 1000.0;
391 if (*ep || ep == optarg || t > (double)INT_MAX)
392 errx(EX_USAGE, "invalid timing interval: `%s'",
393 optarg);
394 options |= F_INTERVAL;
395 interval = (int)t;
396 if (uid && interval < 1000) {
397 errno = EPERM;
398 err(EX_NOPERM, "-i interval too short");
399 }
400 break;
401 case 'L':
402 options |= F_NOLOOP;
403 loop = 0;
404 break;
405 case 'l':
406 ltmp = strtonum(optarg, 0, INT_MAX, &errstr);
407 if (errstr != NULL)
408 errx(EX_USAGE,
409 "invalid preload value: `%s'", optarg);
410 if (uid) {
411 errno = EPERM;
412 err(EX_NOPERM, "-l flag");
413 }
414 preload = (int)ltmp;
415 break;
416 case 'M':
417 switch(optarg[0]) {
418 case 'M':
419 case 'm':
420 options |= F_MASK;
421 break;
422 case 'T':
423 case 't':
424 options |= F_TIME;
425 break;
426 default:
427 errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
428 break;
429 }
430 break;
431 case 'm': /* TTL */
432 ltmp = strtonum(optarg, 0, MAXTTL, &errstr);
433 if (errstr != NULL)
434 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
435 ttl = (int)ltmp;
436 options |= F_TTL;
437 break;
438 case 'n':
439 options &= ~F_HOSTNAME;
440 break;
441 case 'o':
442 options |= F_ONCE;
443 break;
444 #ifdef IPSEC
445 #ifdef IPSEC_POLICY_IPSEC
446 case 'P':
447 options |= F_POLICY;
448 if (!strncmp("in", optarg, 2))
449 policy_in = strdup(optarg);
450 else if (!strncmp("out", optarg, 3))
451 policy_out = strdup(optarg);
452 else
453 errx(1, "invalid security policy");
454 break;
455 #endif /*IPSEC_POLICY_IPSEC*/
456 #endif /*IPSEC*/
457 case 'p': /* fill buffer with user pattern */
458 options |= F_PINGFILLED;
459 payload = optarg;
460 break;
461 case 'Q':
462 options |= F_QUIET2;
463 break;
464 case 'q':
465 options |= F_QUIET;
466 break;
467 case 'R':
468 options |= F_RROUTE;
469 break;
470 case 'r':
471 options |= F_SO_DONTROUTE;
472 break;
473 case 'S':
474 source = optarg;
475 break;
476 case 's': /* size of packet to send */
477 ltmp = strtonum(optarg, 0, INT_MAX, &errstr);
478 if (errstr != NULL)
479 errx(EX_USAGE, "invalid packet size: `%s'",
480 optarg);
481 datalen = (int)ltmp;
482 if (uid != 0 && datalen > DEFDATALEN) {
483 errno = EPERM;
484 err(EX_NOPERM,
485 "packet size too large: %d > %u",
486 datalen, DEFDATALEN);
487 }
488 break;
489 case 'T': /* multicast TTL */
490 ltmp = strtonum(optarg, 0, MAXTTL, &errstr);
491 if (errstr != NULL)
492 errx(EX_USAGE, "invalid multicast TTL: `%s'",
493 optarg);
494 mttl = (unsigned char)ltmp;
495 options |= F_MTTL;
496 break;
497 case 't':
498 alarmtimeout = strtoul(optarg, &ep, 0);
499 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
500 errx(EX_USAGE, "invalid timeout: `%s'",
501 optarg);
502 if (alarmtimeout > MAXALARM)
503 errx(EX_USAGE, "invalid timeout: `%s' > %d",
504 optarg, MAXALARM);
505 {
506 struct itimerval itv;
507
508 timerclear(&itv.it_interval);
509 timerclear(&itv.it_value);
510 itv.it_value.tv_sec = (time_t)alarmtimeout;
511 if (setitimer(ITIMER_REAL, &itv, NULL) != 0)
512 err(1, "setitimer");
513 }
514 break;
515 case 'v':
516 options |= F_VERBOSE;
517 break;
518 case 'W': /* wait ms for answer */
519 t = strtod(optarg, &ep);
520 if (*ep || ep == optarg || t > (double)INT_MAX)
521 errx(EX_USAGE, "invalid timing interval: `%s'",
522 optarg);
523 options |= F_WAITTIME;
524 waittime = (int)t;
525 break;
526 case 'z':
527 options |= F_HDRINCL;
528 ltmp = strtol(optarg, &ep, 0);
529 if (*ep || ep == optarg || ltmp > MAXTOS || ltmp < 0)
530 errx(EX_USAGE, "invalid TOS: `%s'", optarg);
531 tos = ltmp;
532 break;
533 default:
534 usage();
535 }
536 }
537
538 if (argc - optind != 1)
539 usage();
540 target = argv[optind];
541
542 switch (options & (F_MASK|F_TIME)) {
543 case 0: break;
544 case F_MASK:
545 icmp_type = ICMP_MASKREQ;
546 icmp_type_rsp = ICMP_MASKREPLY;
547 phdr_len = MASK_LEN;
548 if (!(options & F_QUIET))
549 (void)printf("ICMP_MASKREQ\n");
550 break;
551 case F_TIME:
552 icmp_type = ICMP_TSTAMP;
553 icmp_type_rsp = ICMP_TSTAMPREPLY;
554 phdr_len = TS_LEN;
555 if (!(options & F_QUIET))
556 (void)printf("ICMP_TSTAMP\n");
557 break;
558 default:
559 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
560 break;
561 }
562 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len;
563 if (options & F_RROUTE)
564 icmp_len += MAX_IPOPTLEN;
565 maxpayload = IP_MAXPACKET - icmp_len;
566 if (datalen > maxpayload)
567 errx(EX_USAGE, "packet size too large: %d > %d", datalen,
568 maxpayload);
569 send_len = icmp_len + datalen;
570 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN];
571 if (options & F_PINGFILLED) {
572 fill((char *)datap, payload);
573 }
574 #ifndef __HAIKU__
575 capdns = capdns_setup();
576 #else
577 #define cap_gethostbyname2(x, y, z) gethostbyname(y);
578 #endif
579 if (source) {
580 bzero((char *)&sock_in, sizeof(sock_in));
581 sock_in.sin_family = AF_INET;
582 if (inet_aton(source, &sock_in.sin_addr) != 0) {
583 shostname = source;
584 } else {
585 hp = cap_gethostbyname2(capdns, source, AF_INET);
586 if (!hp)
587 errx(EX_NOHOST, "cannot resolve %s: %s",
588 source, hstrerror(h_errno));
589
590 sock_in.sin_len = sizeof sock_in;
591 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
592 hp->h_length < 0)
593 errx(1, "gethostbyname2: illegal address");
594 memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
595 sizeof(sock_in.sin_addr));
596 (void)strncpy(snamebuf, hp->h_name,
597 sizeof(snamebuf) - 1);
598 snamebuf[sizeof(snamebuf) - 1] = '\0';
599 shostname = snamebuf;
600 }
601 if (bind(ssend, (struct sockaddr *)&sock_in, sizeof sock_in) ==
602 -1)
603 err(1, "bind");
604 }
605
606 bzero(&whereto, sizeof(whereto));
607 to = &whereto;
608 to->sin_family = AF_INET;
609 to->sin_len = sizeof *to;
610 if (inet_aton(target, &to->sin_addr) != 0) {
611 hostname = target;
612 } else {
613 hp = cap_gethostbyname2(capdns, target, AF_INET);
614 if (!hp)
615 errx(EX_NOHOST, "cannot resolve %s: %s",
616 target, hstrerror(h_errno));
617
618 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
619 errx(1, "gethostbyname2 returned an illegal address");
620 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
621 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
622 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
623 hostname = hnamebuf;
624 }
625
626 /* From now on we will use only reverse DNS lookups. */
627 #ifdef WITH_CASPER
628 if (capdns != NULL) {
629 const char *types[1];
630
631 types[0] = "ADDR2NAME";
632 if (cap_dns_type_limit(capdns, types, 1) < 0)
633 err(1, "unable to limit access to system.dns service");
634 }
635 #endif
636 if (connect(ssend, (struct sockaddr *)&whereto, sizeof(whereto)) != 0)
637 err(1, "connect");
638
639 if (options & F_FLOOD && options & F_INTERVAL)
640 errx(EX_USAGE, "-f and -i: incompatible options");
641
642 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
643 errx(EX_USAGE,
644 "-f flag cannot be used with multicast destination");
645 if (options & (F_MIF | F_NOLOOP | F_MTTL)
646 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
647 errx(EX_USAGE,
648 "-I, -L, -T flags cannot be used with unicast destination");
649
650 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
651 timing = 1;
652
653 if ((options & (F_PINGFILLED | F_SWEEP)) == 0)
654 for (i = TIMEVAL_LEN; i < datalen; ++i)
655 *datap++ = i;
656
657 ident = getpid() & 0xFFFF;
658
659 hold = 1;
660 if (options & F_SO_DEBUG) {
661 (void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold,
662 sizeof(hold));
663 (void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold,
664 sizeof(hold));
665 }
666 if (options & F_SO_DONTROUTE)
667 (void)setsockopt(ssend, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
668 sizeof(hold));
669 #ifndef __HAIKU__
670 if (options & F_IP_VLAN_PCP) {
671 (void)setsockopt(ssend, IPPROTO_IP, IP_VLAN_PCP, (char *)&pcp,
672 sizeof(pcp));
673 }
674 #endif
675 #ifdef IPSEC
676 #ifdef IPSEC_POLICY_IPSEC
677 if (options & F_POLICY) {
678 char *buf;
679 if (policy_in != NULL) {
680 buf = ipsec_set_policy(policy_in, strlen(policy_in));
681 if (buf == NULL)
682 errx(EX_CONFIG, "%s", ipsec_strerror());
683 if (setsockopt(srecv, IPPROTO_IP, IP_IPSEC_POLICY,
684 buf, ipsec_get_policylen(buf)) < 0)
685 err(EX_CONFIG,
686 "ipsec policy cannot be configured");
687 free(buf);
688 }
689
690 if (policy_out != NULL) {
691 buf = ipsec_set_policy(policy_out, strlen(policy_out));
692 if (buf == NULL)
693 errx(EX_CONFIG, "%s", ipsec_strerror());
694 if (setsockopt(ssend, IPPROTO_IP, IP_IPSEC_POLICY,
695 buf, ipsec_get_policylen(buf)) < 0)
696 err(EX_CONFIG,
697 "ipsec policy cannot be configured");
698 free(buf);
699 }
700 }
701 #endif /*IPSEC_POLICY_IPSEC*/
702 #endif /*IPSEC*/
703
704 if (options & F_HDRINCL) {
705 struct ip ip;
706
707 #ifndef __HAIKU__
708 memcpy(&ip, outpackhdr, sizeof(ip));
709 if (!(options & (F_TTL | F_MTTL))) {
710 mib[0] = CTL_NET;
711 mib[1] = PF_INET;
712 mib[2] = IPPROTO_IP;
713 mib[3] = IPCTL_DEFTTL;
714 sz = sizeof(ttl);
715 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
716 err(1, "sysctl(net.inet.ip.ttl)");
717 }
718 #endif
719 setsockopt(ssend, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
720 ip.ip_v = IPVERSION;
721 ip.ip_hl = sizeof(struct ip) >> 2;
722 ip.ip_tos = tos;
723 ip.ip_id = 0;
724 ip.ip_off = htons(df ? IP_DF : 0);
725 ip.ip_ttl = ttl;
726 ip.ip_p = IPPROTO_ICMP;
727 ip.ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
728 ip.ip_dst = to->sin_addr;
729 memcpy(outpackhdr, &ip, sizeof(ip));
730 }
731
732 #ifndef __HAIKU__
733 /*
734 * Here we enter capability mode. Further down access to global
735 * namespaces (e.g filesystem) is restricted (see capsicum(4)).
736 * We must connect(2) our socket before this point.
737 */
738 caph_cache_catpages();
739 if (caph_enter_casper() < 0)
740 err(1, "caph_enter_casper");
741
742 cap_rights_init(&rights, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT);
743 if (caph_rights_limit(srecv, &rights) < 0)
744 err(1, "cap_rights_limit srecv");
745 cap_rights_init(&rights, CAP_SEND, CAP_SETSOCKOPT);
746 if (caph_rights_limit(ssend, &rights) < 0)
747 err(1, "cap_rights_limit ssend");
748 #endif
749
750 /* record route option */
751 if (options & F_RROUTE) {
752 #ifdef IP_OPTIONS
753 bzero(rspace, sizeof(rspace));
754 rspace[IPOPT_OPTVAL] = IPOPT_RR;
755 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
756 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
757 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
758 if (setsockopt(ssend, IPPROTO_IP, IP_OPTIONS, rspace,
759 sizeof(rspace)) < 0)
760 err(EX_OSERR, "setsockopt IP_OPTIONS");
761 #else
762 errx(EX_UNAVAILABLE,
763 "record route not available in this implementation");
764 #endif /* IP_OPTIONS */
765 }
766
767 if (options & F_TTL) {
768 if (setsockopt(ssend, IPPROTO_IP, IP_TTL, &ttl,
769 sizeof(ttl)) < 0) {
770 err(EX_OSERR, "setsockopt IP_TTL");
771 }
772 }
773 if (options & F_NOLOOP) {
774 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
775 sizeof(loop)) < 0) {
776 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
777 }
778 }
779 if (options & F_MTTL) {
780 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
781 sizeof(mttl)) < 0) {
782 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
783 }
784 }
785 if (options & F_MIF) {
786 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
787 sizeof(ifaddr)) < 0) {
788 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
789 }
790 }
791 #ifdef SO_TIMESTAMP
792 {
793 int on = 1;
794 int ts_clock = SO_TS_MONOTONIC;
795 if (setsockopt(srecv, SOL_SOCKET, SO_TIMESTAMP, &on,
796 sizeof(on)) < 0)
797 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
798 if (setsockopt(srecv, SOL_SOCKET, SO_TS_CLOCK, &ts_clock,
799 sizeof(ts_clock)) < 0)
800 err(EX_OSERR, "setsockopt SO_TS_CLOCK");
801 }
802 #endif
803 if (sweepmax) {
804 if (sweepmin > sweepmax)
805 errx(EX_USAGE,
806 "Maximum packet size must be no less than the minimum packet size");
807
808 if (sweepmax > maxpayload - TIMEVAL_LEN)
809 errx(EX_USAGE, "Invalid sweep maximum");
810
811 if (datalen != DEFDATALEN)
812 errx(EX_USAGE,
813 "Packet size and ping sweep are mutually exclusive");
814
815 if (npackets > 0) {
816 snpackets = npackets;
817 npackets = 0;
818 } else
819 snpackets = 1;
820 datalen = sweepmin;
821 send_len = icmp_len + sweepmin;
822 }
823 if (options & F_SWEEP && !sweepmax)
824 errx(EX_USAGE, "Maximum sweep size must be specified");
825
826 /*
827 * When pinging the broadcast address, you can get a lot of answers.
828 * Doing something so evil is useful if you are trying to stress the
829 * ethernet, or just want to fill the arp cache to get some stuff for
830 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
831 * or multicast pings if they wish.
832 */
833
834 /*
835 * XXX receive buffer needs undetermined space for mbuf overhead
836 * as well.
837 */
838 hold = IP_MAXPACKET + 128;
839 (void)setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
840 sizeof(hold));
841 /* CAP_SETSOCKOPT removed */
842 #ifndef __HAIKU__
843 cap_rights_init(&rights, CAP_RECV, CAP_EVENT);
844 if (caph_rights_limit(srecv, &rights) < 0)
845 err(1, "cap_rights_limit srecv setsockopt");
846 #endif
847 if (uid == 0)
848 (void)setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
849 sizeof(hold));
850 /* CAP_SETSOCKOPT removed */
851 #ifndef __HAIKU__
852 cap_rights_init(&rights, CAP_SEND);
853 if (caph_rights_limit(ssend, &rights) < 0)
854 err(1, "cap_rights_limit ssend setsockopt");
855 #endif
856
857 if (to->sin_family == AF_INET) {
858 (void)printf("PING %s (%s)", hostname,
859 inet_ntoa(to->sin_addr));
860 if (source)
861 (void)printf(" from %s", shostname);
862 if (sweepmax)
863 (void)printf(": (%d ... %d) data bytes\n",
864 sweepmin, sweepmax);
865 else
866 (void)printf(": %d data bytes\n", datalen);
867
868 } else {
869 if (sweepmax)
870 (void)printf("PING %s: (%d ... %d) data bytes\n",
871 hostname, sweepmin, sweepmax);
872 else
873 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
874 }
875
876 /*
877 * Use sigaction() instead of signal() to get unambiguous semantics,
878 * in particular with SA_RESTART not set.
879 */
880
881 sigemptyset(&si_sa.sa_mask);
882 si_sa.sa_flags = 0;
883 si_sa.sa_handler = onsignal;
884 if (sigaction(SIGINT, &si_sa, 0) == -1)
885 err(EX_OSERR, "sigaction SIGINT");
886 seenint = 0;
887 #ifndef __HAIKU__
888 if (sigaction(SIGINFO, &si_sa, 0) == -1)
889 err(EX_OSERR, "sigaction SIGINFO");
890 seeninfo = 0;
891 #endif
892 if (alarmtimeout > 0) {
893 if (sigaction(SIGALRM, &si_sa, 0) == -1)
894 err(EX_OSERR, "sigaction SIGALRM");
895 }
896
897 bzero(&msg, sizeof(msg));
898 msg.msg_name = (caddr_t)&from;
899 msg.msg_iov = &iov;
900 msg.msg_iovlen = 1;
901 #ifdef SO_TIMESTAMP
902 msg.msg_control = (caddr_t)ctrl;
903 msg.msg_controllen = sizeof(ctrl);
904 #endif
905 iov.iov_base = packet;
906 iov.iov_len = IP_MAXPACKET;
907
908 if (preload == 0)
909 pinger(); /* send the first ping */
910 else {
911 if (npackets != 0 && preload > npackets)
912 preload = npackets;
913 while (preload--) /* fire off them quickies */
914 pinger();
915 }
916 (void)clock_gettime(CLOCK_MONOTONIC, &last);
917
918 if (options & F_FLOOD) {
919 intvl.tv_sec = 0;
920 intvl.tv_nsec = 10000000;
921 } else {
922 intvl.tv_sec = interval / 1000;
923 intvl.tv_nsec = interval % 1000 * 1000000;
924 }
925
926 almost_done = 0;
927 while (seenint == 0) {
928 struct timespec now, timeout;
929 fd_set rfds;
930 int n;
931 ssize_t cc;
932
933 /* signal handling */
934 if (seeninfo) {
935 pr_summary(stderr);
936 seeninfo = 0;
937 continue;
938 }
939 if ((unsigned)srecv >= FD_SETSIZE)
940 errx(EX_OSERR, "descriptor too large");
941 FD_ZERO(&rfds);
942 FD_SET(srecv, &rfds);
943 (void)clock_gettime(CLOCK_MONOTONIC, &now);
944 timespecadd(&last, &intvl, &timeout);
945 timespecsub(&timeout, &now, &timeout);
946 if (timeout.tv_sec < 0)
947 timespecclear(&timeout);
948
949 n = pselect(srecv + 1, &rfds, NULL, NULL, &timeout, NULL);
950 if (n < 0)
951 continue; /* EINTR */
952 if (n == 1) {
953 struct timespec *tv = NULL;
954 #ifdef SO_TIMESTAMP
955 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
956 #endif
957 msg.msg_namelen = sizeof(from);
958 if ((cc = recvmsg(srecv, &msg, 0)) < 0) {
959 if (errno == EINTR)
960 continue;
961 warn("recvmsg");
962 continue;
963 }
964 /* If we have a 0 byte read from recvfrom continue */
965 if (cc == 0)
966 continue;
967 #ifdef SO_TIMESTAMP
968 if (cmsg != NULL &&
969 cmsg->cmsg_level == SOL_SOCKET &&
970 cmsg->cmsg_type == SCM_TIMESTAMP &&
971 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
972 /* Copy to avoid alignment problems: */
973 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
974 tv = &now;
975 }
976 #endif
977 if (tv == NULL) {
978 (void)clock_gettime(CLOCK_MONOTONIC, &now);
979 tv = &now;
980 }
981 pr_pack((char *)packet, cc, &from, tv);
982 if ((options & F_ONCE && nreceived) ||
983 (npackets && nreceived >= npackets))
984 break;
985 }
986 if (n == 0 || (options & F_FLOOD)) {
987 if (sweepmax && sntransmitted == snpackets) {
988 if (datalen + sweepincr > sweepmax)
989 break;
990 for (i = 0; i < sweepincr; i++)
991 *datap++ = i;
992 datalen += sweepincr;
993 send_len = icmp_len + datalen;
994 sntransmitted = 0;
995 }
996 if (!npackets || ntransmitted < npackets)
997 pinger();
998 else {
999 if (almost_done)
1000 break;
1001 almost_done = 1;
1002 /*
1003 * If we're not transmitting any more packets,
1004 * change the timer to wait two round-trip times
1005 * if we've received any packets or (waittime)
1006 * milliseconds if we haven't.
1007 */
1008 intvl.tv_nsec = 0;
1009 if (nreceived) {
1010 intvl.tv_sec = 2 * tmax / 1000;
1011 if (intvl.tv_sec == 0)
1012 intvl.tv_sec = 1;
1013 } else {
1014 intvl.tv_sec = waittime / 1000;
1015 intvl.tv_nsec =
1016 waittime % 1000 * 1000000;
1017 }
1018 }
1019 (void)clock_gettime(CLOCK_MONOTONIC, &last);
1020 if (ntransmitted - nreceived - 1 > nmissedmax) {
1021 nmissedmax = ntransmitted - nreceived - 1;
1022 if (options & F_MISSED)
1023 (void)write(STDOUT_FILENO, &BBELL, 1);
1024 }
1025 }
1026 }
1027 pr_summary(stdout);
1028
1029 exit(nreceived ? 0 : 2);
1030 }
1031
1032 /*
1033 * pinger --
1034 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1035 * will be added on by the kernel. The ID field is our UNIX process ID,
1036 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
1037 * bytes of the data portion are used to hold a UNIX "timespec" struct in
1038 * host byte-order, to compute the round-trip time.
1039 */
1040 static void
pinger(void)1041 pinger(void)
1042 {
1043 struct timespec now;
1044 struct tv32 tv32;
1045 struct icmp icp;
1046 int cc, i;
1047 u_char *packet;
1048
1049 packet = outpack;
1050 memcpy(&icp, outpack, ICMP_MINLEN + phdr_len);
1051 icp.icmp_type = icmp_type;
1052 icp.icmp_code = 0;
1053 icp.icmp_cksum = 0;
1054 icp.icmp_seq = htons(ntransmitted);
1055 icp.icmp_id = ident; /* ID */
1056
1057 CLR(ntransmitted % mx_dup_ck);
1058
1059 if ((options & F_TIME) || timing) {
1060 (void)clock_gettime(CLOCK_MONOTONIC, &now);
1061 /*
1062 * Truncate seconds down to 32 bits in order
1063 * to fit the timestamp within 8 bytes of the
1064 * packet. We're only concerned with
1065 * durations, not absolute times.
1066 */
1067 tv32.tv32_sec = (uint32_t)htonl(now.tv_sec);
1068 tv32.tv32_nsec = (uint32_t)htonl(now.tv_nsec);
1069 if (options & F_TIME)
1070 icp.icmp_otime = htonl((now.tv_sec % (24*60*60))
1071 * 1000 + now.tv_nsec / 1000000);
1072 if (timing)
1073 bcopy((void *)&tv32,
1074 (void *)&outpack[ICMP_MINLEN + phdr_len],
1075 sizeof(tv32));
1076 }
1077
1078 memcpy(outpack, &icp, ICMP_MINLEN + phdr_len);
1079
1080 cc = ICMP_MINLEN + phdr_len + datalen;
1081
1082 /* compute ICMP checksum here */
1083 icp.icmp_cksum = in_cksum(outpack, cc);
1084 /* Update icmp_cksum in the raw packet data buffer. */
1085 memcpy(outpack + offsetof(struct icmp, icmp_cksum), &icp.icmp_cksum,
1086 sizeof(icp.icmp_cksum));
1087
1088 if (options & F_HDRINCL) {
1089 struct ip ip;
1090
1091 cc += sizeof(struct ip);
1092 ip.ip_len = htons(cc);
1093 /* Update ip_len in the raw packet data buffer. */
1094 memcpy(outpackhdr + offsetof(struct ip, ip_len), &ip.ip_len,
1095 sizeof(ip.ip_len));
1096 ip.ip_sum = in_cksum(outpackhdr, cc);
1097 /* Update ip_sum in the raw packet data buffer. */
1098 memcpy(outpackhdr + offsetof(struct ip, ip_sum), &ip.ip_sum,
1099 sizeof(ip.ip_sum));
1100 packet = outpackhdr;
1101 }
1102 i = send(ssend, (char *)packet, cc, 0);
1103 if (i < 0 || i != cc) {
1104 if (i < 0) {
1105 if (options & F_FLOOD && errno == ENOBUFS) {
1106 usleep(FLOOD_BACKOFF);
1107 return;
1108 }
1109 warn("sendto");
1110 } else {
1111 warn("%s: partial write: %d of %d bytes",
1112 hostname, i, cc);
1113 }
1114 }
1115 ntransmitted++;
1116 sntransmitted++;
1117 if (!(options & F_QUIET) && options & F_DOT)
1118 (void)write(STDOUT_FILENO, &DOT[DOTidx++ % DOTlen], 1);
1119 }
1120
1121 /*
1122 * pr_pack --
1123 * Print out the packet, if it came from us. This logic is necessary
1124 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1125 * which arrive ('tis only fair). This permits multiple copies of this
1126 * program to be run without having intermingled output (or statistics!).
1127 */
1128 static void
pr_pack(char * buf,ssize_t cc,struct sockaddr_in * from,struct timespec * tv)1129 pr_pack(char *buf, ssize_t cc, struct sockaddr_in *from, struct timespec *tv)
1130 {
1131 struct in_addr ina;
1132 u_char *cp, *dp, l;
1133 struct icmp icp;
1134 struct ip ip;
1135 const u_char *icmp_data_raw;
1136 ssize_t icmp_data_raw_len;
1137 double triptime;
1138 int dupflag, i, j, recv_len;
1139 int8_t hlen;
1140 uint16_t seq;
1141 static int old_rrlen;
1142 static char old_rr[MAX_IPOPTLEN];
1143 struct ip oip;
1144 u_char oip_header_len;
1145 struct icmp oicmp;
1146 const u_char *oicmp_raw;
1147
1148 /*
1149 * Get size of IP header of the received packet.
1150 * The header length is contained in the lower four bits of the first
1151 * byte and represents the number of 4 byte octets the header takes up.
1152 *
1153 * The IHL minimum value is 5 (20 bytes) and its maximum value is 15
1154 * (60 bytes).
1155 */
1156 memcpy(&l, buf, sizeof(l));
1157 hlen = (l & 0x0f) << 2;
1158
1159 /* Reject IP packets with a short header */
1160 if (hlen < (int8_t) sizeof(struct ip)) {
1161 if (options & F_VERBOSE)
1162 warn("IHL too short (%d bytes) from %s", hlen,
1163 inet_ntoa(from->sin_addr));
1164 return;
1165 }
1166
1167 memcpy(&ip, buf, sizeof(struct ip));
1168
1169 /* Check packet has enough data to carry a valid ICMP header */
1170 recv_len = cc;
1171 if (cc < hlen + ICMP_MINLEN) {
1172 if (options & F_VERBOSE)
1173 warn("packet too short (%zd bytes) from %s", cc,
1174 inet_ntoa(from->sin_addr));
1175 return;
1176 }
1177
1178 icmp_data_raw_len = cc - (hlen + offsetof(struct icmp, icmp_data));
1179 icmp_data_raw = buf + hlen + offsetof(struct icmp, icmp_data);
1180
1181 /* Now the ICMP part */
1182 cc -= hlen;
1183 memcpy(&icp, buf + hlen, MIN((ssize_t)sizeof(icp), cc));
1184 if (icp.icmp_type == icmp_type_rsp) {
1185 if (icp.icmp_id != ident)
1186 return; /* 'Twas not our ECHO */
1187 ++nreceived;
1188 triptime = 0.0;
1189 if (timing) {
1190 struct timespec tv1;
1191 struct tv32 tv32;
1192 const u_char *tp;
1193
1194 tp = icmp_data_raw + phdr_len;
1195
1196 if ((size_t)(cc - ICMP_MINLEN - phdr_len) >=
1197 sizeof(tv1)) {
1198 /* Copy to avoid alignment problems: */
1199 memcpy(&tv32, tp, sizeof(tv32));
1200 tv1.tv_sec = ntohl(tv32.tv32_sec);
1201 tv1.tv_nsec = ntohl(tv32.tv32_nsec);
1202 timespecsub(tv, &tv1, tv);
1203 triptime = ((double)tv->tv_sec) * 1000.0 +
1204 ((double)tv->tv_nsec) / 1000000.0;
1205 if (triptime < 0) {
1206 warnx("time of day goes back (%.3f ms),"
1207 " clamping time to 0",
1208 triptime);
1209 triptime = 0;
1210 }
1211 tsum += triptime;
1212 tsumsq += triptime * triptime;
1213 if (triptime < tmin)
1214 tmin = triptime;
1215 if (triptime > tmax)
1216 tmax = triptime;
1217 } else
1218 timing = 0;
1219 }
1220
1221 seq = ntohs(icp.icmp_seq);
1222
1223 if (TST(seq % mx_dup_ck)) {
1224 ++nrepeats;
1225 --nreceived;
1226 dupflag = 1;
1227 } else {
1228 SET(seq % mx_dup_ck);
1229 dupflag = 0;
1230 }
1231
1232 if (options & F_QUIET)
1233 return;
1234
1235 if (options & F_WAITTIME && triptime > waittime) {
1236 ++nrcvtimeout;
1237 return;
1238 }
1239
1240 if (options & F_DOT)
1241 (void)write(STDOUT_FILENO, &BSPACE, 1);
1242 else {
1243 (void)printf("%zd bytes from %s: icmp_seq=%u", cc,
1244 pr_addr(from->sin_addr), seq);
1245 (void)printf(" ttl=%d", ip.ip_ttl);
1246 if (timing)
1247 (void)printf(" time=%.3f ms", triptime);
1248 if (dupflag)
1249 (void)printf(" (DUP!)");
1250 if (options & F_AUDIBLE)
1251 (void)write(STDOUT_FILENO, &BBELL, 1);
1252 if (options & F_MASK) {
1253 /* Just prentend this cast isn't ugly */
1254 (void)printf(" mask=%s",
1255 inet_ntoa(*(struct in_addr *)&(icp.icmp_mask)));
1256 }
1257 if (options & F_TIME) {
1258 (void)printf(" tso=%s", pr_ntime(icp.icmp_otime));
1259 (void)printf(" tsr=%s", pr_ntime(icp.icmp_rtime));
1260 (void)printf(" tst=%s", pr_ntime(icp.icmp_ttime));
1261 }
1262 if (recv_len != send_len) {
1263 (void)printf(
1264 "\nwrong total length %d instead of %d",
1265 recv_len, send_len);
1266 }
1267 /* check the data */
1268 cp = (u_char*)(buf + hlen + offsetof(struct icmp,
1269 icmp_data) + phdr_len);
1270 dp = &outpack[ICMP_MINLEN + phdr_len];
1271 cc -= ICMP_MINLEN + phdr_len;
1272 i = 0;
1273 if (timing) { /* don't check variable timestamp */
1274 cp += TIMEVAL_LEN;
1275 dp += TIMEVAL_LEN;
1276 cc -= TIMEVAL_LEN;
1277 i += TIMEVAL_LEN;
1278 }
1279 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
1280 if (*cp != *dp) {
1281 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1282 i, *dp, *cp);
1283 (void)printf("\ncp:");
1284 cp = (u_char*)(buf + hlen +
1285 offsetof(struct icmp, icmp_data));
1286 for (i = 0; i < datalen; ++i, ++cp) {
1287 if ((i % 16) == 8)
1288 (void)printf("\n\t");
1289 (void)printf(" %2x", *cp);
1290 }
1291 (void)printf("\ndp:");
1292 cp = &outpack[ICMP_MINLEN];
1293 for (i = 0; i < datalen; ++i, ++cp) {
1294 if ((i % 16) == 8)
1295 (void)printf("\n\t");
1296 (void)printf(" %2x", *cp);
1297 }
1298 break;
1299 }
1300 }
1301 }
1302 } else {
1303 /*
1304 * We've got something other than an ECHOREPLY.
1305 * See if it's a reply to something that we sent.
1306 * We can compare IP destination, protocol,
1307 * and ICMP type and ID.
1308 *
1309 * Only print all the error messages if we are running
1310 * as root to avoid leaking information not normally
1311 * available to those not running as root.
1312 */
1313
1314 /*
1315 * If we don't have enough bytes for a quoted IP header and an
1316 * ICMP header then stop.
1317 */
1318 if (icmp_data_raw_len <
1319 (ssize_t)(sizeof(struct ip) + sizeof(struct icmp))) {
1320 if (options & F_VERBOSE)
1321 warnx("quoted data too short (%zd bytes) from %s",
1322 icmp_data_raw_len, inet_ntoa(from->sin_addr));
1323 return;
1324 }
1325
1326 memcpy(&oip_header_len, icmp_data_raw, sizeof(oip_header_len));
1327 oip_header_len = (oip_header_len & 0x0f) << 2;
1328
1329 /* Reject IP packets with a short header */
1330 if (oip_header_len < sizeof(struct ip)) {
1331 if (options & F_VERBOSE)
1332 warnx("inner IHL too short (%d bytes) from %s",
1333 oip_header_len, inet_ntoa(from->sin_addr));
1334 return;
1335 }
1336
1337 /*
1338 * Check against the actual IHL length, to protect against
1339 * quoated packets carrying IP options.
1340 */
1341 if (icmp_data_raw_len <
1342 (ssize_t)(oip_header_len + sizeof(struct icmp))) {
1343 if (options & F_VERBOSE)
1344 warnx("inner packet too short (%zd bytes) from %s",
1345 icmp_data_raw_len, inet_ntoa(from->sin_addr));
1346 return;
1347 }
1348
1349 memcpy(&oip, icmp_data_raw, sizeof(struct ip));
1350 oicmp_raw = icmp_data_raw + oip_header_len;
1351 memcpy(&oicmp, oicmp_raw, sizeof(struct icmp));
1352
1353 if (((options & F_VERBOSE) && uid == 0) ||
1354 (!(options & F_QUIET2) &&
1355 (oip.ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1356 (oip.ip_p == IPPROTO_ICMP) &&
1357 (oicmp.icmp_type == ICMP_ECHO) &&
1358 (oicmp.icmp_id == ident))) {
1359 (void)printf("%zd bytes from %s: ", cc,
1360 pr_addr(from->sin_addr));
1361 pr_icmph(&icp, &oip, icmp_data_raw);
1362 } else
1363 return;
1364 }
1365
1366 /* Display any IP options */
1367 cp = (u_char *)buf + sizeof(struct ip);
1368
1369 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1370 switch (*cp) {
1371 case IPOPT_EOL:
1372 hlen = 0;
1373 break;
1374 case IPOPT_LSRR:
1375 case IPOPT_SSRR:
1376 (void)printf(*cp == IPOPT_LSRR ?
1377 "\nLSRR: " : "\nSSRR: ");
1378 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1379 hlen -= 2;
1380 cp += 2;
1381 if (j >= INADDR_LEN &&
1382 j <= hlen - (int)sizeof(struct ip)) {
1383 for (;;) {
1384 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1385 if (ina.s_addr == 0)
1386 (void)printf("\t0.0.0.0");
1387 else
1388 (void)printf("\t%s",
1389 pr_addr(ina));
1390 hlen -= INADDR_LEN;
1391 cp += INADDR_LEN - 1;
1392 j -= INADDR_LEN;
1393 if (j < INADDR_LEN)
1394 break;
1395 (void)putchar('\n');
1396 }
1397 } else
1398 (void)printf("\t(truncated route)");
1399 break;
1400 case IPOPT_RR:
1401 j = cp[IPOPT_OLEN]; /* get length */
1402 i = cp[IPOPT_OFFSET]; /* and pointer */
1403 hlen -= 2;
1404 cp += 2;
1405 if (i > j)
1406 i = j;
1407 i = i - IPOPT_MINOFF + 1;
1408 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1409 old_rrlen = 0;
1410 continue;
1411 }
1412 if (i == old_rrlen
1413 && !bcmp((char *)cp, old_rr, i)
1414 && !(options & F_DOT)) {
1415 (void)printf("\t(same route)");
1416 hlen -= i;
1417 cp += i;
1418 break;
1419 }
1420 old_rrlen = i;
1421 bcopy((char *)cp, old_rr, i);
1422 (void)printf("\nRR: ");
1423 if (i >= INADDR_LEN &&
1424 i <= hlen - (int)sizeof(struct ip)) {
1425 for (;;) {
1426 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1427 if (ina.s_addr == 0)
1428 (void)printf("\t0.0.0.0");
1429 else
1430 (void)printf("\t%s",
1431 pr_addr(ina));
1432 hlen -= INADDR_LEN;
1433 cp += INADDR_LEN - 1;
1434 i -= INADDR_LEN;
1435 if (i < INADDR_LEN)
1436 break;
1437 (void)putchar('\n');
1438 }
1439 } else
1440 (void)printf("\t(truncated route)");
1441 break;
1442 case IPOPT_NOP:
1443 (void)printf("\nNOP");
1444 break;
1445 default:
1446 (void)printf("\nunknown option %x", *cp);
1447 break;
1448 }
1449 if (!(options & F_DOT)) {
1450 (void)putchar('\n');
1451 (void)fflush(stdout);
1452 }
1453 }
1454
1455 /*
1456 * pr_icmph --
1457 * Print a descriptive string about an ICMP header.
1458 */
1459 static void
pr_icmph(struct icmp * icp,struct ip * oip,const u_char * const oicmp_raw)1460 pr_icmph(struct icmp *icp, struct ip *oip, const u_char *const oicmp_raw)
1461 {
1462
1463 switch(icp->icmp_type) {
1464 case ICMP_ECHOREPLY:
1465 (void)printf("Echo Reply\n");
1466 /* XXX ID + Seq + Data */
1467 break;
1468 case ICMP_UNREACH:
1469 switch(icp->icmp_code) {
1470 case ICMP_UNREACH_NET:
1471 (void)printf("Destination Net Unreachable\n");
1472 break;
1473 case ICMP_UNREACH_HOST:
1474 (void)printf("Destination Host Unreachable\n");
1475 break;
1476 case ICMP_UNREACH_PROTOCOL:
1477 (void)printf("Destination Protocol Unreachable\n");
1478 break;
1479 case ICMP_UNREACH_PORT:
1480 (void)printf("Destination Port Unreachable\n");
1481 break;
1482 case ICMP_UNREACH_NEEDFRAG:
1483 (void)printf("frag needed and DF set (MTU %d)\n",
1484 ntohs(icp->icmp_nextmtu));
1485 break;
1486 case ICMP_UNREACH_SRCFAIL:
1487 (void)printf("Source Route Failed\n");
1488 break;
1489 case ICMP_UNREACH_FILTER_PROHIB:
1490 (void)printf("Communication prohibited by filter\n");
1491 break;
1492 default:
1493 (void)printf("Dest Unreachable, Bad Code: %d\n",
1494 icp->icmp_code);
1495 break;
1496 }
1497 /* Print returned IP header information */
1498 pr_iph(oip, oicmp_raw);
1499 break;
1500 case ICMP_SOURCEQUENCH:
1501 (void)printf("Source Quench\n");
1502 pr_iph(oip, oicmp_raw);
1503 break;
1504 case ICMP_REDIRECT:
1505 switch(icp->icmp_code) {
1506 case ICMP_REDIRECT_NET:
1507 (void)printf("Redirect Network");
1508 break;
1509 case ICMP_REDIRECT_HOST:
1510 (void)printf("Redirect Host");
1511 break;
1512 case ICMP_REDIRECT_TOSNET:
1513 (void)printf("Redirect Type of Service and Network");
1514 break;
1515 case ICMP_REDIRECT_TOSHOST:
1516 (void)printf("Redirect Type of Service and Host");
1517 break;
1518 default:
1519 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1520 break;
1521 }
1522 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1523 pr_iph(oip, oicmp_raw);
1524 break;
1525 case ICMP_ECHO:
1526 (void)printf("Echo Request\n");
1527 /* XXX ID + Seq + Data */
1528 break;
1529 case ICMP_TIMXCEED:
1530 switch(icp->icmp_code) {
1531 case ICMP_TIMXCEED_INTRANS:
1532 (void)printf("Time to live exceeded\n");
1533 break;
1534 case ICMP_TIMXCEED_REASS:
1535 (void)printf("Frag reassembly time exceeded\n");
1536 break;
1537 default:
1538 (void)printf("Time exceeded, Bad Code: %d\n",
1539 icp->icmp_code);
1540 break;
1541 }
1542 pr_iph(oip, oicmp_raw);
1543 break;
1544 case ICMP_PARAMPROB:
1545 (void)printf("Parameter problem: pointer = 0x%02x\n",
1546 icp->icmp_hun.ih_pptr);
1547 pr_iph(oip, oicmp_raw);
1548 break;
1549 case ICMP_TSTAMP:
1550 (void)printf("Timestamp\n");
1551 /* XXX ID + Seq + 3 timestamps */
1552 break;
1553 case ICMP_TSTAMPREPLY:
1554 (void)printf("Timestamp Reply\n");
1555 /* XXX ID + Seq + 3 timestamps */
1556 break;
1557 case ICMP_IREQ:
1558 (void)printf("Information Request\n");
1559 /* XXX ID + Seq */
1560 break;
1561 case ICMP_IREQREPLY:
1562 (void)printf("Information Reply\n");
1563 /* XXX ID + Seq */
1564 break;
1565 case ICMP_MASKREQ:
1566 (void)printf("Address Mask Request\n");
1567 break;
1568 case ICMP_MASKREPLY:
1569 (void)printf("Address Mask Reply\n");
1570 break;
1571 case ICMP_ROUTERADVERT:
1572 (void)printf("Router Advertisement\n");
1573 break;
1574 case ICMP_ROUTERSOLICIT:
1575 (void)printf("Router Solicitation\n");
1576 break;
1577 default:
1578 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1579 }
1580 }
1581
1582 /*
1583 * pr_iph --
1584 * Print an IP header with options.
1585 */
1586 static void
pr_iph(struct ip * ip,const u_char * cp)1587 pr_iph(struct ip *ip, const u_char *cp)
1588 {
1589 struct in_addr dst_ina, src_ina;
1590 int hlen;
1591
1592 hlen = ip->ip_hl << 2;
1593 cp = cp + sizeof(struct ip); /* point to options */
1594
1595 memcpy(&src_ina, &ip->ip_src.s_addr, sizeof(src_ina));
1596 memcpy(&dst_ina, &ip->ip_dst.s_addr, sizeof(dst_ina));
1597
1598 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks %*s %*s",
1599 (int)strlen(inet_ntoa(src_ina)), "Src",
1600 (int)strlen(inet_ntoa(dst_ina)), "Dst");
1601 if (hlen > (int)sizeof(struct ip))
1602 (void)printf(" Opts");
1603 (void)putchar('\n');
1604 (void)printf(" %1x %1x %02x %04x %04x",
1605 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1606 ntohs(ip->ip_id));
1607 (void)printf(" %1x %04x",
1608 (ntohs(ip->ip_off) & 0xe000) >> 13,
1609 ntohs(ip->ip_off) & 0x1fff);
1610 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1611 ntohs(ip->ip_sum));
1612 (void)printf(" %s", inet_ntoa(src_ina));
1613 (void)printf(" %s", inet_ntoa(dst_ina));
1614 /* dump any option bytes */
1615 if (hlen > (int)sizeof(struct ip)) {
1616 (void)printf(" ");
1617 while (hlen-- > (int)sizeof(struct ip)) {
1618 (void)printf("%02x", *cp++);
1619 }
1620 }
1621 (void)putchar('\n');
1622 }
1623
1624 /*
1625 * pr_addr --
1626 * Return an ascii host address as a dotted quad and optionally with
1627 * a hostname.
1628 */
1629 static char *
pr_addr(struct in_addr ina)1630 pr_addr(struct in_addr ina)
1631 {
1632 struct hostent *hp;
1633 static char buf[16 + 3 + MAXHOSTNAMELEN];
1634
1635 if (!(options & F_HOSTNAME))
1636 return inet_ntoa(ina);
1637
1638 #ifdef __HAIKU__
1639 #define cap_gethostbyaddr(w, x, y, z) gethostbyaddr(x, y, z)
1640 #endif
1641 hp = cap_gethostbyaddr(capdns, (char *)&ina, sizeof(ina), AF_INET);
1642
1643 if (hp == NULL)
1644 return inet_ntoa(ina);
1645
1646 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1647 inet_ntoa(ina));
1648 return(buf);
1649 }
1650
1651 static char *
pr_ntime(n_time timestamp)1652 pr_ntime(n_time timestamp)
1653 {
1654 static char buf[11];
1655 int hour, min, sec;
1656
1657 sec = ntohl(timestamp) / 1000;
1658 hour = sec / 60 / 60;
1659 min = (sec % (60 * 60)) / 60;
1660 sec = (sec % (60 * 60)) % 60;
1661
1662 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1663
1664 return (buf);
1665 }
1666
1667 static void
fill(char * bp,char * patp)1668 fill(char *bp, char *patp)
1669 {
1670 char *cp;
1671 int pat[16];
1672 u_int ii, jj, kk;
1673
1674 for (cp = patp; *cp; cp++) {
1675 if (!isxdigit(*cp))
1676 errx(EX_USAGE,
1677 "patterns must be specified as hex digits");
1678
1679 }
1680 ii = sscanf(patp,
1681 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1682 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1683 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1684 &pat[13], &pat[14], &pat[15]);
1685
1686 if (ii > 0)
1687 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
1688 for (jj = 0; jj < ii; ++jj)
1689 bp[jj + kk] = pat[jj];
1690 if (!(options & F_QUIET)) {
1691 (void)printf("PATTERN: 0x");
1692 for (jj = 0; jj < ii; ++jj)
1693 (void)printf("%02x", bp[jj] & 0xFF);
1694 (void)printf("\n");
1695 }
1696 }
1697
1698 #ifndef __HAIKU__
1699 static cap_channel_t *
capdns_setup(void)1700 capdns_setup(void)
1701 {
1702 cap_channel_t *capcas, *capdnsloc;
1703 #ifdef WITH_CASPER
1704 const char *types[2];
1705 int families[1];
1706 #endif
1707 capcas = cap_init();
1708 if (capcas == NULL)
1709 err(1, "unable to create casper process");
1710 capdnsloc = cap_service_open(capcas, "system.dns");
1711 /* Casper capability no longer needed. */
1712 cap_close(capcas);
1713 if (capdnsloc == NULL)
1714 err(1, "unable to open system.dns service");
1715 #ifdef WITH_CASPER
1716 types[0] = "NAME2ADDR";
1717 types[1] = "ADDR2NAME";
1718 if (cap_dns_type_limit(capdnsloc, types, 2) < 0)
1719 err(1, "unable to limit access to system.dns service");
1720 families[0] = AF_INET;
1721 if (cap_dns_family_limit(capdnsloc, families, 1) < 0)
1722 err(1, "unable to limit access to system.dns service");
1723 #endif
1724 return (capdnsloc);
1725 }
1726 #endif
1727