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