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