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