xref: /openbsd-src/usr.sbin/mtrace/mtrace.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$NetBSD: mtrace.c,v 1.5 1995/12/10 10:57:15 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) 1998-2001.
25  * The University of Southern California/Information Sciences Institute.
26  * All rights reserved.
27  *
28  * Redistribution and use in source and binary forms, with or without
29  * modification, are permitted provided that the following conditions
30  * are met:
31  * 1. Redistributions of source code must retain the above copyright
32  *    notice, this list of conditions and the following disclaimer.
33  * 2. Redistributions in binary form must reproduce the above copyright
34  *    notice, this list of conditions and the following disclaimer in the
35  *    documentation and/or other materials provided with the distribution.
36  * 3. Neither the name of the project nor the names of its contributors
37  *    may be used to endorse or promote products derived from this software
38  *    without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  */
52 
53 #ifndef lint
54 static char rcsid[] =
55     "@(#) $Id: mtrace.c,v 1.7 2001/07/27 20:34:36 pvalchev Exp $";
56 #endif
57 
58 #include <netdb.h>
59 #include <sys/time.h>
60 #include <memory.h>
61 #include <string.h>
62 #include <ctype.h>
63 #include <sys/ioctl.h>
64 #include "defs.h"
65 #include <arpa/inet.h>
66 #ifdef __STDC__
67 #include <stdarg.h>
68 #else
69 #include <varargs.h>
70 #endif
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 #ifndef SYSV
138 extern long random();
139 #endif
140 extern int errno;
141 
142 char *			inet_name __P((u_int32_t addr));
143 u_int32_t			host_addr __P((char *name));
144 /* u_int is promoted u_char */
145 char *			proto_type __P((u_int type));
146 char *			flag_type __P((u_int type));
147 
148 u_int32_t			get_netmask __P((int s, u_int32_t dst));
149 int			get_ttl __P((struct resp_buf *buf));
150 int			t_diff __P((u_long a, u_long b));
151 u_long			fixtime __P((u_long time));
152 int			send_recv __P((u_int32_t dst, int type, int code,
153 					int tries, struct resp_buf *save));
154 char *			print_host __P((u_int32_t addr));
155 char *			print_host2 __P((u_int32_t addr1, u_int32_t addr2));
156 void			print_trace __P((int index, struct resp_buf *buf));
157 int			what_kind __P((struct resp_buf *buf, char *why));
158 char *			scale __P((int *hop));
159 void			stat_line __P((struct tr_resp *r, struct tr_resp *s,
160 					int have_next, int *res));
161 void			fixup_stats __P((struct resp_buf *base,
162 					struct resp_buf *prev,
163 					struct resp_buf *new));
164 int			print_stats __P((struct resp_buf *base,
165 					struct resp_buf *prev,
166 					struct resp_buf *new));
167 void			check_vif_state __P((void));
168 
169 int			main __P((int argc, char *argv[]));
170 
171 
172 
173 char   *
174 inet_name(addr)
175     u_int32_t  addr;
176 {
177     struct hostent *e;
178 
179     e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
180 
181     return e ? e->h_name : "?";
182 }
183 
184 
185 u_int32_t
186 host_addr(name)
187     char   *name;
188 {
189     struct hostent *e = (struct hostent *)0;
190     u_int32_t  addr;
191     int	i, dots = 3;
192     char	buf[40];
193     char	*ip = name;
194     char	*op = buf;
195 
196     /*
197      * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
198      * if the name is all numeric.
199      */
200     for (i = sizeof(buf) - 7; i > 0; --i) {
201 	if (*ip == '.') --dots;
202 	else if (*ip == '\0') break;
203 	else if (!isdigit(*ip)) dots = 0;  /* Not numeric, don't add zeroes */
204 	*op++ = *ip++;
205     }
206     for (i = 0; i < dots; ++i) {
207 	*op++ = '.';
208 	*op++ = '0';
209     }
210     *op = '\0';
211 
212     if (dots <= 0) e = gethostbyname(name);
213     if (e) memcpy((char *)&addr, e->h_addr_list[0], e->h_length);
214     else {
215 	addr = inet_addr(buf);
216 	if (addr == -1) {
217 	    addr = 0;
218 	    printf("Could not parse %s as host name or address\n", name);
219 	}
220     }
221     return addr;
222 }
223 
224 
225 char *
226 proto_type(type)
227     u_int type;
228 {
229     static char buf[80];
230 
231     switch (type) {
232       case PROTO_DVMRP:
233 	return ("DVMRP");
234       case PROTO_MOSPF:
235 	return ("MOSPF");
236       case PROTO_PIM:
237 	return ("PIM");
238       case PROTO_CBT:
239 	return ("CBT");
240       default:
241 	(void) sprintf(buf, "Unknown protocol code %d", type);
242 	return (buf);
243     }
244 }
245 
246 
247 char *
248 flag_type(type)
249     u_int type;
250 {
251     static char buf[80];
252 
253     switch (type) {
254       case TR_NO_ERR:
255 	return ("");
256       case TR_WRONG_IF:
257 	return ("Wrong interface");
258       case TR_PRUNED:
259 	return ("Prune sent upstream");
260       case TR_OPRUNED:
261 	return ("Output pruned");
262       case TR_SCOPED:
263 	return ("Hit scope boundary");
264       case TR_NO_RTE:
265 	return ("No route");
266       case TR_OLD_ROUTER:
267 	return ("Next router no mtrace");
268       case TR_NO_FWD:
269 	return ("Not forwarding");
270       case TR_NO_SPACE:
271 	return ("No space in packet");
272       default:
273 	(void) sprintf(buf, "Unknown error code %d", type);
274 	return (buf);
275     }
276 }
277 
278 /*
279  * If destination is on a local net, get the netmask, else set the
280  * netmask to all ones.  There are two side effects: if the local
281  * address was not explicitly set, and if the destination is on a
282  * local net, use that one; in either case, verify that the local
283  * address is valid.
284  */
285 
286 u_int32_t
287 get_netmask(s, dst)
288     int s;
289     u_int32_t dst;
290 {
291     unsigned int i;
292     char ifbuf[5000];
293     struct ifconf ifc;
294     struct ifreq *ifr;
295     u_int32_t if_addr, if_mask;
296     u_int32_t retval = 0xFFFFFFFF;
297     int found = FALSE;
298 
299     ifc.ifc_buf = ifbuf;
300     ifc.ifc_len = sizeof(ifbuf);
301     if (ioctl(s, SIOCGIFCONF, (char *) &ifc) < 0) {
302 	perror("ioctl (SIOCGIFCONF)");
303 	return (retval);
304     }
305     for (i = 0; i < ifc.ifc_len; ) {
306 	ifr = (struct ifreq *)((char *)ifc.ifc_req + i);
307 	i += sizeof(ifr->ifr_name) + ifr->ifr_addr.sa_len;
308 	if_addr = ((struct sockaddr_in *)&(ifr->ifr_addr))->sin_addr.s_addr;
309 	if (ioctl(s, SIOCGIFNETMASK, (char *)ifr) >= 0) {
310 	    if_mask = ((struct sockaddr_in *)&(ifr->ifr_addr))->sin_addr.s_addr;
311 	    if ((dst & if_mask) == (if_addr & if_mask)) {
312 		retval = if_mask;
313 		if (lcl_addr == 0) lcl_addr = if_addr;
314 	    }
315 	}
316 	if (lcl_addr == if_addr) found = TRUE;
317     }
318     if (!found && lcl_addr != 0) {
319 	printf("Interface address is not valid\n");
320 	exit(1);
321     }
322     return (retval);
323 }
324 
325 
326 int
327 get_ttl(buf)
328     struct resp_buf *buf;
329 {
330     int rno;
331     struct tr_resp *b;
332     u_int ttl;
333 
334     if (buf && (rno = buf->len) > 0) {
335 	b = buf->resps + rno - 1;
336 	ttl = b->tr_fttl;
337 
338 	while (--rno > 0) {
339 	    --b;
340 	    if (ttl < b->tr_fttl) ttl = b->tr_fttl;
341 	    else ++ttl;
342 	}
343 	ttl += MULTICAST_TTL_INC;
344 	if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
345 	if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
346 	return (ttl);
347     } else return(MULTICAST_TTL1);
348 }
349 
350 /*
351  * Calculate the difference between two 32-bit NTP timestamps and return
352  * the result in milliseconds.
353  */
354 int
355 t_diff(a, b)
356     u_long a, b;
357 {
358     int d = a - b;
359 
360     return ((d * 125) >> 13);
361 }
362 
363 /*
364  * Fixup for incorrect time format in 3.3 mrouted.
365  * This is possible because (JAN_1970 mod 64K) is quite close to 32K,
366  * so correct and incorrect times will be far apart.
367  */
368 u_long
369 fixtime(time)
370     u_long time;
371 {
372     if (abs((int)(time-base.qtime)) > 0x3FFFFFFF)
373         time = ((time & 0xFFFF0000) + (JAN_1970 << 16)) +
374 	       ((time & 0xFFFF) << 14) / 15625;
375     return (time);
376 }
377 
378 /*
379  * Swap bytes for poor little-endian machines that don't byte-swap
380  */
381 u_long
382 byteswap(v)
383     u_long v;
384 {
385     return ((v << 24) | ((v & 0xff00) << 8) |
386 	    ((v >> 8) & 0xff00) | (v >> 24));
387 }
388 
389 int
390 send_recv(dst, type, code, tries, save)
391     u_int32_t dst;
392     int type, code, tries;
393     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 	    FD_SET(igmp_socket, &fds);
467 	    gettimeofday(&tv, 0);
468 	    tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
469 	    tv.tv_usec = tq.tv_usec - tv.tv_usec;
470 	    if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
471 	    if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;
472 
473 	    count = select(igmp_socket + 1, &fds, (fd_set *)0, (fd_set *)0,
474 			   &tv);
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()
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     init_igmp();
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(addr)
738     u_int32_t addr;
739 {
740     return print_host2(addr, 0);
741 }
742 
743 /*
744  * On some routers, one interface has a name and the other doesn't.
745  * We always print the address of the outgoing interface, but can
746  * sometimes get the name from the incoming interface.  This might be
747  * confusing but should be slightly more helpful than just a "?".
748  */
749 char *
750 print_host2(addr1, addr2)
751     u_int32_t addr1, addr2;
752 {
753     char *name;
754 
755     if (numeric) {
756 	printf("%s", inet_fmt(addr1, s1));
757 	return ("");
758     }
759     name = inet_name(addr1);
760     if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
761 	name = inet_name(addr2);
762     printf("%s (%s)", name, inet_fmt(addr1, s1));
763     return (name);
764 }
765 
766 /*
767  * Print responses as received (reverse path from dst to src)
768  */
769 void
770 print_trace(index, buf)
771     int index;
772     struct resp_buf *buf;
773 {
774     struct tr_resp *r;
775     char *name;
776     int i;
777     int hop;
778     char *ms;
779 
780     i = abs(index);
781     r = buf->resps + i - 1;
782 
783     for (; i <= buf->len; ++i, ++r) {
784 	if (index > 0) printf("%3d  ", -i);
785 	name = print_host2(r->tr_outaddr, r->tr_inaddr);
786 	printf("  %s  thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
787 	if (verbose) {
788 	    hop = t_diff(fixtime(ntohl(r->tr_qarr)), buf->qtime);
789 	    ms = scale(&hop);
790 	    printf("  %d%s", hop, ms);
791 	}
792 	printf("  %s\n", flag_type(r->tr_rflags));
793 	memcpy(names[i-1], name, sizeof(names[0]) - 1);
794 	names[i-1][sizeof(names[0])-1] = '\0';
795     }
796 }
797 
798 /*
799  * See what kind of router is the next hop
800  */
801 int
802 what_kind(buf, why)
803     struct resp_buf *buf;
804     char *why;
805 {
806     u_int32_t smask;
807     int retval;
808     int hops = buf->len;
809     struct tr_resp *r = buf->resps + hops - 1;
810     u_int32_t next = r->tr_rmtaddr;
811 
812     retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0]);
813     print_host(next);
814     if (retval) {
815 	u_int32_t version = ntohl(incr[0].igmp.igmp_group.s_addr);
816 	u_int32_t *p = (u_int32_t *)incr[0].ndata;
817 	u_int32_t *ep = p + (incr[0].len >> 2);
818 	char *type = "";
819 	retval = 0;
820 	switch (version & 0xFF) {
821 	  case 1:
822 	    type = "proteon/mrouted ";
823 	    retval = 1;
824 	    break;
825 
826 	  case 2:
827 	  case 3:
828 	    if (((version >> 8) & 0xFF) < 3) retval = 1;
829 				/* Fall through */
830 	  case 4:
831 	    type = "mrouted ";
832 	    break;
833 
834 	  case 10:
835 	    type = "cisco ";
836 	}
837 	printf(" [%s%d.%d] %s\n",
838 	       type, version & 0xFF, (version >> 8) & 0xFF,
839 	       why);
840 	VAL_TO_MASK(smask, r->tr_smask);
841 	while (p < ep) {
842 	    u_int32_t laddr = *p++;
843 	    int flags = (ntohl(*p) & 0xFF00) >> 8;
844 	    int n = ntohl(*p++) & 0xFF;
845 	    if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
846 		 (laddr & smask) == (qsrc & smask)) {
847 		printf("%3d  ", -(hops+2));
848 		print_host(qsrc);
849 		printf("\n");
850 		return 1;
851 	    }
852 	    p += n;
853 	}
854 	return retval;
855     }
856     printf(" %s\n", why);
857     return 0;
858 }
859 
860 
861 char *
862 scale(hop)
863     int *hop;
864 {
865     if (*hop > -1000 && *hop < 10000) return (" ms");
866     *hop /= 1000;
867     if (*hop > -1000 && *hop < 10000) return (" s ");
868     return ("s ");
869 }
870 
871 /*
872  * Calculate and print one line of packet loss and packet rate statistics.
873  * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
874  */
875 #define NEITHER 0
876 #define INS     1
877 #define OUTS    2
878 #define BOTH    3
879 void
880 stat_line(r, s, have_next, rst)
881     struct tr_resp *r, *s;
882     int have_next;
883     int *rst;
884 {
885     int timediff = (fixtime(ntohl(s->tr_qarr)) -
886 			 fixtime(ntohl(r->tr_qarr))) >> 16;
887     int v_lost, v_pct;
888     int g_lost, g_pct;
889     int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
890     int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
891     int v_pps, g_pps;
892     char v_str[8], g_str[8];
893     int have = NEITHER;
894     int res = *rst;
895 
896     if (timediff == 0) timediff = 1;
897     v_pps = v_out / timediff;
898     g_pps = g_out / timediff;
899 
900     if (v_out && (s->tr_vifout != 0xFFFFFFFF && s->tr_vifout != 0) ||
901 		 (r->tr_vifout != 0xFFFFFFFF && r->tr_vifout != 0))
902 	    have |= OUTS;
903 
904     if (have_next) {
905 	--r,  --s,  --rst;
906 	if ((s->tr_vifin != 0xFFFFFFFF && s->tr_vifin != 0) ||
907 	    (r->tr_vifin != 0xFFFFFFFF && r->tr_vifin != 0))
908 	  have |= INS;
909 	if (*rst)
910 	  res = 1;
911     }
912 
913     switch (have) {
914       case BOTH:
915 	v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
916 	if (v_out) v_pct = (v_lost * 100 + (v_out >> 1)) / v_out;
917 	else v_pct = 0;
918 	if (-100 < v_pct && v_pct < 101 && v_out > 10)
919 	  sprintf(v_str, "%3d", v_pct);
920 	else memcpy(v_str, " --", 4);
921 
922 	g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
923 	if (g_out) g_pct = (g_lost * 100 + (g_out >> 1))/ g_out;
924 	else g_pct = 0;
925 	if (-100 < g_pct && g_pct < 101 && g_out > 10)
926 	  sprintf(g_str, "%3d", g_pct);
927 	else memcpy(g_str, " --", 4);
928 
929 	printf("%6d/%-5d=%s%%%4d pps",
930 	       v_lost, v_out, v_str, v_pps);
931 	if (res)
932 	    printf("\n");
933 	else
934 	    printf("%6d/%-5d=%s%%%4d pps\n",
935 		   g_lost, g_out, g_str, g_pps);
936 	break;
937 
938       case INS:
939 	v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
940 	v_pps = v_out / timediff;
941 	/* Fall through */
942 
943       case OUTS:
944 	printf("       %-5d     %4d pps",
945 	       v_out, v_pps);
946 	if (res)
947 	    printf("\n");
948 	else
949 	    printf("       %-5d     %4d pps\n",
950 		   g_out, g_pps);
951 	break;
952 
953       case NEITHER:
954 	printf("\n");
955 	break;
956     }
957 
958     if (debug > 2) {
959 	printf("\t\t\t\tv_in: %u ", ntohl(s->tr_vifin));
960 	printf("v_out: %u ", ntohl(s->tr_vifout));
961 	printf("pkts: %u\n", ntohl(s->tr_pktcnt));
962 	printf("\t\t\t\tv_in: %u ", ntohl(r->tr_vifin));
963 	printf("v_out: %u ", ntohl(r->tr_vifout));
964 	printf("pkts: %u\n", ntohl(r->tr_pktcnt));
965 	printf("\t\t\t\tv_in: %u ", ntohl(s->tr_vifin)-ntohl(r->tr_vifin));
966 	printf("v_out: %u ", ntohl(s->tr_vifout) - ntohl(r->tr_vifout));
967 	printf("pkts: %u ", ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
968 	printf("time: %d\n", timediff);
969 	printf("\t\t\t\tres: %d\n", res);
970     }
971 }
972 
973 /*
974  * A fixup to check if any pktcnt has been reset, and to fix the
975  * byteorder bugs in mrouted 3.6 on little-endian machines.
976  */
977 void
978 fixup_stats(base, prev, new)
979     struct resp_buf *base, *prev, *new;
980 {
981     int rno = base->len;
982     struct tr_resp *b = base->resps + rno;
983     struct tr_resp *p = prev->resps + rno;
984     struct tr_resp *n = new->resps + rno;
985     int *r = reset + rno;
986     int *s = swaps + rno;
987     int res;
988 
989     /* Check for byte-swappers */
990     while (--rno >= 0) {
991 	--n; --p; --b; --s;
992 	if (*s || abs(ntohl(n->tr_vifout) - ntohl(p->tr_vifout)) > 100000) {
993 	    /* This host sends byteswapped reports; swap 'em */
994 	    if (!*s) {
995 		*s = 1;
996 		b->tr_qarr = byteswap(b->tr_qarr);
997 		b->tr_vifin = byteswap(b->tr_vifin);
998 		b->tr_vifout = byteswap(b->tr_vifout);
999 		b->tr_pktcnt = byteswap(b->tr_pktcnt);
1000 	    }
1001 
1002 	    n->tr_qarr = byteswap(n->tr_qarr);
1003 	    n->tr_vifin = byteswap(n->tr_vifin);
1004 	    n->tr_vifout = byteswap(n->tr_vifout);
1005 	    n->tr_pktcnt = byteswap(n->tr_pktcnt);
1006 	}
1007     }
1008 
1009     rno = base->len;
1010     b = base->resps + rno;
1011     p = prev->resps + rno;
1012     n = new->resps + rno;
1013 
1014     while (--rno >= 0) {
1015 	--n; --p; --b; --r;
1016 	res = ((ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
1017 	       (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)));
1018 	if (debug > 2)
1019     	    printf("\t\tr=%d, res=%d\n", *r, res);
1020 	if (*r) {
1021 	    if (res || *r > 1) {
1022 		/*
1023 		 * This router appears to be a 3.4 with that nasty ol'
1024 		 * neighbor version bug, which causes it to constantly
1025 		 * reset.  Just nuke the statistics for this node, and
1026 		 * don't even bother giving it the benefit of the
1027 		 * doubt from now on.
1028 		 */
1029 		p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
1030 		r++;
1031 	    } else {
1032 		/*
1033 		 * This is simply the situation that the original
1034 		 * fixup_stats was meant to deal with -- that a
1035 		 * 3.3 or 3.4 router deleted a cache entry while
1036 		 * traffic was still active.
1037 		 */
1038 		*r = 0;
1039 		break;
1040 	    }
1041 	} else
1042 	    *r = res;
1043     }
1044 
1045     if (rno < 0) return;
1046 
1047     rno = base->len;
1048     b = base->resps + rno;
1049     p = prev->resps + rno;
1050 
1051     while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
1052 }
1053 
1054 /*
1055  * Print responses with statistics for forward path (from src to dst)
1056  */
1057 int
1058 print_stats(base, prev, new)
1059     struct resp_buf *base, *prev, *new;
1060 {
1061     int rtt, hop;
1062     char *ms;
1063     u_int32_t smask;
1064     int rno = base->len - 1;
1065     struct tr_resp *b = base->resps + rno;
1066     struct tr_resp *p = prev->resps + rno;
1067     struct tr_resp *n = new->resps + rno;
1068     int *r = reset + rno;
1069     u_long resptime = new->rtime;
1070     u_long qarrtime = fixtime(ntohl(n->tr_qarr));
1071     u_int ttl = n->tr_fttl;
1072     int first = (base == prev);
1073 
1074     VAL_TO_MASK(smask, b->tr_smask);
1075     printf("  Source        Response Dest");
1076     printf("    Packet Statistics For     Only For Traffic\n");
1077     printf("%-15s %-15s  All Multicast Traffic     From %s\n",
1078 	   ((b->tr_inaddr & smask) == (qsrc & smask)) ? s1 : "   * * *       ",
1079 	   inet_fmt(base->qhdr.tr_raddr, s2), inet_fmt(qsrc, s1));
1080     rtt = t_diff(resptime, new->qtime);
1081     ms = scale(&rtt);
1082     printf("     %c       __/  rtt%5d%s    Lost/Sent = Pct  Rate       To %s\n",
1083 	   first ? 'v' : '|', rtt, ms, inet_fmt(qgrp, s2));
1084     if (!first) {
1085 	hop = t_diff(resptime, qarrtime);
1086 	ms = scale(&hop);
1087 	printf("     v      /     hop%5d%s", hop, ms);
1088 	printf("    ---------------------     --------------------\n");
1089     }
1090     if (debug > 2) {
1091 	printf("\t\t\t\tv_in: %u ", ntohl(n->tr_vifin));
1092 	printf("v_out: %u ", ntohl(n->tr_vifout));
1093 	printf("pkts: %u\n", ntohl(n->tr_pktcnt));
1094 	printf("\t\t\t\tv_in: %u ", ntohl(b->tr_vifin));
1095 	printf("v_out: %u ", ntohl(b->tr_vifout));
1096 	printf("pkts: %u\n", ntohl(b->tr_pktcnt));
1097 	printf("\t\t\t\tv_in: %u ", ntohl(n->tr_vifin) - ntohl(b->tr_vifin));
1098 	printf("v_out: %u ", ntohl(n->tr_vifout) - ntohl(b->tr_vifout));
1099 	printf("pkts: %u\n", ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt));
1100 	printf("\t\t\t\treset: %d\n", *r);
1101     }
1102 
1103     while (TRUE) {
1104 	if ((n->tr_inaddr != b->tr_inaddr) || (n->tr_inaddr != b->tr_inaddr))
1105 	  return 1;		/* Route changed */
1106 
1107 	if ((n->tr_inaddr != n->tr_outaddr))
1108 	  printf("%-15s\n", inet_fmt(n->tr_inaddr, s1));
1109 	printf("%-15s %-14s %s\n", inet_fmt(n->tr_outaddr, s1), names[rno],
1110 		 flag_type(n->tr_rflags));
1111 
1112 	if (rno-- < 1) break;
1113 
1114 	printf("     %c     ^      ttl%5d   ", first ? 'v' : '|', ttl);
1115 	stat_line(p, n, TRUE, r);
1116 	if (!first) {
1117 	    resptime = qarrtime;
1118 	    qarrtime = fixtime(ntohl((n-1)->tr_qarr));
1119 	    hop = t_diff(resptime, qarrtime);
1120 	    ms = scale(&hop);
1121 	    printf("     v     |      hop%5d%s", hop, ms);
1122 	    stat_line(b, n, TRUE, r);
1123 	}
1124 
1125 	--b, --p, --n, --r;
1126 	if (ttl < n->tr_fttl) ttl = n->tr_fttl;
1127 	else ++ttl;
1128     }
1129 
1130     printf("     %c      \\__   ttl%5d   ", first ? 'v' : '|', ttl);
1131     stat_line(p, n, FALSE, r);
1132     if (!first) {
1133 	hop = t_diff(qarrtime, new->qtime);
1134 	ms = scale(&hop);
1135 	printf("     v         \\  hop%5d%s", hop, ms);
1136 	stat_line(b, n, FALSE, r);
1137     }
1138     printf("%-15s %s\n", inet_fmt(qdst, s1), inet_fmt(lcl_addr, s2));
1139     printf("  Receiver      Query Source\n\n");
1140     return 0;
1141 }
1142 
1143 
1144 /***************************************************************************
1145  *	main
1146  ***************************************************************************/
1147 
1148 int
1149 main(argc, argv)
1150 int argc;
1151 char *argv[];
1152 {
1153     int udp;
1154     struct sockaddr_in addr;
1155     int addrlen = sizeof(addr);
1156     int recvlen;
1157     struct timeval tv;
1158     struct resp_buf *prev, *new;
1159     struct tr_resp *r;
1160     u_int32_t smask;
1161     int rno;
1162     int hops, nexthop, tries;
1163     u_int32_t lastout = 0;
1164     int numstats = 1;
1165     int waittime;
1166     int seed;
1167 
1168     init_igmp();
1169     seteuid(getuid());
1170     setuid(getuid());
1171 
1172     argv++, argc--;
1173     if (argc == 0) goto usage;
1174 
1175     while (argc > 0 && *argv[0] == '-') {
1176 	char *p = *argv++;  argc--;
1177 	p++;
1178 	do {
1179 	    char c = *p++;
1180 	    char *arg = (char *) 0;
1181 	    if (isdigit(*p)) {
1182 		arg = p;
1183 		p = "";
1184 	    } else if (argc > 0) arg = argv[0];
1185 	    switch (c) {
1186 	      case 'd':			/* Unlisted debug print option */
1187 		if (arg && isdigit(*arg)) {
1188 		    debug = atoi(arg);
1189 		    if (debug < 0) debug = 0;
1190 		    if (debug > 3) debug = 3;
1191 		    if (arg == argv[0]) argv++, argc--;
1192 		    break;
1193 		} else
1194 		    goto usage;
1195 	      case 'M':			/* Use multicast for reponse */
1196 		multicast = TRUE;
1197 		break;
1198 	      case 'l':			/* Loop updating stats indefinitely */
1199 		numstats = 3153600;
1200 		break;
1201 	      case 'n':			/* Don't reverse map host addresses */
1202 		numeric = TRUE;
1203 		break;
1204 	      case 'p':			/* Passive listen for traces */
1205 		passive = TRUE;
1206 		break;
1207 	      case 'v':			/* Verbosity */
1208 		verbose = TRUE;
1209 		break;
1210 	      case 's':			/* Short form, don't wait for stats */
1211 		numstats = 0;
1212 		break;
1213 	      case 'w':			/* Time to wait for packet arrival */
1214 		if (arg && isdigit(*arg)) {
1215 		    timeout = atoi(arg);
1216 		    if (timeout < 1) timeout = 1;
1217 		    if (arg == argv[0]) argv++, argc--;
1218 		    break;
1219 		} else
1220 		    goto usage;
1221 	      case 'm':			/* Max number of hops to trace */
1222 		if (arg && isdigit(*arg)) {
1223 		    qno = atoi(arg);
1224 		    if (qno > MAXHOPS) qno = MAXHOPS;
1225 		    else if (qno < 1) qno = 0;
1226 		    if (arg == argv[0]) argv++, argc--;
1227 		    break;
1228 		} else
1229 		    goto usage;
1230 	      case 'q':			/* Number of query retries */
1231 		if (arg && isdigit(*arg)) {
1232 		    nqueries = atoi(arg);
1233 		    if (nqueries < 1) nqueries = 1;
1234 		    if (arg == argv[0]) argv++, argc--;
1235 		    break;
1236 		} else
1237 		    goto usage;
1238 	      case 'g':			/* Last-hop gateway (dest of query) */
1239 		if (arg && (gwy = host_addr(arg))) {
1240 		    if (arg == argv[0]) argv++, argc--;
1241 		    break;
1242 		} else
1243 		    goto usage;
1244 	      case 't':			/* TTL for query packet */
1245 		if (arg && isdigit(*arg)) {
1246 		    qttl = atoi(arg);
1247 		    if (qttl < 1) qttl = 1;
1248 		    rttl = qttl;
1249 		    if (arg == argv[0]) argv++, argc--;
1250 		    break;
1251 		} else
1252 		    goto usage;
1253 	      case 'r':			/* Dest for response packet */
1254 		if (arg && (raddr = host_addr(arg))) {
1255 		    if (arg == argv[0]) argv++, argc--;
1256 		    break;
1257 		} else
1258 		    goto usage;
1259 	      case 'i':			/* Local interface address */
1260 		if (arg && (lcl_addr = host_addr(arg))) {
1261 		    if (arg == argv[0]) argv++, argc--;
1262 		    break;
1263 		} else
1264 		    goto usage;
1265 	      case 'S':			/* Stat accumulation interval */
1266 		if (arg && isdigit(*arg)) {
1267 		    statint = atoi(arg);
1268 		    if (statint < 1) statint = 1;
1269 		    if (arg == argv[0]) argv++, argc--;
1270 		    break;
1271 		} else
1272 		    goto usage;
1273 	      default:
1274 		goto usage;
1275 	    }
1276 	} while (*p);
1277     }
1278 
1279     if (argc > 0 && (qsrc = host_addr(argv[0]))) {          /* Source of path */
1280 	if (IN_MULTICAST(ntohl(qsrc))) goto usage;
1281 	argv++, argc--;
1282 	if (argc > 0 && (qdst = host_addr(argv[0]))) {      /* Dest of path */
1283 	    argv++, argc--;
1284 	    if (argc > 0 && (qgrp = host_addr(argv[0]))) {  /* Path via group */
1285 		argv++, argc--;
1286 	    }
1287 	    if (IN_MULTICAST(ntohl(qdst))) {
1288 		u_int32_t temp = qdst;
1289 		qdst = qgrp;
1290 		qgrp = temp;
1291 		if (IN_MULTICAST(ntohl(qdst))) goto usage;
1292 	    } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) goto usage;
1293 	}
1294     }
1295 
1296     if (passive) {
1297 	passive_mode();
1298 	return(0);
1299     }
1300 
1301     if (argc > 0 || qsrc == 0) {
1302 usage:	printf("\
1303 Usage: mtrace [-Mlnps] [-w wait] [-m max_hops] [-q nqueries] [-g gateway]\n\
1304               [-S statint] [-t ttl] [-r resp_dest] [-i if_addr] source [receiver] [group]\n");
1305 	exit(1);
1306     }
1307 
1308     /*
1309      * Set useful defaults for as many parameters as possible.
1310      */
1311 
1312     defgrp = htonl(0xE0020001);		/* MBone Audio (224.2.0.1) */
1313     query_cast = htonl(0xE0000002);	/* All routers multicast addr */
1314     resp_cast = htonl(0xE0000120);	/* Mtrace response multicast addr */
1315     if (qgrp == 0) qgrp = defgrp;
1316 
1317     /*
1318      * Get default local address for multicasts to use in setting defaults.
1319      */
1320     addr.sin_family = AF_INET;
1321 #if (defined(BSD) && (BSD >= 199103))
1322     addr.sin_len = sizeof(addr);
1323 #endif
1324     addr.sin_addr.s_addr = qgrp;
1325     addr.sin_port = htons(2000);	/* Any port above 1024 will do */
1326 
1327     if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
1328 	(connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
1329 	getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0) {
1330 	perror("Determining local address");
1331 	exit(1);
1332     }
1333 
1334 #ifdef SUNOS5
1335     /*
1336      * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
1337      * This call to sysinfo will return the hostname.
1338      * If the default multicast interfface (set with the route
1339      * for 224.0.0.0) is not the same as the hostname,
1340      * mtrace -i [if_addr] will have to be used.
1341      */
1342     if (addr.sin_addr.s_addr == 0) {
1343 	char myhostname[MAXHOSTNAMELEN];
1344 	struct hostent *hp;
1345 	int error;
1346 
1347 	error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
1348 	if (error == -1) {
1349 	    perror("Getting my hostname");
1350 	    exit(1);
1351 	}
1352 
1353 	hp = gethostbyname(myhostname);
1354 	if (hp == NULL || hp->h_addrtype != AF_INET ||
1355 	    hp->h_length != sizeof(addr.sin_addr)) {
1356 	    perror("Finding IP address for my hostname");
1357 	    exit(1);
1358 	}
1359 
1360 	memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr, hp->h_length);
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 for that source\n",
1596 		   inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
1597 		   qttl ? qttl : MULTICAST_TTL1);
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()
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 #ifdef __STDC__
1681 void
1682 log(int severity, int syserr, char *format, ...)
1683 {
1684 	va_list ap;
1685 	char    fmt[100];
1686 
1687 	va_start(ap, format);
1688 #else
1689 /*VARARGS3*/
1690 void
1691 log(severity, syserr, format, va_alist)
1692 	int     severity, syserr;
1693 	char   *format;
1694 	va_dcl
1695 {
1696 	va_list ap;
1697 	char    fmt[100];
1698 
1699 	va_start(ap);
1700 #endif
1701 
1702     switch (debug) {
1703 	case 0: if (severity > LOG_WARNING) return;
1704 	case 1: if (severity > LOG_NOTICE) return;
1705 	case 2: if (severity > LOG_INFO  ) return;
1706 	default:
1707 	    fmt[0] = '\0';
1708 	    if (severity == LOG_WARNING) strcat(fmt, "warning - ");
1709 	    strncat(fmt, format, 80);
1710 	    vfprintf(stderr, fmt, ap);
1711 	    if (syserr == 0)
1712 		fprintf(stderr, "\n");
1713 	    else if(syserr < sys_nerr)
1714 		fprintf(stderr, ": %s\n", sys_errlist[syserr]);
1715 	    else
1716 		fprintf(stderr, ": errno %d\n", syserr);
1717     }
1718     if (severity <= LOG_ERR) exit(1);
1719 }
1720 
1721 /* dummies */
1722 void accept_probe(src, dst, p, datalen, level)
1723 	u_int32_t src, dst, level;
1724 	char *p;
1725 	int datalen;
1726 {
1727 }
1728 void accept_group_report(src, dst, group, r_type)
1729 	u_int32_t src, dst, group;
1730 	int r_type;
1731 {
1732 }
1733 void accept_neighbor_request2(src, dst)
1734 	u_int32_t src, dst;
1735 {
1736 }
1737 void accept_report(src, dst, p, datalen, level)
1738 	u_int32_t src, dst, level;
1739 	char *p;
1740 	int datalen;
1741 {
1742 }
1743 void accept_neighbor_request(src, dst)
1744 	u_int32_t src, dst;
1745 {
1746 }
1747 void accept_prune(src, dst, p, datalen)
1748 	u_int32_t src, dst;
1749 	char *p;
1750 	int datalen;
1751 {
1752 }
1753 void accept_graft(src, dst, p, datalen)
1754 	u_int32_t src, dst;
1755 	char *p;
1756 	int datalen;
1757 {
1758 }
1759 void accept_g_ack(src, dst, p, datalen)
1760 	u_int32_t src, dst;
1761 	char *p;
1762 	int datalen;
1763 {
1764 }
1765 void add_table_entry(origin, mcastgrp)
1766 	u_int32_t origin, mcastgrp;
1767 {
1768 }
1769 void accept_leave_message(src, dst, group)
1770 	u_int32_t src, dst, group;
1771 {
1772 }
1773 void accept_mtrace(src, dst, group, data, no, datalen)
1774 	u_int32_t src, dst, group;
1775 	char *data;
1776 	u_int no;
1777 	int datalen;
1778 {
1779 }
1780 void accept_membership_query(src, dst, group, tmo)
1781 	u_int32_t src, dst, group;
1782 	int tmo;
1783 {
1784 }
1785 void accept_neighbors(src, dst, p, datalen, level)
1786 	u_int32_t src, dst, level;
1787 	u_char *p;
1788 	int datalen;
1789 {
1790 }
1791 void accept_neighbors2(src, dst, p, datalen, level)
1792 	u_int32_t src, dst, level;
1793 	u_char *p;
1794 	int datalen;
1795 {
1796 }
1797 void accept_info_request(src, dst, p, datalen)
1798 	u_int32_t src, dst;
1799 	u_char *p;
1800 	int datalen;
1801 {
1802 }
1803 void accept_info_reply(src, dst, p, datalen)
1804 	u_int32_t src, dst;
1805 	u_char *p;
1806 	int datalen;
1807 {
1808 }
1809