MTrace 89.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
/* Copyright 1999 Pace Micro Technology plc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * mtrace.c
 *
 * This tool traces the branch of a multicast tree from a source to a
 * receiver for a particular multicast group and gives statistics
 * about packet rate and loss for each hop along the path.  It can
 * usually be invoked just as
 *
 * 	mtrace source
 *
 * to trace the route from that source to the local host for a default
 * group when only the route is desired and not group-specific packet
 * counts.  See the usage line for more complex forms.
 *
 *
 * Released 4 Apr 1995.  This program was adapted by Steve Casner
 * (USC/ISI) from a prototype written by Ajit Thyagarajan (UDel and
 * Xerox PARC).  It attempts to parallel in command syntax and output
 * format the unicast traceroute program written by Van Jacobson (LBL)
 * for the parts where that makes sense.
 *
 * Copyright (c) 1995 by the University of Southern California
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation in source and binary forms for any purposes and without
 * fee is hereby granted, provided that the above copyright notice
 * appear in all copies and that both the copyright notice and this
 * permission notice appear in supporting documentation, and that any
 * documentation, advertising materials, and other materials related to
 * such distribution and use acknowledge that the software was developed
 * by the University of Southern California, Information Sciences
 * Institute.  The name of the University may not be used to endorse or
 * promote products derived from this software without specific prior
 * written permission.
 *
 * THE UNIVERSITY OF SOUTHERN CALIFORNIA makes no representations about
 * the suitability of this software for any purpose.  THIS SOFTWARE IS
 * PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Other copyrights might apply to parts of this software and are so
 * noted when applicable.
 *
 * Parts of this software are derived from mrouted, which has the
 * following license:
 *
 * The mrouted program is covered by the following license.  Use of the
 * mrouted program represents acceptance of these terms and conditions.
 *
 * 1. STANFORD grants to LICENSEE a nonexclusive and nontransferable
 * license to use, copy and modify the computer software ``mrouted''
 * (hereinafter called the ``Program''), upon the terms and conditions
 * hereinafter set out and until Licensee discontinues use of the Licensed
 * Program.
 *
 * 2. LICENSEE acknowledges that the Program is a research tool still in
 * the development state, that it is being supplied ``as is,'' without any
 * accompanying services from STANFORD, and that this license is entered
 * into in order to encourage scientific collaboration aimed at further
 * development and application of the Program.
 *
 * 3. LICENSEE may copy the Program and may sublicense others to use
 * object code copies of the Program or any derivative version of the
 * Program.  All copies must contain all copyright and other proprietary
 * notices found in the Program as provided by STANFORD.  Title to
 * copyright to the Program remains with STANFORD.
 *
 * 4. LICENSEE may create derivative versions of the Program.  LICENSEE
 * hereby grants STANFORD a royalty-free license to use, copy, modify,
 * distribute and sublicense any such derivative works.  At the time
 * LICENSEE provides a copy of a derivative version of the Program to a
 * third party, LICENSEE shall provide STANFORD with one copy of the
 * source code of the derivative version at no charge to STANFORD.
 *
 * 5. STANFORD MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
 * IMPLIED.  By way of example, but not limitation, STANFORD MAKES NO
 * REPRESENTATION OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
 * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED PROGRAM WILL NOT
 * INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. STANFORD
 * shall not be held liable for any liability nor for any direct, indirect
 * or consequential damages with respect to any claim by LICENSEE or any
 * third party on account of or arising from this Agreement or use of the
 * Program.
 *
 * 6. This agreement shall be construed, interpreted and applied in
 * accordance with the State of California and any legal action arising
 * out of this Agreement or use of the Program shall be filed in a court
 * in the State of California.
 *
 * 7. Nothing in this Agreement shall be construed as conferring rights to
 * use in advertising, publicity or otherwise any trademark or the name
 * of ``Stanford''.
 *
 * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of
 * Leland Stanford Junior University.
 *
 *
 * The mtrace program has been modified and improved by Xerox
 * Corporation.  Xerox grants to LICENSEE a non-exclusive and
 * non-transferable license to use, copy, and modify the Xerox modified
 * and improved mrouted software on the same terms and conditions which
 * govern the license Stanford and ISI grant with respect to the mtrace
 * program.  These terms and conditions are incorporated in this grant
 * by reference and shall be deemed to have been accepted by LICENSEE
 * to cover its relationship with Xerox Corporation with respect to any
 * use of the Xerox improved program.
 *
 * The mtrace program is COPYRIGHT 1998 by Xerox Corporation.
 *
 */

#ifndef lint
static const char rcsid[] =
    "$Id$";
#endif

#include <ctype.h>
#include <err.h>
#ifndef __riscos
Robert Sprowson's avatar
Robert Sprowson committed
136
#include <errno.h>
137 138
#include <memory.h>
#endif
ROOL's avatar
ROOL committed
139 140
#include <sys/types.h>
#include <sys/socket.h>
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef __riscos
#include <syslog.h>
#endif
#include <unistd.h>
#include <sys/param.h>
#include <sys/time.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/igmp.h>
#include <sys/ioctl.h>
#ifdef SYSV
#include <sys/sockio.h>
#endif
#include <arpa/inet.h>
#ifdef __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif
#ifdef SUNOS5
#include <sys/systeminfo.h>
#endif
#ifdef __riscos
#include <sys/errno.h>
#include <sys/syslog.h>
#include <socklib.h>
#include <unixlib.h>
#include <swis.h>

/* Override <ctype.h> */
#undef __P
#define __P(a) a
179
char *__progname = "mtrace";
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

int udp = -1;

/* Our rand() is good :) */
#define random(n) rand(n)
#define srandom(n) srand(n)

/* Don't clash with <math.h> */
#define log my_log

#define setuid(a)

static void closesockets(void);
#endif

typedef unsigned int u_int32;	/* XXX */
#include "mtrace.h"

#define DEFAULT_TIMEOUT	3	/* How long to wait before retrying requests */
#define DEFAULT_RETRIES 3	/* How many times to try */
#define DEFAULT_EXTRAHOPS 3	/* How many hops past a non-responding rtr */
#define MAXHOPS 60		/* Don't need more hops than this */
#define UNICAST_TTL 255		/* TTL for unicast response */
#define MULTICAST_TTL1 127	/* Default TTL for multicast query/response */
#define MULTICAST_TTL_INC 32	/* TTL increment for increase after timeout */
#define MULTICAST_TTL_MAX 192	/* Maximum TTL allowed (protect low-BW links */

#define TRUE 1
#define FALSE 0
#define DVMRP_ASK_NEIGHBORS2	5	/* DVMRP msg requesting neighbors */
#define DVMRP_NEIGHBORS2	6	/* reply to above */
#define DVMRP_NF_DOWN		0x10	/* kernel state of interface */
#define DVMRP_NF_DISABLED	0x20	/* administratively disabled */
#define MAX_IP_PACKET_LEN	576
#define MIN_IP_HEADER_LEN	20
#define MAX_IP_HEADER_LEN	60
#define MAX_DVMRP_DATA_LEN \
		( MAX_IP_PACKET_LEN - MAX_IP_HEADER_LEN - IGMP_MINLEN )

struct resp_buf {
    u_long qtime;		/* Time query was issued */
    u_long rtime;		/* Time response was received */
    int	len;			/* Number of reports or length of data */
    struct igmp igmp;		/* IGMP header */
    union {
	struct {
	    struct tr_query q;		/* Query/response header */
	    struct tr_resp r[MAXHOPS];	/* Per-hop reports */
	} t;
	char d[MAX_DVMRP_DATA_LEN];	/* Neighbor data */
    } u;
} base, incr[2];

#define qhdr u.t.q
#define resps u.t.r
#define ndata u.d

char *names[MAXHOPS];

/*
 * In mrouted 3.3 and 3.4 (and in some Cisco IOS releases),
 * cache entries can get deleted even if there is traffic
 * flowing, which will reset the per-source/group counters.
 */
#define		BUG_RESET	0x01

/*
 * Also in mrouted 3.3 and 3.4, there's a bug in neighbor
 * version processing which can cause them to believe that
 * the neighbor is constantly resetting.  This causes them
 * to constantly delete all their state.
 */
#define		BUG_RESET2X	0x02

/*
 * Pre-3.7 mrouted's forget to byte-swap their reports.
 */
#define		BUG_SWAP	0x04

/*
 * Pre-3.9 mrouted's forgot a parenthesis in the htonl()
 * on the time calculation so supply bogus times.
 */
#define		BUG_BOGUSTIME	0x08

#define BUG_NOPRINT	(BUG_RESET | BUG_RESET2X)

int bugs[MAXHOPS];			/* List of bugs noticed at each hop */

struct mtrace {
	struct mtrace	*next;
	struct resp_buf	 base, incr[2];
	struct resp_buf	*new, *prev;
	int		 nresp;
	struct timeval	 last;
	int		 bugs[MAXHOPS];
	char		*names[MAXHOPS];
	int		 lastqid;
};

int timeout = DEFAULT_TIMEOUT;
int nqueries = DEFAULT_RETRIES;
int numeric = FALSE;
int debug = 0;
int passive = FALSE;
int multicast = FALSE;
int unicast = FALSE;
int statint = 10;
int verbose = FALSE;
int tunstats = FALSE;
int weak = FALSE;
int extrahops = DEFAULT_EXTRAHOPS;
int printstats = TRUE;
int sendopts = TRUE;
int lossthresh = 0;
int fflag = FALSE;
int staticqid = 0;

u_int32 defgrp;				/* Default group if not specified */
u_int32 query_cast;			/* All routers multicast addr */
u_int32 resp_cast;			/* Mtrace response multicast addr */

u_int32 lcl_addr = 0;			/* This host address, in NET order */
u_int32 dst_netmask = 0;		/* netmask to go with qdst */

/*
 * Query/response parameters, all initialized to zero and set later
 * to default values or from options.
 */
u_int32 qsrc = 0;		/* Source address in the query */
u_int32 qgrp = 0;		/* Group address in the query */
u_int32 qdst = 0;		/* Destination (receiver) address in query */
u_char qno  = 0;		/* Max number of hops to query */
u_int32 raddr = 0;		/* Address where response should be sent */
int    qttl = 0;		/* TTL for the query packet */
u_char rttl = 0;		/* TTL for the response packet */
u_int32 gwy = 0;		/* User-supplied last-hop router address */
u_int32 tdst = 0;		/* Address where trace is sent (last-hop) */

char s1[19];		/* buffers to hold the string representations  */
char s2[19];		/* of IP addresses, to be passed to inet_fmt() */
char s3[19];		/* or inet_fmts().                             */

#if !(defined(BSD) && (BSD >= 199103))
extern int		errno;
extern int		sys_nerr;
extern char *		sys_errlist[];
#endif

#define RECV_BUF_SIZE 8192
char	*send_buf, *recv_buf;
#ifdef __riscos
int	igmp_socket=-1;
#else
int	igmp_socket;
#endif
u_int32	allrtrs_group;
char	router_alert[4];	     	/* Router Alert IP Option	    */
#ifndef	IPOPT_RA
#define	IPOPT_RA		148
#endif
#ifdef SUNOS5
char	eol[4];		     		/* EOL IP Option		    */
int ip_addlen = 0;		     	/* Workaround for Option bug #2     */
#endif

/*
 * max macro, with weird case to avoid conflicts
 */
#define	MaX(a,b)	((a) > (b) ? (a) : (b))

#ifndef __P
#ifdef __STDC__
#define __P(x)	x
#else
#define __P(x)	()
#endif
#endif

typedef int (*callback_t) __P((int, u_char *, int, struct igmp *, int,
			struct sockaddr *, int *, struct timeval *));

void			init_igmp __P((void));
void			send_igmp __P((u_int32 src, u_int32 dst, int type,
						int code, u_int32 group,
						int datalen));
int			inet_cksum __P((u_short *addr, u_int len));
void			k_set_rcvbuf __P((int bufsize));
void			k_hdr_include __P((int bool));
void			k_set_ttl __P((int t));
void			k_set_loop __P((int l));
void			k_set_if __P((u_int32 ifa));
372 373 374
#ifdef __riscos
void			k_set_sleep __P((int s));
#endif
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
void			k_join __P((u_int32 grp, u_int32 ifa));
void			k_leave __P((u_int32 grp, u_int32 ifa));
char *			inet_fmt __P((u_int32 addr, char *s));
char *			inet_fmts __P((u_int32 addr, u_int32 mask, char *s));
char *			inet_name __P((u_int32 addr));
u_int32			host_addr __P((char *name));
/* u_int is promoted u_char */
char *			proto_type __P((u_int type));
char *			flag_type __P((u_int type));

u_int32			get_netmask __P((int s, u_int32 *dst));
int			get_ttl __P((struct resp_buf *buf));
int			t_diff __P((u_long a, u_long b));
u_long			byteswap __P((u_long v));
int			mtrace_callback __P((int, u_char *, int, struct igmp *,
					int, struct sockaddr *, int *,
					struct timeval *));
int			send_recv __P((u_int32 dst, int type, int code,
					int tries, struct resp_buf *save,
					callback_t callback));
void			passive_mode __P((void));
char *			print_host __P((u_int32 addr));
char *			print_host2 __P((u_int32 addr1, u_int32 addr2));
void			print_trace __P((int idx, struct resp_buf *buf,
					char **names));
int			what_kind __P((struct resp_buf *buf, char *why));
char *			scale __P((int *hop));
void			stat_line __P((struct tr_resp *r, struct tr_resp *s,
					int have_next, int *res));
void			fixup_stats __P((struct resp_buf *base,
					struct resp_buf *prev,
					struct resp_buf *new,
					int *bugs));
int			check_thresh __P((int thresh,
					struct resp_buf *base,
					struct resp_buf *prev,
					struct resp_buf *new));
int			print_stats __P((struct resp_buf *base,
					struct resp_buf *prev,
					struct resp_buf *new,
					int *bugs,
					char **names));
int			path_changed __P((struct resp_buf *base,
					struct resp_buf *new));
void			check_vif_state __P((void));

int			main __P((int argc, char *argv[]));
void			log __P((int, int, char *, ...));
static void		usage __P((void));


/*
 * Open and initialize the igmp socket, and fill in the non-changing
 * IP header fields in the output packet buffer.
 */
void
init_igmp()
{
    struct ip *ip;

    recv_buf = (char *)malloc(RECV_BUF_SIZE);
    if (recv_buf == 0)
	log(LOG_ERR, 0, "Out of memory allocating recv_buf!");
    send_buf = (char *)malloc(RECV_BUF_SIZE);
    if (send_buf == 0)
	log(LOG_ERR, 0, "Out of memory allocating send_buf!");

    if ((igmp_socket = socket(AF_INET, SOCK_RAW, IPPROTO_IGMP)) < 0)
	log(LOG_ERR, errno, "IGMP socket");

445 446 447
#ifdef __riscos
    k_set_sleep(TRUE);		/* sleep taskwindows */
#endif
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
    k_hdr_include(TRUE);	/* include IP header when sending */
    k_set_rcvbuf(48*1024);	/* lots of input buffering        */
    k_set_ttl(1);		/* restrict multicasts to one hop */
    k_set_loop(FALSE);		/* disable multicast loopback     */

    ip         = (struct ip *)send_buf;
    ip->ip_hl  = sizeof(struct ip) >> 2;
    ip->ip_v   = IPVERSION;
    ip->ip_tos = 0;
    ip->ip_off = 0;
    ip->ip_p   = IPPROTO_IGMP;
    ip->ip_ttl = MAXTTL;	/* applies to unicasts only */

#ifndef INADDR_ALLRTRS_GROUP
#define	INADDR_ALLRTRS_GROUP	0xe0000002	/* 224.0.0.2 */
#endif
    allrtrs_group  = htonl(INADDR_ALLRTRS_GROUP);

    router_alert[0] = IPOPT_RA;	/* Router Alert */
    router_alert[1] = 4;	/* 4 bytes */
    router_alert[2] = 0;
    router_alert[3] = 0;
}

#ifdef SUNOS5
void
checkforsolarisbug()
{
    u_int32 localhost = htonl(0x7f000001);

    eol[0] = IPOPT_EOL;
    eol[1] = IPOPT_EOL;
    eol[2] = IPOPT_EOL;
    eol[3] = IPOPT_EOL;

    setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS, eol, sizeof(eol));
    /*
     * Check if the kernel adds the options length to the packet
     * length.  Send myself an IGMP packet of type 0 (illegal),
     * with 4 IPOPT_EOL options, my PID (for collision detection)
     * and 4 bytes of zero (so that the checksum works whether
     * the 4 bytes of zero get truncated or not).
     */
    bzero(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN, 8);
    *(int *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN) = getpid();
    send_igmp(localhost, localhost, 0, 0, 0, 8);
    while (1) {
	int recvlen, dummy = 0;

	recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
				0, NULL, &dummy);
	/* 8 == 4 bytes of options and 4 bytes of PID */
	if (recvlen >= MIN_IP_HEADER_LEN + IGMP_MINLEN + 8) {
	    struct ip *ip = (struct ip *)recv_buf;
	    struct igmp *igmp;
	    int *p;

	    if (ip->ip_hl != 6 ||
		ip->ip_p != IPPROTO_IGMP ||
	        ip->ip_src.s_addr != localhost ||
		ip->ip_dst.s_addr != localhost)
		continue;

	    igmp = (struct igmp *)(recv_buf + (ip->ip_hl << 2));
	    if (igmp->igmp_group.s_addr != 0)
		continue;
	    if (igmp->igmp_type != 0 || igmp->igmp_code != 0)
		continue;

	    p = (int *)((char *)igmp + IGMP_MINLEN);
	    if (*p != getpid())
		continue;

#ifdef RAW_INPUT_IS_RAW
	    ip->ip_len = ntohs(ip->ip_len);
#endif
	    if (ip->ip_len == IGMP_MINLEN + 4)
		ip_addlen = 4;
	    else if (ip->ip_len == IGMP_MINLEN + 8)
		ip_addlen = 0;
	    else
		log(LOG_ERR, 0, "while checking for Solaris bug: Sent %d bytes and got back %d!", IGMP_MINLEN + 8, ip->ip_len);

	    break;
	}
    }
}
#endif

/*
 * Construct an IGMP message in the output packet buffer.  The caller may
 * have already placed data in that buffer, of length 'datalen'.  Then send
 * the message from the interface with IP address 'src' to destination 'dst'.
 */
void
send_igmp(src, dst, type, code, group, datalen)
    u_int32 src, dst;
    int type, code;
    u_int32 group;
    int datalen;
{
    struct sockaddr_in sdst;
    struct ip *ip;
    struct igmp *igmp;
    int setloop = 0;
    static int raset = 0;
    int sendra = 0;
    int sendlen;

    ip                      = (struct ip *)send_buf;
    ip->ip_src.s_addr       = src;
    ip->ip_dst.s_addr       = dst;
    ip->ip_len              = MIN_IP_HEADER_LEN + IGMP_MINLEN + datalen;
    sendlen		    = ip->ip_len;
#ifdef SUNOS5
    ip->ip_len		   += ip_addlen;
#endif
#ifdef RAW_OUTPUT_IS_RAW
    ip->ip_len		    = htons(ip->ip_len);
#endif

    igmp                    = (struct igmp *)(send_buf + MIN_IP_HEADER_LEN);
    igmp->igmp_type         = type;
    igmp->igmp_code         = code;
    igmp->igmp_group.s_addr = group;
    igmp->igmp_cksum        = 0;
    igmp->igmp_cksum        = inet_cksum((u_short *)igmp,
					 IGMP_MINLEN + datalen);

    if (IN_MULTICAST(ntohl(dst))) {
	k_set_if(src);
	setloop = 1;
	k_set_loop(TRUE);
	if (dst != allrtrs_group)
	    sendra = 1;
    }

    if (sendopts && sendra && !raset) {
	setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
			router_alert, sizeof(router_alert));
	raset = 1;
    } else if (!sendra && raset) {
#ifdef SUNOS5
	/*
	 * SunOS5 < 5.6 cannot properly reset the IP_OPTIONS "socket"
	 * option.  Instead, set up a string of 4 EOL's.
	 */
	setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
			eol, sizeof(eol));
#else
	setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
			NULL, 0);
#endif
	raset = 0;
    }

    bzero(&sdst, sizeof(sdst));
    sdst.sin_family = AF_INET;
#if (defined(BSD) && (BSD >= 199103))
    sdst.sin_len = sizeof(sdst);
#endif
    sdst.sin_addr.s_addr = dst;
    if (sendto(igmp_socket, send_buf, sendlen, 0,
			(struct sockaddr *)&sdst, sizeof(sdst)) < 0) {
	    log(LOG_WARNING, errno, "sendto to %s on %s",
		inet_fmt(dst, s1), inet_fmt(src, s2));
    }

    if (setloop)
	    k_set_loop(FALSE);

    log(LOG_DEBUG, 0, "SENT %s from %-15s to %s",
	type == IGMP_MTRACE ? "mtrace request" : "ask_neighbors",
	src == INADDR_ANY ? "INADDR_ANY" : inet_fmt(src, s1),
	inet_fmt(dst, s2));
}

/*
 * inet_cksum extracted from:
 *			P I N G . C
 *
 * Author -
 *	Mike Muuss
 *	U. S. Army Ballistic Research Laboratory
 *	December, 1983
 * Modified at Uc Berkeley
 *
 * (ping.c) Status -
 *	Public Domain.  Distribution Unlimited.
 *
 *			I N _ C K S U M
 *
 * Checksum routine for Internet Protocol family headers (C Version)
 *
 */
int
inet_cksum(addr, len)
	u_short *addr;
	u_int len;
{
	register int nleft = (int)len;
	register u_short *w = addr;
	u_short answer = 0;
	register int sum = 0;

	/*
	 *  Our algorithm is simple, using a 32 bit accumulator (sum),
	 *  we add sequential 16 bit words to it, and at the end, fold
	 *  back all the carry bits from the top 16 bits into the lower
	 *  16 bits.
	 */
	while (nleft > 1)  {
		sum += *w++;
		nleft -= 2;
	}

	/* mop up an odd byte, if necessary */
	if (nleft == 1) {
		*(u_char *) (&answer) = *(u_char *)w ;
		sum += answer;
	}

	/*
	 * add back carry outs from top 16 bits to low 16 bits
	 */
	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
	sum += (sum >> 16);			/* add carry */
	answer = ~sum;				/* truncate to 16 bits */
	return (answer);
}

void
k_set_rcvbuf(bufsize)
    int bufsize;
{
    if (setsockopt(igmp_socket, SOL_SOCKET, SO_RCVBUF,
		   (char *)&bufsize, sizeof(bufsize)) < 0)
	log(LOG_ERR, errno, "setsockopt SO_RCVBUF %u", bufsize);
}


void
k_hdr_include(bool)
    int bool;
{
#ifdef IP_HDRINCL
    if (setsockopt(igmp_socket, IPPROTO_IP, IP_HDRINCL,
		   (char *)&bool, sizeof(bool)) < 0)
	log(LOG_ERR, errno, "setsockopt IP_HDRINCL %u", bool);
#endif
}

void
k_set_ttl(t)
    int t;
{
    u_char ttl;

    ttl = t;
    if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_TTL,
		   (char *)&ttl, sizeof(ttl)) < 0)
	log(LOG_ERR, errno, "setsockopt IP_MULTICAST_TTL %u", ttl);
}


void
k_set_loop(l)
    int l;
{
    u_char loop;

    loop = l;
    if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_LOOP,
		   (char *)&loop, sizeof(loop)) < 0)
	log(LOG_ERR, errno, "setsockopt IP_MULTICAST_LOOP %u", loop);
}

725 726 727 728 729 730 731 732 733 734
#ifdef __riscos
void
k_set_sleep(s)
    int s;
{
    if (ioctl(igmp_socket, FIOSLEEPTW, &s) < 0)
	log(LOG_ERR, errno, "ioctl FIOSLEEPTW %u", s);
}
#endif

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
void
k_set_if(ifa)
    u_int32 ifa;
{
    struct in_addr adr;

    adr.s_addr = ifa;
    if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_IF,
		   (char *)&adr, sizeof(adr)) < 0)
	log(LOG_ERR, errno, "setsockopt IP_MULTICAST_IF %s",
	    		    inet_fmt(ifa, s1));
}

void
k_join(grp, ifa)
    u_int32 grp;
    u_int32 ifa;
{
    struct ip_mreq mreq;

    mreq.imr_multiaddr.s_addr = grp;
    mreq.imr_interface.s_addr = ifa;

    if (setsockopt(igmp_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
		   (char *)&mreq, sizeof(mreq)) < 0)
	log(LOG_WARNING, errno, "can't join group %s on interface %s",
				inet_fmt(grp, s1), inet_fmt(ifa, s2));
}


void
k_leave(grp, ifa)
    u_int32 grp;
    u_int32 ifa;
{
    struct ip_mreq mreq;

    mreq.imr_multiaddr.s_addr = grp;
    mreq.imr_interface.s_addr = ifa;

    if (setsockopt(igmp_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
		   (char *)&mreq, sizeof(mreq)) < 0)
	log(LOG_WARNING, errno, "can't leave group %s on interface %s",
				inet_fmt(grp, s1), inet_fmt(ifa, s2));
}

/*
 * Convert an IP address in u_long (network) format into a printable string.
 */
char *
inet_fmt(addr, s)
    u_int32 addr;
    char *s;
{
    register u_char *a;

    a = (u_char *)&addr;
    sprintf(s, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
    return (s);
}


/*
 * Convert an IP subnet number in u_long (network) format into a printable
 * string including the netmask as a number of bits.
 */
char *
inet_fmts(addr, mask, s)
    u_int32 addr, mask;
    char *s;
{
    register u_char *a, *m;
    int bits;

    if ((addr == 0) && (mask == 0)) {
	sprintf(s, "default");
	return (s);
    }
    a = (u_char *)&addr;
    m = (u_char *)&mask;
    bits = 33 - ffs(ntohl(mask));

    if      (m[3] != 0) sprintf(s, "%u.%u.%u.%u/%d", a[0], a[1], a[2], a[3],
						bits);
    else if (m[2] != 0) sprintf(s, "%u.%u.%u/%d",    a[0], a[1], a[2], bits);
    else if (m[1] != 0) sprintf(s, "%u.%u/%d",       a[0], a[1], bits);
    else                sprintf(s, "%u/%d",          a[0], bits);

    return (s);
}

char   *
inet_name(addr)
    u_int32  addr;
{
    struct hostent *e;

    e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);

    return e ? e->h_name : "?";
}


u_int32
host_addr(name)
    char   *name;
{
    struct hostent *e = (struct hostent *)0;
    u_int32  addr;
    int	i, dots = 3;
    char	buf[40];
    char	*ip = name;
    char	*op = buf;

    /*
     * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
     * if the name is all numeric.
     */
    for (i = sizeof(buf) - 7; i > 0; --i) {
	if (*ip == '.') --dots;
	else if (*ip == '\0') break;
	else if (!isdigit(*ip)) dots = 0;  /* Not numeric, don't add zeroes */
	*op++ = *ip++;
    }
    for (i = 0; i < dots; ++i) {
	*op++ = '.';
	*op++ = '0';
    }
    *op = '\0';

    if (dots <= 0)
	e = gethostbyname(name);
    if (e && (e->h_length == sizeof(addr))) {
	memcpy((char *)&addr, e->h_addr_list[0], e->h_length);
	if (e->h_addr_list[1])
	    fprintf(stderr, "Warning: %s has multiple addresses, using %s\n",
			name, inet_fmt(addr, s1));
    } else {
	addr = inet_addr(buf);
	if (addr == -1 || (IN_MULTICAST(addr) && dots)) {
	    addr = 0;
	    printf("Could not parse %s as host name or address\n", name);
	}
    }
    return addr;
}


char *
proto_type(type)
    u_int type;
{
    static char buf[80];

    switch (type) {
      case PROTO_DVMRP:
	return ("DVMRP");
      case PROTO_MOSPF:
	return ("MOSPF");
      case PROTO_PIM:
	return ("PIM");
      case PROTO_CBT:
	return ("CBT");
      case PROTO_PIM_SPECIAL:
	return ("PIM/Special");
      case PROTO_PIM_STATIC:
	return ("PIM/Static");
      case PROTO_DVMRP_STATIC:
	return ("DVMRP/Static");
      case PROTO_PIM_BGP4PLUS:
	return ("PIM/BGP4+");
      case PROTO_CBT_SPECIAL:
	return ("CBT/Special");
      case PROTO_CBT_STATIC:
	return ("CBT/Static");
      case PROTO_PIM_ASSERT:
	return ("PIM/Assert");
      case 0:
	return ("None");
      default:
	(void) sprintf(buf, "Unknown protocol code %d", type);
	return (buf);
    }
}


char *
flag_type(type)
    u_int type;
{
    static char buf[80];

    switch (type) {
      case TR_NO_ERR:
	return ("");
      case TR_WRONG_IF:
	return ("Wrong interface");
      case TR_PRUNED:
	return ("Prune sent upstream");
      case TR_OPRUNED:
	return ("Output pruned");
      case TR_SCOPED:
	return ("Hit scope boundary");
      case TR_NO_RTE:
	return ("No route");
      case TR_NO_FWD:
	return ("Not forwarding");
      case TR_HIT_RP:
	return ("Reached RP/Core");
      case TR_RPF_IF:
	return ("RPF Interface");
      case TR_NO_MULTI:
	return ("Multicast disabled");
      case TR_OLD_ROUTER:
	return ("Next router no mtrace");
      case TR_NO_SPACE:
	return ("No space in packet");
      case TR_ADMIN_PROHIB:
	return ("Admin. Prohibited");
      default:
	(void) sprintf(buf, "Unknown error code %d", type);
	return (buf);
    }
}

/*
 * If destination is on a local net, get the netmask, else set the
 * netmask to all ones.  There are two side effects: if the local
 * address was not explicitly set, and if the destination is on a
 * local net, use that one; in either case, verify that the local
 * address is valid.
 */
u_int32
get_netmask(s, dst)
    int s;
    u_int32 *dst;
{
    unsigned int n;
    struct ifconf ifc;
    struct ifreq *ifrp, *ifend;
    u_int32 if_addr, if_mask;
    u_int32 retval = 0xFFFFFFFF;
    int found = FALSE;
    int num_ifreq = 32;

    ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
    ifc.ifc_buf = malloc(ifc.ifc_len);
    while (ifc.ifc_buf) {
	if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) {
	    perror("ioctl SIOCGIFCONF");
	    return retval;
	}

	/*
	 * If the buffer was large enough to hold all the addresses
	 * then break out, otherwise increase the buffer size and
	 * try again.
	 *
	 * The only way to know that we definitely had enough space
	 * is to know that there was enough space for at least one
	 * more struct ifreq. ???
	 */
	if ((num_ifreq * sizeof(struct ifreq)) >=
	     ifc.ifc_len + sizeof(struct ifreq))
	     break;

	num_ifreq *= 2;
	ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
	ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
    }
    if (ifc.ifc_buf == NULL) {
	fprintf(stderr, "getting interface list: ran out of memory");
	exit(1);
    }

    ifrp = (struct ifreq *)ifc.ifc_buf;
    ifend = (struct ifreq *)(ifc.ifc_buf + ifc.ifc_len);
    /*
     * Loop through all of the interfaces.
     */
    for (; ifrp < ifend && !found; ifrp = (struct ifreq *)((char *)ifrp + n)) {
#if BSD >= 199006
	n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
	if (n < sizeof(*ifrp))
	    n = sizeof(*ifrp);
#else
	n = sizeof(*ifrp);
#endif
	/*
	 * Ignore any interface for an address family other than IP.
	 */
	if (ifrp->ifr_addr.sa_family != AF_INET)
	    continue;

	if_addr = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
	if (ioctl(s, SIOCGIFFLAGS, (char *)ifrp) < 0) {
	    fprintf(stderr, "SIOCGIFFLAGS on ");
	    perror(ifrp->ifr_name);
	    continue;
	}
	if ((ifrp->ifr_flags & (IFF_MULTICAST|IFF_UP|IFF_LOOPBACK)) !=
				(IFF_MULTICAST|IFF_UP))
	    continue;
	if (*dst == 0)
	    *dst = if_addr;
	if (ioctl(s, SIOCGIFNETMASK, (char *)ifrp) >= 0) {
	    if_mask = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
	    if (if_mask != 0 && (*dst & if_mask) == (if_addr & if_mask)) {
		retval = if_mask;
		if (lcl_addr == 0) lcl_addr = if_addr;	/* XXX what about aliases? */
	    }
	}
	if (lcl_addr == if_addr) found = TRUE;
    }
    if (!found && lcl_addr != 0) {
	printf("Interface address is not valid\n");
	exit(1);
    }
    return (retval);
}


/*
 * Try to pick a TTL that will get past all the thresholds in the path.
 */
int
get_ttl(buf)
    struct resp_buf *buf;
{
    int rno;
    struct tr_resp *b;
    u_int ttl;

    if (buf && (rno = buf->len) > 0) {
	b = buf->resps + rno - 1;
	ttl = b->tr_fttl;

	while (--rno > 0) {
	    --b;
	    if (ttl < b->tr_fttl) ttl = b->tr_fttl;
	    else ++ttl;
	}
	ttl += MULTICAST_TTL_INC;
	if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
	if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
	return (ttl);
    } else return(MULTICAST_TTL1);
}

/*
 * Calculate the difference between two 32-bit NTP timestamps and return
 * the result in milliseconds.
 */
int
t_diff(a, b)
    u_long a, b;
{
    int d = a - b;

    return ((d * 125) >> 13);
}

/*
 * Swap bytes for poor little-endian machines that don't byte-swap
 */
u_long
byteswap(v)
    u_long v;
{
    return ((v << 24) | ((v & 0xff00) << 8) |
	    ((v >> 8) & 0xff00) | (v >> 24));
}

#if 0
/*
 * XXX incomplete - need private callback data, too?
 * XXX since dst doesn't get passed through?
 */
int
neighbors_callback(tmo, buf, buflen, igmp, igmplen, addr, addrlen, ts)
    int tmo;
    u_char *buf;
    int buflen;
    struct igmp *igmp;
    int igmplen;
    struct sockaddr *addr;
    int *addrlen;
    struct timeval *ts;
{
    int len;
    u_int32 dst;
    struct ip *ip = (struct ip *)buf;

    if (tmo)
	return 0;

    if (igmp->igmp_code != DVMRP_NEIGHBORS2)
	return 0;
    len = igmplen;
    /*
     * Accept DVMRP_NEIGHBORS2 response if it comes from the
     * address queried or if that address is one of the local
     * addresses in the response.
     */
    if (ip->ip_src.s_addr != dst) {
	u_int32 *p = (u_int32 *)(igmp + 1);
	u_int32 *ep = p + (len >> 2);
	while (p < ep) {
	    u_int32 laddr = *p++;
	    int n = ntohl(*p++) & 0xFF;
	    if (laddr == dst) {
		ep = p + 1;		/* ensure p < ep after loop */
		break;
	    }
	    p += n;
	}
	if (p >= ep)
	    return 0;
    }
    return buflen;
}
#endif

int
mtrace_callback(tmo, buf, buflen, igmp, igmplen, addr, addrlen, ts)
    int tmo;
    u_char *buf;
    int buflen;
    struct igmp *igmp;
    int igmplen;
    struct sockaddr *addr;
    int *addrlen;
    struct timeval *ts;
{
    static u_char *savbuf = NULL;
    static int savbuflen;
    static struct sockaddr *savaddr;
    static int savaddrlen;
    static struct timeval savts;

    int len = (igmplen - QLEN) / RLEN;
    struct tr_resp *r = (struct tr_resp *)((struct tr_query *)(igmp + 1) + 1);

    if (tmo == 1) {
	/*
	 * If we timed out with a packet saved, then return that packet.
	 * send_recv won't send this same packet to the callback again.
	 */
	if (savbuf) {
	    bcopy(savbuf, buf, savbuflen);
	    free(savbuf);
	    savbuf = NULL;
	    bcopy(savaddr, addr, savaddrlen);
	    free(savaddr);
	    *addrlen = savaddrlen;
	    bcopy(&savts, ts, sizeof(savts));
	    return savbuflen;
	}
	return 0;
    }
    if (savbuf) {
	free(savbuf);
	savbuf = NULL;
	free(savaddr);
    }
    /*
     * Check for IOS bug described in CSCdi68628, where a router that does
     *  not have multicast enabled responds to an mtrace request with a 1-hop
     *  error packet.
     * Heuristic is:
     *  If there is only one hop reported in the packet,
     *	And the protocol code is 0,
     *  And there is no previous hop,
     *	And the forwarding information is "Not Forwarding",
     *	And the router is not on the same subnet as the destination of the
     *		trace,
     *  then drop this packet.  The "#if 0"'d code saves it and returns
     *   it on timeout, but timeouts are too common (e.g. routers with
     *   limited unicast routing tables, etc).
     */
    if (len == 1 && r->tr_rproto == 0 && r->tr_rmtaddr == 0 &&
					r->tr_rflags == TR_NO_FWD) {
	u_int32 smask;

	VAL_TO_MASK(smask, r->tr_smask);
	if ((r->tr_outaddr & smask) != (qdst & smask)) {
#if 0
	    /* XXX should do this silently? */
	    fprintf(stderr, "mtrace: probably IOS-buggy packet from %s\n",
		inet_fmt(((struct sockaddr_in *)addr)->sin_addr.s_addr, s1));
	    /* Save the packet to return if a timeout occurs. */
	    savbuf = (u_char *)malloc(buflen);
	    if (savbuf != NULL) {
		bcopy(buf, savbuf, buflen);
		savbuflen = buflen;
		savaddr = (struct sockaddr *)malloc(*addrlen);
		if (savaddr != NULL) {
		    bcopy(addr, savaddr, *addrlen);
		    savaddrlen = *addrlen;
		    bcopy(ts, &savts, sizeof(savts));
		} else {
		    free(savbuf);
		    savbuf = NULL;
		}
	    }
#endif
	    return 0;
	}
    }
    return buflen;
}

int
send_recv(dst, type, code, tries, save, callback)
    u_int32 dst;
    int type, code, tries;
    struct resp_buf *save;
    callback_t callback;
{
    fd_set  fds;
    struct timeval tq, tr, tv;
    struct ip *ip;
    struct igmp *igmp;
    struct tr_query *query, *rquery;
    struct tr_resp *r;
    struct sockaddr_in recvaddr;
    u_int32 local, group;
    int ipdatalen, iphdrlen, igmpdatalen;
    int datalen;
    int count, recvlen, socklen = sizeof(recvaddr);
    int len;
    int i;

    if (type == IGMP_MTRACE) {
	group = qgrp;
	datalen = sizeof(struct tr_query);
    } else {
	group = htonl(0xff03);
	datalen = 0;
    }
    if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
    else local = INADDR_ANY;

    /*
     * If the reply address was not explictly specified, start off
     * with the standard multicast reply address, or the unicast
     * address of this host if the unicast flag was specified.
     * Then, if there is no response after trying half the tries
     * with multicast, switch to the unicast address of this host
     * if the multicast flag was not specified.  If the TTL was
     * also not specified, set a multicast TTL and increase it
     * for every try.
     */
    query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
    query->tr_raddr = raddr ? raddr : unicast ? lcl_addr : resp_cast;
    TR_SETTTL(query->tr_rttlqid, rttl ? rttl :
      IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL);
    query->tr_src   = qsrc;
    query->tr_dst   = qdst;

    for (i = tries ; i > 0; --i) {
	int oqid;

	if (tries == nqueries && raddr == 0) {
	    if (i == (nqueries >> 1)) {
		if (multicast && unicast) {
		    query->tr_raddr = resp_cast;
		    if (!rttl)
			TR_SETTTL(query->tr_rttlqid, get_ttl(save));
		} else if (!multicast) {
		    query->tr_raddr = lcl_addr;
		    TR_SETTTL(query->tr_rttlqid, UNICAST_TTL);
		}
	    }
	    if (i < tries && IN_MULTICAST(ntohl(query->tr_raddr)) &&
								rttl == 0) {
		TR_SETTTL(query->tr_rttlqid,
			TR_GETTTL(query->tr_rttlqid) + MULTICAST_TTL_INC);
		if (TR_GETTTL(query->tr_rttlqid) > MULTICAST_TTL_MAX)
		  TR_SETTTL(query->tr_rttlqid, MULTICAST_TTL_MAX);
	    }
	}

	/*
	 * Change the qid for each request sent to avoid being confused
	 * by duplicate responses
	 */
	oqid = TR_GETQID(query->tr_rttlqid);
	if (staticqid)
	    TR_SETQID(query->tr_rttlqid, staticqid);
	else
#ifdef SYSV
	    TR_SETQID(query->tr_rttlqid, ((u_int32)lrand48() >> 8));
#else
	    TR_SETQID(query->tr_rttlqid, ((u_int32)random() >> 8));
#endif

	/*
	 * Set timer to calculate delays, then send query
	 */
	gettimeofday(&tq, 0);
	send_igmp(local, dst, type, code, group, datalen);

	/*
	 * Wait for response, discarding false alarms
	 */
	while (TRUE) {
	    FD_ZERO(&fds);
	    FD_SET(igmp_socket, &fds);
	    gettimeofday(&tv, 0);
	    tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
	    tv.tv_usec = tq.tv_usec - tv.tv_usec;
	    if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
	    if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;

	    count = select(igmp_socket + 1, &fds, (fd_set *)0, (fd_set *)0,
			   &tv);

	    if (count < 0) {
		if (errno != EINTR) warn("select");
		continue;
	    } else if (count == 0) {
		/*
		 * Timed out.  Notify the callback.
		 */
		if (!callback || (recvlen = (callback)(1, (u_char *) recv_buf, 0, NULL, 0, (struct sockaddr *)&recvaddr, &socklen, &tr)) == 0) {
		    printf("* ");
		    fflush(stdout);
		    break;
		}
	    } else {
		/*
		 * Data is available on the socket, so read it.
		 */
		gettimeofday(&tr, 0);
		recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
				   0, (struct sockaddr *)&recvaddr, &socklen);
	    }

	    if (recvlen <= 0) {
		if (recvlen && errno != EINTR) warn("recvfrom");
		continue;
	    }

	    if (recvlen < sizeof(struct ip)) {
		warnx("packet too short (%u bytes) for IP header", recvlen);
		continue;
	    }
	    ip = (struct ip *) recv_buf;
	    if (ip->ip_p == 0)	/* ignore cache creation requests */
		continue;

	    iphdrlen = ip->ip_hl << 2;
#ifdef RAW_INPUT_IS_RAW
	    ipdatalen = ntohs(ip->ip_len);
#else
	    ipdatalen = ip->ip_len;
#endif
	    if (iphdrlen + ipdatalen != recvlen) {
		warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
			recvlen, iphdrlen, ipdatalen);
		continue;
	    }

	    igmp = (struct igmp *) (recv_buf + iphdrlen);
	    igmpdatalen = ipdatalen - IGMP_MINLEN;
	    if (igmpdatalen < 0) {
		warnx("IP data field too short (%u bytes) for IGMP from %s",
			ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
		continue;
	    }

	    switch (igmp->igmp_type) {

	      case IGMP_DVMRP:
		if (type != IGMP_DVMRP || code != DVMRP_ASK_NEIGHBORS2)
			continue;
		if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
		len = igmpdatalen;
		/*
		 * Accept DVMRP_NEIGHBORS2 response if it comes from the
		 * address queried or if that address is one of the local
		 * addresses in the response.
		 */
		if (ip->ip_src.s_addr != dst) {
		    u_int32 *p = (u_int32 *)(igmp + 1);
		    u_int32 *ep = p + (len >> 2);
		    while (p < ep) {
			u_int32 laddr = *p++;
			int n = ntohl(*p++) & 0xFF;
			if (laddr == dst) {
			    ep = p + 1;		/* ensure p < ep after loop */
			    break;
			}
			p += n;
		    }
		    if (p >= ep) continue;
		}
		break;

	      case IGMP_MTRACE:	    /* For backward compatibility with 3.3 */
	      case IGMP_MTRACE_RESP:
		if (type != IGMP_MTRACE) continue;
		if (igmpdatalen <= QLEN) continue;
		if ((igmpdatalen - QLEN)%RLEN) {
		    printf("packet with incomplete responses (%d bytes)\n",
			igmpdatalen);
		    continue;
		}

		/*
		 * Ignore responses that don't match query.
		 */
		rquery = (struct tr_query *)(igmp + 1);
		if (rquery->tr_src != qsrc || rquery->tr_dst != qdst)
		    continue;
		if (TR_GETQID(rquery->tr_rttlqid) !=
			TR_GETQID(query->tr_rttlqid)) {
		    if (verbose && TR_GETQID(rquery->tr_rttlqid) == oqid)
			printf("[D]");
		    continue;
		}
		len = (igmpdatalen - QLEN)/RLEN;
		r = (struct tr_resp *)(rquery+1) + len - 1;

		/*
		 * Ignore trace queries passing through this node when
		 * mtrace is run on an mrouter that is in the path
		 * (needed only because IGMP_MTRACE is accepted above
		 * for backward compatibility with multicast release 3.3).
		 */
		if (igmp->igmp_type == IGMP_MTRACE) {
		    u_int32 smask;

		    VAL_TO_MASK(smask, r->tr_smask);
		    if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
			&& r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
		      continue;
		}
		/*
		 * Some routers will return error messages without
		 * filling in their addresses.  We fill in the address
		 * for them.
		 */
		if (r->tr_outaddr == 0)
		    r->tr_outaddr = recvaddr.sin_addr.s_addr;

		/*
		 * A match, we'll keep this one.
		 */
		if (len > code) {
		    warnx("num hops received (%d) exceeds request (%d)",
			    len, code);
		}
		rquery->tr_raddr = query->tr_raddr;	/* Insure these are */
		TR_SETTTL(rquery->tr_rttlqid, TR_GETTTL(query->tr_rttlqid));
							/* as we sent them */
		break;

	      default:
		continue;
	    }

	    /*
	     * We're pretty sure we want to use this packet now,
	     * but if the caller gave a callback function, it might
	     * want to handle it instead.  Give the callback a chance,
	     * unless the select timed out (in which case the only way
	     * to get here is because the callback returned a packet).
	     */
	    if (callback && (count != 0) && ((callback)(0, (u_char *) recv_buf, recvlen, igmp, igmpdatalen, (struct sockaddr*)&recvaddr, &socklen, &tr)) == 0) {
		/*
		 * The callback function didn't like this packet.
		 * Go try receiving another one.
		 */
		continue;
	    }

	    /*
	     * Most of the sanity checking done at this point.
	     * Return this packet we have been waiting for.
	     */
	    if (save) {
		save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
			      (tq.tv_usec << 10) / 15625;
		save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
			      (tr.tv_usec << 10) / 15625;
		save->len = len;
		bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
	    }
	    return (recvlen);
	}
    }
    return (0);
}

/*
 * Most of this code is duplicated elsewhere.  I'm not sure if
 * the duplication is absolutely required or not.
 *
 * Ideally, this would keep track of ongoing statistics
 * collection and print out statistics.  (& keep track
 * of h-b-h traces and only print the longest)  For now,
 * it just snoops on what traces it can.
 */
void
passive_mode()
{
    struct timeval tr;
    time_t tr_sec;
    struct ip *ip;
    struct igmp *igmp;
    struct tr_resp *r;
    struct sockaddr_in recvaddr;
    struct tm *now;
    char timebuf[32];
    int socklen;
    int ipdatalen, iphdrlen, igmpdatalen;
    int len, recvlen;
    int qid;
    u_int32 smask;
    struct mtrace *remembered = NULL, *m, *n, **nn;
    int pc = 0;

    if (raddr) {
	if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
    } else k_join(htonl(0xE0000120), lcl_addr);

    while (1) {
	fflush(stdout);		/* make sure previous trace is flushed */

	socklen = sizeof(recvaddr);
	recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
			   0, (struct sockaddr *)&recvaddr, &socklen);
	gettimeofday(&tr,0);

	if (recvlen <= 0) {
	    if (recvlen && errno != EINTR) warn("recvfrom");
	    continue;
	}

	if (recvlen < sizeof(struct ip)) {
	    warnx("packet too short (%u bytes) for IP header", recvlen);
	    continue;
	}
	ip = (struct ip *) recv_buf;
	if (ip->ip_p == 0)	/* ignore cache creation requests */
	    continue;

	iphdrlen = ip->ip_hl << 2;
#ifdef RAW_INPUT_IS_RAW
	ipdatalen = ntohs(ip->ip_len);
#else
	ipdatalen = ip->ip_len;
#endif
	if (iphdrlen + ipdatalen != recvlen) {
	    warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
		    recvlen, iphdrlen, ipdatalen);
	    continue;
	}

	igmp = (struct igmp *) (recv_buf + iphdrlen);
	igmpdatalen = ipdatalen - IGMP_MINLEN;
	if (igmpdatalen < 0) {
	    warnx("IP data field too short (%u bytes) for IGMP from %s",
		    ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
	    continue;
	}

	switch (igmp->igmp_type) {

	  case IGMP_MTRACE:	    /* For backward compatibility with 3.3 */
	  case IGMP_MTRACE_RESP:
	    if (igmpdatalen < QLEN) continue;
	    if ((igmpdatalen - QLEN)%RLEN) {
		printf("packet with incorrect datalen\n");
		continue;
	    }

	    len = (igmpdatalen - QLEN)/RLEN;

	    break;

	  default:
	    continue;
	}

	base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
		      (tr.tv_usec << 10) / 15625;
	base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
		      (tr.tv_usec << 10) / 15625;
	base.len = len;
	bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
	/*
	 * If the user specified which traces to monitor,
	 * only accept traces that correspond to the
	 * request
	 */
	if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
	    (qdst != 0 && qdst != base.qhdr.tr_dst) ||
	    (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
	    continue;

	/* XXX This should be a hash table */
	/* XXX garbage-collection should be more efficient */
	for (nn = &remembered, n = *nn, m = 0; n; n = *nn) {
	    if ((n->base.qhdr.tr_src == base.qhdr.tr_src) &&
		(n->base.qhdr.tr_dst == base.qhdr.tr_dst) &&
		(n->base.igmp.igmp_group.s_addr == igmp->igmp_group.s_addr)) {
		m = n;
		m->last = tr;
	    }
	    if (tr.tv_sec - n->last.tv_sec > 500) { /* XXX don't hardcode */
		*nn = n->next;
		free(n);
	    } else {
		nn = &n->next;
	    }
	}

	tr_sec = tr.tv_sec;
	now = localtime(&tr_sec);
1657 1658 1659 1660 1661 1662
#ifdef __riscos
	/* %e and %k aren't standard ISO C, and hence not supported by our
	 * C library (which is a bit officious about these things).
	 */
	strftime(timebuf, sizeof(timebuf) - 1, "%b %d %H:%M:%S", now);
#else
1663
	strftime(timebuf, sizeof(timebuf) - 1, "%b %e %k:%M:%S", now);
1664
#endif
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364