Home | History | Annotate | Line # | Download | only in mtrace
mtrace.c revision 1.5
      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) 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 #ifndef lint
     54 static char rcsid[] =
     55     "@(#) $Id: mtrace.c,v 1.5 1995/12/10 10:57:15 mycroft 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: %ld ", ntohl(s->tr_vifin));
    960 	printf("v_out: %ld ", ntohl(s->tr_vifout));
    961 	printf("pkts: %ld\n", ntohl(s->tr_pktcnt));
    962 	printf("\t\t\t\tv_in: %ld ", ntohl(r->tr_vifin));
    963 	printf("v_out: %ld ", ntohl(r->tr_vifout));
    964 	printf("pkts: %ld\n", ntohl(r->tr_pktcnt));
    965 	printf("\t\t\t\tv_in: %ld ",ntohl(s->tr_vifin)-ntohl(r->tr_vifin));
    966 	printf("v_out: %ld ", ntohl(s->tr_vifout) - ntohl(r->tr_vifout));
    967 	printf("pkts: %ld ", 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: %ld ", ntohl(n->tr_vifin));
   1092 	printf("v_out: %ld ", ntohl(n->tr_vifout));
   1093 	printf("pkts: %ld\n", ntohl(n->tr_pktcnt));
   1094 	printf("\t\t\t\tv_in: %ld ", ntohl(b->tr_vifin));
   1095 	printf("v_out: %ld ", ntohl(b->tr_vifout));
   1096 	printf("pkts: %ld\n", ntohl(b->tr_pktcnt));
   1097 	printf("\t\t\t\tv_in: %ld ", ntohl(n->tr_vifin) - ntohl(b->tr_vifin));
   1098 	printf("v_out: %ld ", ntohl(n->tr_vifout) - ntohl(b->tr_vifout));
   1099 	printf("pkts: %ld\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     if (geteuid() != 0) {
   1169 	fprintf(stderr, "mtrace: must be root\n");
   1170 	exit(1);
   1171     }
   1172 
   1173     argv++, argc--;
   1174     if (argc == 0) goto usage;
   1175 
   1176     while (argc > 0 && *argv[0] == '-') {
   1177 	char *p = *argv++;  argc--;
   1178 	p++;
   1179 	do {
   1180 	    char c = *p++;
   1181 	    char *arg = (char *) 0;
   1182 	    if (isdigit(*p)) {
   1183 		arg = p;
   1184 		p = "";
   1185 	    } else if (argc > 0) arg = argv[0];
   1186 	    switch (c) {
   1187 	      case 'd':			/* Unlisted debug print option */
   1188 		if (arg && isdigit(*arg)) {
   1189 		    debug = atoi(arg);
   1190 		    if (debug < 0) debug = 0;
   1191 		    if (debug > 3) debug = 3;
   1192 		    if (arg == argv[0]) argv++, argc--;
   1193 		    break;
   1194 		} else
   1195 		    goto usage;
   1196 	      case 'M':			/* Use multicast for reponse */
   1197 		multicast = TRUE;
   1198 		break;
   1199 	      case 'l':			/* Loop updating stats indefinitely */
   1200 		numstats = 3153600;
   1201 		break;
   1202 	      case 'n':			/* Don't reverse map host addresses */
   1203 		numeric = TRUE;
   1204 		break;
   1205 	      case 'p':			/* Passive listen for traces */
   1206 		passive = TRUE;
   1207 		break;
   1208 	      case 'v':			/* Verbosity */
   1209 		verbose = TRUE;
   1210 		break;
   1211 	      case 's':			/* Short form, don't wait for stats */
   1212 		numstats = 0;
   1213 		break;
   1214 	      case 'w':			/* Time to wait for packet arrival */
   1215 		if (arg && isdigit(*arg)) {
   1216 		    timeout = atoi(arg);
   1217 		    if (timeout < 1) timeout = 1;
   1218 		    if (arg == argv[0]) argv++, argc--;
   1219 		    break;
   1220 		} else
   1221 		    goto usage;
   1222 	      case 'm':			/* Max number of hops to trace */
   1223 		if (arg && isdigit(*arg)) {
   1224 		    qno = atoi(arg);
   1225 		    if (qno > MAXHOPS) qno = MAXHOPS;
   1226 		    else if (qno < 1) qno = 0;
   1227 		    if (arg == argv[0]) argv++, argc--;
   1228 		    break;
   1229 		} else
   1230 		    goto usage;
   1231 	      case 'q':			/* Number of query retries */
   1232 		if (arg && isdigit(*arg)) {
   1233 		    nqueries = atoi(arg);
   1234 		    if (nqueries < 1) nqueries = 1;
   1235 		    if (arg == argv[0]) argv++, argc--;
   1236 		    break;
   1237 		} else
   1238 		    goto usage;
   1239 	      case 'g':			/* Last-hop gateway (dest of query) */
   1240 		if (arg && (gwy = host_addr(arg))) {
   1241 		    if (arg == argv[0]) argv++, argc--;
   1242 		    break;
   1243 		} else
   1244 		    goto usage;
   1245 	      case 't':			/* TTL for query packet */
   1246 		if (arg && isdigit(*arg)) {
   1247 		    qttl = atoi(arg);
   1248 		    if (qttl < 1) qttl = 1;
   1249 		    rttl = qttl;
   1250 		    if (arg == argv[0]) argv++, argc--;
   1251 		    break;
   1252 		} else
   1253 		    goto usage;
   1254 	      case 'r':			/* Dest for response packet */
   1255 		if (arg && (raddr = host_addr(arg))) {
   1256 		    if (arg == argv[0]) argv++, argc--;
   1257 		    break;
   1258 		} else
   1259 		    goto usage;
   1260 	      case 'i':			/* Local interface address */
   1261 		if (arg && (lcl_addr = host_addr(arg))) {
   1262 		    if (arg == argv[0]) argv++, argc--;
   1263 		    break;
   1264 		} else
   1265 		    goto usage;
   1266 	      case 'S':			/* Stat accumulation interval */
   1267 		if (arg && isdigit(*arg)) {
   1268 		    statint = atoi(arg);
   1269 		    if (statint < 1) statint = 1;
   1270 		    if (arg == argv[0]) argv++, argc--;
   1271 		    break;
   1272 		} else
   1273 		    goto usage;
   1274 	      default:
   1275 		goto usage;
   1276 	    }
   1277 	} while (*p);
   1278     }
   1279 
   1280     if (argc > 0 && (qsrc = host_addr(argv[0]))) {          /* Source of path */
   1281 	if (IN_MULTICAST(ntohl(qsrc))) goto usage;
   1282 	argv++, argc--;
   1283 	if (argc > 0 && (qdst = host_addr(argv[0]))) {      /* Dest of path */
   1284 	    argv++, argc--;
   1285 	    if (argc > 0 && (qgrp = host_addr(argv[0]))) {  /* Path via group */
   1286 		argv++, argc--;
   1287 	    }
   1288 	    if (IN_MULTICAST(ntohl(qdst))) {
   1289 		u_int32_t temp = qdst;
   1290 		qdst = qgrp;
   1291 		qgrp = temp;
   1292 		if (IN_MULTICAST(ntohl(qdst))) goto usage;
   1293 	    } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) goto usage;
   1294 	}
   1295     }
   1296 
   1297     if (passive) {
   1298 	passive_mode();
   1299 	return(0);
   1300     }
   1301 
   1302     if (argc > 0 || qsrc == 0) {
   1303 usage:	printf("\
   1304 Usage: mtrace [-Mlnps] [-w wait] [-m max_hops] [-q nqueries] [-g gateway]\n\
   1305               [-S statint] [-t ttl] [-r resp_dest] [-i if_addr] source [receiver] [group]\n");
   1306 	exit(1);
   1307     }
   1308 
   1309     init_igmp();
   1310 
   1311     /*
   1312      * Set useful defaults for as many parameters as possible.
   1313      */
   1314 
   1315     defgrp = htonl(0xE0020001);		/* MBone Audio (224.2.0.1) */
   1316     query_cast = htonl(0xE0000002);	/* All routers multicast addr */
   1317     resp_cast = htonl(0xE0000120);	/* Mtrace response multicast addr */
   1318     if (qgrp == 0) qgrp = defgrp;
   1319 
   1320     /*
   1321      * Get default local address for multicasts to use in setting defaults.
   1322      */
   1323     addr.sin_family = AF_INET;
   1324 #if (defined(BSD) && (BSD >= 199103))
   1325     addr.sin_len = sizeof(addr);
   1326 #endif
   1327     addr.sin_addr.s_addr = qgrp;
   1328     addr.sin_port = htons(2000);	/* Any port above 1024 will do */
   1329 
   1330     if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
   1331 	(connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
   1332 	getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0) {
   1333 	perror("Determining local address");
   1334 	exit(-1);
   1335     }
   1336 
   1337 #ifdef SUNOS5
   1338     /*
   1339      * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
   1340      * This call to sysinfo will return the hostname.
   1341      * If the default multicast interfface (set with the route
   1342      * for 224.0.0.0) is not the same as the hostname,
   1343      * mtrace -i [if_addr] will have to be used.
   1344      */
   1345     if (addr.sin_addr.s_addr == 0) {
   1346 	char myhostname[MAXHOSTNAMELEN];
   1347 	struct hostent *hp;
   1348 	int error;
   1349 
   1350 	error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
   1351 	if (error == -1) {
   1352 	    perror("Getting my hostname");
   1353 	    exit(-1);
   1354 	}
   1355 
   1356 	hp = gethostbyname(myhostname);
   1357 	if (hp == NULL || hp->h_addrtype != AF_INET ||
   1358 	    hp->h_length != sizeof(addr.sin_addr)) {
   1359 	    perror("Finding IP address for my hostname");
   1360 	    exit(-1);
   1361 	}
   1362 
   1363 	memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr, hp->h_length);
   1364     }
   1365 #endif
   1366 
   1367     /*
   1368      * Default destination for path to be queried is the local host.
   1369      */
   1370     if (qdst == 0) qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
   1371     dst_netmask = get_netmask(udp, qdst);
   1372     close(udp);
   1373     if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
   1374 
   1375     /*
   1376      * Initialize the seed for random query identifiers.
   1377      */
   1378     gettimeofday(&tv, 0);
   1379     seed = tv.tv_usec ^ lcl_addr;
   1380 #ifdef SYSV
   1381     srand48(seed);
   1382 #else
   1383     srandom(seed);
   1384 #endif
   1385 
   1386     /*
   1387      * Protect against unicast queries to mrouted versions that might crash.
   1388      */
   1389     if (gwy && !IN_MULTICAST(ntohl(gwy)))
   1390       if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0])) {
   1391 	  int version = ntohl(incr[0].igmp.igmp_group.s_addr) & 0xFFFF;
   1392 	  if (version == 0x0303 || version == 0x0503) {
   1393 	    printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
   1394 		   (version >> 8) & 0xFF);
   1395 	    exit(0);
   1396 	}
   1397       }
   1398 
   1399     printf("Mtrace from %s to %s via group %s\n",
   1400 	   inet_fmt(qsrc, s1), inet_fmt(qdst, s2), inet_fmt(qgrp, s3));
   1401 
   1402     if ((qdst & dst_netmask) == (qsrc & dst_netmask)) {
   1403 	printf("Source & receiver are directly connected, no path to trace\n");
   1404 	exit(0);
   1405     }
   1406 
   1407     /*
   1408      * If the response is to be a multicast address, make sure we
   1409      * are listening on that multicast address.
   1410      */
   1411     if (raddr) {
   1412 	if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
   1413     } else k_join(resp_cast, lcl_addr);
   1414 
   1415     /*
   1416      * If the destination is on the local net, the last-hop router can
   1417      * be found by multicast to the all-routers multicast group.
   1418      * Otherwise, use the group address that is the subject of the
   1419      * query since by definition the last-hop router will be a member.
   1420      * Set default TTLs for local remote multicasts.
   1421      */
   1422     restart:
   1423 
   1424     if (gwy == 0)
   1425       if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
   1426       else tdst = qgrp;
   1427     else tdst = gwy;
   1428 
   1429     if (IN_MULTICAST(ntohl(tdst))) {
   1430       k_set_loop(1);	/* If I am running on a router, I need to hear this */
   1431       if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
   1432       else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
   1433     }
   1434 
   1435     /*
   1436      * Try a query at the requested number of hops or MAXHOPS if unspecified.
   1437      */
   1438     if (qno == 0) {
   1439 	hops = MAXHOPS;
   1440 	tries = 1;
   1441 	printf("Querying full reverse path... ");
   1442 	fflush(stdout);
   1443     } else {
   1444 	hops = qno;
   1445 	tries = nqueries;
   1446 	printf("Querying reverse path, maximum %d hops... ", qno);
   1447 	fflush(stdout);
   1448     }
   1449     base.rtime = 0;
   1450     base.len = 0;
   1451 
   1452     recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, tries, &base);
   1453 
   1454     /*
   1455      * If the initial query was successful, print it.  Otherwise, if
   1456      * the query max hop count is the default of zero, loop starting
   1457      * from one until there is no response for four hops.  The extra
   1458      * hops allow getting past an mtrace-capable mrouter that can't
   1459      * send multicast packets because all phyints are disabled.
   1460      */
   1461     if (recvlen) {
   1462 	printf("\n  0  ");
   1463 	print_host(qdst);
   1464 	printf("\n");
   1465 	print_trace(1, &base);
   1466 	r = base.resps + base.len - 1;
   1467 	if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
   1468 		qno != 0) {
   1469 	    printf("%3d  ", -(base.len+1));
   1470 	    what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
   1471 				   "doesn't support mtrace"
   1472 				 : "is the next hop");
   1473 	} else {
   1474 	    VAL_TO_MASK(smask, r->tr_smask);
   1475 	    if ((r->tr_inaddr & smask) == (qsrc & smask)) {
   1476 		printf("%3d  ", -(base.len+1));
   1477 		print_host(qsrc);
   1478 		printf("\n");
   1479 	    }
   1480 	}
   1481     } else if (qno == 0) {
   1482 	printf("switching to hop-by-hop:\n  0  ");
   1483 	print_host(qdst);
   1484 	printf("\n");
   1485 
   1486 	for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
   1487 	    printf("%3d  ", -hops);
   1488 	    fflush(stdout);
   1489 
   1490 	    /*
   1491 	     * After a successful first hop, try switching to the unicast
   1492 	     * address of the last-hop router instead of multicasting the
   1493 	     * trace query.  This should be safe for mrouted versions 3.3
   1494 	     * and 3.5 because there is a long route timeout with metric
   1495 	     * infinity before a route disappears.  Switching to unicast
   1496 	     * reduces the amount of multicast traffic and avoids a bug
   1497 	     * with duplicate suppression in mrouted 3.5.
   1498 	     */
   1499 	    if (hops == 2 && gwy == 0 &&
   1500 		(recvlen = send_recv(lastout, IGMP_MTRACE_QUERY, hops, 1, &base)))
   1501 	      tdst = lastout;
   1502 	    else recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, nqueries, &base);
   1503 
   1504 	    if (recvlen == 0) {
   1505 		if (hops == 1) break;
   1506 		if (hops == nexthop) {
   1507 		    if (what_kind(&base, "didn't respond")) {
   1508 			/* the ask_neighbors determined that the
   1509 			 * not-responding router is the first-hop. */
   1510 			break;
   1511 		    }
   1512 		} else if (hops < nexthop + 3) {
   1513 		    printf("\n");
   1514 		} else {
   1515 		    printf("...giving up\n");
   1516 		    break;
   1517 		}
   1518 		continue;
   1519 	    }
   1520 	    r = base.resps + base.len - 1;
   1521 	    if (base.len == hops &&
   1522 		(hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
   1523 	    	if (hops == nexthop) {
   1524 		    print_trace(-hops, &base);
   1525 		} else {
   1526 		    printf("\nResuming...\n");
   1527 		    print_trace(nexthop, &base);
   1528 		}
   1529 	    } else {
   1530 		if (base.len < hops) {
   1531 		    /*
   1532 		     * A shorter trace than requested means a fatal error
   1533 		     * occurred along the path, or that the route changed
   1534 		     * to a shorter one.
   1535 		     *
   1536 		     * If the trace is longer than the last one we received,
   1537 		     * then we are resuming from a skipped router (but there
   1538 		     * is still probably a problem).
   1539 		     *
   1540 		     * If the trace is shorter than the last one we
   1541 		     * received, then the route must have changed (and
   1542 		     * there is still probably a problem).
   1543 		     */
   1544 		    if (nexthop <= base.len) {
   1545 			printf("\nResuming...\n");
   1546 			print_trace(nexthop, &base);
   1547 		    } else if (nexthop > base.len + 1) {
   1548 			hops = base.len;
   1549 			printf("\nRoute must have changed...\n");
   1550 			print_trace(1, &base);
   1551 		    }
   1552 		} else {
   1553 		    /*
   1554 		     * The last hop address is not the same as it was;
   1555 		     * the route probably changed underneath us.
   1556 		     */
   1557 		    hops = base.len;
   1558 		    printf("\nRoute must have changed...\n");
   1559 		    print_trace(1, &base);
   1560 		}
   1561 	    }
   1562 	    lastout = r->tr_outaddr;
   1563 
   1564 	    if (base.len < hops ||
   1565 		r->tr_rmtaddr == 0 ||
   1566 		(r->tr_rflags & 0x80)) {
   1567 		VAL_TO_MASK(smask, r->tr_smask);
   1568 		if (r->tr_rmtaddr) {
   1569 		    if (hops != nexthop) {
   1570 			printf("\n%3d  ", -(base.len+1));
   1571 		    }
   1572 		    what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
   1573 				"doesn't support mtrace" :
   1574 				"would be the next hop");
   1575 		    /* XXX could do segmented trace if TR_NO_SPACE */
   1576 		} else if (r->tr_rflags == TR_NO_ERR &&
   1577 			   (r->tr_inaddr & smask) == (qsrc & smask)) {
   1578 		    printf("%3d  ", -(hops + 1));
   1579 		    print_host(qsrc);
   1580 		    printf("\n");
   1581 		}
   1582 		break;
   1583 	    }
   1584 
   1585 	    nexthop = hops + 1;
   1586 	}
   1587     }
   1588 
   1589     if (base.rtime == 0) {
   1590 	printf("Timed out receiving responses\n");
   1591 	if (IN_MULTICAST(ntohl(tdst)))
   1592 	  if (tdst == query_cast)
   1593 	    printf("Perhaps no local router has a route for source %s\n",
   1594 		   inet_fmt(qsrc, s1));
   1595 	  else
   1596 	    printf("Perhaps receiver %s is not a member of group %s,\n\
   1597 or no router local to it has a route for source %s,\n\
   1598 or multicast at ttl %d doesn't reach its last-hop router for that source\n",
   1599 		   inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
   1600 		   qttl ? qttl : MULTICAST_TTL1);
   1601 	exit(1);
   1602     }
   1603 
   1604     printf("Round trip time %d ms\n\n", t_diff(base.rtime, base.qtime));
   1605 
   1606     /*
   1607      * Use the saved response which was the longest one received,
   1608      * and make additional probes after delay to measure loss.
   1609      */
   1610     raddr = base.qhdr.tr_raddr;
   1611     rttl = base.qhdr.tr_rttl;
   1612     gettimeofday(&tv, 0);
   1613     waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
   1614     prev = &base;
   1615     new = &incr[numstats&1];
   1616 
   1617     while (numstats--) {
   1618 	if (waittime < 1) printf("\n");
   1619 	else {
   1620 	    printf("Waiting to accumulate statistics... ");
   1621 	    fflush(stdout);
   1622 	    sleep((unsigned)waittime);
   1623 	}
   1624 	rno = base.len;
   1625 	recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, rno, nqueries, new);
   1626 
   1627 	if (recvlen == 0) {
   1628 	    printf("Timed out.\n");
   1629 	    exit(1);
   1630 	}
   1631 
   1632 	if (rno != new->len) {
   1633 	    printf("Trace length doesn't match:\n");
   1634 	    /*
   1635 	     * XXX Should this trace result be printed, or is that
   1636 	     * too verbose?  Perhaps it should just say restarting.
   1637 	     * But if the path is changing quickly, this may be the
   1638 	     * only snapshot of the current path.  But, if the path
   1639 	     * is changing that quickly, does the current path really
   1640 	     * matter?
   1641 	     */
   1642 	    print_trace(1, new);
   1643 	    printf("Restarting.\n\n");
   1644 	    numstats++;
   1645 	    goto restart;
   1646 	}
   1647 
   1648 	printf("Results after %d seconds:\n\n",
   1649 	       (int)((new->qtime - base.qtime) >> 16));
   1650 	fixup_stats(&base, prev, new);
   1651 	if (print_stats(&base, prev, new)) {
   1652 	    printf("Route changed:\n");
   1653 	    print_trace(1, new);
   1654 	    printf("Restarting.\n\n");
   1655 	    goto restart;
   1656 	}
   1657 	prev = new;
   1658 	new = &incr[numstats&1];
   1659 	waittime = statint;
   1660     }
   1661 
   1662     /*
   1663      * If the response was multicast back, leave the group
   1664      */
   1665     if (raddr) {
   1666 	if (IN_MULTICAST(ntohl(raddr)))	k_leave(raddr, lcl_addr);
   1667     } else k_leave(resp_cast, lcl_addr);
   1668 
   1669     return (0);
   1670 }
   1671 
   1672 void
   1673 check_vif_state()
   1674 {
   1675     log(LOG_WARNING, errno, "sendto");
   1676 }
   1677 
   1678 /*
   1679  * Log errors and other messages to stderr, according to the severity
   1680  * of the message and the current debug level.  For errors of severity
   1681  * LOG_ERR or worse, terminate the program.
   1682  */
   1683 #ifdef __STDC__
   1684 void
   1685 log(int severity, int syserr, char *format, ...)
   1686 {
   1687 	va_list ap;
   1688 	char    fmt[100];
   1689 
   1690 	va_start(ap, format);
   1691 #else
   1692 /*VARARGS3*/
   1693 void
   1694 log(severity, syserr, format, va_alist)
   1695 	int     severity, syserr;
   1696 	char   *format;
   1697 	va_dcl
   1698 {
   1699 	va_list ap;
   1700 	char    fmt[100];
   1701 
   1702 	va_start(ap);
   1703 #endif
   1704 
   1705     switch (debug) {
   1706 	case 0: if (severity > LOG_WARNING) return;
   1707 	case 1: if (severity > LOG_NOTICE) return;
   1708 	case 2: if (severity > LOG_INFO  ) return;
   1709 	default:
   1710 	    fmt[0] = '\0';
   1711 	    if (severity == LOG_WARNING) strcat(fmt, "warning - ");
   1712 	    strncat(fmt, format, 80);
   1713 	    vfprintf(stderr, fmt, ap);
   1714 	    if (syserr == 0)
   1715 		fprintf(stderr, "\n");
   1716 	    else if(syserr < sys_nerr)
   1717 		fprintf(stderr, ": %s\n", sys_errlist[syserr]);
   1718 	    else
   1719 		fprintf(stderr, ": errno %d\n", syserr);
   1720     }
   1721     if (severity <= LOG_ERR) exit(-1);
   1722 }
   1723 
   1724 /* dummies */
   1725 void accept_probe(src, dst, p, datalen, level)
   1726 	u_int32_t src, dst, level;
   1727 	char *p;
   1728 	int datalen;
   1729 {
   1730 }
   1731 void accept_group_report(src, dst, group, r_type)
   1732 	u_int32_t src, dst, group;
   1733 	int r_type;
   1734 {
   1735 }
   1736 void accept_neighbor_request2(src, dst)
   1737 	u_int32_t src, dst;
   1738 {
   1739 }
   1740 void accept_report(src, dst, p, datalen, level)
   1741 	u_int32_t src, dst, level;
   1742 	char *p;
   1743 	int datalen;
   1744 {
   1745 }
   1746 void accept_neighbor_request(src, dst)
   1747 	u_int32_t src, dst;
   1748 {
   1749 }
   1750 void accept_prune(src, dst, p, datalen)
   1751 	u_int32_t src, dst;
   1752 	char *p;
   1753 	int datalen;
   1754 {
   1755 }
   1756 void accept_graft(src, dst, p, datalen)
   1757 	u_int32_t src, dst;
   1758 	char *p;
   1759 	int datalen;
   1760 {
   1761 }
   1762 void accept_g_ack(src, dst, p, datalen)
   1763 	u_int32_t src, dst;
   1764 	char *p;
   1765 	int datalen;
   1766 {
   1767 }
   1768 void add_table_entry(origin, mcastgrp)
   1769 	u_int32_t origin, mcastgrp;
   1770 {
   1771 }
   1772 void accept_leave_message(src, dst, group)
   1773 	u_int32_t src, dst, group;
   1774 {
   1775 }
   1776 void accept_mtrace(src, dst, group, data, no, datalen)
   1777 	u_int32_t src, dst, group;
   1778 	char *data;
   1779 	u_int no;
   1780 	int datalen;
   1781 {
   1782 }
   1783 void accept_membership_query(src, dst, group, tmo)
   1784 	u_int32_t src, dst, group;
   1785 	int tmo;
   1786 {
   1787 }
   1788 void accept_neighbors(src, dst, p, datalen, level)
   1789 	u_int32_t src, dst, level;
   1790 	u_char *p;
   1791 	int datalen;
   1792 {
   1793 }
   1794 void accept_neighbors2(src, dst, p, datalen, level)
   1795 	u_int32_t src, dst, level;
   1796 	u_char *p;
   1797 	int datalen;
   1798 {
   1799 }
   1800 void accept_info_request(src, dst, p, datalen)
   1801 	u_int32_t src, dst;
   1802 	u_char *p;
   1803 	int datalen;
   1804 {
   1805 }
   1806 void accept_info_reply(src, dst, p, datalen)
   1807 	u_int32_t src, dst;
   1808 	u_char *p;
   1809 	int datalen;
   1810 {
   1811 }
   1812