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