xref: /netbsd-src/usr.sbin/mtrace/mtrace.c (revision 08c81a9c2dc8c7300e893321eb65c0925d60871c)
1 /*	$NetBSD: mtrace.c,v 1.23 2002/08/09 02:09:25 itojun 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.23 2002/08/09 02:09:25 itojun 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 #include <stdarg.h>
70 #ifdef SUNOS5
71 #include <sys/systeminfo.h>
72 #endif
73 
74 #define DEFAULT_TIMEOUT	3	/* How long to wait before retrying requests */
75 #define DEFAULT_RETRIES 3	/* How many times to try */
76 #define MAXHOPS UNREACHABLE	/* Don't need more hops than max metric */
77 #define UNICAST_TTL 255		/* TTL for unicast response */
78 #define MULTICAST_TTL1 64	/* Default TTL for multicast query/response */
79 #define MULTICAST_TTL_INC 32	/* TTL increment for increase after timeout */
80 #define MULTICAST_TTL_MAX 192	/* Maximum TTL allowed (protect low-BW links */
81 
82 struct resp_buf {
83     u_long qtime;		/* Time query was issued */
84     u_long rtime;		/* Time response was received */
85     int	len;			/* Number of reports or length of data */
86     struct igmp igmp;		/* IGMP header */
87     union {
88 	struct {
89 	    struct tr_query q;		/* Query/response header */
90 	    struct tr_resp r[MAXHOPS];	/* Per-hop reports */
91 	} t;
92 	char d[MAX_DVMRP_DATA_LEN];	/* Neighbor data */
93     } u;
94 } base, incr[2];
95 
96 #define qhdr u.t.q
97 #define resps u.t.r
98 #define ndata u.d
99 
100 char names[MAXHOPS][40];
101 int reset[MAXHOPS];			/* To get around 3.4 bug, ... */
102 int swaps[MAXHOPS];			/* To get around 3.6 bug, ... */
103 
104 int timeout = DEFAULT_TIMEOUT;
105 int nqueries = DEFAULT_RETRIES;
106 int numeric = FALSE;
107 int debug = 0;
108 int passive = FALSE;
109 int multicast = FALSE;
110 int statint = 10;
111 int verbose = 0;
112 
113 u_int32_t defgrp;			/* Default group if not specified */
114 u_int32_t query_cast;			/* All routers multicast addr */
115 u_int32_t resp_cast;			/* Mtrace response multicast addr */
116 
117 u_int32_t lcl_addr = 0;			/* This host address, in NET order */
118 u_int32_t dst_netmask;			/* netmask to go with qdst */
119 
120 /*
121  * Query/response parameters, all initialized to zero and set later
122  * to default values or from options.
123  */
124 u_int32_t qsrc = 0;		/* Source address in the query */
125 u_int32_t qgrp = 0;		/* Group address in the query */
126 u_int32_t qdst = 0;		/* Destination (receiver) address in query */
127 u_char qno  = 0;		/* Max number of hops to query */
128 u_int32_t raddr = 0;		/* Address where response should be sent */
129 int    qttl = 0;		/* TTL for the query packet */
130 u_char rttl = 0;		/* TTL for the response packet */
131 u_int32_t gwy = 0;		/* User-supplied last-hop router address */
132 u_int32_t tdst = 0;		/* Address where trace is sent (last-hop) */
133 
134 vifi_t  numvifs;		/* to keep loader happy */
135 				/* (see kern.c) */
136 
137 u_long			byteswap(u_long);
138 char *			inet_name(u_int32_t addr);
139 u_int32_t			host_addr(char *name);
140 /* u_int is promoted u_char */
141 char *			proto_type(u_int type);
142 char *			flag_type(u_int type);
143 
144 u_int32_t		get_netmask(int s, u_int32_t dst);
145 int			get_ttl(struct resp_buf *buf);
146 int			t_diff(u_long a, u_long b);
147 u_long			fixtime(u_long time);
148 int			send_recv(u_int32_t dst, int type, int code,
149 				  int tries, struct resp_buf *save);
150 char *			print_host(u_int32_t addr);
151 char *			print_host2(u_int32_t addr1, u_int32_t addr2);
152 void			print_trace(int index, struct resp_buf *buf);
153 int			what_kind(struct resp_buf *buf, char *why);
154 char *			scale(int *hop);
155 void			stat_line(struct tr_resp *r, struct tr_resp *s,
156 				  int have_next, int *res);
157 void			fixup_stats(struct resp_buf *base,
158 				    struct resp_buf *prev,
159 				    struct resp_buf *new);
160 int			print_stats(struct resp_buf *base,
161 				    struct resp_buf *prev,
162 				    struct resp_buf *new);
163 void			check_vif_state(void);
164 void			passive_mode(void);
165 
166 int			main(int argc, char *argv[]);
167 /* log() prototyped in defs.h */
168 
169 
170 char   *
171 inet_name(u_int32_t addr)
172 {
173     struct hostent *e;
174 
175     e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
176 
177     return e ? e->h_name : "?";
178 }
179 
180 
181 u_int32_t
182 host_addr(char *name)
183 {
184     struct hostent *e = (struct hostent *)0;
185     u_int32_t  addr;
186     int	i, dots = 3;
187     char	buf[40];
188     char	*ip = name;
189     char	*op = buf;
190 
191     /*
192      * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
193      * if the name is all numeric.
194      */
195     for (i = sizeof(buf) - 7; i > 0; --i) {
196 	if (*ip == '.') --dots;
197 	else if (*ip == '\0') break;
198 	else if (!isdigit(*ip)) dots = 0;  /* Not numeric, don't add zeroes */
199 	*op++ = *ip++;
200     }
201     for (i = 0; i < dots; ++i) {
202 	*op++ = '.';
203 	*op++ = '0';
204     }
205     *op = '\0';
206 
207     if (dots <= 0) e = gethostbyname(name);
208     if (e) memcpy((char *)&addr, e->h_addr_list[0], sizeof(addr));
209     else {
210 	addr = inet_addr(buf);
211 	if (addr == -1) {
212 	    addr = 0;
213 	    printf("Could not parse %s as host name or address\n", name);
214 	}
215     }
216     return addr;
217 }
218 
219 
220 char *
221 proto_type(u_int type)
222 {
223     static char buf[80];
224 
225     switch (type) {
226       case PROTO_DVMRP:
227 	return ("DVMRP");
228       case PROTO_MOSPF:
229 	return ("MOSPF");
230       case PROTO_PIM:
231 	return ("PIM");
232       case PROTO_CBT:
233 	return ("CBT");
234       case PROTO_PIM_SPEC:
235 	return ("PIM-special");
236       case PROTO_PIM_STAT:
237 	return ("PIM-static");
238       case PROTO_DVMRP_STAT:
239 	return ("DVMRP-static");
240       case PROTO_PIM_MBGP:
241 	return ("PIM/MBGP");
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(u_int type)
251 {
252     static char buf[80];
253 
254     switch (type) {
255       case TR_NO_ERR:
256 	return ("");
257       case TR_WRONG_IF:
258 	return ("Wrong interface");
259       case TR_PRUNED:
260 	return ("Prune sent upstream");
261       case TR_OPRUNED:
262 	return ("Output pruned");
263       case TR_SCOPED:
264 	return ("Hit scope boundary");
265       case TR_NO_RTE:
266 	return ("No route");
267       case TR_OLD_ROUTER:
268 	return ("Next router no mtrace");
269       case TR_NO_FWD:
270 	return ("Not forwarding");
271       case TR_NO_SPACE:
272 	return ("No space in packet");
273       case TR_RP_OR_CORE:
274 	return ("RP/Core");
275       case TR_RPF_INT:
276 	return ("Trace packet on RPT interface");
277       case TR_NO_MULTICAST:
278 	return ("Trace packet on non-MC interface");
279       case TR_ADMIN_DENY:
280 	return ("Trace admin-denied");
281       default:
282 	(void)snprintf(buf, sizeof buf, "Unknown error code %d", type);
283 	return (buf);
284     }
285 }
286 
287 /*
288  * If destination is on a local net, get the netmask, else set the
289  * netmask to all ones.  There are two side effects: if the local
290  * address was not explicitly set, and if the destination is on a
291  * local net, use that one; in either case, verify that the local
292  * address is valid.
293  */
294 
295 u_int32_t
296 get_netmask(int s, u_int32_t dst)
297 {
298     unsigned int i;
299     char ifbuf[5000];
300     struct ifconf ifc;
301     struct ifreq *ifr;
302     u_int32_t if_addr, if_mask;
303     u_int32_t retval = 0xFFFFFFFF;
304     int found = FALSE;
305 
306     ifc.ifc_buf = ifbuf;
307     ifc.ifc_len = sizeof(ifbuf);
308     if (ioctl(s, SIOCGIFCONF, (char *) &ifc) < 0) {
309 	perror("ioctl (SIOCGIFCONF)");
310 	return (retval);
311     }
312     for (i = 0; i < ifc.ifc_len; ) {
313 	ifr = (struct ifreq *)((char *)ifc.ifc_req + i);
314 	i += sizeof(ifr->ifr_name) + ifr->ifr_addr.sa_len;
315 	if_addr = ((struct sockaddr_in *)&(ifr->ifr_addr))->sin_addr.s_addr;
316 	if (ioctl(s, SIOCGIFNETMASK, (char *)ifr) >= 0) {
317 	    if_mask = ((struct sockaddr_in *)&(ifr->ifr_addr))->sin_addr.s_addr;
318 	    if ((dst & if_mask) == (if_addr & if_mask)) {
319 		retval = if_mask;
320 		if (lcl_addr == 0) lcl_addr = if_addr;
321 	    }
322 	}
323 	if (lcl_addr == if_addr) found = TRUE;
324     }
325     if (!found && lcl_addr != 0) {
326 	printf("Interface address is not valid\n");
327 	exit(1);
328     }
329     return (retval);
330 }
331 
332 
333 int
334 get_ttl(struct resp_buf *buf)
335 {
336     int rno;
337     struct tr_resp *b;
338     u_int ttl;
339 
340     if (buf && (rno = buf->len) > 0) {
341 	b = buf->resps + rno - 1;
342 	ttl = b->tr_fttl;
343 
344 	while (--rno > 0) {
345 	    --b;
346 	    if (ttl < b->tr_fttl) ttl = b->tr_fttl;
347 	    else ++ttl;
348 	}
349 	ttl += MULTICAST_TTL_INC;
350 	if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
351 	if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
352 	return (ttl);
353     } else return(MULTICAST_TTL1);
354 }
355 
356 /*
357  * Calculate the difference between two 32-bit NTP timestamps and return
358  * the result in milliseconds.
359  */
360 int
361 t_diff(u_long a, u_long b)
362 {
363     int d = a - b;
364 
365     return ((d * 125) >> 13);
366 }
367 
368 /*
369  * Fixup for incorrect time format in 3.3 mrouted.
370  * This is possible because (JAN_1970 mod 64K) is quite close to 32K,
371  * so correct and incorrect times will be far apart.
372  */
373 u_long
374 fixtime(u_long time)
375 {
376     if (abs((int)(time-base.qtime)) > 0x3FFFFFFF)
377         time = ((time & 0xFFFF0000) + (JAN_1970 << 16)) +
378 	       ((time & 0xFFFF) << 14) / 15625;
379     return (time);
380 }
381 
382 /*
383  * Swap bytes for poor little-endian machines that don't byte-swap
384  */
385 u_long
386 byteswap(u_long v)
387 {
388     return ((v << 24) | ((v & 0xff00) << 8) |
389 	    ((v >> 8) & 0xff00) | (v >> 24));
390 }
391 
392 int
393 send_recv(u_int32_t dst, int type, int code, int tries, struct resp_buf *save)
394 {
395     fd_set  fds;
396     struct timeval tq, tr, tv;
397     struct ip *ip;
398     struct igmp *igmp;
399     struct tr_query *query, *rquery;
400     int ipdatalen, iphdrlen, igmpdatalen;
401     u_int32_t local, group;
402     int datalen;
403     int count, recvlen, dummy = 0;
404     int len;
405     int i;
406 
407     if (type == IGMP_MTRACE_QUERY) {
408 	group = qgrp;
409 	datalen = sizeof(struct tr_query);
410     } else {
411 	group = htonl(MROUTED_LEVEL);
412 	datalen = 0;
413     }
414     if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
415     else local = INADDR_ANY;
416 
417     /*
418      * If the reply address was not explictly specified, start off
419      * with the unicast address of this host.  Then, if there is no
420      * response after trying half the tries with unicast, switch to
421      * the standard multicast reply address.  If the TTL was also not
422      * specified, set a multicast TTL and if needed increase it for the
423      * last quarter of the tries.
424      */
425     query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
426     query->tr_raddr = raddr ? raddr : multicast ? resp_cast : lcl_addr;
427     query->tr_rttl  = rttl ? rttl :
428       IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL;
429     query->tr_src   = qsrc;
430     query->tr_dst   = qdst;
431 
432     for (i = tries ; i > 0; --i) {
433 	if (tries == nqueries && raddr == 0) {
434 	    if (i == ((nqueries + 1) >> 1)) {
435 		query->tr_raddr = resp_cast;
436 		if (rttl == 0) query->tr_rttl = get_ttl(save);
437 	    }
438 	    if (i <= ((nqueries + 3) >> 2) && rttl == 0) {
439 		query->tr_rttl += MULTICAST_TTL_INC;
440 		if (query->tr_rttl > MULTICAST_TTL_MAX)
441 		  query->tr_rttl = MULTICAST_TTL_MAX;
442 	    }
443 	}
444 
445 	/*
446 	 * Change the qid for each request sent to avoid being confused
447 	 * by duplicate responses
448 	 */
449 #ifdef SYSV
450 	query->tr_qid  = ((u_int32_t)lrand48() >> 8);
451 #else
452 	query->tr_qid  = ((u_int32_t)random() >> 8);
453 #endif
454 
455 	/*
456 	 * Set timer to calculate delays, then send query
457 	 */
458 	gettimeofday(&tq, 0);
459 	send_igmp(local, dst, type, code, group, datalen);
460 
461 	/*
462 	 * Wait for response, discarding false alarms
463 	 */
464 	while (TRUE) {
465 	    FD_ZERO(&fds);
466 	    if (igmp_socket >= FD_SETSIZE)
467 		log(LOG_ERR, 0, "descriptor too big");
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(void)
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     if (raddr) {
637 	if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, INADDR_ANY);
638     } else k_join(htonl(0xE0000120), INADDR_ANY);
639 
640     while (1) {
641 	recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
642 			   0, (struct sockaddr *)0, &dummy);
643 	gettimeofday(&tr,0);
644 
645 	if (recvlen <= 0) {
646 	    if (recvlen && errno != EINTR) perror("recvfrom");
647 	    continue;
648 	}
649 
650 	if (recvlen < sizeof(struct ip)) {
651 	    fprintf(stderr,
652 		    "packet too short (%u bytes) for IP header", recvlen);
653 	    continue;
654 	}
655 	ip = (struct ip *) recv_buf;
656 	if (ip->ip_p == 0)	/* ignore cache creation requests */
657 	    continue;
658 
659 	iphdrlen = ip->ip_hl << 2;
660 	ipdatalen = ip->ip_len;
661 	if (iphdrlen + ipdatalen != recvlen) {
662 	    fprintf(stderr,
663 		    "packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
664 		    recvlen, iphdrlen, ipdatalen);
665 	    continue;
666 	}
667 
668 	igmp = (struct igmp *) (recv_buf + iphdrlen);
669 	igmpdatalen = ipdatalen - IGMP_MINLEN;
670 	if (igmpdatalen < 0) {
671 	    fprintf(stderr,
672 		    "IP data field too short (%u bytes) for IGMP from %s\n",
673 		    ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
674 	    continue;
675 	}
676 
677 	switch (igmp->igmp_type) {
678 
679 	  case IGMP_MTRACE_QUERY:	    /* For backward compatibility with 3.3 */
680 	  case IGMP_MTRACE_REPLY:
681 	    if (igmpdatalen < QLEN) continue;
682 	    if ((igmpdatalen - QLEN)%RLEN) {
683 		printf("packet with incorrect datalen\n");
684 		continue;
685 	    }
686 
687 	    len = (igmpdatalen - QLEN)/RLEN;
688 
689 	    break;
690 
691 	  default:
692 	    continue;
693 	}
694 
695 	base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
696 		      (tr.tv_usec << 10) / 15625;
697 	base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
698 		      (tr.tv_usec << 10) / 15625;
699 	base.len = len;
700 	bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
701 	/*
702 	 * If the user specified which traces to monitor,
703 	 * only accept traces that correspond to the
704 	 * request
705 	 */
706 	if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
707 	    (qdst != 0 && qdst != base.qhdr.tr_dst) ||
708 	    (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
709 	    continue;
710 
711 	printf("Mtrace from %s to %s via group %s (mxhop=%d)\n",
712 		inet_fmt(base.qhdr.tr_dst, s1), inet_fmt(base.qhdr.tr_src, s2),
713 		inet_fmt(igmp->igmp_group.s_addr, s3), 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, s1));
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, s1));
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     u_int32_t smask;
1057     int rno = base->len - 1;
1058     struct tr_resp *b = base->resps + rno;
1059     struct tr_resp *p = prev->resps + rno;
1060     struct tr_resp *n = new->resps + rno;
1061     int *r = reset + rno;
1062     u_long resptime = new->rtime;
1063     u_long qarrtime = fixtime(ntohl(n->tr_qarr));
1064     u_int ttl = n->tr_fttl;
1065     int first = (base == prev);
1066 
1067     VAL_TO_MASK(smask, b->tr_smask);
1068     printf("  Source        Response Dest");
1069     printf("    Packet Statistics For     Only For Traffic\n");
1070     printf("%-15s %-15s  All Multicast Traffic     From %s\n",
1071 	   ((b->tr_inaddr & smask) == (qsrc & smask)) ? s1 : "   * * *       ",
1072 	   inet_fmt(base->qhdr.tr_raddr, s2), inet_fmt(qsrc, s1));
1073     rtt = t_diff(resptime, new->qtime);
1074     ms = scale(&rtt);
1075     printf("     %c       __/  rtt%5d%s    Lost/Sent = Pct  Rate       To %s\n",
1076 	   first ? 'v' : '|', rtt, ms, inet_fmt(qgrp, s2));
1077     if (!first) {
1078 	hop = t_diff(resptime, qarrtime);
1079 	ms = scale(&hop);
1080 	printf("     v      /     hop%5d%s", hop, ms);
1081 	printf("    ---------------------     --------------------\n");
1082     }
1083     if (debug > 2) {
1084 	printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
1085 	printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
1086 	printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
1087 	printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
1088 	printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
1089 	printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
1090 	printf("\t\t\t\tv_in: %ld ",
1091 	    (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
1092 	printf("v_out: %ld ",
1093 	    (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
1094 	printf("pkts: %ld\n",
1095 	    (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
1096 	printf("\t\t\t\treset: %d\n", *r);
1097     }
1098 
1099     while (TRUE) {
1100 	if ((n->tr_inaddr != b->tr_inaddr) || (n->tr_inaddr != b->tr_inaddr))
1101 	  return 1;		/* Route changed */
1102 
1103 	if ((n->tr_inaddr != n->tr_outaddr))
1104 	  printf("%-15s\n", inet_fmt(n->tr_inaddr, s1));
1105 	printf("%-15s %-14s %s\n", inet_fmt(n->tr_outaddr, s1), names[rno],
1106 		 flag_type(n->tr_rflags));
1107 
1108 	if (rno-- < 1) break;
1109 
1110 	printf("     %c     ^      ttl%5d   ", first ? 'v' : '|', ttl);
1111 	stat_line(p, n, TRUE, r);
1112 	if (!first) {
1113 	    resptime = qarrtime;
1114 	    qarrtime = fixtime(ntohl((n-1)->tr_qarr));
1115 	    hop = t_diff(resptime, qarrtime);
1116 	    ms = scale(&hop);
1117 	    printf("     v     |      hop%5d%s", hop, ms);
1118 	    stat_line(b, n, TRUE, r);
1119 	}
1120 
1121 	--b, --p, --n, --r;
1122 	if (ttl < n->tr_fttl) ttl = n->tr_fttl;
1123 	else ++ttl;
1124     }
1125 
1126     printf("     %c      \\__   ttl%5d   ", first ? 'v' : '|', ttl);
1127     stat_line(p, n, FALSE, r);
1128     if (!first) {
1129 	hop = t_diff(qarrtime, new->qtime);
1130 	ms = scale(&hop);
1131 	printf("     v         \\  hop%5d%s", hop, ms);
1132 	stat_line(b, n, FALSE, r);
1133     }
1134     printf("%-15s %s\n", inet_fmt(qdst, s1), inet_fmt(lcl_addr, s2));
1135     printf("  Receiver      Query Source\n\n");
1136     return 0;
1137 }
1138 
1139 
1140 /***************************************************************************
1141  *	main
1142  ***************************************************************************/
1143 
1144 int
1145 main(int argc, char **argv)
1146 {
1147     int udp;
1148     struct sockaddr_in addr;
1149     int addrlen = sizeof(addr);
1150     int recvlen;
1151     struct timeval tv;
1152     struct resp_buf *prev, *new;
1153     struct tr_resp *r;
1154     u_int32_t smask;
1155     int rno;
1156     int hops, nexthop, tries;
1157     u_int32_t lastout = 0;
1158     int numstats = 1;
1159     int waittime;
1160     int seed;
1161 
1162     if (geteuid() != 0) {
1163 	fprintf(stderr, "mtrace: must be root\n");
1164 	exit(1);
1165     }
1166     init_igmp();
1167     if (setuid(getuid()) == -1)
1168 	log(LOG_ERR, errno, "setuid");
1169 
1170     argv++, argc--;
1171     if (argc == 0) goto usage;
1172 
1173     while (argc > 0 && *argv[0] == '-') {
1174 	char *p = *argv++;  argc--;
1175 	p++;
1176 	do {
1177 	    char c = *p++;
1178 	    char *arg = (char *) 0;
1179 	    if (isdigit(*p)) {
1180 		arg = p;
1181 		p = "";
1182 	    } else if (argc > 0) arg = argv[0];
1183 	    switch (c) {
1184 	      case 'd':			/* Unlisted debug print option */
1185 		if (arg && isdigit(*arg)) {
1186 		    debug = atoi(arg);
1187 		    if (debug < 0) debug = 0;
1188 		    if (debug > 3) debug = 3;
1189 		    if (arg == argv[0]) argv++, argc--;
1190 		    break;
1191 		} else
1192 		    goto usage;
1193 	      case 'M':			/* Use multicast for reponse */
1194 		multicast = TRUE;
1195 		break;
1196 	      case 'l':			/* Loop updating stats indefinitely */
1197 		numstats = 3153600;
1198 		break;
1199 	      case 'n':			/* Don't reverse map host addresses */
1200 		numeric = TRUE;
1201 		break;
1202 	      case 'p':			/* Passive listen for traces */
1203 		passive = TRUE;
1204 		break;
1205 	      case 'v':			/* Verbosity */
1206 		verbose = TRUE;
1207 		break;
1208 	      case 's':			/* Short form, don't wait for stats */
1209 		numstats = 0;
1210 		break;
1211 	      case 'w':			/* Time to wait for packet arrival */
1212 		if (arg && isdigit(*arg)) {
1213 		    timeout = atoi(arg);
1214 		    if (timeout < 1) timeout = 1;
1215 		    if (arg == argv[0]) argv++, argc--;
1216 		    break;
1217 		} else
1218 		    goto usage;
1219 	      case 'm':			/* Max number of hops to trace */
1220 		if (arg && isdigit(*arg)) {
1221 		    qno = atoi(arg);
1222 		    if (qno > MAXHOPS) qno = MAXHOPS;
1223 		    else if (qno < 1) qno = 0;
1224 		    if (arg == argv[0]) argv++, argc--;
1225 		    break;
1226 		} else
1227 		    goto usage;
1228 	      case 'q':			/* Number of query retries */
1229 		if (arg && isdigit(*arg)) {
1230 		    nqueries = atoi(arg);
1231 		    if (nqueries < 1) nqueries = 1;
1232 		    if (arg == argv[0]) argv++, argc--;
1233 		    break;
1234 		} else
1235 		    goto usage;
1236 	      case 'g':			/* Last-hop gateway (dest of query) */
1237 		if (arg && (gwy = host_addr(arg))) {
1238 		    if (arg == argv[0]) argv++, argc--;
1239 		    break;
1240 		} else
1241 		    goto usage;
1242 	      case 't':			/* TTL for query packet */
1243 		if (arg && isdigit(*arg)) {
1244 		    qttl = atoi(arg);
1245 		    if (qttl < 1) qttl = 1;
1246 		    rttl = qttl;
1247 		    if (arg == argv[0]) argv++, argc--;
1248 		    break;
1249 		} else
1250 		    goto usage;
1251 	      case 'r':			/* Dest for response packet */
1252 		if (arg && (raddr = host_addr(arg))) {
1253 		    if (arg == argv[0]) argv++, argc--;
1254 		    break;
1255 		} else
1256 		    goto usage;
1257 	      case 'i':			/* Local interface address */
1258 		if (arg && (lcl_addr = host_addr(arg))) {
1259 		    if (arg == argv[0]) argv++, argc--;
1260 		    break;
1261 		} else
1262 		    goto usage;
1263 	      case 'S':			/* Stat accumulation interval */
1264 		if (arg && isdigit(*arg)) {
1265 		    statint = atoi(arg);
1266 		    if (statint < 1) statint = 1;
1267 		    if (arg == argv[0]) argv++, argc--;
1268 		    break;
1269 		} else
1270 		    goto usage;
1271 	      default:
1272 		goto usage;
1273 	    }
1274 	} while (*p);
1275     }
1276 
1277     if (argc > 0 && (qsrc = host_addr(argv[0]))) {          /* Source of path */
1278 	if (IN_MULTICAST(ntohl(qsrc))) goto usage;
1279 	argv++, argc--;
1280 	if (argc > 0 && (qdst = host_addr(argv[0]))) {      /* Dest of path */
1281 	    argv++, argc--;
1282 	    if (argc > 0 && (qgrp = host_addr(argv[0]))) {  /* Path via group */
1283 		argv++, argc--;
1284 	    }
1285 	    if (IN_MULTICAST(ntohl(qdst))) {
1286 		u_int32_t temp = qdst;
1287 		qdst = qgrp;
1288 		qgrp = temp;
1289 		if (IN_MULTICAST(ntohl(qdst))) goto usage;
1290 	    } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) goto usage;
1291 	}
1292     }
1293 
1294     if (passive) {
1295 	passive_mode();
1296 	return(0);
1297     }
1298 
1299     if (argc > 0 || qsrc == 0) {
1300 usage:	printf("\
1301 Usage: mtrace [-Mlnps] [-w wait] [-m max_hops] [-q nqueries] [-g gateway]\n\
1302               [-S statint] [-t ttl] [-r resp_dest] [-i if_addr] source [receiver] [group]\n");
1303 	exit(1);
1304     }
1305 
1306     /*
1307      * Set useful defaults for as many parameters as possible.
1308      */
1309 
1310     defgrp = htonl(0xE0020001);		/* MBone Audio (224.2.0.1) */
1311     query_cast = htonl(0xE0000002);	/* All routers multicast addr */
1312     resp_cast = htonl(0xE0000120);	/* Mtrace response multicast addr */
1313     if (qgrp == 0) qgrp = defgrp;
1314 
1315     /*
1316      * Get default local address for multicasts to use in setting defaults.
1317      */
1318     memset(&addr, 0, sizeof(addr));
1319     addr.sin_family = AF_INET;
1320 #if (defined(BSD) && (BSD >= 199103))
1321     addr.sin_len = sizeof(addr);
1322 #endif
1323     addr.sin_addr.s_addr = qgrp;
1324     addr.sin_port = htons(2000);	/* Any port above 1024 will do */
1325 
1326     if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
1327 	(connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
1328 	getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0) {
1329 	perror("Determining local address");
1330 	exit(1);
1331     }
1332 
1333 #ifdef SUNOS5
1334     /*
1335      * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
1336      * This call to sysinfo will return the hostname.
1337      * If the default multicast interfface (set with the route
1338      * for 224.0.0.0) is not the same as the hostname,
1339      * mtrace -i [if_addr] will have to be used.
1340      */
1341     if (addr.sin_addr.s_addr == 0) {
1342 	char myhostname[MAXHOSTNAMELEN];
1343 	struct hostent *hp;
1344 	int error;
1345 
1346 	error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
1347 	if (error == -1) {
1348 	    perror("Getting my hostname");
1349 	    exit(1);
1350 	}
1351 
1352 	hp = gethostbyname(myhostname);
1353 	if (hp == NULL || hp->h_addrtype != AF_INET ||
1354 	    hp->h_length != sizeof(addr.sin_addr)) {
1355 	    perror("Finding IP address for my hostname");
1356 	    exit(1);
1357 	}
1358 
1359 	memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr,
1360 	    sizeof(addr.sin_addr.s_addr));
1361     }
1362 #endif
1363 
1364     /*
1365      * Default destination for path to be queried is the local host.
1366      */
1367     if (qdst == 0) qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
1368     dst_netmask = get_netmask(udp, qdst);
1369     close(udp);
1370     if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
1371 
1372     /*
1373      * Initialize the seed for random query identifiers.
1374      */
1375     gettimeofday(&tv, 0);
1376     seed = tv.tv_usec ^ lcl_addr;
1377 #ifdef SYSV
1378     srand48(seed);
1379 #else
1380     srandom(seed);
1381 #endif
1382 
1383     /*
1384      * Protect against unicast queries to mrouted versions that might crash.
1385      */
1386     if (gwy && !IN_MULTICAST(ntohl(gwy)))
1387       if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0])) {
1388 	  int version = ntohl(incr[0].igmp.igmp_group.s_addr) & 0xFFFF;
1389 	  if (version == 0x0303 || version == 0x0503) {
1390 	    printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
1391 		   (version >> 8) & 0xFF);
1392 	    exit(0);
1393 	}
1394       }
1395 
1396     printf("Mtrace from %s to %s via group %s\n",
1397 	   inet_fmt(qsrc, s1), inet_fmt(qdst, s2), inet_fmt(qgrp, s3));
1398 
1399     if ((qdst & dst_netmask) == (qsrc & dst_netmask)) {
1400 	printf("Source & receiver are directly connected, no path to trace\n");
1401 	exit(0);
1402     }
1403 
1404     /*
1405      * If the response is to be a multicast address, make sure we
1406      * are listening on that multicast address.
1407      */
1408     if (raddr) {
1409 	if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1410     } else k_join(resp_cast, lcl_addr);
1411 
1412     /*
1413      * If the destination is on the local net, the last-hop router can
1414      * be found by multicast to the all-routers multicast group.
1415      * Otherwise, use the group address that is the subject of the
1416      * query since by definition the last-hop router will be a member.
1417      * Set default TTLs for local remote multicasts.
1418      */
1419     restart:
1420 
1421     if (gwy == 0)
1422       if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
1423       else tdst = qgrp;
1424     else tdst = gwy;
1425 
1426     if (IN_MULTICAST(ntohl(tdst))) {
1427       k_set_loop(1);	/* If I am running on a router, I need to hear this */
1428       if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
1429       else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
1430     }
1431 
1432     /*
1433      * Try a query at the requested number of hops or MAXHOPS if unspecified.
1434      */
1435     if (qno == 0) {
1436 	hops = MAXHOPS;
1437 	tries = 1;
1438 	printf("Querying full reverse path... ");
1439 	fflush(stdout);
1440     } else {
1441 	hops = qno;
1442 	tries = nqueries;
1443 	printf("Querying reverse path, maximum %d hops... ", qno);
1444 	fflush(stdout);
1445     }
1446     base.rtime = 0;
1447     base.len = 0;
1448 
1449     recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, tries, &base);
1450 
1451     /*
1452      * If the initial query was successful, print it.  Otherwise, if
1453      * the query max hop count is the default of zero, loop starting
1454      * from one until there is no response for four hops.  The extra
1455      * hops allow getting past an mtrace-capable mrouter that can't
1456      * send multicast packets because all phyints are disabled.
1457      */
1458     if (recvlen) {
1459 	printf("\n  0  ");
1460 	print_host(qdst);
1461 	printf("\n");
1462 	print_trace(1, &base);
1463 	r = base.resps + base.len - 1;
1464 	if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
1465 		qno != 0) {
1466 	    printf("%3d  ", -(base.len+1));
1467 	    what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1468 				   "doesn't support mtrace"
1469 				 : "is the next hop");
1470 	} else {
1471 	    VAL_TO_MASK(smask, r->tr_smask);
1472 	    if ((r->tr_inaddr & smask) == (qsrc & smask)) {
1473 		printf("%3d  ", -(base.len+1));
1474 		print_host(qsrc);
1475 		printf("\n");
1476 	    }
1477 	}
1478     } else if (qno == 0) {
1479 	printf("switching to hop-by-hop:\n  0  ");
1480 	print_host(qdst);
1481 	printf("\n");
1482 
1483 	for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
1484 	    printf("%3d  ", -hops);
1485 	    fflush(stdout);
1486 
1487 	    /*
1488 	     * After a successful first hop, try switching to the unicast
1489 	     * address of the last-hop router instead of multicasting the
1490 	     * trace query.  This should be safe for mrouted versions 3.3
1491 	     * and 3.5 because there is a long route timeout with metric
1492 	     * infinity before a route disappears.  Switching to unicast
1493 	     * reduces the amount of multicast traffic and avoids a bug
1494 	     * with duplicate suppression in mrouted 3.5.
1495 	     */
1496 	    if (hops == 2 && gwy == 0 &&
1497 		(recvlen = send_recv(lastout, IGMP_MTRACE_QUERY, hops, 1, &base)))
1498 	      tdst = lastout;
1499 	    else recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, nqueries, &base);
1500 
1501 	    if (recvlen == 0) {
1502 		if (hops == 1) break;
1503 		if (hops == nexthop) {
1504 		    if (what_kind(&base, "didn't respond")) {
1505 			/* the ask_neighbors determined that the
1506 			 * not-responding router is the first-hop. */
1507 			break;
1508 		    }
1509 		} else if (hops < nexthop + 3) {
1510 		    printf("\n");
1511 		} else {
1512 		    printf("...giving up\n");
1513 		    break;
1514 		}
1515 		continue;
1516 	    }
1517 	    r = base.resps + base.len - 1;
1518 	    if (base.len == hops &&
1519 		(hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
1520 	    	if (hops == nexthop) {
1521 		    print_trace(-hops, &base);
1522 		} else {
1523 		    printf("\nResuming...\n");
1524 		    print_trace(nexthop, &base);
1525 		}
1526 	    } else {
1527 		if (base.len < hops) {
1528 		    /*
1529 		     * A shorter trace than requested means a fatal error
1530 		     * occurred along the path, or that the route changed
1531 		     * to a shorter one.
1532 		     *
1533 		     * If the trace is longer than the last one we received,
1534 		     * then we are resuming from a skipped router (but there
1535 		     * is still probably a problem).
1536 		     *
1537 		     * If the trace is shorter than the last one we
1538 		     * received, then the route must have changed (and
1539 		     * there is still probably a problem).
1540 		     */
1541 		    if (nexthop <= base.len) {
1542 			printf("\nResuming...\n");
1543 			print_trace(nexthop, &base);
1544 		    } else if (nexthop > base.len + 1) {
1545 			hops = base.len;
1546 			printf("\nRoute must have changed...\n");
1547 			print_trace(1, &base);
1548 		    }
1549 		} else {
1550 		    /*
1551 		     * The last hop address is not the same as it was;
1552 		     * the route probably changed underneath us.
1553 		     */
1554 		    hops = base.len;
1555 		    printf("\nRoute must have changed...\n");
1556 		    print_trace(1, &base);
1557 		}
1558 	    }
1559 	    lastout = r->tr_outaddr;
1560 
1561 	    if (base.len < hops ||
1562 		r->tr_rmtaddr == 0 ||
1563 		(r->tr_rflags & 0x80)) {
1564 		VAL_TO_MASK(smask, r->tr_smask);
1565 		if (r->tr_rmtaddr) {
1566 		    if (hops != nexthop) {
1567 			printf("\n%3d  ", -(base.len+1));
1568 		    }
1569 		    what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1570 				"doesn't support mtrace" :
1571 				"would be the next hop");
1572 		    /* XXX could do segmented trace if TR_NO_SPACE */
1573 		} else if (r->tr_rflags == TR_NO_ERR &&
1574 			   (r->tr_inaddr & smask) == (qsrc & smask)) {
1575 		    printf("%3d  ", -(hops + 1));
1576 		    print_host(qsrc);
1577 		    printf("\n");
1578 		}
1579 		break;
1580 	    }
1581 
1582 	    nexthop = hops + 1;
1583 	}
1584     }
1585 
1586     if (base.rtime == 0) {
1587 	printf("Timed out receiving responses\n");
1588 	if (IN_MULTICAST(ntohl(tdst))) {
1589 	  if (tdst == query_cast)
1590 	    printf("Perhaps no local router has a route for source %s\n",
1591 		   inet_fmt(qsrc, s1));
1592 	  else
1593 	    printf("Perhaps receiver %s is not a member of group %s,\n"
1594 		"or no router local to it has a route for source %s,\n"
1595 		"or multicast at ttl %d doesn't reach its last-hop router"
1596 		" for that source\n",
1597 		inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
1598 		qttl ? qttl : MULTICAST_TTL1);
1599 	}
1600 	exit(1);
1601     }
1602 
1603     printf("Round trip time %d ms\n\n", t_diff(base.rtime, base.qtime));
1604 
1605     /*
1606      * Use the saved response which was the longest one received,
1607      * and make additional probes after delay to measure loss.
1608      */
1609     raddr = base.qhdr.tr_raddr;
1610     rttl = base.qhdr.tr_rttl;
1611     gettimeofday(&tv, 0);
1612     waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
1613     prev = &base;
1614     new = &incr[numstats&1];
1615 
1616     while (numstats--) {
1617 	if (waittime < 1) printf("\n");
1618 	else {
1619 	    printf("Waiting to accumulate statistics... ");
1620 	    fflush(stdout);
1621 	    sleep((unsigned)waittime);
1622 	}
1623 	rno = base.len;
1624 	recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, rno, nqueries, new);
1625 
1626 	if (recvlen == 0) {
1627 	    printf("Timed out.\n");
1628 	    exit(1);
1629 	}
1630 
1631 	if (rno != new->len) {
1632 	    printf("Trace length doesn't match:\n");
1633 	    /*
1634 	     * XXX Should this trace result be printed, or is that
1635 	     * too verbose?  Perhaps it should just say restarting.
1636 	     * But if the path is changing quickly, this may be the
1637 	     * only snapshot of the current path.  But, if the path
1638 	     * is changing that quickly, does the current path really
1639 	     * matter?
1640 	     */
1641 	    print_trace(1, new);
1642 	    printf("Restarting.\n\n");
1643 	    numstats++;
1644 	    goto restart;
1645 	}
1646 
1647 	printf("Results after %d seconds:\n\n",
1648 	       (int)((new->qtime - base.qtime) >> 16));
1649 	fixup_stats(&base, prev, new);
1650 	if (print_stats(&base, prev, new)) {
1651 	    printf("Route changed:\n");
1652 	    print_trace(1, new);
1653 	    printf("Restarting.\n\n");
1654 	    goto restart;
1655 	}
1656 	prev = new;
1657 	new = &incr[numstats&1];
1658 	waittime = statint;
1659     }
1660 
1661     /*
1662      * If the response was multicast back, leave the group
1663      */
1664     if (raddr) {
1665 	if (IN_MULTICAST(ntohl(raddr)))	k_leave(raddr, lcl_addr);
1666     } else k_leave(resp_cast, lcl_addr);
1667 
1668     return (0);
1669 }
1670 
1671 void
1672 check_vif_state(void)
1673 {
1674     log(LOG_WARNING, errno, "sendto");
1675 }
1676 
1677 /*
1678  * Log errors and other messages to stderr, according to the severity
1679  * of the message and the current debug level.  For errors of severity
1680  * LOG_ERR or worse, terminate the program.
1681  */
1682 void
1683 log(int severity, int syserr, const char *format, ...)
1684 {
1685     va_list ap;
1686 
1687     switch (debug) {
1688 	case 0: if (severity > LOG_WARNING) return;
1689 	case 1: if (severity > LOG_NOTICE) return;
1690 	case 2: if (severity > LOG_INFO  ) return;
1691 	default:
1692 	    if (severity == LOG_WARNING)
1693 		fprintf(stderr, "warning - ");
1694 	    va_start(ap, format);
1695 	    vfprintf(stderr, format, ap);
1696 	    va_end(ap);
1697 	    if (syserr == 0)
1698 		fprintf(stderr, "\n");
1699 	    else
1700 		fprintf(stderr, ": %s\n", strerror(syserr));
1701     }
1702     if (severity <= LOG_ERR) exit(1);
1703 }
1704 
1705 /* dummies */
1706 void accept_probe(u_int32_t src, u_int32_t dst, char *p, int datalen,
1707 		  u_int32_t level)
1708 {
1709 }
1710 void accept_group_report(u_int32_t src, u_int32_t dst, u_int32_t group,
1711 			 int r_type)
1712 {
1713 }
1714 void accept_neighbor_request2(u_int32_t src, u_int32_t dst)
1715 {
1716 }
1717 void accept_report(u_int32_t src, u_int32_t dst, char *p, int datalen,
1718 		   u_int32_t level)
1719 {
1720 }
1721 void accept_neighbor_request(u_int32_t src, u_int32_t dst)
1722 {
1723 }
1724 void accept_prune(u_int32_t src, u_int32_t dst, char *p, int datalen)
1725 {
1726 }
1727 void accept_graft(u_int32_t src, u_int32_t dst, char *p, int datalen)
1728 {
1729 }
1730 void accept_g_ack(u_int32_t src, u_int32_t dst, char *p, int datalen)
1731 {
1732 }
1733 void add_table_entry(u_int32_t origin, u_int32_t mcastgrp)
1734 {
1735 }
1736 void accept_leave_message(u_int32_t src, u_int32_t dst, u_int32_t group)
1737 {
1738 }
1739 void accept_mtrace(u_int32_t src, u_int32_t dst, u_int32_t group, char *data,
1740 		   u_int no, int datalen)
1741 {
1742 }
1743 void accept_membership_query(u_int32_t src, u_int32_t dst, u_int32_t group,
1744 			     int tmo)
1745 {
1746 }
1747 void accept_neighbors(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1748 		      u_int32_t level)
1749 {
1750 }
1751 void accept_neighbors2(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1752 		       u_int32_t level)
1753 {
1754 }
1755 void accept_info_request(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1756 {
1757 }
1758 void accept_info_reply(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1759 {
1760 }
1761