xref: /netbsd/usr.sbin/mtrace/mtrace.c (revision e4abc357)
1 /*	$NetBSD: mtrace.c,v 1.43 2021/10/21 13:21:55 andvar Exp $	*/
2 
3 /*
4  * mtrace.c
5  *
6  * This tool traces the branch of a multicast tree from a source to a
7  * receiver for a particular multicast group and gives statistics
8  * about packet rate and loss for each hop along the path.  It can
9  * usually be invoked just as
10  *
11  * 	mtrace source
12  *
13  * to trace the route from that source to the local host for a default
14  * group when only the route is desired and not group-specific packet
15  * counts.  See the usage line for more complex forms.
16  *
17  *
18  * Released 4 Apr 1995.  This program was adapted by Steve Casner
19  * (USC/ISI) from a prototype written by Ajit Thyagarajan (UDel and
20  * Xerox PARC).  It attempts to parallel in command syntax and output
21  * format the unicast traceroute program written by Van Jacobson (LBL)
22  * for the parts where that makes sense.
23  *
24  * Copyright (c) 1998-2001.
25  * The University of Southern California/Information Sciences Institute.
26  * All rights reserved.
27  *
28  * Redistribution and use in source and binary forms, with or without
29  * modification, are permitted provided that the following conditions
30  * are met:
31  * 1. Redistributions of source code must retain the above copyright
32  *    notice, this list of conditions and the following disclaimer.
33  * 2. Redistributions in binary form must reproduce the above copyright
34  *    notice, this list of conditions and the following disclaimer in the
35  *    documentation and/or other materials provided with the distribution.
36  * 3. Neither the name of the project nor the names of its contributors
37  *    may be used to endorse or promote products derived from this software
38  *    without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  */
52 
53 #include <sys/cdefs.h>
54 #ifndef lint
55 __RCSID("$NetBSD: mtrace.c,v 1.43 2021/10/21 13:21:55 andvar Exp $");
56 #endif
57 
58 #include <sys/types.h>
59 #include <sys/ioctl.h>
60 #include <sys/time.h>
61 #include <poll.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 #include <ctype.h>
65 #include <memory.h>
66 #include <netdb.h>
67 #include <string.h>
68 #include <ifaddrs.h>
69 #include "defs.h"
70 
71 #include <stdarg.h>
72 #ifdef SUNOS5
73 #include <sys/systeminfo.h>
74 #endif
75 
76 #define DEFAULT_TIMEOUT	3	/* How long to wait before retrying requests */
77 #define DEFAULT_RETRIES 3	/* How many times to try */
78 #define MAXHOPS UNREACHABLE	/* Don't need more hops than max metric */
79 #define UNICAST_TTL 255		/* TTL for unicast response */
80 #define MULTICAST_TTL1 64	/* Default TTL for multicast query/response */
81 #define MULTICAST_TTL_INC 32	/* TTL increment for increase after timeout */
82 #define MULTICAST_TTL_MAX 192	/* Maximum TTL allowed (protect low-BW links */
83 
84 struct resp_buf {
85     u_long qtime;		/* Time query was issued */
86     u_long rtime;		/* Time response was received */
87     int	len;			/* Number of reports or length of data */
88     struct igmp igmp;		/* IGMP header */
89     union {
90 	struct {
91 	    struct tr_query q;		/* Query/response header */
92 	    struct tr_resp r[MAXHOPS];	/* Per-hop reports */
93 	} t;
94 	char d[MAX_DVMRP_DATA_LEN];	/* Neighbor data */
95     } u;
96 } base, incr[2];
97 
98 #define qhdr u.t.q
99 #define resps u.t.r
100 #define ndata u.d
101 
102 char names[MAXHOPS][40];
103 int reset[MAXHOPS];			/* To get around 3.4 bug, ... */
104 int swaps[MAXHOPS];			/* To get around 3.6 bug, ... */
105 
106 int timeout = DEFAULT_TIMEOUT;
107 int nqueries = DEFAULT_RETRIES;
108 int numeric = FALSE;
109 int debug = 0;
110 int passive = FALSE;
111 int multicast = FALSE;
112 int statint = 10;
113 int verbose = 0;
114 
115 u_int32_t defgrp;			/* Default group if not specified */
116 u_int32_t query_cast;			/* All routers multicast addr */
117 u_int32_t resp_cast;			/* Mtrace response multicast addr */
118 
119 u_int32_t lcl_addr = 0;			/* This host address, in NET order */
120 u_int32_t dst_netmask;			/* netmask to go with qdst */
121 
122 /*
123  * Query/response parameters, all initialized to zero and set later
124  * to default values or from options.
125  */
126 u_int32_t qsrc = 0;		/* Source address in the query */
127 u_int32_t qgrp = 0;		/* Group address in the query */
128 u_int32_t qdst = 0;		/* Destination (receiver) address in query */
129 u_char qno  = 0;		/* Max number of hops to query */
130 u_int32_t raddr = 0;		/* Address where response should be sent */
131 int    qttl = 0;		/* TTL for the query packet */
132 u_char rttl = 0;		/* TTL for the response packet */
133 u_int32_t gwy = 0;		/* User-supplied last-hop router address */
134 u_int32_t tdst = 0;		/* Address where trace is sent (last-hop) */
135 
136 vifi_t  numvifs;		/* to keep loader happy */
137 				/* (see kern.c) */
138 
139 u_long			byteswap(u_long);
140 const char *		inet_name(u_int32_t addr);
141 u_int32_t			host_addr(const char *name);
142 /* u_int is promoted u_char */
143 const char *		proto_type(u_int type);
144 const char *		flag_type(u_int type);
145 
146 u_int32_t		get_netmask(int s, u_int32_t dst);
147 int			get_ttl(struct resp_buf *buf);
148 int			t_diff(u_long a, u_long b);
149 u_long			fixtime(u_long time);
150 int			send_recv(u_int32_t dst, int type, int code,
151 				  int tries, struct resp_buf *save);
152 const char *		print_host(u_int32_t addr);
153 const char *		print_host2(u_int32_t addr1, u_int32_t addr2);
154 void			print_trace(int index, struct resp_buf *buf);
155 int			what_kind(struct resp_buf *buf, const char *why);
156 const char *		scale(int *hop);
157 void			stat_line(struct tr_resp *r, struct tr_resp *s,
158 				  int have_next, int *res);
159 void			fixup_stats(struct resp_buf *base,
160 				    struct resp_buf *prev,
161 				    struct resp_buf *new);
162 int			print_stats(struct resp_buf *base,
163 				    struct resp_buf *prev,
164 				    struct resp_buf *new);
165 void			check_vif_state(void);
166 void			passive_mode(void) __dead;
167 
168 int			main(int argc, char *argv[]);
169 /* logit() prototyped in defs.h */
170 
171 
172 const char *
inet_name(u_int32_t addr)173 inet_name(u_int32_t addr)
174 {
175     struct hostent *e;
176 
177     e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
178 
179     return e ? e->h_name : "?";
180 }
181 
182 
183 u_int32_t
host_addr(const char * name)184 host_addr(const char *name)
185 {
186     struct hostent *e = (struct hostent *)0;
187     u_int32_t  addr;
188     int	i, dots = 3;
189     char	buf[40];
190     const char	*ip = name;
191     char	*op = buf;
192 
193     /*
194      * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
195      * if the name is all numeric.
196      */
197     for (i = sizeof(buf) - 7; i > 0; --i) {
198 	if (*ip == '.') --dots;
199 	else if (*ip == '\0') break;
200 	else if (!isdigit((unsigned char)*ip)) dots = 0;  /* Not numeric, don't add zeroes */
201 	*op++ = *ip++;
202     }
203     for (i = 0; i < dots; ++i) {
204 	*op++ = '.';
205 	*op++ = '0';
206     }
207     *op = '\0';
208 
209     if (dots <= 0) e = gethostbyname(name);
210     if (e) memcpy((char *)&addr, e->h_addr_list[0], sizeof(addr));
211     else {
212 	addr = inet_addr(buf);
213 	if (addr == (in_addr_t)-1) {
214 	    addr = 0;
215 	    printf("Could not parse %s as host name or address\n", name);
216 	}
217     }
218     return addr;
219 }
220 
221 
222 const char *
proto_type(u_int type)223 proto_type(u_int type)
224 {
225     static char buf[80];
226 
227     switch (type) {
228       case PROTO_DVMRP:
229 	return ("DVMRP");
230       case PROTO_MOSPF:
231 	return ("MOSPF");
232       case PROTO_PIM:
233 	return ("PIM");
234       case PROTO_CBT:
235 	return ("CBT");
236       case PROTO_PIM_SPEC:
237 	return ("PIM-special");
238       case PROTO_PIM_STAT:
239 	return ("PIM-static");
240       case PROTO_DVMRP_STAT:
241 	return ("DVMRP-static");
242       case PROTO_PIM_MBGP:
243 	return ("PIM/MBGP");
244       default:
245 	(void)snprintf(buf, sizeof buf, "Unknown protocol code %d", type);
246 	return (buf);
247     }
248 }
249 
250 
251 const char *
flag_type(u_int type)252 flag_type(u_int type)
253 {
254     static char buf[80];
255 
256     switch (type) {
257       case TR_NO_ERR:
258 	return ("");
259       case TR_WRONG_IF:
260 	return ("Wrong interface");
261       case TR_PRUNED:
262 	return ("Prune sent upstream");
263       case TR_OPRUNED:
264 	return ("Output pruned");
265       case TR_SCOPED:
266 	return ("Hit scope boundary");
267       case TR_NO_RTE:
268 	return ("No route");
269       case TR_OLD_ROUTER:
270 	return ("Next router no mtrace");
271       case TR_NO_FWD:
272 	return ("Not forwarding");
273       case TR_NO_SPACE:
274 	return ("No space in packet");
275       case TR_RP_OR_CORE:
276 	return ("RP/Core");
277       case TR_RPF_INT:
278 	return ("Trace packet on RPT interface");
279       case TR_NO_MULTICAST:
280 	return ("Trace packet on non-MC interface");
281       case TR_ADMIN_DENY:
282 	return ("Trace admin-denied");
283       default:
284 	(void)snprintf(buf, sizeof buf, "Unknown error code %d", type);
285 	return (buf);
286     }
287 }
288 
289 /*
290  * If destination is on a local net, get the netmask, else set the
291  * netmask to all ones.  There are two side effects: if the local
292  * address was not explicitly set, and if the destination is on a
293  * local net, use that one; in either case, verify that the local
294  * address is valid.
295  */
296 
297 u_int32_t
get_netmask(int s,u_int32_t dst)298 get_netmask(int s, u_int32_t dst)
299 {
300     u_int32_t if_addr, if_mask;
301     u_int32_t retval = 0xFFFFFFFF;
302     int found = FALSE;
303     struct ifaddrs *ifap, *ifa;
304 
305     if (getifaddrs(&ifap) != 0) {
306 	perror("getifaddrs");
307 	return (retval);
308     }
309     for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
310 	if (ifa->ifa_addr->sa_family != AF_INET)
311 	    continue;
312 	if_addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr;
313 	if_mask = ((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr.s_addr;
314 	if ((dst & if_mask) == (if_addr & if_mask)) {
315 	    retval = if_mask;
316 	    if (lcl_addr == 0)
317 		lcl_addr = if_addr;
318 	}
319 	if (lcl_addr == if_addr)
320 	    found = TRUE;
321     }
322     if (!found && lcl_addr != 0) {
323 	printf("Interface address is not valid\n");
324 	exit(1);
325     }
326     freeifaddrs(ifap);
327     return (retval);
328 }
329 
330 
331 int
get_ttl(struct resp_buf * buf)332 get_ttl(struct resp_buf *buf)
333 {
334     int rno;
335     struct tr_resp *b;
336     u_int ttl;
337 
338     if (buf && (rno = buf->len) > 0) {
339 	b = buf->resps + rno - 1;
340 	ttl = b->tr_fttl;
341 
342 	while (--rno > 0) {
343 	    --b;
344 	    if (ttl < b->tr_fttl) ttl = b->tr_fttl;
345 	    else ++ttl;
346 	}
347 	ttl += MULTICAST_TTL_INC;
348 	if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
349 	if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
350 	return (ttl);
351     } else return(MULTICAST_TTL1);
352 }
353 
354 /*
355  * Calculate the difference between two 32-bit NTP timestamps and return
356  * the result in milliseconds.
357  */
358 int
t_diff(u_long a,u_long b)359 t_diff(u_long a, u_long b)
360 {
361     int d = a - b;
362 
363     return ((d * 125) >> 13);
364 }
365 
366 /*
367  * Fixup for incorrect time format in 3.3 mrouted.
368  * This is possible because (JAN_1970 mod 64K) is quite close to 32K,
369  * so correct and incorrect times will be far apart.
370  */
371 u_long
fixtime(u_long tim)372 fixtime(u_long tim)
373 {
374     if (abs((int)(tim-base.qtime)) > 0x3FFFFFFF)
375         tim = ((tim & 0xFFFF0000) + (JAN_1970 << 16)) +
376 	       ((tim & 0xFFFF) << 14) / 15625;
377     return (tim);
378 }
379 
380 /*
381  * Swap bytes for poor little-endian machines that don't byte-swap
382  */
383 u_long
byteswap(u_long v)384 byteswap(u_long v)
385 {
386     return ((v << 24) | ((v & 0xff00) << 8) |
387 	    ((v >> 8) & 0xff00) | (v >> 24));
388 }
389 
390 int
send_recv(u_int32_t dst,int type,int code,int tries,struct resp_buf * save)391 send_recv(u_int32_t dst, int type, int code, int tries, struct resp_buf *save)
392 {
393     struct pollfd set[1];
394     struct timeval tq, tr, tv;
395     struct ip *ip;
396     struct igmp *igmp;
397     struct tr_query *query, *rquery;
398     int ipdatalen, iphdrlen, igmpdatalen;
399     u_int32_t local, group;
400     int datalen;
401     int count, recvlen;
402     socklen_t dummy;
403     int len;
404     int i;
405 
406     if (type == IGMP_MTRACE_QUERY) {
407 	group = qgrp;
408 	datalen = sizeof(struct tr_query);
409     } else {
410 	group = htonl(MROUTED_LEVEL);
411 	datalen = 0;
412     }
413     if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
414     else local = INADDR_ANY;
415 
416     /*
417      * If the reply address was not explicitly specified, start off
418      * with the unicast address of this host.  Then, if there is no
419      * response after trying half the tries with unicast, switch to
420      * the standard multicast reply address.  If the TTL was also not
421      * specified, set a multicast TTL and if needed increase it for the
422      * last quarter of the tries.
423      */
424     query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
425     query->tr_raddr = raddr ? raddr : multicast ? resp_cast : lcl_addr;
426     query->tr_rttl  = rttl ? rttl :
427       IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL;
428     query->tr_src   = qsrc;
429     query->tr_dst   = qdst;
430 
431     for (i = tries ; i > 0; --i) {
432 	if (tries == nqueries && raddr == 0) {
433 	    if (i == ((nqueries + 1) >> 1)) {
434 		query->tr_raddr = resp_cast;
435 		if (rttl == 0) query->tr_rttl = get_ttl(save);
436 	    }
437 	    if (i <= ((nqueries + 3) >> 2) && rttl == 0) {
438 		query->tr_rttl += MULTICAST_TTL_INC;
439 		if (query->tr_rttl > MULTICAST_TTL_MAX)
440 		  query->tr_rttl = MULTICAST_TTL_MAX;
441 	    }
442 	}
443 
444 	/*
445 	 * Change the qid for each request sent to avoid being confused
446 	 * by duplicate responses
447 	 */
448 	query->tr_qid  = arc4random() >> 8;
449 
450 	/*
451 	 * Set timer to calculate delays, then send query
452 	 */
453 	gettimeofday(&tq, 0);
454 	send_igmp(local, dst, type, code, group, datalen);
455 
456 	/*
457 	 * Wait for response, discarding false alarms
458 	 */
459 	set[0].fd = igmp_socket;
460 	set[0].events = POLLIN;
461 	while (TRUE) {
462 	    gettimeofday(&tv, 0);
463 	    tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
464 	    tv.tv_usec = tq.tv_usec - tv.tv_usec;
465 	    if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
466 	    if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;
467 
468 	    count = poll(set, 1, tv.tv_sec * 1000 + tv.tv_usec / 1000);
469 
470 	    if (count < 0) {
471 		if (errno != EINTR) perror("select");
472 		continue;
473 	    } else if (count == 0) {
474 		printf("* ");
475 		fflush(stdout);
476 		break;
477 	    }
478 
479 	    gettimeofday(&tr, 0);
480 	    recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
481 			       0, (struct sockaddr *)0, &dummy);
482 
483 	    if (recvlen <= 0) {
484 		if (recvlen && errno != EINTR) perror("recvfrom");
485 		continue;
486 	    }
487 
488 	    if (recvlen < (int)sizeof(struct ip)) {
489 		fprintf(stderr,
490 			"packet too short (%u bytes) for IP header", recvlen);
491 		continue;
492 	    }
493 	    ip = (struct ip *) recv_buf;
494 	    if (ip->ip_p == 0)	/* ignore cache creation requests */
495 		continue;
496 
497 	    iphdrlen = ip->ip_hl << 2;
498 	    ipdatalen = ip->ip_len;
499 	    if (iphdrlen + ipdatalen != recvlen) {
500 		fprintf(stderr,
501 			"packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
502 			recvlen, iphdrlen, ipdatalen);
503 		continue;
504 	    }
505 
506 	    igmp = (struct igmp *) (recv_buf + iphdrlen);
507 	    igmpdatalen = ipdatalen - IGMP_MINLEN;
508 	    if (igmpdatalen < 0) {
509 		fprintf(stderr,
510 			"IP data field too short (%u bytes) for IGMP from %s\n",
511 			ipdatalen, inet_fmt(ip->ip_src.s_addr));
512 		continue;
513 	    }
514 
515 	    switch (igmp->igmp_type) {
516 
517 	      case IGMP_DVMRP:
518 		if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
519 		len = igmpdatalen;
520 		/*
521 		 * Accept DVMRP_NEIGHBORS2 response if it comes from the
522 		 * address queried or if that address is one of the local
523 		 * addresses in the response.
524 		 */
525 		if (ip->ip_src.s_addr != dst) {
526 		    u_int32_t *p = (u_int32_t *)(igmp + 1);
527 		    u_int32_t *ep = p + (len >> 2);
528 		    while (p < ep) {
529 			u_int32_t laddr = *p++;
530 			int n = ntohl(*p++) & 0xFF;
531 			if (laddr == dst) {
532 			    ep = p + 1;		/* ensure p < ep after loop */
533 			    break;
534 			}
535 			p += n;
536 		    }
537 		    if (p >= ep) continue;
538 		}
539 		break;
540 
541 	      case IGMP_MTRACE_QUERY:	    /* For backward compatibility with 3.3 */
542 	      case IGMP_MTRACE_REPLY:
543 		if (igmpdatalen <= (int)QLEN) continue;
544 		if ((igmpdatalen - QLEN)%RLEN) {
545 		    printf("packet with incorrect datalen\n");
546 		    continue;
547 		}
548 
549 		/*
550 		 * Ignore responses that don't match query.
551 		 */
552 		rquery = (struct tr_query *)(igmp + 1);
553 		if (rquery->tr_qid != query->tr_qid) continue;
554 		if (rquery->tr_src != qsrc) continue;
555 		if (rquery->tr_dst != qdst) continue;
556 		len = (igmpdatalen - QLEN)/RLEN;
557 
558 		/*
559 		 * Ignore trace queries passing through this node when
560 		 * mtrace is run on an mrouter that is in the path
561 		 * (needed only because IGMP_MTRACE_QUERY is accepted above
562 		 * for backward compatibility with multicast release 3.3).
563 		 */
564 		if (igmp->igmp_type == IGMP_MTRACE_QUERY) {
565 		    struct tr_resp *r = (struct tr_resp *)(rquery+1) + len - 1;
566 		    u_int32_t smask;
567 
568 		    VAL_TO_MASK(smask, r->tr_smask);
569 		    if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
570 			&& r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
571 		      continue;
572 		}
573 
574 		/*
575 		 * A match, we'll keep this one.
576 		 */
577 		if (len > code) {
578 		    fprintf(stderr,
579 			    "Num hops received (%d) exceeds request (%d)\n",
580 			    len, code);
581 		}
582 		rquery->tr_raddr = query->tr_raddr;	/* Insure these are */
583 		rquery->tr_rttl = query->tr_rttl;	/* as we sent them */
584 		break;
585 
586 	      default:
587 		continue;
588 	    }
589 
590 	    /*
591 	     * Most of the sanity checking done at this point.
592 	     * Return this packet we have been waiting for.
593 	     */
594 	    if (save) {
595 		save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
596 			      (tq.tv_usec << 10) / 15625;
597 		save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
598 			      (tr.tv_usec << 10) / 15625;
599 		save->len = len;
600 		bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
601 	    }
602 	    return (recvlen);
603 	}
604     }
605     return (0);
606 }
607 
608 /*
609  * Most of this code is duplicated elsewhere.  I'm not sure if
610  * the duplication is absolutely required or not.
611  *
612  * Ideally, this would keep track of ongoing statistics
613  * collection and print out statistics.  (& keep track
614  * of h-b-h traces and only print the longest)  For now,
615  * it just snoops on what traces it can.
616  */
617 void
passive_mode(void)618 passive_mode(void)
619 {
620     struct timeval tr;
621     struct ip *ip;
622     struct igmp *igmp;
623     struct tr_resp *r;
624     int ipdatalen, iphdrlen, igmpdatalen;
625     int len, recvlen;
626     socklen_t dummy;
627     u_int32_t smask;
628 
629     if (raddr) {
630 	if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, INADDR_ANY);
631     } else k_join(htonl(0xE0000120), INADDR_ANY);
632 
633     while (1) {
634 	recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
635 			   0, (struct sockaddr *)0, &dummy);
636 	gettimeofday(&tr,0);
637 
638 	if (recvlen <= 0) {
639 	    if (recvlen && errno != EINTR) perror("recvfrom");
640 	    continue;
641 	}
642 
643 	if (recvlen < (int)sizeof(struct ip)) {
644 	    fprintf(stderr,
645 		    "packet too short (%u bytes) for IP header", recvlen);
646 	    continue;
647 	}
648 	ip = (struct ip *) recv_buf;
649 	if (ip->ip_p == 0)	/* ignore cache creation requests */
650 	    continue;
651 
652 	iphdrlen = ip->ip_hl << 2;
653 	ipdatalen = ip->ip_len;
654 	if (iphdrlen + ipdatalen != recvlen) {
655 	    fprintf(stderr,
656 		    "packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
657 		    recvlen, iphdrlen, ipdatalen);
658 	    continue;
659 	}
660 
661 	igmp = (struct igmp *) (recv_buf + iphdrlen);
662 	igmpdatalen = ipdatalen - IGMP_MINLEN;
663 	if (igmpdatalen < 0) {
664 	    fprintf(stderr,
665 		    "IP data field too short (%u bytes) for IGMP from %s\n",
666 		    ipdatalen, inet_fmt(ip->ip_src.s_addr));
667 	    continue;
668 	}
669 
670 	switch (igmp->igmp_type) {
671 
672 	  case IGMP_MTRACE_QUERY:	    /* For backward compatibility with 3.3 */
673 	  case IGMP_MTRACE_REPLY:
674 	    if (igmpdatalen < (int)QLEN) continue;
675 	    if ((igmpdatalen - QLEN)%RLEN) {
676 		printf("packet with incorrect datalen\n");
677 		continue;
678 	    }
679 
680 	    len = (igmpdatalen - QLEN)/RLEN;
681 
682 	    break;
683 
684 	  default:
685 	    continue;
686 	}
687 
688 	base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
689 		      (tr.tv_usec << 10) / 15625;
690 	base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
691 		      (tr.tv_usec << 10) / 15625;
692 	base.len = len;
693 	bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
694 	/*
695 	 * If the user specified which traces to monitor,
696 	 * only accept traces that correspond to the
697 	 * request
698 	 */
699 	if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
700 	    (qdst != 0 && qdst != base.qhdr.tr_dst) ||
701 	    (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
702 	    continue;
703 
704 	printf("Mtrace from %s to %s via group %s (mxhop=%d)\n",
705 		inet_fmt(base.qhdr.tr_dst),
706 		inet_fmt(base.qhdr.tr_src),
707 		inet_fmt(igmp->igmp_group.s_addr),
708 		igmp->igmp_code);
709 	if (len == 0)
710 	    continue;
711 	printf("  0  ");
712 	print_host(base.qhdr.tr_dst);
713 	printf("\n");
714 	print_trace(1, &base);
715 	r = base.resps + base.len - 1;
716 	VAL_TO_MASK(smask, r->tr_smask);
717 	if ((r->tr_inaddr & smask) == (base.qhdr.tr_src & smask)) {
718 	    printf("%3d  ", -(base.len+1));
719 	    print_host(base.qhdr.tr_src);
720 	    printf("\n");
721 	} else if (r->tr_rmtaddr != 0) {
722 	    printf("%3d  ", -(base.len+1));
723 	    what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
724 				   "doesn't support mtrace"
725 				 : "is the next hop");
726 	}
727 	printf("\n");
728     }
729 }
730 
731 const char *
print_host(u_int32_t addr)732 print_host(u_int32_t addr)
733 {
734     return print_host2(addr, 0);
735 }
736 
737 /*
738  * On some routers, one interface has a name and the other doesn't.
739  * We always print the address of the outgoing interface, but can
740  * sometimes get the name from the incoming interface.  This might be
741  * confusing but should be slightly more helpful than just a "?".
742  */
743 const char *
print_host2(u_int32_t addr1,u_int32_t addr2)744 print_host2(u_int32_t addr1, u_int32_t addr2)
745 {
746     const char *name;
747 
748     if (numeric) {
749 	printf("%s", inet_fmt(addr1));
750 	return ("");
751     }
752     name = inet_name(addr1);
753     if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
754 	name = inet_name(addr2);
755     printf("%s (%s)", name, inet_fmt(addr1));
756     return (name);
757 }
758 
759 /*
760  * Print responses as received (reverse path from dst to src)
761  */
762 void
print_trace(int idx,struct resp_buf * buf)763 print_trace(int idx, struct resp_buf *buf)
764 {
765     struct tr_resp *r;
766     const char *name;
767     int i;
768     int hop;
769     const char *ms, *ft;
770 
771     i = abs(idx);
772     r = buf->resps + i - 1;
773 
774     for (; i <= buf->len; ++i, ++r) {
775 	if (idx > 0) printf("%3d  ", -i);
776 	name = print_host2(r->tr_outaddr, r->tr_inaddr);
777 	printf("  %s  thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
778 	if (verbose) {
779 	    hop = t_diff(fixtime(ntohl(r->tr_qarr)), buf->qtime);
780 	    ms = scale(&hop);
781 	    printf("  %d%s", hop, ms);
782 	}
783 	ft = flag_type(r->tr_rflags);
784 	if (strlen(ft) != 0)
785 	    printf("  %s", ft);
786 	printf("\n");
787 	memcpy(names[i-1], name, sizeof(names[0]) - 1);
788 	names[i-1][sizeof(names[0])-1] = '\0';
789     }
790 }
791 
792 /*
793  * See what kind of router is the next hop
794  */
795 int
what_kind(struct resp_buf * buf,const char * why)796 what_kind(struct resp_buf *buf, const char *why)
797 {
798     u_int32_t smask;
799     int retval;
800     int hops = buf->len;
801     struct tr_resp *r = buf->resps + hops - 1;
802     u_int32_t next = r->tr_rmtaddr;
803 
804     retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0]);
805     print_host(next);
806     if (retval) {
807 	u_int32_t version = ntohl(incr[0].igmp.igmp_group.s_addr);
808 	u_int32_t *p = (u_int32_t *)incr[0].ndata;
809 	u_int32_t *ep = p + (incr[0].len >> 2);
810 	const char *type = "";
811 	retval = 0;
812 	switch (version & 0xFF) {
813 	  case 1:
814 	    type = "proteon/mrouted ";
815 	    retval = 1;
816 	    break;
817 
818 	  case 2:
819 	  case 3:
820 	    if (((version >> 8) & 0xFF) < 3) retval = 1;
821 				/* Fall through */
822 	  case 4:
823 	    type = "mrouted ";
824 	    break;
825 
826 	  case 10:
827 	    type = "cisco ";
828 	}
829 	printf(" [%s%d.%d] %s\n",
830 	       type, version & 0xFF, (version >> 8) & 0xFF,
831 	       why);
832 	VAL_TO_MASK(smask, r->tr_smask);
833 	while (p < ep) {
834 	    u_int32_t laddr = *p++;
835 	    int flags = (ntohl(*p) & 0xFF00) >> 8;
836 	    int n = ntohl(*p++) & 0xFF;
837 	    if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
838 		 (laddr & smask) == (qsrc & smask)) {
839 		printf("%3d  ", -(hops+2));
840 		print_host(qsrc);
841 		printf("\n");
842 		return 1;
843 	    }
844 	    p += n;
845 	}
846 	return retval;
847     }
848     printf(" %s\n", why);
849     return 0;
850 }
851 
852 
853 const char *
scale(int * hop)854 scale(int *hop)
855 {
856     if (*hop > -1000 && *hop < 10000) return (" ms");
857     *hop /= 1000;
858     if (*hop > -1000 && *hop < 10000) return (" s ");
859     return ("s ");
860 }
861 
862 /*
863  * Calculate and print one line of packet loss and packet rate statistics.
864  * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
865  */
866 #define NEITHER 0
867 #define INS     1
868 #define OUTS    2
869 #define BOTH    3
870 void
stat_line(struct tr_resp * r,struct tr_resp * s,int have_next,int * rst)871 stat_line(struct tr_resp *r, struct tr_resp *s, int have_next, int *rst)
872 {
873     int timediff = (fixtime(ntohl(s->tr_qarr)) -
874 			 fixtime(ntohl(r->tr_qarr))) >> 16;
875     int v_lost, v_pct;
876     int g_lost, g_pct;
877     int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
878     int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
879     int v_pps, g_pps;
880     char v_str[8], g_str[8];
881     int have = NEITHER;
882     int res = *rst;
883 
884     if (timediff == 0) timediff = 1;
885     v_pps = v_out / timediff;
886     g_pps = g_out / timediff;
887 
888     if ((v_out && (s->tr_vifout != 0xFFFFFFFF && s->tr_vifout != 0)) ||
889 		 (r->tr_vifout != 0xFFFFFFFF && r->tr_vifout != 0))
890 	    have |= OUTS;
891 
892     if (have_next) {
893 	--r,  --s,  --rst;
894 	if ((s->tr_vifin != 0xFFFFFFFF && s->tr_vifin != 0) ||
895 	    (r->tr_vifin != 0xFFFFFFFF && r->tr_vifin != 0))
896 	  have |= INS;
897 	if (*rst)
898 	  res = 1;
899     }
900 
901     switch (have) {
902       case BOTH:
903 	v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
904 	if (v_out) v_pct = (v_lost * 100 + (v_out >> 1)) / v_out;
905 	else v_pct = 0;
906 	if (-100 < v_pct && v_pct < 101 && v_out > 10)
907 	  (void)snprintf(v_str, sizeof v_str, "%3d", v_pct);
908 	else memcpy(v_str, " --", 4);
909 
910 	g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
911 	if (g_out) g_pct = (g_lost * 100 + (g_out >> 1))/ g_out;
912 	else g_pct = 0;
913 	if (-100 < g_pct && g_pct < 101 && g_out > 10)
914 	  (void)snprintf(g_str, sizeof g_str, "%3d", g_pct);
915 	else memcpy(g_str, " --", 4);
916 
917 	printf("%6d/%-5d=%s%%%4d pps",
918 	       v_lost, v_out, v_str, v_pps);
919 	if (res)
920 	    printf("\n");
921 	else
922 	    printf("%6d/%-5d=%s%%%4d pps\n",
923 		   g_lost, g_out, g_str, g_pps);
924 	break;
925 
926       case INS:
927 	v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
928 	v_pps = v_out / timediff;
929 	/* Fall through */
930 
931       case OUTS:
932 	printf("       %-5d     %4d pps",
933 	       v_out, v_pps);
934 	if (res)
935 	    printf("\n");
936 	else
937 	    printf("       %-5d     %4d pps\n",
938 		   g_out, g_pps);
939 	break;
940 
941       case NEITHER:
942 	printf("\n");
943 	break;
944     }
945 
946     if (debug > 2) {
947 	printf("\t\t\t\tv_in: %ld ", (long)ntohl(s->tr_vifin));
948 	printf("v_out: %ld ", (long)ntohl(s->tr_vifout));
949 	printf("pkts: %ld\n", (long)ntohl(s->tr_pktcnt));
950 	printf("\t\t\t\tv_in: %ld ", (long)ntohl(r->tr_vifin));
951 	printf("v_out: %ld ", (long)ntohl(r->tr_vifout));
952 	printf("pkts: %ld\n", (long)ntohl(r->tr_pktcnt));
953 	printf("\t\t\t\tv_in: %ld ",
954 	    (long)ntohl(s->tr_vifin)-ntohl(r->tr_vifin));
955 	printf("v_out: %ld ",
956 	    (long)(ntohl(s->tr_vifout) - ntohl(r->tr_vifout)));
957 	printf("pkts: %ld ", (long)(ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt)));
958 	printf("time: %d\n", timediff);
959 	printf("\t\t\t\tres: %d\n", res);
960     }
961 }
962 
963 /*
964  * A fixup to check if any pktcnt has been reset, and to fix the
965  * byteorder bugs in mrouted 3.6 on little-endian machines.
966  */
967 void
fixup_stats(struct resp_buf * basep,struct resp_buf * prev,struct resp_buf * new)968 fixup_stats(struct resp_buf *basep, struct resp_buf *prev, struct resp_buf *new)
969 {
970     int rno = basep->len;
971     struct tr_resp *b = basep->resps + rno;
972     struct tr_resp *p = prev->resps + rno;
973     struct tr_resp *n = new->resps + rno;
974     int *r = reset + rno;
975     int *s = swaps + rno;
976     int res;
977 
978     /* Check for byte-swappers */
979     while (--rno >= 0) {
980 	--n; --p; --b; --s;
981 	if (*s || (ntohl(n->tr_vifout) - ntohl(p->tr_vifout)) > 100000) {
982 	    /* This host sends byteswapped reports; swap 'em */
983 	    if (!*s) {
984 		*s = 1;
985 		b->tr_qarr = byteswap(b->tr_qarr);
986 		b->tr_vifin = byteswap(b->tr_vifin);
987 		b->tr_vifout = byteswap(b->tr_vifout);
988 		b->tr_pktcnt = byteswap(b->tr_pktcnt);
989 	    }
990 
991 	    n->tr_qarr = byteswap(n->tr_qarr);
992 	    n->tr_vifin = byteswap(n->tr_vifin);
993 	    n->tr_vifout = byteswap(n->tr_vifout);
994 	    n->tr_pktcnt = byteswap(n->tr_pktcnt);
995 	}
996     }
997 
998     rno = basep->len;
999     b = basep->resps + rno;
1000     p = prev->resps + rno;
1001     n = new->resps + rno;
1002 
1003     while (--rno >= 0) {
1004 	--n; --p; --b; --r;
1005 	res = ((ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
1006 	       (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)));
1007 	if (debug > 2)
1008     	    printf("\t\tr=%d, res=%d\n", *r, res);
1009 	if (*r) {
1010 	    if (res || *r > 1) {
1011 		/*
1012 		 * This router appears to be a 3.4 with that nasty ol'
1013 		 * neighbor version bug, which causes it to constantly
1014 		 * reset.  Just nuke the statistics for this node, and
1015 		 * don't even bother giving it the benefit of the
1016 		 * doubt from now on.
1017 		 */
1018 		p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
1019 		r++;
1020 	    } else {
1021 		/*
1022 		 * This is simply the situation that the original
1023 		 * fixup_stats was meant to deal with -- that a
1024 		 * 3.3 or 3.4 router deleted a cache entry while
1025 		 * traffic was still active.
1026 		 */
1027 		*r = 0;
1028 		break;
1029 	    }
1030 	} else
1031 	    *r = res;
1032     }
1033 
1034     if (rno < 0) return;
1035 
1036     rno = basep->len;
1037     b = basep->resps + rno;
1038     p = prev->resps + rno;
1039 
1040     while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
1041 }
1042 
1043 /*
1044  * Print responses with statistics for forward path (from src to dst)
1045  */
1046 int
print_stats(struct resp_buf * basep,struct resp_buf * prev,struct resp_buf * new)1047 print_stats(struct resp_buf *basep, struct resp_buf *prev, struct resp_buf *new)
1048 {
1049     int rtt, hop;
1050     const char *ms;
1051     char *s1;
1052     u_int32_t smask;
1053     int rno = basep->len - 1;
1054     struct tr_resp *b = basep->resps + rno;
1055     struct tr_resp *p = prev->resps + rno;
1056     struct tr_resp *n = new->resps + rno;
1057     int *r = reset + rno;
1058     u_long resptime = new->rtime;
1059     u_long qarrtime = fixtime(ntohl(n->tr_qarr));
1060     u_int ttl = n->tr_fttl;
1061     int first = (basep == prev);
1062 
1063     VAL_TO_MASK(smask, b->tr_smask);
1064     printf("  Source        Response Dest");
1065     printf("    Packet Statistics For     Only For Traffic\n");
1066     s1 = inet_fmt(qsrc);
1067     printf("%-15s %-15s  All Multicast Traffic     From %s\n",
1068 	   ((b->tr_inaddr & smask) == (qsrc & smask)) ? s1 : "   * * *       ",
1069 	   inet_fmt(basep->qhdr.tr_raddr), s1);
1070     rtt = t_diff(resptime, new->qtime);
1071     ms = scale(&rtt);
1072     printf("     %c       __/  rtt%5d%s    Lost/Sent = Pct  Rate       To %s\n",
1073 	   first ? 'v' : '|', rtt, ms, inet_fmt(qgrp));
1074     if (!first) {
1075 	hop = t_diff(resptime, qarrtime);
1076 	ms = scale(&hop);
1077 	printf("     v      /     hop%5d%s", hop, ms);
1078 	printf("    ---------------------     --------------------\n");
1079     }
1080     if (debug > 2) {
1081 	printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
1082 	printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
1083 	printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
1084 	printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
1085 	printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
1086 	printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
1087 	printf("\t\t\t\tv_in: %ld ",
1088 	    (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
1089 	printf("v_out: %ld ",
1090 	    (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
1091 	printf("pkts: %ld\n",
1092 	    (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
1093 	printf("\t\t\t\treset: %d\n", *r);
1094     }
1095 
1096     while (TRUE) {
1097 	if ((n->tr_inaddr != b->tr_inaddr) || (p->tr_inaddr != b->tr_inaddr))
1098 	  return 1;		/* Route changed */
1099 
1100 	if ((n->tr_inaddr != n->tr_outaddr))
1101 	  printf("%-15s\n", inet_fmt(n->tr_inaddr));
1102 	printf("%-15s %-14s %s\n", inet_fmt(n->tr_outaddr), names[rno],
1103 		 flag_type(n->tr_rflags));
1104 
1105 	if (rno-- < 1) break;
1106 
1107 	printf("     %c     ^      ttl%5d   ", first ? 'v' : '|', ttl);
1108 	stat_line(p, n, TRUE, r);
1109 	if (!first) {
1110 	    resptime = qarrtime;
1111 	    qarrtime = fixtime(ntohl((n-1)->tr_qarr));
1112 	    hop = t_diff(resptime, qarrtime);
1113 	    ms = scale(&hop);
1114 	    printf("     v     |      hop%5d%s", hop, ms);
1115 	    stat_line(b, n, TRUE, r);
1116 	}
1117 
1118 	--b, --p, --n, --r;
1119 	if (ttl < n->tr_fttl) ttl = n->tr_fttl;
1120 	else ++ttl;
1121     }
1122 
1123     printf("     %c      \\__   ttl%5d   ", first ? 'v' : '|', ttl);
1124     stat_line(p, n, FALSE, r);
1125     if (!first) {
1126 	hop = t_diff(qarrtime, new->qtime);
1127 	ms = scale(&hop);
1128 	printf("     v         \\  hop%5d%s", hop, ms);
1129 	stat_line(b, n, FALSE, r);
1130     }
1131     printf("%-15s %s\n", inet_fmt(qdst), inet_fmt(lcl_addr));
1132     printf("  Receiver      Query Source\n\n");
1133     return 0;
1134 }
1135 
1136 
1137 /***************************************************************************
1138  *	main
1139  ***************************************************************************/
1140 
1141 int
main(int argc,char ** argv)1142 main(int argc, char **argv)
1143 {
1144     int udp;
1145     struct sockaddr_in addr;
1146     socklen_t addrlen = sizeof(addr);
1147     int recvlen;
1148     struct timeval tv;
1149     struct resp_buf *prev, *new;
1150     struct tr_resp *r;
1151     u_int32_t smask;
1152     int rno;
1153     int hops, nexthop, tries;
1154     u_int32_t lastout = 0;
1155     int numstats = 1;
1156     int waittime;
1157 
1158     if (geteuid() != 0) {
1159 	fprintf(stderr, "mtrace: must be root\n");
1160 	exit(1);
1161     }
1162     init_igmp();
1163     if (setuid(getuid()) == -1)
1164 	logit(LOG_ERR, errno, "setuid");
1165 
1166     argv++, argc--;
1167     if (argc == 0) goto usage;
1168 
1169     while (argc > 0 && *argv[0] == '-') {
1170 	const char *p = *argv++;  argc--;
1171 	p++;
1172 	do {
1173 	    char c = *p++;
1174 	    const char *arg = (char *) 0;
1175 	    if (isdigit((unsigned char)*p)) {
1176 		arg = p;
1177 		p = "";
1178 	    } else if (argc > 0) arg = argv[0];
1179 	    switch (c) {
1180 	      case 'd':			/* Unlisted debug print option */
1181 		if (arg && isdigit((unsigned char)*arg)) {
1182 		    debug = atoi(arg);
1183 		    if (debug < 0) debug = 0;
1184 		    if (debug > 3) debug = 3;
1185 		    if (arg == argv[0]) argv++, argc--;
1186 		    break;
1187 		} else
1188 		    goto usage;
1189 	      case 'M':			/* Use multicast for response */
1190 		multicast = TRUE;
1191 		break;
1192 	      case 'l':			/* Loop updating stats indefinitely */
1193 		numstats = 3153600;
1194 		break;
1195 	      case 'n':			/* Don't reverse map host addresses */
1196 		numeric = TRUE;
1197 		break;
1198 	      case 'p':			/* Passive listen for traces */
1199 		passive = TRUE;
1200 		break;
1201 	      case 'v':			/* Verbosity */
1202 		verbose = TRUE;
1203 		break;
1204 	      case 's':			/* Short form, don't wait for stats */
1205 		numstats = 0;
1206 		break;
1207 	      case 'w':			/* Time to wait for packet arrival */
1208 		if (arg && isdigit((unsigned char)*arg)) {
1209 		    timeout = atoi(arg);
1210 		    if (timeout < 1) timeout = 1;
1211 		    if (arg == argv[0]) argv++, argc--;
1212 		    break;
1213 		} else
1214 		    goto usage;
1215 	      case 'm':			/* Max number of hops to trace */
1216 		if (arg && isdigit((unsigned char)*arg)) {
1217 		    qno = atoi(arg);
1218 		    if (qno > MAXHOPS) qno = MAXHOPS;
1219 		    else if (qno < 1) qno = 0;
1220 		    if (arg == argv[0]) argv++, argc--;
1221 		    break;
1222 		} else
1223 		    goto usage;
1224 	      case 'q':			/* Number of query retries */
1225 		if (arg && isdigit((unsigned char)*arg)) {
1226 		    nqueries = atoi(arg);
1227 		    if (nqueries < 1) nqueries = 1;
1228 		    if (arg == argv[0]) argv++, argc--;
1229 		    break;
1230 		} else
1231 		    goto usage;
1232 	      case 'g':			/* Last-hop gateway (dest of query) */
1233 		if (arg && (gwy = host_addr(arg))) {
1234 		    if (arg == argv[0]) argv++, argc--;
1235 		    break;
1236 		} else
1237 		    goto usage;
1238 	      case 't':			/* TTL for query packet */
1239 		if (arg && isdigit((unsigned char)*arg)) {
1240 		    qttl = atoi(arg);
1241 		    if (qttl < 1) qttl = 1;
1242 		    rttl = qttl;
1243 		    if (arg == argv[0]) argv++, argc--;
1244 		    break;
1245 		} else
1246 		    goto usage;
1247 	      case 'r':			/* Dest for response packet */
1248 		if (arg && (raddr = host_addr(arg))) {
1249 		    if (arg == argv[0]) argv++, argc--;
1250 		    break;
1251 		} else
1252 		    goto usage;
1253 	      case 'i':			/* Local interface address */
1254 		if (arg && (lcl_addr = host_addr(arg))) {
1255 		    if (arg == argv[0]) argv++, argc--;
1256 		    break;
1257 		} else
1258 		    goto usage;
1259 	      case 'S':			/* Stat accumulation interval */
1260 		if (arg && isdigit((unsigned char)*arg)) {
1261 		    statint = atoi(arg);
1262 		    if (statint < 1) statint = 1;
1263 		    if (arg == argv[0]) argv++, argc--;
1264 		    break;
1265 		} else
1266 		    goto usage;
1267 	      default:
1268 		goto usage;
1269 	    }
1270 	} while (*p);
1271     }
1272 
1273     if (argc > 0 && (qsrc = host_addr(argv[0]))) {          /* Source of path */
1274 	if (IN_MULTICAST(ntohl(qsrc))) goto usage;
1275 	argv++, argc--;
1276 	if (argc > 0 && (qdst = host_addr(argv[0]))) {      /* Dest of path */
1277 	    argv++, argc--;
1278 	    if (argc > 0 && (qgrp = host_addr(argv[0]))) {  /* Path via group */
1279 		argv++, argc--;
1280 	    }
1281 	    if (IN_MULTICAST(ntohl(qdst))) {
1282 		u_int32_t temp = qdst;
1283 		qdst = qgrp;
1284 		qgrp = temp;
1285 		if (IN_MULTICAST(ntohl(qdst))) goto usage;
1286 	    } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) goto usage;
1287 	}
1288     }
1289 
1290     if (passive) {
1291 	passive_mode();
1292 	return(0);
1293     }
1294 
1295     if (argc > 0 || qsrc == 0) {
1296 usage:	printf("\
1297 Usage: mtrace [-Mlnps] [-w wait] [-m max_hops] [-q nqueries] [-g gateway]\n\
1298               [-S statint] [-t ttl] [-r resp_dest] [-i if_addr] source [receiver] [group]\n");
1299 	exit(1);
1300     }
1301 
1302     /*
1303      * Set useful defaults for as many parameters as possible.
1304      */
1305 
1306     defgrp = htonl(0xE0020001);		/* MBone Audio (224.2.0.1) */
1307     query_cast = htonl(0xE0000002);	/* All routers multicast addr */
1308     resp_cast = htonl(0xE0000120);	/* Mtrace response multicast addr */
1309     if (qgrp == 0) qgrp = defgrp;
1310 
1311     /*
1312      * Get default local address for multicasts to use in setting defaults.
1313      */
1314     memset(&addr, 0, sizeof(addr));
1315     addr.sin_family = AF_INET;
1316 #if (defined(BSD) && (BSD >= 199103))
1317     addr.sin_len = sizeof(addr);
1318 #endif
1319     addr.sin_addr.s_addr = qgrp;
1320     addr.sin_port = htons(2000);	/* Any port above 1024 will do */
1321 
1322     if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
1323 	(connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
1324 	getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0) {
1325 	perror("Determining local address");
1326 	exit(1);
1327     }
1328 
1329 #ifdef SUNOS5
1330     /*
1331      * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
1332      * This call to sysinfo will return the hostname.
1333      * If the default multicast interfface (set with the route
1334      * for 224.0.0.0) is not the same as the hostname,
1335      * mtrace -i [if_addr] will have to be used.
1336      */
1337     if (addr.sin_addr.s_addr == 0) {
1338 	char myhostname[MAXHOSTNAMELEN];
1339 	struct hostent *hp;
1340 	int error;
1341 
1342 	error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
1343 	if (error == -1) {
1344 	    perror("Getting my hostname");
1345 	    exit(1);
1346 	}
1347 
1348 	hp = gethostbyname(myhostname);
1349 	if (hp == NULL || hp->h_addrtype != AF_INET ||
1350 	    hp->h_length != sizeof(addr.sin_addr)) {
1351 	    perror("Finding IP address for my hostname");
1352 	    exit(1);
1353 	}
1354 
1355 	memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr,
1356 	    sizeof(addr.sin_addr.s_addr));
1357     }
1358 #endif
1359 
1360     /*
1361      * Default destination for path to be queried is the local host.
1362      */
1363     if (qdst == 0) qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
1364     dst_netmask = get_netmask(udp, qdst);
1365     close(udp);
1366     if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
1367 
1368     /*
1369      * Protect against unicast queries to mrouted versions that might crash.
1370      */
1371     if (gwy && !IN_MULTICAST(ntohl(gwy)))
1372       if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0])) {
1373 	  int version = ntohl(incr[0].igmp.igmp_group.s_addr) & 0xFFFF;
1374 	  if (version == 0x0303 || version == 0x0503) {
1375 	    printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
1376 		   (version >> 8) & 0xFF);
1377 	    exit(0);
1378 	}
1379       }
1380 
1381     printf("Mtrace from %s to %s via group %s\n",
1382 	   inet_fmt(qsrc), inet_fmt(qdst),
1383 	   inet_fmt(qgrp));
1384 
1385     if ((qdst & dst_netmask) == (qsrc & dst_netmask)) {
1386 	printf("Source & receiver are directly connected, no path to trace\n");
1387 	exit(0);
1388     }
1389 
1390     /*
1391      * If the response is to be a multicast address, make sure we
1392      * are listening on that multicast address.
1393      */
1394     if (raddr) {
1395 	if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1396     } else k_join(resp_cast, lcl_addr);
1397 
1398     /*
1399      * If the destination is on the local net, the last-hop router can
1400      * be found by multicast to the all-routers multicast group.
1401      * Otherwise, use the group address that is the subject of the
1402      * query since by definition the last-hop router will be a member.
1403      * Set default TTLs for local remote multicasts.
1404      */
1405     restart:
1406 
1407     if (gwy == 0)
1408       if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
1409       else tdst = qgrp;
1410     else tdst = gwy;
1411 
1412     if (IN_MULTICAST(ntohl(tdst))) {
1413       k_set_loop(1);	/* If I am running on a router, I need to hear this */
1414       if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
1415       else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
1416     }
1417 
1418     /*
1419      * Try a query at the requested number of hops or MAXHOPS if unspecified.
1420      */
1421     if (qno == 0) {
1422 	hops = MAXHOPS;
1423 	tries = 1;
1424 	printf("Querying full reverse path... ");
1425 	fflush(stdout);
1426     } else {
1427 	hops = qno;
1428 	tries = nqueries;
1429 	printf("Querying reverse path, maximum %d hops... ", qno);
1430 	fflush(stdout);
1431     }
1432     base.rtime = 0;
1433     base.len = 0;
1434 
1435     recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, tries, &base);
1436 
1437     /*
1438      * If the initial query was successful, print it.  Otherwise, if
1439      * the query max hop count is the default of zero, loop starting
1440      * from one until there is no response for four hops.  The extra
1441      * hops allow getting past an mtrace-capable mrouter that can't
1442      * send multicast packets because all phyints are disabled.
1443      */
1444     if (recvlen) {
1445 	printf("\n  0  ");
1446 	print_host(qdst);
1447 	printf("\n");
1448 	print_trace(1, &base);
1449 	r = base.resps + base.len - 1;
1450 	if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
1451 		qno != 0) {
1452 	    printf("%3d  ", -(base.len+1));
1453 	    what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1454 				   "doesn't support mtrace"
1455 				 : "is the next hop");
1456 	} else {
1457 	    VAL_TO_MASK(smask, r->tr_smask);
1458 	    if ((r->tr_inaddr & smask) == (qsrc & smask)) {
1459 		printf("%3d  ", -(base.len+1));
1460 		print_host(qsrc);
1461 		printf("\n");
1462 	    }
1463 	}
1464     } else if (qno == 0) {
1465 	printf("switching to hop-by-hop:\n  0  ");
1466 	print_host(qdst);
1467 	printf("\n");
1468 
1469 	for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
1470 	    printf("%3d  ", -hops);
1471 	    fflush(stdout);
1472 
1473 	    /*
1474 	     * After a successful first hop, try switching to the unicast
1475 	     * address of the last-hop router instead of multicasting the
1476 	     * trace query.  This should be safe for mrouted versions 3.3
1477 	     * and 3.5 because there is a long route timeout with metric
1478 	     * infinity before a route disappears.  Switching to unicast
1479 	     * reduces the amount of multicast traffic and avoids a bug
1480 	     * with duplicate suppression in mrouted 3.5.
1481 	     */
1482 	    if (hops == 2 && gwy == 0 &&
1483 		(recvlen = send_recv(lastout, IGMP_MTRACE_QUERY, hops, 1, &base)))
1484 	      tdst = lastout;
1485 	    else recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, nqueries, &base);
1486 
1487 	    if (recvlen == 0) {
1488 		if (hops == 1) break;
1489 		if (hops == nexthop) {
1490 		    if (what_kind(&base, "didn't respond")) {
1491 			/* the ask_neighbors determined that the
1492 			 * not-responding router is the first-hop. */
1493 			break;
1494 		    }
1495 		} else if (hops < nexthop + 3) {
1496 		    printf("\n");
1497 		} else {
1498 		    printf("...giving up\n");
1499 		    break;
1500 		}
1501 		continue;
1502 	    }
1503 	    r = base.resps + base.len - 1;
1504 	    if (base.len == hops &&
1505 		(hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
1506 	    	if (hops == nexthop) {
1507 		    print_trace(-hops, &base);
1508 		} else {
1509 		    printf("\nResuming...\n");
1510 		    print_trace(nexthop, &base);
1511 		}
1512 	    } else {
1513 		if (base.len < hops) {
1514 		    /*
1515 		     * A shorter trace than requested means a fatal error
1516 		     * occurred along the path, or that the route changed
1517 		     * to a shorter one.
1518 		     *
1519 		     * If the trace is longer than the last one we received,
1520 		     * then we are resuming from a skipped router (but there
1521 		     * is still probably a problem).
1522 		     *
1523 		     * If the trace is shorter than the last one we
1524 		     * received, then the route must have changed (and
1525 		     * there is still probably a problem).
1526 		     */
1527 		    if (nexthop <= base.len) {
1528 			printf("\nResuming...\n");
1529 			print_trace(nexthop, &base);
1530 		    } else if (nexthop > base.len + 1) {
1531 			hops = base.len;
1532 			printf("\nRoute must have changed...\n");
1533 			print_trace(1, &base);
1534 		    }
1535 		} else {
1536 		    /*
1537 		     * The last hop address is not the same as it was;
1538 		     * the route probably changed underneath us.
1539 		     */
1540 		    hops = base.len;
1541 		    printf("\nRoute must have changed...\n");
1542 		    print_trace(1, &base);
1543 		}
1544 	    }
1545 	    lastout = r->tr_outaddr;
1546 
1547 	    if (base.len < hops ||
1548 		r->tr_rmtaddr == 0 ||
1549 		(r->tr_rflags & 0x80)) {
1550 		VAL_TO_MASK(smask, r->tr_smask);
1551 		if (r->tr_rmtaddr) {
1552 		    if (hops != nexthop) {
1553 			printf("\n%3d  ", -(base.len+1));
1554 		    }
1555 		    what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1556 				"doesn't support mtrace" :
1557 				"would be the next hop");
1558 		    /* XXX could do segmented trace if TR_NO_SPACE */
1559 		} else if (r->tr_rflags == TR_NO_ERR &&
1560 			   (r->tr_inaddr & smask) == (qsrc & smask)) {
1561 		    printf("%3d  ", -(hops + 1));
1562 		    print_host(qsrc);
1563 		    printf("\n");
1564 		}
1565 		break;
1566 	    }
1567 
1568 	    nexthop = hops + 1;
1569 	}
1570     }
1571 
1572     if (base.rtime == 0) {
1573 	printf("Timed out receiving responses\n");
1574 	if (IN_MULTICAST(ntohl(tdst))) {
1575 	  if (tdst == query_cast)
1576 	    printf("Perhaps no local router has a route for source %s\n",
1577 		   inet_fmt(qsrc));
1578 	  else
1579 	    printf("Perhaps receiver %s is not a member of group %s,\n"
1580 		"or no router local to it has a route for source %s,\n"
1581 		"or multicast at ttl %d doesn't reach its last-hop router"
1582 		" for that source\n",
1583 		inet_fmt(qdst), inet_fmt(qgrp), inet_fmt(qsrc),
1584 		qttl ? qttl : MULTICAST_TTL1);
1585 	}
1586 	exit(1);
1587     }
1588 
1589     printf("Round trip time %d ms\n\n", t_diff(base.rtime, base.qtime));
1590 
1591     /*
1592      * Use the saved response which was the longest one received,
1593      * and make additional probes after delay to measure loss.
1594      */
1595     raddr = base.qhdr.tr_raddr;
1596     rttl = base.qhdr.tr_rttl;
1597     gettimeofday(&tv, 0);
1598     waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
1599     prev = &base;
1600     new = &incr[numstats&1];
1601 
1602     while (numstats--) {
1603 	if (waittime < 1) printf("\n");
1604 	else {
1605 	    printf("Waiting to accumulate statistics... ");
1606 	    fflush(stdout);
1607 	    sleep((unsigned)waittime);
1608 	}
1609 	rno = base.len;
1610 	recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, rno, nqueries, new);
1611 
1612 	if (recvlen == 0) {
1613 	    printf("Timed out.\n");
1614 	    exit(1);
1615 	}
1616 
1617 	if (rno != new->len) {
1618 	    printf("Trace length doesn't match:\n");
1619 	    /*
1620 	     * XXX Should this trace result be printed, or is that
1621 	     * too verbose?  Perhaps it should just say restarting.
1622 	     * But if the path is changing quickly, this may be the
1623 	     * only snapshot of the current path.  But, if the path
1624 	     * is changing that quickly, does the current path really
1625 	     * matter?
1626 	     */
1627 	    print_trace(1, new);
1628 	    printf("Restarting.\n\n");
1629 	    numstats++;
1630 	    goto restart;
1631 	}
1632 
1633 	printf("Results after %d seconds:\n\n",
1634 	       (int)((new->qtime - base.qtime) >> 16));
1635 	fixup_stats(&base, prev, new);
1636 	if (print_stats(&base, prev, new)) {
1637 	    printf("Route changed:\n");
1638 	    print_trace(1, new);
1639 	    printf("Restarting.\n\n");
1640 	    goto restart;
1641 	}
1642 	prev = new;
1643 	new = &incr[numstats&1];
1644 	waittime = statint;
1645     }
1646 
1647     /*
1648      * If the response was multicast back, leave the group
1649      */
1650     if (raddr) {
1651 	if (IN_MULTICAST(ntohl(raddr)))	k_leave(raddr, lcl_addr);
1652     } else k_leave(resp_cast, lcl_addr);
1653 
1654     return (0);
1655 }
1656 
1657 void
check_vif_state(void)1658 check_vif_state(void)
1659 {
1660     logit(LOG_WARNING, errno, "sendto");
1661 }
1662 
1663 /*
1664  * Log errors and other messages to stderr, according to the severity
1665  * of the message and the current debug level.  For errors of severity
1666  * LOG_ERR or worse, terminate the program.
1667  */
1668 void
logit(int severity,int syserr,const char * format,...)1669 logit(int severity, int syserr, const char *format, ...)
1670 {
1671     va_list ap;
1672 
1673     switch (debug) {
1674 	case 0: if (severity > LOG_WARNING) return;
1675 		/* FALLTHROUGH */
1676 	case 1: if (severity > LOG_NOTICE) return;
1677 		/* FALLTHROUGH */
1678 	case 2: if (severity > LOG_INFO  ) return;
1679 		/* FALLTHROUGH */
1680 	default:
1681 	    if (severity == LOG_WARNING)
1682 		fprintf(stderr, "warning - ");
1683 	    va_start(ap, format);
1684 	    vfprintf(stderr, format, ap);
1685 	    va_end(ap);
1686 	    if (syserr == 0)
1687 		fprintf(stderr, "\n");
1688 	    else
1689 		fprintf(stderr, ": %s\n", strerror(syserr));
1690     }
1691     if (severity <= LOG_ERR) exit(1);
1692 }
1693 
1694 /* dummies */
accept_probe(u_int32_t src,u_int32_t dst,char * p,int datalen,u_int32_t level)1695 void accept_probe(u_int32_t src, u_int32_t dst, char *p, int datalen,
1696 		  u_int32_t level)
1697 {
1698 }
accept_group_report(u_int32_t src,u_int32_t dst,u_int32_t group,int r_type)1699 void accept_group_report(u_int32_t src, u_int32_t dst, u_int32_t group,
1700 			 int r_type)
1701 {
1702 }
accept_neighbor_request2(u_int32_t src,u_int32_t dst)1703 void accept_neighbor_request2(u_int32_t src, u_int32_t dst)
1704 {
1705 }
accept_report(u_int32_t src,u_int32_t dst,char * p,int datalen,u_int32_t level)1706 void accept_report(u_int32_t src, u_int32_t dst, char *p, int datalen,
1707 		   u_int32_t level)
1708 {
1709 }
accept_neighbor_request(u_int32_t src,u_int32_t dst)1710 void accept_neighbor_request(u_int32_t src, u_int32_t dst)
1711 {
1712 }
accept_prune(u_int32_t src,u_int32_t dst,char * p,int datalen)1713 void accept_prune(u_int32_t src, u_int32_t dst, char *p, int datalen)
1714 {
1715 }
accept_graft(u_int32_t src,u_int32_t dst,char * p,int datalen)1716 void accept_graft(u_int32_t src, u_int32_t dst, char *p, int datalen)
1717 {
1718 }
accept_g_ack(u_int32_t src,u_int32_t dst,char * p,int datalen)1719 void accept_g_ack(u_int32_t src, u_int32_t dst, char *p, int datalen)
1720 {
1721 }
add_table_entry(u_int32_t origin,u_int32_t mcastgrp)1722 void add_table_entry(u_int32_t origin, u_int32_t mcastgrp)
1723 {
1724 }
accept_leave_message(u_int32_t src,u_int32_t dst,u_int32_t group)1725 void accept_leave_message(u_int32_t src, u_int32_t dst, u_int32_t group)
1726 {
1727 }
accept_mtrace(u_int32_t src,u_int32_t dst,u_int32_t group,char * data,u_int no,int datalen)1728 void accept_mtrace(u_int32_t src, u_int32_t dst, u_int32_t group, char *data,
1729 		   u_int no, int datalen)
1730 {
1731 }
accept_membership_query(u_int32_t src,u_int32_t dst,u_int32_t group,int tmo)1732 void accept_membership_query(u_int32_t src, u_int32_t dst, u_int32_t group,
1733 			     int tmo)
1734 {
1735 }
accept_neighbors(u_int32_t src,u_int32_t dst,u_char * p,int datalen,u_int32_t level)1736 void accept_neighbors(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1737 		      u_int32_t level)
1738 {
1739 }
accept_neighbors2(u_int32_t src,u_int32_t dst,u_char * p,int datalen,u_int32_t level)1740 void accept_neighbors2(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1741 		       u_int32_t level)
1742 {
1743 }
accept_info_request(u_int32_t src,u_int32_t dst,u_char * p,int datalen)1744 void accept_info_request(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1745 {
1746 }
accept_info_reply(u_int32_t src,u_int32_t dst,u_char * p,int datalen)1747 void accept_info_reply(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1748 {
1749 }
1750