Remove some unnecessary casts.
[dragonfly.git] / usr.sbin / mrouted / mtrace.c
CommitLineData
984263bc
MD
1/*
2 * mtrace.c
3 *
4 * This tool traces the branch of a multicast tree from a source to a
5 * receiver for a particular multicast group and gives statistics
6 * about packet rate and loss for each hop along the path. It can
7 * usually be invoked just as
8 *
9 * mtrace source
10 *
11 * to trace the route from that source to the local host for a default
12 * group when only the route is desired and not group-specific packet
13 * counts. See the usage line for more complex forms.
14 *
15 *
16 * Released 4 Apr 1995. This program was adapted by Steve Casner
17 * (USC/ISI) from a prototype written by Ajit Thyagarajan (UDel and
18 * Xerox PARC). It attempts to parallel in command syntax and output
19 * format the unicast traceroute program written by Van Jacobson (LBL)
20 * for the parts where that makes sense.
21 *
22 * Copyright (c) 1995 by the University of Southern California
23 * All rights reserved.
24 *
25 * Permission to use, copy, modify, and distribute this software and its
26 * documentation in source and binary forms for any purposes and without
27 * fee is hereby granted, provided that the above copyright notice
28 * appear in all copies and that both the copyright notice and this
29 * permission notice appear in supporting documentation, and that any
30 * documentation, advertising materials, and other materials related to
31 * such distribution and use acknowledge that the software was developed
32 * by the University of Southern California, Information Sciences
33 * Institute. The name of the University may not be used to endorse or
34 * promote products derived from this software without specific prior
35 * written permission.
36 *
37 * THE UNIVERSITY OF SOUTHERN CALIFORNIA makes no representations about
38 * the suitability of this software for any purpose. THIS SOFTWARE IS
39 * PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
40 * INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
41 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
42 *
43 * Other copyrights might apply to parts of this software and are so
44 * noted when applicable.
45 *
46 * Parts of this software are derived from mrouted, which has the
47 * following license:
48 *
49 * The mrouted program is covered by the following license. Use of the
50 * mrouted program represents acceptance of these terms and conditions.
51 *
52 * 1. STANFORD grants to LICENSEE a nonexclusive and nontransferable
53 * license to use, copy and modify the computer software ``mrouted''
54 * (hereinafter called the ``Program''), upon the terms and conditions
55 * hereinafter set out and until Licensee discontinues use of the Licensed
56 * Program.
57 *
58 * 2. LICENSEE acknowledges that the Program is a research tool still in
59 * the development state, that it is being supplied ``as is,'' without any
60 * accompanying services from STANFORD, and that this license is entered
61 * into in order to encourage scientific collaboration aimed at further
62 * development and application of the Program.
63 *
64 * 3. LICENSEE may copy the Program and may sublicense others to use
65 * object code copies of the Program or any derivative version of the
66 * Program. All copies must contain all copyright and other proprietary
67 * notices found in the Program as provided by STANFORD. Title to
68 * copyright to the Program remains with STANFORD.
69 *
70 * 4. LICENSEE may create derivative versions of the Program. LICENSEE
71 * hereby grants STANFORD a royalty-free license to use, copy, modify,
72 * distribute and sublicense any such derivative works. At the time
73 * LICENSEE provides a copy of a derivative version of the Program to a
74 * third party, LICENSEE shall provide STANFORD with one copy of the
75 * source code of the derivative version at no charge to STANFORD.
76 *
77 * 5. STANFORD MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
78 * IMPLIED. By way of example, but not limitation, STANFORD MAKES NO
79 * REPRESENTATION OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
80 * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED PROGRAM WILL NOT
81 * INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. STANFORD
82 * shall not be held liable for any liability nor for any direct, indirect
83 * or consequential damages with respect to any claim by LICENSEE or any
84 * third party on account of or arising from this Agreement or use of the
85 * Program.
86 *
87 * 6. This agreement shall be construed, interpreted and applied in
88 * accordance with the State of California and any legal action arising
89 * out of this Agreement or use of the Program shall be filed in a court
90 * in the State of California.
91 *
92 * 7. Nothing in this Agreement shall be construed as conferring rights to
93 * use in advertising, publicity or otherwise any trademark or the name
94 * of ``Stanford''.
95 *
96 * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of
97 * Leland Stanford Junior University.
98 *
99 *
100 * The mtrace program has been modified and improved by Xerox
101 * Corporation. Xerox grants to LICENSEE a non-exclusive and
102 * non-transferable license to use, copy, and modify the Xerox modified
103 * and improved mrouted software on the same terms and conditions which
104 * govern the license Stanford and ISI grant with respect to the mtrace
105 * program. These terms and conditions are incorporated in this grant
106 * by reference and shall be deemed to have been accepted by LICENSEE
107 * to cover its relationship with Xerox Corporation with respect to any
108 * use of the Xerox improved program.
109 *
110 * The mtrace program is COPYRIGHT 1998 by Xerox Corporation.
111 *
1de703da 112 * $FreeBSD: src/usr.sbin/mrouted/mtrace.c,v 1.17.2.3 2002/09/12 16:27:49 nectar Exp $
fd0e91da 113 * $DragonFly: src/usr.sbin/mrouted/mtrace.c,v 1.8 2005/12/05 00:58:50 swildner Exp $
984263bc
MD
114 */
115
984263bc
MD
116#include <ctype.h>
117#include <err.h>
118#include <errno.h>
119#include <memory.h>
120#include <netdb.h>
121#include <stdio.h>
122#include <stdlib.h>
123#include <string.h>
124#include <syslog.h>
125#include <unistd.h>
126#include <sys/param.h>
127#include <sys/types.h>
128#include <sys/socket.h>
129#include <sys/time.h>
130#include <net/if.h>
131#include <netinet/in.h>
132#include <netinet/in_systm.h>
133#include <netinet/ip.h>
134#include <netinet/igmp.h>
135#include <sys/ioctl.h>
136#ifdef SYSV
137#include <sys/sockio.h>
138#endif
139#include <arpa/inet.h>
984263bc 140#include <stdarg.h>
984263bc
MD
141#ifdef SUNOS5
142#include <sys/systeminfo.h>
143#endif
144
145typedef unsigned int u_int32; /* XXX */
146#include "mtrace.h"
147
fd0e91da 148const char version[] = "$DragonFly: src/usr.sbin/mrouted/mtrace.c,v 1.8 2005/12/05 00:58:50 swildner Exp $";
1de703da 149
984263bc
MD
150#define DEFAULT_TIMEOUT 3 /* How long to wait before retrying requests */
151#define DEFAULT_RETRIES 3 /* How many times to try */
152#define DEFAULT_EXTRAHOPS 3 /* How many hops past a non-responding rtr */
153#define MAXHOPS 60 /* Don't need more hops than this */
154#define UNICAST_TTL 255 /* TTL for unicast response */
155#define MULTICAST_TTL1 127 /* Default TTL for multicast query/response */
156#define MULTICAST_TTL_INC 32 /* TTL increment for increase after timeout */
157#define MULTICAST_TTL_MAX 192 /* Maximum TTL allowed (protect low-BW links */
158
159#define TRUE 1
160#define FALSE 0
161#define DVMRP_ASK_NEIGHBORS2 5 /* DVMRP msg requesting neighbors */
162#define DVMRP_NEIGHBORS2 6 /* reply to above */
163#define DVMRP_NF_DOWN 0x10 /* kernel state of interface */
164#define DVMRP_NF_DISABLED 0x20 /* administratively disabled */
165#define MAX_IP_PACKET_LEN 576
166#define MIN_IP_HEADER_LEN 20
167#define MAX_IP_HEADER_LEN 60
168#define MAX_DVMRP_DATA_LEN \
169 ( MAX_IP_PACKET_LEN - MAX_IP_HEADER_LEN - IGMP_MINLEN )
170
171struct resp_buf {
172 u_long qtime; /* Time query was issued */
173 u_long rtime; /* Time response was received */
174 int len; /* Number of reports or length of data */
175 struct igmp igmp; /* IGMP header */
176 union {
177 struct {
178 struct tr_query q; /* Query/response header */
179 struct tr_resp r[MAXHOPS]; /* Per-hop reports */
180 } t;
181 char d[MAX_DVMRP_DATA_LEN]; /* Neighbor data */
182 } u;
183} base, incr[2];
184
185#define qhdr u.t.q
186#define resps u.t.r
187#define ndata u.d
188
189char *names[MAXHOPS];
190
191/*
192 * In mrouted 3.3 and 3.4 (and in some Cisco IOS releases),
193 * cache entries can get deleted even if there is traffic
194 * flowing, which will reset the per-source/group counters.
195 */
196#define BUG_RESET 0x01
197
198/*
199 * Also in mrouted 3.3 and 3.4, there's a bug in neighbor
200 * version processing which can cause them to believe that
201 * the neighbor is constantly resetting. This causes them
202 * to constantly delete all their state.
203 */
204#define BUG_RESET2X 0x02
205
206/*
207 * Pre-3.7 mrouted's forget to byte-swap their reports.
208 */
209#define BUG_SWAP 0x04
210
211/*
212 * Pre-3.9 mrouted's forgot a parenthesis in the htonl()
213 * on the time calculation so supply bogus times.
214 */
215#define BUG_BOGUSTIME 0x08
216
217#define BUG_NOPRINT (BUG_RESET | BUG_RESET2X)
218
219int bugs[MAXHOPS]; /* List of bugs noticed at each hop */
220
221struct mtrace {
222 struct mtrace *next;
223 struct resp_buf base, incr[2];
224 struct resp_buf *new, *prev;
225 int nresp;
226 struct timeval last;
227 int bugs[MAXHOPS];
228 char *names[MAXHOPS];
229 int lastqid;
230};
231
232int timeout = DEFAULT_TIMEOUT;
233int nqueries = DEFAULT_RETRIES;
234int numeric = FALSE;
235int debug = 0;
236int passive = FALSE;
237int multicast = FALSE;
238int unicast = FALSE;
239int statint = 10;
240int verbose = FALSE;
241int tunstats = FALSE;
242int weak = FALSE;
243int extrahops = DEFAULT_EXTRAHOPS;
244int printstats = TRUE;
245int sendopts = TRUE;
246int lossthresh = 0;
247int fflag = FALSE;
248int staticqid = 0;
249
250u_int32 defgrp; /* Default group if not specified */
251u_int32 query_cast; /* All routers multicast addr */
252u_int32 resp_cast; /* Mtrace response multicast addr */
253
254u_int32 lcl_addr = 0; /* This host address, in NET order */
255u_int32 dst_netmask = 0; /* netmask to go with qdst */
256
257/*
258 * Query/response parameters, all initialized to zero and set later
259 * to default values or from options.
260 */
261u_int32 qsrc = 0; /* Source address in the query */
262u_int32 qgrp = 0; /* Group address in the query */
263u_int32 qdst = 0; /* Destination (receiver) address in query */
264u_char qno = 0; /* Max number of hops to query */
265u_int32 raddr = 0; /* Address where response should be sent */
266int qttl = 0; /* TTL for the query packet */
267u_char rttl = 0; /* TTL for the response packet */
268u_int32 gwy = 0; /* User-supplied last-hop router address */
269u_int32 tdst = 0; /* Address where trace is sent (last-hop) */
270
271char s1[19]; /* buffers to hold the string representations */
272char s2[19]; /* of IP addresses, to be passed to inet_fmt() */
273char s3[19]; /* or inet_fmts(). */
274
275#if !(defined(BSD) && (BSD >= 199103))
276extern int errno;
277extern int sys_nerr;
278extern char * sys_errlist[];
279#endif
280
281#define RECV_BUF_SIZE 8192
282char *send_buf, *recv_buf;
283int igmp_socket;
284u_int32 allrtrs_group;
285char router_alert[4]; /* Router Alert IP Option */
286#ifndef IPOPT_RA
287#define IPOPT_RA 148
288#endif
289#ifdef SUNOS5
290char eol[4]; /* EOL IP Option */
291int ip_addlen = 0; /* Workaround for Option bug #2 */
292#endif
293
294/*
295 * max macro, with weird case to avoid conflicts
296 */
297#define MaX(a,b) ((a) > (b) ? (a) : (b))
298
2d8a3be7
EN
299typedef int (*callback_t)(int, u_char *, int, struct igmp *, int,
300 struct sockaddr *, int *, struct timeval *);
984263bc 301
2d8a3be7
EN
302void init_igmp(void);
303void send_igmp(u_int32 src, u_int32 dst, int type,
984263bc 304 int code, u_int32 group,
2d8a3be7
EN
305 int datalen);
306int inet_cksum(u_short *addr, u_int len);
307void k_set_rcvbuf(int bufsize);
5fe88d64 308void k_hdr_include(int boolv);
2d8a3be7
EN
309void k_set_ttl(int t);
310void k_set_loop(int l);
311void k_set_if(u_int32 ifa);
312void k_join(u_int32 grp, u_int32 ifa);
313void k_leave(u_int32 grp, u_int32 ifa);
314char * inet_fmt(u_int32 addr, char *s);
315char * inet_fmts(u_int32 addr, u_int32 mask, char *s);
316char * inet_name(u_int32 addr);
317u_int32 host_addr(char *name);
984263bc 318/* u_int is promoted u_char */
2d8a3be7
EN
319char * proto_type(u_int type);
320char * flag_type(u_int type);
984263bc 321
2d8a3be7
EN
322u_int32 get_netmask(int s, u_int32 *dst);
323int get_ttl(struct resp_buf *buf);
324int t_diff(u_long a, u_long b);
325u_long byteswap(u_long v);
326int mtrace_callback(int, u_char *, int, struct igmp *,
984263bc 327 int, struct sockaddr *, int *,
2d8a3be7
EN
328 struct timeval *);
329int send_recv(u_int32 dst, int type, int code,
984263bc 330 int tries, struct resp_buf *save,
2d8a3be7
EN
331 callback_t callback);
332void passive_mode(void);
333char * print_host(u_int32 addr);
334char * print_host2(u_int32 addr1, u_int32 addr2);
335void print_trace(int idx, struct resp_buf *buf,
336 char **names);
337int what_kind(struct resp_buf *buf, char *why);
338char * scale(int *hop);
339void stat_line(struct tr_resp *r, struct tr_resp *s,
340 int have_next, int *res);
341void fixup_stats(struct resp_buf *base,
984263bc
MD
342 struct resp_buf *prev,
343 struct resp_buf *new,
2d8a3be7
EN
344 int *bugs);
345int check_thresh(int thresh,
984263bc
MD
346 struct resp_buf *base,
347 struct resp_buf *prev,
2d8a3be7
EN
348 struct resp_buf *new);
349int print_stats(struct resp_buf *base,
984263bc
MD
350 struct resp_buf *prev,
351 struct resp_buf *new,
352 int *bugs,
2d8a3be7
EN
353 char **names);
354int path_changed(struct resp_buf *base,
355 struct resp_buf *new);
356void check_vif_state(void);
984263bc 357
33745200 358int main(int argc, char **argv);
2d8a3be7
EN
359void log(int, int, char *, ...);
360static void usage(void);
984263bc
MD
361
362
363/*
364 * Open and initialize the igmp socket, and fill in the non-changing
365 * IP header fields in the output packet buffer.
366 */
367void
33745200 368init_igmp(void)
984263bc
MD
369{
370 struct ip *ip;
371
372 recv_buf = (char *)malloc(RECV_BUF_SIZE);
373 if (recv_buf == 0)
374 log(LOG_ERR, 0, "Out of memory allocating recv_buf!");
375 send_buf = (char *)malloc(RECV_BUF_SIZE);
376 if (send_buf == 0)
377 log(LOG_ERR, 0, "Out of memory allocating send_buf!");
378
379 if ((igmp_socket = socket(AF_INET, SOCK_RAW, IPPROTO_IGMP)) < 0)
380 log(LOG_ERR, errno, "IGMP socket");
381
382 k_hdr_include(TRUE); /* include IP header when sending */
383 k_set_rcvbuf(48*1024); /* lots of input buffering */
384 k_set_ttl(1); /* restrict multicasts to one hop */
385 k_set_loop(FALSE); /* disable multicast loopback */
386
387 ip = (struct ip *)send_buf;
388 ip->ip_hl = sizeof(struct ip) >> 2;
389 ip->ip_v = IPVERSION;
390 ip->ip_tos = 0;
391 ip->ip_off = 0;
392 ip->ip_p = IPPROTO_IGMP;
393 ip->ip_ttl = MAXTTL; /* applies to unicasts only */
394
395#ifndef INADDR_ALLRTRS_GROUP
396#define INADDR_ALLRTRS_GROUP 0xe0000002 /* 224.0.0.2 */
397#endif
398 allrtrs_group = htonl(INADDR_ALLRTRS_GROUP);
399
400 router_alert[0] = IPOPT_RA; /* Router Alert */
401 router_alert[1] = 4; /* 4 bytes */
402 router_alert[2] = 0;
403 router_alert[3] = 0;
404}
405
406#ifdef SUNOS5
407void
33745200 408checkforsolarisbug(void)
984263bc
MD
409{
410 u_int32 localhost = htonl(0x7f000001);
411
412 eol[0] = IPOPT_EOL;
413 eol[1] = IPOPT_EOL;
414 eol[2] = IPOPT_EOL;
415 eol[3] = IPOPT_EOL;
416
417 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS, eol, sizeof(eol));
418 /*
419 * Check if the kernel adds the options length to the packet
420 * length. Send myself an IGMP packet of type 0 (illegal),
421 * with 4 IPOPT_EOL options, my PID (for collision detection)
422 * and 4 bytes of zero (so that the checksum works whether
423 * the 4 bytes of zero get truncated or not).
424 */
425 bzero(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN, 8);
426 *(int *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN) = getpid();
427 send_igmp(localhost, localhost, 0, 0, 0, 8);
428 while (1) {
429 int recvlen, dummy = 0;
430
431 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
432 0, NULL, &dummy);
433 /* 8 == 4 bytes of options and 4 bytes of PID */
434 if (recvlen >= MIN_IP_HEADER_LEN + IGMP_MINLEN + 8) {
435 struct ip *ip = (struct ip *)recv_buf;
436 struct igmp *igmp;
437 int *p;
438
439 if (ip->ip_hl != 6 ||
440 ip->ip_p != IPPROTO_IGMP ||
441 ip->ip_src.s_addr != localhost ||
442 ip->ip_dst.s_addr != localhost)
443 continue;
444
445 igmp = (struct igmp *)(recv_buf + (ip->ip_hl << 2));
446 if (igmp->igmp_group.s_addr != 0)
447 continue;
448 if (igmp->igmp_type != 0 || igmp->igmp_code != 0)
449 continue;
450
451 p = (int *)((char *)igmp + IGMP_MINLEN);
452 if (*p != getpid())
453 continue;
454
455#ifdef RAW_INPUT_IS_RAW
456 ip->ip_len = ntohs(ip->ip_len);
457#endif
458 if (ip->ip_len == IGMP_MINLEN + 4)
459 ip_addlen = 4;
460 else if (ip->ip_len == IGMP_MINLEN + 8)
461 ip_addlen = 0;
462 else
463 log(LOG_ERR, 0, "while checking for Solaris bug: Sent %d bytes and got back %d!", IGMP_MINLEN + 8, ip->ip_len);
464
465 break;
466 }
467 }
468}
469#endif
470
471/*
472 * Construct an IGMP message in the output packet buffer. The caller may
473 * have already placed data in that buffer, of length 'datalen'. Then send
474 * the message from the interface with IP address 'src' to destination 'dst'.
475 */
476void
33745200
MD
477send_igmp(u_int32 src, u_int32 dst, int type, int code, u_int32 group,
478 int datalen)
984263bc
MD
479{
480 struct sockaddr_in sdst;
481 struct ip *ip;
482 struct igmp *igmp;
483 int setloop = 0;
484 static int raset = 0;
485 int sendra = 0;
486 int sendlen;
487
488 ip = (struct ip *)send_buf;
489 ip->ip_src.s_addr = src;
490 ip->ip_dst.s_addr = dst;
491 ip->ip_len = MIN_IP_HEADER_LEN + IGMP_MINLEN + datalen;
492 sendlen = ip->ip_len;
493#ifdef SUNOS5
494 ip->ip_len += ip_addlen;
495#endif
496#ifdef RAW_OUTPUT_IS_RAW
497 ip->ip_len = htons(ip->ip_len);
498#endif
499
500 igmp = (struct igmp *)(send_buf + MIN_IP_HEADER_LEN);
501 igmp->igmp_type = type;
502 igmp->igmp_code = code;
503 igmp->igmp_group.s_addr = group;
504 igmp->igmp_cksum = 0;
505 igmp->igmp_cksum = inet_cksum((u_short *)igmp,
506 IGMP_MINLEN + datalen);
507
508 if (IN_MULTICAST(ntohl(dst))) {
509 k_set_if(src);
510 setloop = 1;
511 k_set_loop(TRUE);
512 if (dst != allrtrs_group)
513 sendra = 1;
514 }
515
516 if (sendopts && sendra && !raset) {
517 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
518 router_alert, sizeof(router_alert));
519 raset = 1;
520 } else if (!sendra && raset) {
521#ifdef SUNOS5
522 /*
523 * SunOS5 < 5.6 cannot properly reset the IP_OPTIONS "socket"
524 * option. Instead, set up a string of 4 EOL's.
525 */
526 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
527 eol, sizeof(eol));
528#else
529 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
530 NULL, 0);
531#endif
532 raset = 0;
533 }
534
535 bzero(&sdst, sizeof(sdst));
536 sdst.sin_family = AF_INET;
537#if (defined(BSD) && (BSD >= 199103))
538 sdst.sin_len = sizeof(sdst);
539#endif
540 sdst.sin_addr.s_addr = dst;
541 if (sendto(igmp_socket, send_buf, sendlen, 0,
542 (struct sockaddr *)&sdst, sizeof(sdst)) < 0) {
543 log(LOG_WARNING, errno, "sendto to %s on %s",
544 inet_fmt(dst, s1), inet_fmt(src, s2));
545 }
546
547 if (setloop)
548 k_set_loop(FALSE);
549
550 log(LOG_DEBUG, 0, "SENT %s from %-15s to %s",
551 type == IGMP_MTRACE ? "mtrace request" : "ask_neighbors",
552 src == INADDR_ANY ? "INADDR_ANY" : inet_fmt(src, s1),
553 inet_fmt(dst, s2));
554}
555
556/*
557 * inet_cksum extracted from:
558 * P I N G . C
559 *
560 * Author -
561 * Mike Muuss
562 * U. S. Army Ballistic Research Laboratory
563 * December, 1983
564 * Modified at Uc Berkeley
565 *
566 * (ping.c) Status -
567 * Public Domain. Distribution Unlimited.
568 *
569 * I N _ C K S U M
570 *
571 * Checksum routine for Internet Protocol family headers (C Version)
572 *
573 */
574int
33745200 575inet_cksum(u_short *addr, u_int len)
984263bc 576{
33745200
MD
577 int nleft = (int)len;
578 u_short *w = addr;
984263bc 579 u_short answer = 0;
33745200 580 int sum = 0;
984263bc
MD
581
582 /*
583 * Our algorithm is simple, using a 32 bit accumulator (sum),
584 * we add sequential 16 bit words to it, and at the end, fold
585 * back all the carry bits from the top 16 bits into the lower
586 * 16 bits.
587 */
588 while (nleft > 1) {
589 sum += *w++;
590 nleft -= 2;
591 }
592
593 /* mop up an odd byte, if necessary */
594 if (nleft == 1) {
595 *(u_char *) (&answer) = *(u_char *)w ;
596 sum += answer;
597 }
598
599 /*
600 * add back carry outs from top 16 bits to low 16 bits
601 */
602 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
603 sum += (sum >> 16); /* add carry */
604 answer = ~sum; /* truncate to 16 bits */
605 return (answer);
606}
607
608void
33745200 609k_set_rcvbuf(int bufsize)
984263bc
MD
610{
611 if (setsockopt(igmp_socket, SOL_SOCKET, SO_RCVBUF,
612 (char *)&bufsize, sizeof(bufsize)) < 0)
613 log(LOG_ERR, errno, "setsockopt SO_RCVBUF %u", bufsize);
614}
615
616
617void
5fe88d64 618k_hdr_include(int boolv)
984263bc
MD
619{
620#ifdef IP_HDRINCL
621 if (setsockopt(igmp_socket, IPPROTO_IP, IP_HDRINCL,
5fe88d64
MD
622 (char *)&boolv, sizeof(boolv)) < 0)
623 log(LOG_ERR, errno, "setsockopt IP_HDRINCL %u", boolv);
984263bc
MD
624#endif
625}
626
627void
33745200 628k_set_ttl(int t)
984263bc
MD
629{
630 u_char ttl;
631
632 ttl = t;
633 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_TTL,
634 (char *)&ttl, sizeof(ttl)) < 0)
635 log(LOG_ERR, errno, "setsockopt IP_MULTICAST_TTL %u", ttl);
636}
637
638
639void
33745200 640k_set_loop(int l)
984263bc
MD
641{
642 u_char loop;
643
644 loop = l;
645 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_LOOP,
646 (char *)&loop, sizeof(loop)) < 0)
647 log(LOG_ERR, errno, "setsockopt IP_MULTICAST_LOOP %u", loop);
648}
649
650void
33745200 651k_set_if(u_int32 ifa)
984263bc
MD
652{
653 struct in_addr adr;
654
655 adr.s_addr = ifa;
656 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_IF,
657 (char *)&adr, sizeof(adr)) < 0)
658 log(LOG_ERR, errno, "setsockopt IP_MULTICAST_IF %s",
659 inet_fmt(ifa, s1));
660}
661
662void
33745200 663k_join(u_int32 grp, u_int32 ifa)
984263bc
MD
664{
665 struct ip_mreq mreq;
666
667 mreq.imr_multiaddr.s_addr = grp;
668 mreq.imr_interface.s_addr = ifa;
669
670 if (setsockopt(igmp_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
671 (char *)&mreq, sizeof(mreq)) < 0)
672 log(LOG_WARNING, errno, "can't join group %s on interface %s",
673 inet_fmt(grp, s1), inet_fmt(ifa, s2));
674}
675
676
677void
33745200 678k_leave(u_int32 grp, u_int32 ifa)
984263bc
MD
679{
680 struct ip_mreq mreq;
681
682 mreq.imr_multiaddr.s_addr = grp;
683 mreq.imr_interface.s_addr = ifa;
684
685 if (setsockopt(igmp_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
686 (char *)&mreq, sizeof(mreq)) < 0)
687 log(LOG_WARNING, errno, "can't leave group %s on interface %s",
688 inet_fmt(grp, s1), inet_fmt(ifa, s2));
689}
690
691/*
692 * Convert an IP address in u_long (network) format into a printable string.
693 */
694char *
33745200 695inet_fmt(u_int32 addr, char *s)
984263bc 696{
33745200 697 u_char *a;
984263bc
MD
698
699 a = (u_char *)&addr;
700 sprintf(s, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
701 return (s);
702}
703
704
705/*
706 * Convert an IP subnet number in u_long (network) format into a printable
707 * string including the netmask as a number of bits.
708 */
709char *
33745200 710inet_fmts(u_int32 addr, u_int32 mask, char *s)
984263bc 711{
33745200 712 u_char *a, *m;
984263bc
MD
713 int bits;
714
715 if ((addr == 0) && (mask == 0)) {
716 sprintf(s, "default");
717 return (s);
718 }
719 a = (u_char *)&addr;
720 m = (u_char *)&mask;
721 bits = 33 - ffs(ntohl(mask));
722
723 if (m[3] != 0) sprintf(s, "%u.%u.%u.%u/%d", a[0], a[1], a[2], a[3],
724 bits);
725 else if (m[2] != 0) sprintf(s, "%u.%u.%u/%d", a[0], a[1], a[2], bits);
726 else if (m[1] != 0) sprintf(s, "%u.%u/%d", a[0], a[1], bits);
727 else sprintf(s, "%u/%d", a[0], bits);
728
729 return (s);
730}
731
fd0e91da
SW
732char *
733inet_name(u_int32 addr)
984263bc
MD
734{
735 struct hostent *e;
736
15b85273 737 e = gethostbyaddr(&addr, sizeof(addr), AF_INET);
984263bc
MD
738
739 return e ? e->h_name : "?";
740}
741
742
743u_int32
33745200 744host_addr(char *name)
984263bc
MD
745{
746 struct hostent *e = (struct hostent *)0;
747 u_int32 addr;
748 int i, dots = 3;
749 char buf[40];
750 char *ip = name;
751 char *op = buf;
752
753 /*
754 * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
755 * if the name is all numeric.
756 */
757 for (i = sizeof(buf) - 7; i > 0; --i) {
758 if (*ip == '.') --dots;
759 else if (*ip == '\0') break;
760 else if (!isdigit(*ip)) dots = 0; /* Not numeric, don't add zeroes */
761 *op++ = *ip++;
762 }
763 for (i = 0; i < dots; ++i) {
764 *op++ = '.';
765 *op++ = '0';
766 }
767 *op = '\0';
768
769 if (dots <= 0)
770 e = gethostbyname(name);
771 if (e && (e->h_length == sizeof(addr))) {
772 memcpy((char *)&addr, e->h_addr_list[0], e->h_length);
773 if (e->h_addr_list[1])
774 fprintf(stderr, "Warning: %s has multiple addresses, using %s\n",
775 name, inet_fmt(addr, s1));
776 } else {
777 addr = inet_addr(buf);
778 if (addr == -1 || (IN_MULTICAST(addr) && dots)) {
779 addr = 0;
780 printf("Could not parse %s as host name or address\n", name);
781 }
782 }
783 return addr;
784}
785
786
787char *
33745200 788proto_type(u_int type)
984263bc
MD
789{
790 static char buf[80];
791
792 switch (type) {
793 case PROTO_DVMRP:
794 return ("DVMRP");
795 case PROTO_MOSPF:
796 return ("MOSPF");
797 case PROTO_PIM:
798 return ("PIM");
799 case PROTO_CBT:
800 return ("CBT");
801 case PROTO_PIM_SPECIAL:
802 return ("PIM/Special");
803 case PROTO_PIM_STATIC:
804 return ("PIM/Static");
805 case PROTO_DVMRP_STATIC:
806 return ("DVMRP/Static");
807 case PROTO_PIM_BGP4PLUS:
808 return ("PIM/BGP4+");
809 case PROTO_CBT_SPECIAL:
810 return ("CBT/Special");
811 case PROTO_CBT_STATIC:
812 return ("CBT/Static");
813 case PROTO_PIM_ASSERT:
814 return ("PIM/Assert");
815 case 0:
816 return ("None");
817 default:
71126e33 818 sprintf(buf, "Unknown protocol code %d", type);
984263bc
MD
819 return (buf);
820 }
821}
822
823
824char *
33745200 825flag_type(u_int type)
984263bc
MD
826{
827 static char buf[80];
828
829 switch (type) {
830 case TR_NO_ERR:
831 return ("");
832 case TR_WRONG_IF:
833 return ("Wrong interface");
834 case TR_PRUNED:
835 return ("Prune sent upstream");
836 case TR_OPRUNED:
837 return ("Output pruned");
838 case TR_SCOPED:
839 return ("Hit scope boundary");
840 case TR_NO_RTE:
841 return ("No route");
842 case TR_NO_FWD:
843 return ("Not forwarding");
844 case TR_HIT_RP:
845 return ("Reached RP/Core");
846 case TR_RPF_IF:
847 return ("RPF Interface");
848 case TR_NO_MULTI:
849 return ("Multicast disabled");
850 case TR_OLD_ROUTER:
851 return ("Next router no mtrace");
852 case TR_NO_SPACE:
853 return ("No space in packet");
854 case TR_ADMIN_PROHIB:
855 return ("Admin. Prohibited");
856 default:
71126e33 857 sprintf(buf, "Unknown error code %d", type);
984263bc
MD
858 return (buf);
859 }
860}
861
862/*
863 * If destination is on a local net, get the netmask, else set the
864 * netmask to all ones. There are two side effects: if the local
865 * address was not explicitly set, and if the destination is on a
866 * local net, use that one; in either case, verify that the local
867 * address is valid.
868 */
869u_int32
33745200 870get_netmask(int s, u_int32 *dst)
984263bc
MD
871{
872 unsigned int n;
873 struct ifconf ifc;
874 struct ifreq *ifrp, *ifend;
875 u_int32 if_addr, if_mask;
876 u_int32 retval = 0xFFFFFFFF;
877 int found = FALSE;
878 int num_ifreq = 32;
879
880 ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
881 ifc.ifc_buf = malloc(ifc.ifc_len);
882 while (ifc.ifc_buf) {
883 if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) {
884 perror("ioctl SIOCGIFCONF");
885 return retval;
886 }
887
888 /*
889 * If the buffer was large enough to hold all the addresses
890 * then break out, otherwise increase the buffer size and
891 * try again.
892 *
893 * The only way to know that we definitely had enough space
894 * is to know that there was enough space for at least one
895 * more struct ifreq. ???
896 */
897 if ((num_ifreq * sizeof(struct ifreq)) >=
898 ifc.ifc_len + sizeof(struct ifreq))
899 break;
900
901 num_ifreq *= 2;
902 ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
903 ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
904 }
905 if (ifc.ifc_buf == NULL) {
906 fprintf(stderr, "getting interface list: ran out of memory");
907 exit(1);
908 }
909
910 ifrp = (struct ifreq *)ifc.ifc_buf;
911 ifend = (struct ifreq *)(ifc.ifc_buf + ifc.ifc_len);
912 /*
913 * Loop through all of the interfaces.
914 */
915 for (; ifrp < ifend && !found; ifrp = (struct ifreq *)((char *)ifrp + n)) {
916#if BSD >= 199006
917 n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
918 if (n < sizeof(*ifrp))
919 n = sizeof(*ifrp);
920#else
921 n = sizeof(*ifrp);
922#endif
923 /*
924 * Ignore any interface for an address family other than IP.
925 */
926 if (ifrp->ifr_addr.sa_family != AF_INET)
927 continue;
928
929 if_addr = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
930 if (ioctl(s, SIOCGIFFLAGS, (char *)ifrp) < 0) {
931 fprintf(stderr, "SIOCGIFFLAGS on ");
932 perror(ifrp->ifr_name);
933 continue;
934 }
935 if ((ifrp->ifr_flags & (IFF_MULTICAST|IFF_UP|IFF_LOOPBACK)) !=
936 (IFF_MULTICAST|IFF_UP))
937 continue;
938 if (*dst == 0)
939 *dst = if_addr;
940 if (ioctl(s, SIOCGIFNETMASK, (char *)ifrp) >= 0) {
941 if_mask = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
942 if (if_mask != 0 && (*dst & if_mask) == (if_addr & if_mask)) {
943 retval = if_mask;
944 if (lcl_addr == 0) lcl_addr = if_addr; /* XXX what about aliases? */
945 }
946 }
947 if (lcl_addr == if_addr) found = TRUE;
948 }
949 if (!found && lcl_addr != 0) {
950 printf("Interface address is not valid\n");
951 exit(1);
952 }
953 return (retval);
954}
955
956
957/*
958 * Try to pick a TTL that will get past all the thresholds in the path.
959 */
960int
33745200 961get_ttl(struct resp_buf *buf)
984263bc
MD
962{
963 int rno;
964 struct tr_resp *b;
965 u_int ttl;
966
967 if (buf && (rno = buf->len) > 0) {
968 b = buf->resps + rno - 1;
969 ttl = b->tr_fttl;
970
971 while (--rno > 0) {
972 --b;
973 if (ttl < b->tr_fttl) ttl = b->tr_fttl;
974 else ++ttl;
975 }
976 ttl += MULTICAST_TTL_INC;
977 if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
978 if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
979 return (ttl);
980 } else return(MULTICAST_TTL1);
981}
982
983/*
984 * Calculate the difference between two 32-bit NTP timestamps and return
985 * the result in milliseconds.
986 */
987int
33745200 988t_diff(u_long a, u_long b)
984263bc
MD
989{
990 int d = a - b;
991
992 return ((d * 125) >> 13);
993}
994
995/*
996 * Swap bytes for poor little-endian machines that don't byte-swap
997 */
998u_long
33745200 999byteswap(u_long v)
984263bc
MD
1000{
1001 return ((v << 24) | ((v & 0xff00) << 8) |
1002 ((v >> 8) & 0xff00) | (v >> 24));
1003}
1004
1005#if 0
1006/*
1007 * XXX incomplete - need private callback data, too?
1008 * XXX since dst doesn't get passed through?
1009 */
1010int
33745200
MD
1011neighbors_callback(int tmo, u_char *buf, int buflen, struct igmp *igmp,
1012 int igmplen, struct sockaddr *addr, int *addrlen,
1013 struct timeval *ts)
984263bc
MD
1014{
1015 int len;
1016 u_int32 dst;
1017 struct ip *ip = (struct ip *)buf;
1018
1019 if (tmo)
1020 return 0;
1021
1022 if (igmp->igmp_code != DVMRP_NEIGHBORS2)
1023 return 0;
1024 len = igmplen;
1025 /*
1026 * Accept DVMRP_NEIGHBORS2 response if it comes from the
1027 * address queried or if that address is one of the local
1028 * addresses in the response.
1029 */
1030 if (ip->ip_src.s_addr != dst) {
1031 u_int32 *p = (u_int32 *)(igmp + 1);
1032 u_int32 *ep = p + (len >> 2);
1033 while (p < ep) {
1034 u_int32 laddr = *p++;
1035 int n = ntohl(*p++) & 0xFF;
1036 if (laddr == dst) {
1037 ep = p + 1; /* ensure p < ep after loop */
1038 break;
1039 }
1040 p += n;
1041 }
1042 if (p >= ep)
1043 return 0;
1044 }
1045 return buflen;
1046}
1047#endif
1048
1049int
33745200
MD
1050mtrace_callback(int tmo, u_char *buf, int buflen, struct igmp *igmp,
1051 int igmplen, struct sockaddr *addr, int *addrlen,
1052 struct timeval *ts)
984263bc
MD
1053{
1054 static u_char *savbuf = NULL;
1055 static int savbuflen;
1056 static struct sockaddr *savaddr;
1057 static int savaddrlen;
1058 static struct timeval savts;
1059
1060 int len = (igmplen - QLEN) / RLEN;
1061 struct tr_resp *r = (struct tr_resp *)((struct tr_query *)(igmp + 1) + 1);
1062
1063 if (tmo == 1) {
1064 /*
1065 * If we timed out with a packet saved, then return that packet.
1066 * send_recv won't send this same packet to the callback again.
1067 */
1068 if (savbuf) {
1069 bcopy(savbuf, buf, savbuflen);
1070 free(savbuf);
1071 savbuf = NULL;
1072 bcopy(savaddr, addr, savaddrlen);
1073 free(savaddr);
1074 *addrlen = savaddrlen;
1075 bcopy(&savts, ts, sizeof(savts));
1076 return savbuflen;
1077 }
1078 return 0;
1079 }
1080 if (savbuf) {
1081 free(savbuf);
1082 savbuf = NULL;
1083 free(savaddr);
1084 }
1085 /*
1086 * Check for IOS bug described in CSCdi68628, where a router that does
1087 * not have multicast enabled responds to an mtrace request with a 1-hop
1088 * error packet.
1089 * Heuristic is:
1090 * If there is only one hop reported in the packet,
1091 * And the protocol code is 0,
1092 * And there is no previous hop,
1093 * And the forwarding information is "Not Forwarding",
1094 * And the router is not on the same subnet as the destination of the
1095 * trace,
1096 * then drop this packet. The "#if 0"'d code saves it and returns
1097 * it on timeout, but timeouts are too common (e.g. routers with
1098 * limited unicast routing tables, etc).
1099 */
1100 if (len == 1 && r->tr_rproto == 0 && r->tr_rmtaddr == 0 &&
1101 r->tr_rflags == TR_NO_FWD) {
1102 u_int32 smask;
1103
1104 VAL_TO_MASK(smask, r->tr_smask);
1105 if ((r->tr_outaddr & smask) != (qdst & smask)) {
1106#if 0
1107 /* XXX should do this silently? */
1108 fprintf(stderr, "mtrace: probably IOS-buggy packet from %s\n",
1109 inet_fmt(((struct sockaddr_in *)addr)->sin_addr.s_addr, s1));
1110 /* Save the packet to return if a timeout occurs. */
1111 savbuf = (u_char *)malloc(buflen);
1112 if (savbuf != NULL) {
1113 bcopy(buf, savbuf, buflen);
1114 savbuflen = buflen;
1115 savaddr = (struct sockaddr *)malloc(*addrlen);
1116 if (savaddr != NULL) {
1117 bcopy(addr, savaddr, *addrlen);
1118 savaddrlen = *addrlen;
1119 bcopy(ts, &savts, sizeof(savts));
1120 } else {
1121 free(savbuf);
1122 savbuf = NULL;
1123 }
1124 }
1125#endif
1126 return 0;
1127 }
1128 }
1129 return buflen;
1130}
1131
1132int
33745200
MD
1133send_recv(u_int32 dst, int type, int code, int tries, struct resp_buf *save,
1134 callback_t callback)
984263bc
MD
1135{
1136 fd_set fds;
1137 struct timeval tq, tr, tv;
1138 struct ip *ip;
1139 struct igmp *igmp;
1140 struct tr_query *query, *rquery;
1141 struct tr_resp *r;
1142 struct sockaddr_in recvaddr;
1143 u_int32 local, group;
1144 int ipdatalen, iphdrlen, igmpdatalen;
1145 int datalen;
1146 int count, recvlen, socklen = sizeof(recvaddr);
1147 int len;
1148 int i;
1149
1150 if (type == IGMP_MTRACE) {
1151 group = qgrp;
1152 datalen = sizeof(struct tr_query);
1153 } else {
1154 group = htonl(0xff03);
1155 datalen = 0;
1156 }
1157 if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
1158 else local = INADDR_ANY;
1159
1160 /*
1161 * If the reply address was not explictly specified, start off
1162 * with the standard multicast reply address, or the unicast
1163 * address of this host if the unicast flag was specified.
1164 * Then, if there is no response after trying half the tries
1165 * with multicast, switch to the unicast address of this host
1166 * if the multicast flag was not specified. If the TTL was
1167 * also not specified, set a multicast TTL and increase it
1168 * for every try.
1169 */
1170 query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
1171 query->tr_raddr = raddr ? raddr : unicast ? lcl_addr : resp_cast;
1172 TR_SETTTL(query->tr_rttlqid, rttl ? rttl :
1173 IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL);
1174 query->tr_src = qsrc;
1175 query->tr_dst = qdst;
1176
1177 for (i = tries ; i > 0; --i) {
1178 int oqid;
1179
1180 if (tries == nqueries && raddr == 0) {
1181 if (i == (nqueries >> 1)) {
1182 if (multicast && unicast) {
1183 query->tr_raddr = resp_cast;
1184 if (!rttl)
1185 TR_SETTTL(query->tr_rttlqid, get_ttl(save));
1186 } else if (!multicast) {
1187 query->tr_raddr = lcl_addr;
1188 TR_SETTTL(query->tr_rttlqid, UNICAST_TTL);
1189 }
1190 }
1191 if (i < tries && IN_MULTICAST(ntohl(query->tr_raddr)) &&
1192 rttl == 0) {
1193 TR_SETTTL(query->tr_rttlqid,
1194 TR_GETTTL(query->tr_rttlqid) + MULTICAST_TTL_INC);
1195 if (TR_GETTTL(query->tr_rttlqid) > MULTICAST_TTL_MAX)
1196 TR_SETTTL(query->tr_rttlqid, MULTICAST_TTL_MAX);
1197 }
1198 }
1199
1200 /*
1201 * Change the qid for each request sent to avoid being confused
1202 * by duplicate responses
1203 */
1204 oqid = TR_GETQID(query->tr_rttlqid);
1205 if (staticqid)
1206 TR_SETQID(query->tr_rttlqid, staticqid);
1207 else
1208#ifdef SYSV
1209 TR_SETQID(query->tr_rttlqid, ((u_int32)lrand48() >> 8));
1210#else
1211 TR_SETQID(query->tr_rttlqid, ((u_int32)arc4random() >> 8));
1212#endif
1213
1214 /*
1215 * Set timer to calculate delays, then send query
1216 */
1217 gettimeofday(&tq, 0);
1218 send_igmp(local, dst, type, code, group, datalen);
1219
1220 /*
1221 * Wait for response, discarding false alarms
1222 */
1223 while (TRUE) {
1224 if (igmp_socket >= FD_SETSIZE)
1225 log(LOG_ERR, 0, "descriptor too big");
1226 FD_ZERO(&fds);
1227 FD_SET(igmp_socket, &fds);
1228 gettimeofday(&tv, 0);
1229 tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
1230 tv.tv_usec = tq.tv_usec - tv.tv_usec;
1231 if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
1232 if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;
1233
1234 count = select(igmp_socket + 1, &fds, (fd_set *)0, (fd_set *)0,
1235 &tv);
1236
1237 if (count < 0) {
1238 if (errno != EINTR) warn("select");
1239 continue;
1240 } else if (count == 0) {
1241 /*
1242 * Timed out. Notify the callback.
1243 */
1244 if (!callback || (recvlen = (callback)(1, recv_buf, 0, NULL, 0, (struct sockaddr *)&recvaddr, &socklen, &tr)) == 0) {
1245 printf("* ");
1246 fflush(stdout);
1247 break;
1248 }
1249 } else {
1250 /*
1251 * Data is available on the socket, so read it.
1252 */
1253 gettimeofday(&tr, 0);
1254 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1255 0, (struct sockaddr *)&recvaddr, &socklen);
1256 }
1257
1258 if (recvlen <= 0) {
1259 if (recvlen && errno != EINTR) warn("recvfrom");
1260 continue;
1261 }
1262
1263 if (recvlen < sizeof(struct ip)) {
1264 warnx("packet too short (%u bytes) for IP header", recvlen);
1265 continue;
1266 }
1267 ip = (struct ip *) recv_buf;
1268 if (ip->ip_p == 0) /* ignore cache creation requests */
1269 continue;
1270
1271 iphdrlen = ip->ip_hl << 2;
1272#ifdef RAW_INPUT_IS_RAW
1273 ipdatalen = ntohs(ip->ip_len);
1274#else
1275 ipdatalen = ip->ip_len;
1276#endif
1277 if (iphdrlen + ipdatalen != recvlen) {
1278 warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1279 recvlen, iphdrlen, ipdatalen);
1280 continue;
1281 }
1282
1283 igmp = (struct igmp *) (recv_buf + iphdrlen);
1284 igmpdatalen = ipdatalen - IGMP_MINLEN;
1285 if (igmpdatalen < 0) {
1286 warnx("IP data field too short (%u bytes) for IGMP from %s",
1287 ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1288 continue;
1289 }
1290
1291 switch (igmp->igmp_type) {
1292
1293 case IGMP_DVMRP:
1294 if (type != IGMP_DVMRP || code != DVMRP_ASK_NEIGHBORS2)
1295 continue;
1296 if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
1297 len = igmpdatalen;
1298 /*
1299 * Accept DVMRP_NEIGHBORS2 response if it comes from the
1300 * address queried or if that address is one of the local
1301 * addresses in the response.
1302 */
1303 if (ip->ip_src.s_addr != dst) {
1304 u_int32 *p = (u_int32 *)(igmp + 1);
1305 u_int32 *ep = p + (len >> 2);
1306 while (p < ep) {
1307 u_int32 laddr = *p++;
1308 int n = ntohl(*p++) & 0xFF;
1309 if (laddr == dst) {
1310 ep = p + 1; /* ensure p < ep after loop */
1311 break;
1312 }
1313 p += n;
1314 }
1315 if (p >= ep) continue;
1316 }
1317 break;
1318
1319 case IGMP_MTRACE: /* For backward compatibility with 3.3 */
1320 case IGMP_MTRACE_RESP:
1321 if (type != IGMP_MTRACE) continue;
1322 if (igmpdatalen <= QLEN) continue;
1323 if ((igmpdatalen - QLEN)%RLEN) {
1324 printf("packet with incomplete responses (%d bytes)\n",
1325 igmpdatalen);
1326 continue;
1327 }
1328
1329 /*
1330 * Ignore responses that don't match query.
1331 */
1332 rquery = (struct tr_query *)(igmp + 1);
1333 if (rquery->tr_src != qsrc || rquery->tr_dst != qdst)
1334 continue;
1335 if (TR_GETQID(rquery->tr_rttlqid) !=
1336 TR_GETQID(query->tr_rttlqid)) {
1337 if (verbose && TR_GETQID(rquery->tr_rttlqid) == oqid)
1338 printf("[D]");
1339 continue;
1340 }
1341 len = (igmpdatalen - QLEN)/RLEN;
1342 r = (struct tr_resp *)(rquery+1) + len - 1;
1343
1344 /*
1345 * Ignore trace queries passing through this node when
1346 * mtrace is run on an mrouter that is in the path
1347 * (needed only because IGMP_MTRACE is accepted above
1348 * for backward compatibility with multicast release 3.3).
1349 */
1350 if (igmp->igmp_type == IGMP_MTRACE) {
1351 u_int32 smask;
1352
1353 VAL_TO_MASK(smask, r->tr_smask);
1354 if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
1355 && r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
1356 continue;
1357 }
1358 /*
1359 * Some routers will return error messages without
1360 * filling in their addresses. We fill in the address
1361 * for them.
1362 */
1363 if (r->tr_outaddr == 0)
1364 r->tr_outaddr = recvaddr.sin_addr.s_addr;
1365
1366 /*
1367 * A match, we'll keep this one.
1368 */
1369 if (len > code) {
1370 warnx("num hops received (%d) exceeds request (%d)",
1371 len, code);
1372 }
1373 rquery->tr_raddr = query->tr_raddr; /* Insure these are */
1374 TR_SETTTL(rquery->tr_rttlqid, TR_GETTTL(query->tr_rttlqid));
1375 /* as we sent them */
1376 break;
1377
1378 default:
1379 continue;
1380 }
1381
1382 /*
1383 * We're pretty sure we want to use this packet now,
1384 * but if the caller gave a callback function, it might
1385 * want to handle it instead. Give the callback a chance,
1386 * unless the select timed out (in which case the only way
1387 * to get here is because the callback returned a packet).
1388 */
1389 if (callback && (count != 0) && ((callback)(0, recv_buf, recvlen, igmp, igmpdatalen, (struct sockaddr*)&recvaddr, &socklen, &tr)) == 0) {
1390 /*
1391 * The callback function didn't like this packet.
1392 * Go try receiving another one.
1393 */
1394 continue;
1395 }
1396
1397 /*
1398 * Most of the sanity checking done at this point.
1399 * Return this packet we have been waiting for.
1400 */
1401 if (save) {
1402 save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
1403 (tq.tv_usec << 10) / 15625;
1404 save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
1405 (tr.tv_usec << 10) / 15625;
1406 save->len = len;
1407 bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
1408 }
1409 return (recvlen);
1410 }
1411 }
1412 return (0);
1413}
1414
1415/*
1416 * Most of this code is duplicated elsewhere. I'm not sure if
1417 * the duplication is absolutely required or not.
1418 *
1419 * Ideally, this would keep track of ongoing statistics
1420 * collection and print out statistics. (& keep track
1421 * of h-b-h traces and only print the longest) For now,
1422 * it just snoops on what traces it can.
1423 */
1424void
33745200 1425passive_mode(void)
984263bc
MD
1426{
1427 struct timeval tr;
1428 time_t tr_sec;
1429 struct ip *ip;
1430 struct igmp *igmp;
1431 struct tr_resp *r;
1432 struct sockaddr_in recvaddr;
1433 struct tm *now;
1434 char timebuf[32];
1435 int socklen;
1436 int ipdatalen, iphdrlen, igmpdatalen;
1437 int len, recvlen;
1438 int qid;
1439 u_int32 smask;
1440 struct mtrace *remembered = NULL, *m, *n, **nn;
1441 int pc = 0;
1442
1443 if (raddr) {
1444 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1445 } else k_join(htonl(0xE0000120), lcl_addr);
1446
1447 while (1) {
1448 fflush(stdout); /* make sure previous trace is flushed */
1449
1450 socklen = sizeof(recvaddr);
1451 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1452 0, (struct sockaddr *)&recvaddr, &socklen);
1453 gettimeofday(&tr,0);
1454
1455 if (recvlen <= 0) {
1456 if (recvlen && errno != EINTR) warn("recvfrom");
1457 continue;
1458 }
1459
1460 if (recvlen < sizeof(struct ip)) {
1461 warnx("packet too short (%u bytes) for IP header", recvlen);
1462 continue;
1463 }
1464 ip = (struct ip *) recv_buf;
1465 if (ip->ip_p == 0) /* ignore cache creation requests */
1466 continue;
1467
1468 iphdrlen = ip->ip_hl << 2;
1469#ifdef RAW_INPUT_IS_RAW
1470 ipdatalen = ntohs(ip->ip_len);
1471#else
1472 ipdatalen = ip->ip_len;
1473#endif
1474 if (iphdrlen + ipdatalen != recvlen) {
1475 warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1476 recvlen, iphdrlen, ipdatalen);
1477 continue;
1478 }
1479
1480 igmp = (struct igmp *) (recv_buf + iphdrlen);
1481 igmpdatalen = ipdatalen - IGMP_MINLEN;
1482 if (igmpdatalen < 0) {
1483 warnx("IP data field too short (%u bytes) for IGMP from %s",
1484 ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1485 continue;
1486 }
1487
1488 switch (igmp->igmp_type) {
1489
1490 case IGMP_MTRACE: /* For backward compatibility with 3.3 */
1491 case IGMP_MTRACE_RESP:
1492 if (igmpdatalen < QLEN) continue;
1493 if ((igmpdatalen - QLEN)%RLEN) {
1494 printf("packet with incorrect datalen\n");
1495 continue;
1496 }
1497
1498 len = (igmpdatalen - QLEN)/RLEN;
1499
1500 break;
1501
1502 default:
1503 continue;
1504 }
1505
1506 base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
1507 (tr.tv_usec << 10) / 15625;
1508 base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
1509 (tr.tv_usec << 10) / 15625;
1510 base.len = len;
1511 bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
1512 /*
1513 * If the user specified which traces to monitor,
1514 * only accept traces that correspond to the
1515 * request
1516 */
1517 if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
1518 (qdst != 0 && qdst != base.qhdr.tr_dst) ||
1519 (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
1520 continue;
1521
1522 /* XXX This should be a hash table */
1523 /* XXX garbage-collection should be more efficient */
1524 for (nn = &remembered, n = *nn, m = 0; n; n = *nn) {
1525 if ((n->base.qhdr.tr_src == base.qhdr.tr_src) &&
1526 (n->base.qhdr.tr_dst == base.qhdr.tr_dst) &&
1527 (n->base.igmp.igmp_group.s_addr == igmp->igmp_group.s_addr)) {
1528 m = n;
1529 m->last = tr;
1530 }
1531 if (tr.tv_sec - n->last.tv_sec > 500) { /* XXX don't hardcode */
1532 *nn = n->next;
1533 free(n);
1534 } else {
1535 nn = &n->next;
1536 }
1537 }
1538
1539 tr_sec = tr.tv_sec;
1540 now = localtime(&tr_sec);
1541 strftime(timebuf, sizeof(timebuf) - 1, "%b %e %k:%M:%S", now);
1542 printf("Mtrace %s at %s",
1543 len == 0 ? "query" :
1544 igmp->igmp_type == IGMP_MTRACE_RESP ? "response" :
1545 "in transit",
1546 timebuf);
1547 if (len == 0)
1548 printf(" by %s", inet_fmt(recvaddr.sin_addr.s_addr, s1));
1549 if (!IN_MULTICAST(base.qhdr.tr_raddr))
1550 printf(", resp to %s", (len == 0 && recvaddr.sin_addr.s_addr == base.qhdr.tr_raddr) ? "same" : inet_fmt(base.qhdr.tr_raddr, s1));
1551 else
1552 printf(", respttl %d", TR_GETTTL(base.qhdr.tr_rttlqid));
1553 printf(", qid %06x\n", qid = TR_GETQID(base.qhdr.tr_rttlqid));
1554 printf("packet from %s to %s\n",
1555 inet_fmt(ip->ip_src.s_addr, s1),
1556 inet_fmt(ip->ip_dst.s_addr, s2));
1557
1558 printf("from %s to %s via group %s (mxhop=%d)\n",
1559 inet_fmt(base.qhdr.tr_dst, s1), inet_fmt(base.qhdr.tr_src, s2),
1560 inet_fmt(igmp->igmp_group.s_addr, s3), igmp->igmp_code);
1561 if (len == 0) {
1562 printf("\n");
1563 continue;
1564 }
1565 r = base.resps + base.len - 1;
1566 /*
1567 * Some routers will return error messages without
1568 * filling in their addresses. We fill in the address
1569 * for them.
1570 */
1571 if (r->tr_outaddr == 0)
1572 r->tr_outaddr = recvaddr.sin_addr.s_addr;
1573
1574 /*
1575 * If there was a previous trace, it see if this is a
1576 * statistics candidate.
1577 */
1578 if (m && base.len == m->base.len &&
1579 !(pc = path_changed(&m->base, &base))) {
1580 /*
1581 * Some mtrace responders send multiple copies of the same
1582 * reply. Skip this packet if it's got the same query-id
1583 * as the last one.
1584 */
1585 if (m->lastqid == qid) {
1586 printf("Skipping duplicate reply\n");
1587 continue;
1588 }
1589
1590 m->lastqid = qid;
1591
1592 ++m->nresp;
1593
1594 bcopy(&base, m->new, sizeof(base));
1595
1596 printf("Results after %d seconds:\n\n",
1597 (int)((m->new->qtime - m->base.qtime) >> 16));
1598 fixup_stats(&m->base, m->prev, m->new, m->bugs);
1599 print_stats(&m->base, m->prev, m->new, m->bugs, m->names);
1600 m->prev = m->new;
1601 m->new = &m->incr[(m->nresp & 1)];
1602
1603 continue;
1604 }
1605
1606 if (m == NULL) {
1607 m = (struct mtrace *)malloc(sizeof(struct mtrace));
1608 if (m == NULL) {
1609 fprintf(stderr, "Out of memory!\n");
1610 continue;
1611 }
1612 bzero(m, sizeof(struct mtrace));
1613 m->next = remembered;
1614 remembered = m;
1615 bcopy(&tr, &m->last, sizeof(tr));
1616 }
1617
1618 /* Either it's a hop-by-hop in progress, or the path changed. */
1619 if (pc) {
1620 printf("[Path Changed...]\n");
1621 bzero(m->bugs, sizeof(m->bugs));
1622 }
1623 bcopy(&base, &m->base, sizeof(base));
1624 m->prev = &m->base;
1625 m->new = &m->incr[0];
1626 m->nresp = 0;
1627
1628 printf(" 0 ");
1629 print_host(base.qhdr.tr_dst);
1630 printf("\n");
1631 print_trace(1, &base, m->names);
1632 VAL_TO_MASK(smask, r->tr_smask);
1633 if ((r->tr_inaddr & smask) == (base.qhdr.tr_src & smask)) {
1634 printf("%3d ", -(base.len+1));
1635 print_host(base.qhdr.tr_src);
1636 printf("\n");
1637 } else if (r->tr_rmtaddr != 0) {
1638 printf("%3d ", -(base.len+1));
1639 print_host(r->tr_rmtaddr);
1640 printf(" %s\n", r->tr_rflags == TR_OLD_ROUTER ?
1641 "doesn't support mtrace"
1642 : "is the next hop");
1643 }
1644 printf("\n");
1645 }
1646}
1647
1648char *
33745200 1649print_host(u_int32 addr)
984263bc
MD
1650{
1651 return print_host2(addr, 0);
1652}
1653
1654/*
1655 * On some routers, one interface has a name and the other doesn't.
1656 * We always print the address of the outgoing interface, but can
1657 * sometimes get the name from the incoming interface. This might be
1658 * confusing but should be slightly more helpful than just a "?".
1659 */
1660char *
33745200 1661print_host2(u_int32 addr1, u_int32 addr2)
984263bc
MD
1662{
1663 char *name;
1664
1665 if (numeric) {
1666 printf("%s", inet_fmt(addr1, s1));
1667 return ("");
1668 }
1669 name = inet_name(addr1);
1670 if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
1671 name = inet_name(addr2);
1672 printf("%s (%s)", name, inet_fmt(addr1, s1));
1673 return (name);
1674}
1675
1676/*
1677 * Print responses as received (reverse path from dst to src)
1678 */
1679void
33745200 1680print_trace(int idx, struct resp_buf *buf, char **names)
984263bc
MD
1681{
1682 struct tr_resp *r;
1683 char *name;
1684 int i;
1685 int hop;
1686 char *ms;
1687
1688 i = abs(idx);
1689 r = buf->resps + i - 1;
1690
1691 for (; i <= buf->len; ++i, ++r) {
1692 if (idx > 0) printf("%3d ", -i);
1693 name = print_host2(r->tr_outaddr, r->tr_inaddr);
1694 if (r->tr_rflags != TR_NO_RTE)
1695 printf(" %s thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
1696 if (verbose) {
1697 hop = t_diff(ntohl(r->tr_qarr), buf->qtime);
1698 ms = scale(&hop);
1699 printf(" %d%s", hop, ms);
1700 }
1701 printf(" %s", flag_type(r->tr_rflags));
1702 if (i > 1 && r->tr_outaddr != (r-1)->tr_rmtaddr) {
1703 printf(" !RPF!");
1704 print_host((r-1)->tr_rmtaddr);
1705 }
1706 if (r->tr_rflags != TR_NO_RTE) {
1707 if (r->tr_smask <= 1) /* MASK_TO_VAL() returns 1 for default */
1708 printf(" [default]");
1709 else if (verbose) {
1710 u_int32 smask;
1711
1712 VAL_TO_MASK(smask, r->tr_smask);
1713 printf(" [%s]", inet_fmts(buf->qhdr.tr_src & smask,
1714 smask, s1));
1715 }
1716 }
1717 printf("\n");
1718 if (names[i-1])
1719 free(names[i-1]);
1720 names[i-1]=malloc(strlen(name) + 1);
1721 strcpy(names[i-1], name);
1722 }
1723}
1724
1725/*
1726 * See what kind of router is the next hop
1727 */
1728int
33745200 1729what_kind(struct resp_buf *buf, char *why)
984263bc
MD
1730{
1731 u_int32 smask;
1732 int retval;
1733 int hops = buf->len;
1734 struct tr_resp *r = buf->resps + hops - 1;
1735 u_int32 next = r->tr_rmtaddr;
1736
1737 retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL);
1738 print_host(next);
1739 if (retval) {
1740 u_int32 version = ntohl(incr[0].igmp.igmp_group.s_addr);
1741 u_int32 *p = (u_int32 *)incr[0].ndata;
1742 u_int32 *ep = p + (incr[0].len >> 2);
1743 char *type = "version ";
1744
1745 retval = 0;
1746 switch (version & 0xFF) {
1747 case 1:
1748 type = "proteon/mrouted ";
1749 retval = 1;
1750 break;
1751
1752 case 10:
1753 case 11:
1754 type = "cisco ";
1755 }
1756 printf(" [%s%d.%d] %s\n",
1757 type, version & 0xFF, (version >> 8) & 0xFF,
1758 why);
1759 VAL_TO_MASK(smask, r->tr_smask);
1760 while (p < ep) {
1761 u_int32 laddr = *p++;
1762 int flags = (ntohl(*p) & 0xFF00) >> 8;
1763 int n = ntohl(*p++) & 0xFF;
1764 if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
1765 (laddr & smask) == (qsrc & smask)) {
1766 printf("%3d ", -(hops+2));
1767 print_host(qsrc);
1768 printf("\n");
1769 return 1;
1770 }
1771 p += n;
1772 }
1773 return retval;
1774 }
1775 printf(" %s\n", why);
1776 return 0;
1777}
1778
1779
1780char *
33745200 1781scale(int *hop)
984263bc 1782{
33745200
MD
1783 if (*hop > -1000 && *hop < 10000)
1784 return (" ms");
984263bc 1785 *hop /= 1000;
33745200
MD
1786 if (*hop > -1000 && *hop < 10000)
1787 return (" s ");
984263bc
MD
1788 return ("s ");
1789}
1790
1791/*
1792 * Calculate and print one line of packet loss and packet rate statistics.
1793 * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
1794 */
1795#define NEITHER 0
1796#define INS 1
1797#define OUTS 2
1798#define BOTH 3
1799void
33745200 1800stat_line(struct tr_resp *r, struct tr_resp *s, int have_next, int *rst)
984263bc
MD
1801{
1802 int timediff = (ntohl(s->tr_qarr) - ntohl(r->tr_qarr)) >> 16;
1803 int v_lost, v_pct;
1804 int g_lost, g_pct;
1805 int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
1806 int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1807 int v_pps, g_pps;
1808 char v_str[8], g_str[8];
1809 int vhave = NEITHER;
1810 int ghave = NEITHER;
1811 int gmissing = NEITHER;
1812 char whochar;
1813 int badtime = 0;
1814
1815 if (timediff == 0) {
1816 badtime = 1;
1817 /* Might be 32 bits of int seconds instead of 16int+16frac */
1818 timediff = ntohl(s->tr_qarr) - ntohl(r->tr_qarr);
1819 if (timediff == 0 || abs(timediff - statint) > statint)
1820 timediff = 1;
1821 }
1822 v_pps = v_out / timediff;
1823 g_pps = g_out / timediff;
1824
1825#define STATS_MISSING(x) ((x) == 0xFFFFFFFF)
1826
1827 if (!STATS_MISSING(s->tr_vifout) && !STATS_MISSING(r->tr_vifout))
1828 vhave |= OUTS;
1829 if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1830 gmissing |= OUTS;
1831 if (!(*rst & BUG_NOPRINT))
1832 ghave |= OUTS;
1833
1834 if (have_next) {
1835 --r, --s, --rst;
1836 if (!STATS_MISSING(s->tr_vifin) && !STATS_MISSING(r->tr_vifin))
1837 vhave |= INS;
1838 if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1839 gmissing |= INS;
1840 if (!(*rst & BUG_NOPRINT))
1841 ghave |= INS;
1842 }
1843
1844 /*
1845 * Stats can be missing for any number of reasons:
1846 * - The hop may not be capable of collecting stats
1847 * - Traffic may be getting dropped at the previous hop
1848 * and so this hop may not have any state
1849 *
1850 * We need a stronger heuristic to tell between these
1851 * two cases; in case 1 we don't want to print the stats
1852 * and in case 2 we want to print 100% loss. We used to
1853 * err on the side of not printing, which is less useful
1854 * than printing 100% loss and dealing with it.
1855 */
1856#if 0
1857 /*
1858 * If both hops report as missing, then it's likely that there's just
1859 * no traffic flowing.
1860 *
1861 * If just one hop is missing, then we really don't have it.
1862 */
1863 if (gmissing != BOTH)
1864 ghave &= ~gmissing;
1865#endif
1866
1867 whochar = have_next ? '^' : ' ';
1868 switch (vhave) {
1869 case BOTH:
1870 v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
1871 if (v_out) v_pct = v_lost * 100 / v_out;
1872 else v_pct = 0;
1873 if (-20 < v_pct && v_pct < 101 && v_out > 10)
1874 sprintf(v_str, "%3d%%", v_pct);
1875 else if (v_pct < -900 && v_out > 10)
1876 sprintf(v_str, "%3dx", (int)(-v_pct / 100. + 1.));
1877 else if (v_pct <= -20 && v_out > 10)
1878 sprintf(v_str, "%1.1fx", -v_pct / 100. + 1.);
1879 else
1880 memcpy(v_str, " -- ", 5);
1881
1882 if (tunstats)
1883 printf("%6d/%-5d=%s", v_lost, v_out, v_str);
1884 else
1885 printf(" ");
1886 printf("%4d pps", v_pps);
1887 if (v_pps && badtime)
1888 printf("?");
1889
1890 break;
1891
1892 case INS:
1893 v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
1894 v_pps = v_out / timediff;
1895 whochar = 'v';
1896 /* FALLTHROUGH */
1897
1898 case OUTS:
1899 if (tunstats)
1900 printf(" %c%-5d ", whochar, v_out);
1901 else
1902 printf(" %c", whochar);
1903 printf("%4d pps", v_pps);
1904 if (v_pps && badtime)
1905 printf("?");
1906
1907 break;
1908
1909 case NEITHER:
1910 if (ghave != NEITHER)
1911 if (tunstats)
1912 printf(" ");
1913 else
1914 printf(" ");
1915
1916 break;
1917 }
1918
1919 whochar = have_next ? '^' : ' ';
1920 switch (ghave) {
1921 case BOTH:
1922 g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
1923 if (g_out) g_pct = g_lost * 100 / g_out;
1924 else g_pct = 0;
1925 if (-20 < g_pct && g_pct < 101 && g_out > 10)
1926 sprintf(g_str, "%3d%%", g_pct);
1927 else if (g_pct < -900 && g_out > 10)
1928 sprintf(g_str, "%3dx", (int)(-g_pct / 100. + 1.));
1929 else if (g_pct <= -20 && g_out > 10)
1930 sprintf(g_str, "%1.1fx", -g_pct / 100. + 1.);
1931 else
1932 memcpy(g_str, " -- ", 5);
1933
1934 printf("%s%6d/%-5d=%s%4d pps",
1935 tunstats ? "" : " ", g_lost, g_out, g_str, g_pps);
1936 if (g_pps && badtime)
1937 printf("?");
1938 printf("\n");
1939 break;
1940
1941#if 0
1942 case INS:
1943 g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1944 g_pps = g_out / timediff;
1945 whochar = 'v';
1946 /* FALLTHROUGH */
1947#endif
1948
1949 case OUTS:
1950 printf("%s ?/%-5d %4d pps",
1951 tunstats ? "" : " ", g_out, g_pps);
1952 if (badtime)
1953 printf("?");
1954 printf("\n");
1955 break;
1956
1957 case INS:
1958 case NEITHER:
1959 printf("\n");
1960 break;
1961 }
1962
1963
1964 if (debug > 2) {
1965 printf("\t\t\t\tv_in: %ld ", (long)ntohl(s->tr_vifin));
1966 printf("v_out: %ld ", (long)ntohl(s->tr_vifout));
1967 printf("pkts: %ld\n", (long)ntohl(s->tr_pktcnt));
1968 printf("\t\t\t\tv_in: %ld ", (long)ntohl(r->tr_vifin));
1969 printf("v_out: %ld ", (long)ntohl(r->tr_vifout));
1970 printf("pkts: %ld\n", (long)ntohl(r->tr_pktcnt));
1971 printf("\t\t\t\tv_in: %ld ",
1972 (long)(ntohl(s->tr_vifin) - ntohl(r->tr_vifin)));
1973 printf("v_out: %ld ",
1974 (long)(ntohl(s->tr_vifout) - ntohl(r->tr_vifout)));
1975 printf("pkts: %ld ", (long)(ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt)));
1976 printf("time: %d\n", timediff);
1977 printf("\t\t\t\treset: %x hoptime: %lx\n", *rst, ntohl(s->tr_qarr));
1978 }
1979}
1980
1981/*
1982 * A fixup to check if any pktcnt has been reset, and to fix the
1983 * byteorder bugs in mrouted 3.6 on little-endian machines.
1984 *
1985 * XXX Since periodic traffic sources are likely to have their
1986 * pktcnt periodically reset, should we save old values when
1987 * the reset occurs to keep slightly better statistics over
1988 * the long term? (e.g. SAP)
1989 */
1990void
33745200
MD
1991fixup_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new,
1992 int *bugs)
984263bc
MD
1993{
1994 int rno = base->len;
1995 struct tr_resp *b = base->resps + rno;
1996 struct tr_resp *p = prev->resps + rno;
1997 struct tr_resp *n = new->resps + rno;
1998 int *r = bugs + rno;
1999 int res;
2000 int cleanup = 0;
2001
2002 /* Check for byte-swappers. Only check on the first trace,
2003 * since long-running traces can wrap around and falsely trigger. */
2004 while (--rno >= 0) {
2005#ifdef TEST_ONLY
2006 u_int32 nvifout = ntohl(n->tr_vifout);
2007 u_int32 pvifout = ntohl(p->tr_vifout);
2008#endif
2009 --n; --p; --b;
2010#ifdef TEST_ONLY /*XXX this is still buggy, so disable it for release */
2011 if ((*r & BUG_SWAP) ||
2012 ((base == prev) &&
2013 (nvifout - pvifout) > (byteswap(nvifout) - byteswap(pvifout)))) {
2014 if (1 || debug > 2) {
2015 printf("ip %s swaps; b %08x p %08x n %08x\n",
2016 inet_fmt(n->tr_inaddr, s1),
2017 ntohl(b->tr_vifout), pvifout, nvifout);
2018 }
2019 /* This host sends byteswapped reports; swap 'em */
2020 if (!(*r & BUG_SWAP)) {
2021 *r |= BUG_SWAP;
2022 b->tr_qarr = byteswap(b->tr_qarr);
2023 b->tr_vifin = byteswap(b->tr_vifin);
2024 b->tr_vifout = byteswap(b->tr_vifout);
2025 b->tr_pktcnt = byteswap(b->tr_pktcnt);
2026 }
2027
2028 n->tr_qarr = byteswap(n->tr_qarr);
2029 n->tr_vifin = byteswap(n->tr_vifin);
2030 n->tr_vifout = byteswap(n->tr_vifout);
2031 n->tr_pktcnt = byteswap(n->tr_pktcnt);
2032 }
2033#endif
2034 /*
2035 * A missing parenthesis in mrouted 3.5-3.8's prune.c
2036 * causes extremely bogus time diff's.
2037 * One half of the time calculation was
2038 * inside an htonl() and one half wasn't. Therefore, on
2039 * a little-endian machine, both halves of the calculation
2040 * would get added together in the little end. Thus, the
2041 * low-order 2 bytes are either 0000 (no overflow) or
2042 * 0100 (overflow from the addition).
2043 *
2044 * Odds are against these particular bit patterns
2045 * happening in both prev and new for actual time values.
2046 */
2047 if ((*r & BUG_BOGUSTIME) || (((ntohl(n->tr_qarr) & 0xfeff) == 0x0000) &&
2048 ((ntohl(p->tr_qarr) & 0xfeff) == 0x0000))) {
2049 *r |= BUG_BOGUSTIME;
2050 n->tr_qarr = new->rtime;
2051 p->tr_qarr = prev->rtime;
2052 b->tr_qarr = base->rtime;
2053 }
2054 }
2055
2056 rno = base->len;
2057 b = base->resps + rno;
2058 p = prev->resps + rno;
2059 n = new->resps + rno;
2060 r = bugs + rno;
2061
2062 while (--rno >= 0) {
2063 --n; --p; --b; --r;
2064 /*
2065 * This hop has reset if:
2066 * - There were statistics in the base AND previous pass, AND
2067 * - There are less packets this time than the first time and
2068 * we didn't reset last time, OR
2069 * - There are less packets this time than last time, OR
2070 * - There are no statistics on this pass.
2071 *
2072 * The "and we didn't reset last time" is necessary in the
2073 * first branch of the OR because if the base is large and
2074 * we reset last time but the constant-resetter-avoidance
2075 * code kicked in so we delayed the copy of prev to base,
2076 * new could still be below base so we trigger the
2077 * constant-resetter code even though it was really only
2078 * a single reset.
2079 */
2080 res = ((b->tr_pktcnt != 0xFFFFFFFF) && (p->tr_pktcnt != 0xFFFFFFFF) &&
2081 ((!(*r & BUG_RESET) && ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
2082 (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)) ||
2083 (n->tr_pktcnt == 0xFFFFFFFF)));
2084 if (debug > 2) {
2085 printf("\t\tip=%s, r=%d, res=%d\n", inet_fmt(b->tr_inaddr, s1), *r, res);
2086 if (res)
2087 printf("\t\tbase=%ld, prev=%ld, new=%ld\n", ntohl(b->tr_pktcnt),
2088 ntohl(p->tr_pktcnt), ntohl(n->tr_pktcnt));
2089 }
2090 if (*r & BUG_RESET) {
2091 if (res || (*r & BUG_RESET2X)) {
2092 /*
2093 * This router appears to be a 3.4 with that nasty ol'
2094 * neighbor version bug, which causes it to constantly
2095 * reset. Just nuke the statistics for this node, and
2096 * don't even bother giving it the benefit of the
2097 * doubt from now on.
2098 */
2099 p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
2100 *r |= BUG_RESET2X;
2101 } else {
2102 /*
2103 * This is simply the situation that the original
2104 * fixup_stats was meant to deal with -- that a
2105 * 3.3 or 3.4 router deleted a cache entry while
2106 * traffic was still active.
2107 */
2108 *r &= ~BUG_RESET;
2109 cleanup = 1;
2110 }
2111 } else
2112 if (res)
2113 *r |= BUG_RESET;
2114 }
2115
2116 if (cleanup == 0) return;
2117
2118 /*
2119 * If some hop reset its counters and didn't continue to
2120 * reset, then we pretend that the previous
2121 * trace was the first one.
2122 */
2123 rno = base->len;
2124 b = base->resps + rno;
2125 p = prev->resps + rno;
2126
2127 while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
2128 base->qtime = prev->qtime;
2129 base->rtime = prev->rtime;
2130}
2131
2132/*
2133 * Check per-source losses along path and compare with threshold.
2134 */
2135int
33745200
MD
2136check_thresh(int thresh, struct resp_buf *base, struct resp_buf *prev,
2137 struct resp_buf *new)
984263bc
MD
2138{
2139 int rno = base->len - 1;
2140 struct tr_resp *b = base->resps + rno;
2141 struct tr_resp *p = prev->resps + rno;
2142 struct tr_resp *n = new->resps + rno;
2143 int g_out, g_lost;
2144
2145 while (TRUE) {
2146 if ((n->tr_inaddr != b->tr_inaddr) ||
2147 (n->tr_outaddr != b->tr_outaddr) ||
2148 (n->tr_rmtaddr != b->tr_rmtaddr))
2149 return 1; /* Route changed */
2150
2151 if (rno-- < 1) break;
2152 g_out = ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt);
2153 b--; n--; p--;
2154 g_lost = g_out - (ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt));
2155 if (g_out && ((g_lost * 100 + (g_out >> 1))/ g_out) > thresh) {
2156 return TRUE;
2157 }
2158 }
2159 return FALSE;
2160}
2161
2162/*
2163 * Print responses with statistics for forward path (from src to dst)
2164 */
2165int
33745200
MD
2166print_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new,
2167 int *bugs, char **names)
984263bc
MD
2168{
2169 int rtt, hop;
2170 char *ms;
2171 u_int32 smask;
2172 int rno = base->len - 1;
2173 struct tr_resp *b = base->resps + rno;
2174 struct tr_resp *p = prev->resps + rno;
2175 struct tr_resp *n = new->resps + rno;
2176 int *r = bugs + rno;
2177 u_long resptime = new->rtime;
2178 u_long qarrtime = ntohl(n->tr_qarr);
2179 u_int ttl = MaX(1, n->tr_fttl) + 1;
2180 int first = (base == prev);
2181
2182 VAL_TO_MASK(smask, b->tr_smask);
2183 printf(" Source Response Dest ");
2184 if (tunstats)
2185 printf("Packet Statistics For Only For Traffic\n");
2186 else
2187 printf("Overall Packet Statistics For Traffic From\n");
71126e33 2188 inet_fmt(base->qhdr.tr_src, s1);
984263bc
MD
2189 printf("%-15s %-15s ",
2190 ((b->tr_inaddr & smask) == (base->qhdr.tr_src & smask)) ?
2191 s1 : " * * * ",
2192 inet_fmt(base->qhdr.tr_raddr, s2));
71126e33 2193 inet_fmt(base->igmp.igmp_group.s_addr, s2);
984263bc
MD
2194 if (tunstats)
2195 printf("All Multicast Traffic From %s\n", s1);
2196 else
2197 printf("Packet %s To %s\n", s1, s2);
2198 rtt = t_diff(resptime, new->qtime);
2199 ms = scale(&rtt);
2200 printf(" %c __/ rtt%5d%s ",
2201 (first && !verbose) ? 'v' : '|', rtt, ms);
2202 if (tunstats)
2203 printf("Lost/Sent = Pct Rate To %s\n", s2);
2204 else
2205 printf(" Rate Lost/Sent = Pct Rate\n");
2206 if (!first || verbose) {
2207 hop = t_diff(resptime, qarrtime);
2208 ms = scale(&hop);
2209 printf(" v / hop%5d%s ", hop, ms);
2210 if (tunstats)
2211 printf("--------------------- --------------------\n");
2212 else
2213 printf("------- ---------------------\n");
2214 }
2215 if ((b->tr_inaddr & smask) != (base->qhdr.tr_src & smask) &&
2216 b->tr_rmtaddr != 0) {
2217 printf("%-15s %-14s is the previous hop\n", inet_fmt(b->tr_rmtaddr, s1),
2218 inet_name(b->tr_rmtaddr));
2219 printf(" v ^\n");
2220 }
2221 if (debug > 2) {
2222 printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
2223 printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
2224 printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
2225 printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
2226 printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
2227 printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
2228 printf("\t\t\t\tv_in: %ld ",
2229 (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
2230 printf("v_out: %ld ",
2231 (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
2232 printf("pkts: %ld\n",
2233 (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
2234 printf("\t\t\t\treset: %x hoptime: %lx\n", *r, (long)ntohl(n->tr_qarr));
2235 }
2236
2237 while (TRUE) {
2238 if ((n->tr_inaddr != b->tr_inaddr) ||
2239 (n->tr_outaddr != b->tr_outaddr) ||
2240 (n->tr_rmtaddr != b->tr_rmtaddr))
2241 return 1; /* Route changed */
2242
2243 if ((n->tr_inaddr != n->tr_outaddr) && n->tr_inaddr)
2244 printf("%-15s\n", inet_fmt(n->tr_inaddr, s1));
2245 printf("%-15s %-14s %s%s\n", inet_fmt(n->tr_outaddr, s1), names[rno],
2246 flag_type(n->tr_rflags),
2247 (*r & BUG_NOPRINT) ? " [reset counters]" : "");
2248
2249 if (rno-- < 1) break;
2250
2251 printf(" %c ^ ttl%5d ", (first && !verbose) ? 'v' : '|',
2252 ttl);
2253 stat_line(p, n, TRUE, r);
2254 if (!first || verbose) {
2255 resptime = qarrtime;
2256 qarrtime = ntohl((n-1)->tr_qarr);
2257 hop = t_diff(resptime, qarrtime);
2258 ms = scale(&hop);
2259 printf(" v | hop%5d%s", hop, ms);
2260 if (first)
2261 printf("\n");
2262 else
2263 stat_line(b, n, TRUE, r);
2264 }
2265
2266 --b, --p, --n, --r;
2267 ttl = MaX(ttl, MaX(1, n->tr_fttl) + base->len - rno);
2268 }
2269
2270 printf(" %c \\__ ttl%5d ", (first && !verbose) ? 'v' : '|',
2271 ttl);
2272 stat_line(p, n, FALSE, r);
2273 if (!first || verbose) {
2274 hop = t_diff(qarrtime, new->qtime);
2275 ms = scale(&hop);
2276 printf(" v \\ hop%5d%s", hop, ms);
2277 if (first)
2278 printf("\n");
2279 else
2280 stat_line(b, n, FALSE, r);
2281 }
2282 printf("%-15s %s\n", inet_fmt(base->qhdr.tr_dst, s1),
2283 !passive ? inet_fmt(lcl_addr, s2) : " * * * ");
2284 printf(" Receiver Query Source\n\n");
2285 return 0;
2286}
2287
2288/*
2289 * Determine whether or not the path has changed.
2290 */
2291int
33745200 2292path_changed(struct resp_buf *base, struct resp_buf *new)
984263bc
MD
2293{
2294 int rno = base->len - 1;
2295 struct tr_resp *b = base->resps + rno;
2296 struct tr_resp *n = new->resps + rno;
2297
2298 while (rno-- >= 0) {
2299 if ((n->tr_inaddr != b->tr_inaddr) ||
2300 (n->tr_outaddr != b->tr_outaddr) ||
2301 (n->tr_rmtaddr != b->tr_rmtaddr))
2302 return 1; /* Route changed */
2303 if ((b->tr_rflags == TR_NO_RTE) &&
2304 (n->tr_rflags != TR_NO_RTE))
2305 return 1; /* Route got longer? */
2306 --n;
2307 --b;
2308 }
2309 return 0;
2310}
2311
2312
2313/***************************************************************************
2314 * main
2315 ***************************************************************************/
2316
2317int
33745200 2318main(int argc, char **argv)
984263bc
MD
2319{
2320 int udp;
2321 struct sockaddr_in addr;
2322 int addrlen = sizeof(addr);
2323 int recvlen;
2324 struct timeval tv;
2325 struct resp_buf *prev, *new;
2326 struct tr_resp *r;
2327 u_int32 smask;
2328 int rno;
2329 int hops, nexthop, tries;
2330 u_int32 lastout = 0;
2331 int numstats = 1;
2332 int waittime;
2333 int seed;
2334 int hopbyhop;
2335 int i;
2336 int printed = 1;
2337
2338 if (geteuid() != 0)
2339 errx(1, "must be root");
2340
2341 /*
2342 * We might get spawned by vat with the audio device open.
2343 * Close everything but stdin, stdout, stderr.
2344 */
2345 for (i = 3; i < 255; i++)
2346 close(i);
2347
2348 init_igmp();
2349 setuid(getuid());
2350
2351 argv++, argc--;
2352 if (argc == 0) usage();
2353
2354 while (argc > 0 && *argv[0] == '-') {
2355 char *p = *argv++; argc--;
2356 p++;
2357 do {
2358 char c = *p++;
2359 char *arg = (char *) 0;
2360 if (isdigit(*p)) {
2361 arg = p;
2362 p = "";
2363 } else if (argc > 0) arg = argv[0];
2364 switch (c) {
2365 case 'd': /* Unlisted debug print option */
2366 if (arg && isdigit(*arg)) {
2367 debug = atoi(arg);
2368 if (debug < 0) debug = 0;
2369 if (debug > 3) debug = 3;
2370 if (arg == argv[0]) argv++, argc--;
2371 break;
2372 } else
2373 usage();
2374 case 'M': /* Use multicast for reponse */
2375 multicast = TRUE;
2376 break;
2377 case 'U': /* Use unicast for response */
2378 unicast = TRUE;
2379 break;
2380 case 'L': /* Trace w/ loss threshold */
2381 if (arg && isdigit(*arg)) {
2382 lossthresh = atoi(arg);
2383 if (lossthresh < 0)
2384 lossthresh = 0;
2385 numstats = 3153600;
2386 if (arg == argv[0]) argv++, argc--;
2387 break;
2388 } else
2389 usage();
2390 break;
2391 case 'O': /* Don't use IP options */
2392 sendopts = FALSE;
2393 break;
2394 case 'P': /* Just watch the path */
2395 printstats = FALSE;
2396 numstats = 3153600;
2397 break;
2398 case 'Q': /* (undoc.) always use this QID */
2399 if (arg && isdigit(*arg)) {
2400 staticqid = atoi(arg);
2401 if (staticqid < 0)
2402 staticqid = 0;
2403 if (arg == argv[0]) argv++, argc--;
2404 break;
2405 } else
2406 usage();
2407 break;
2408 case 'T': /* Print confusing tunnel stats */
2409 tunstats = TRUE;
2410 break;
2411 case 'W': /* Cisco's "weak" mtrace */
2412 weak = TRUE;
2413 break;
2414 case 'V': /* Print version and exit */
2415 /*
2416 * FreeBSD wants to have its own Id string, so
2417 * determination of the version number has to change.
2418 * XXX Note that this must be changed by hand on importing
2419 * XXX new versions!
2420 */
2421 {
1de703da 2422 char *r = strdup(version);
984263bc
MD
2423 char *s = strchr(r, ',');
2424
2425 while (s && *(s+1) != 'v')
2426 s = strchr(s + 1, ',');
2427
2428 if (s) {
2429 char *q;
2430
2431 s += 3; /* , v sp */
2432 q = strchr(s, ' ');
2433 if (q)
2434 *q = '\0';
2435 fprintf(stderr, "mtrace version 5.2/%s\n", s);
2436 } else {
2437 fprintf(stderr, "mtrace could not determine version number!?\n");
2438 }
2439 exit(1);
2440 }
2441 break;
2442 case 'l': /* Loop updating stats indefinitely */
2443 numstats = 3153600;
2444 break;
2445 case 'n': /* Don't reverse map host addresses */
2446 numeric = TRUE;
2447 break;
2448 case 'p': /* Passive listen for traces */
2449 passive = TRUE;
2450 break;
2451 case 'v': /* Verbosity */
2452 verbose = TRUE;
2453 break;
2454 case 's': /* Short form, don't wait for stats */
2455 numstats = 0;
2456 break;
2457 case 'w': /* Time to wait for packet arrival */
2458 if (arg && isdigit(*arg)) {
2459 timeout = atoi(arg);
2460 if (timeout < 1) timeout = 1;
2461 if (arg == argv[0]) argv++, argc--;
2462 break;
2463 } else
2464 usage();
2465 case 'f': /* first hop */
2466 if (arg && isdigit(*arg)) {
2467 qno = atoi(arg);
2468 if (qno > MAXHOPS) qno = MAXHOPS;
2469 else if (qno < 1) qno = 0;
2470 if (arg == argv[0]) argv++, argc--;
2471 fflag++;
2472 break;
2473 } else
2474 usage();
2475 case 'm': /* Max number of hops to trace */
2476 if (arg && isdigit(*arg)) {
2477 qno = atoi(arg);
2478 if (qno > MAXHOPS) qno = MAXHOPS;
2479 else if (qno < 1) qno = 0;
2480 if (arg == argv[0]) argv++, argc--;
2481 break;
2482 } else
2483 usage();
2484 case 'q': /* Number of query retries */
2485 if (arg && isdigit(*arg)) {
2486 nqueries = atoi(arg);
2487 if (nqueries < 1) nqueries = 1;
2488 if (arg == argv[0]) argv++, argc--;
2489 break;
2490 } else
2491 usage();
2492 case 'g': /* Last-hop gateway (dest of query) */
2493 if (arg && (gwy = host_addr(arg))) {
2494 if (arg == argv[0]) argv++, argc--;
2495 break;
2496 } else
2497 usage();
2498 case 't': /* TTL for query packet */
2499 if (arg && isdigit(*arg)) {
2500 qttl = atoi(arg);
2501 if (qttl < 1) qttl = 1;
2502 rttl = qttl;
2503 if (arg == argv[0]) argv++, argc--;
2504 break;
2505 } else
2506 usage();
2507 case 'e': /* Extra hops past non-responder */
2508 if (arg && isdigit(*arg)) {
2509 extrahops = atoi(arg);
2510 if (extrahops < 0) extrahops = 0;
2511 if (arg == argv[0]) argv++, argc--;
2512 break;
2513 } else
2514 usage();
2515 case 'r': /* Dest for response packet */
2516 if (arg && (raddr = host_addr(arg))) {
2517 if (arg == argv[0]) argv++, argc--;
2518 break;
2519 } else
2520 usage();
2521 case 'i': /* Local interface address */
2522 if (arg && (lcl_addr = host_addr(arg))) {
2523 if (arg == argv[0]) argv++, argc--;
2524 break;
2525 } else
2526 usage();
2527 case 'S': /* Stat accumulation interval */
2528 if (arg && isdigit(*arg)) {
2529 statint = atoi(arg);
2530 if (statint < 1) statint = 1;
2531 if (arg == argv[0]) argv++, argc--;
2532 break;
2533 } else
2534 usage();
2535 default:
2536 usage();
2537 }
2538 } while (*p);
2539 }
2540
2541 if (argc > 0 && (qsrc = host_addr(argv[0]))) { /* Source of path */
2542 if (IN_MULTICAST(ntohl(qsrc))) {
2543 if (gwy) {
2544 /* Should probably rewrite arg parsing at some point, as
2545 * this makes "mtrace -g foo 224.1.2.3 224.2.3.4" valid!... */
2546 qgrp = qsrc;
2547 qsrc = 0;
2548 } else {
2549 usage();
2550 }
2551 }
2552 argv++, argc--;
2553 if (argc > 0 && (qdst = host_addr(argv[0]))) { /* Dest of path */
2554 argv++, argc--;
2555 if (argc > 0 && (qgrp = host_addr(argv[0]))) { /* Path via group */
2556 argv++, argc--;
2557 }
2558 if (IN_MULTICAST(ntohl(qdst))) {
2559 u_int32 temp = qdst;
2560 qdst = qgrp;
2561 qgrp = temp;
2562 if (IN_MULTICAST(ntohl(qdst))) usage();
2563 } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) usage();
2564 }
2565 }
2566
2567 if (passive) {
2568 passive_mode();
2569 return(0);
2570 }
2571
2572 if (argc > 0) {
2573 usage();
2574 }
2575
2576#ifdef SUNOS5
2577 if (sendopts)
2578 checkforsolarisbug();
2579#endif
2580
2581 /*
2582 * Set useful defaults for as many parameters as possible.
2583 */
2584
2585 defgrp = 0; /* Default to no group */
2586 query_cast = htonl(0xE0000002); /* All routers multicast addr */
2587 resp_cast = htonl(0xE0000120); /* Mtrace response multicast addr */
2588 if (qgrp == 0) {
2589 if (!weak)
2590 qgrp = defgrp;
2591 if (printstats && numstats != 0 && !tunstats) {
2592 /* Stats are useless without a group */
2593 warnx(
2594 "WARNING: no multicast group specified, so no statistics printed");
2595 numstats = 0;
2596 }
2597 } else {
2598 if (weak)
2599 warnx(
2600 "WARNING: group was specified so not performing \"weak\" mtrace");
2601 }
2602
2603 /*
2604 * Get default local address for multicasts to use in setting defaults.
2605 */
2606 addr.sin_family = AF_INET;
2607#if (defined(BSD) && (BSD >= 199103))
2608 addr.sin_len = sizeof(addr);
2609#endif
2610 addr.sin_addr.s_addr = qgrp ? qgrp : query_cast;
2611 addr.sin_port = htons(2000); /* Any port above 1024 will do */
2612
2613 /*
2614 * Note that getsockname() can return 0 on some systems
2615 * (notably SunOS 5.x, x < 6). This is taken care of in
2616 * get_netmask(). If the default multicast interface (set
2617 * with the route for 224.0.0.0) is not the same as the
2618 * hostname, mtrace -i [if_addr] will have to be used.
2619 */
2620 if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
2621 (connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
2622 getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0)
2623 err(-1, "determining local address");
2624
2625#ifdef SUNOS5
2626 /*
2627 * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
2628 * This call to sysinfo will return the hostname.
2629 * If the default multicast interfface (set with the route
2630 * for 224.0.0.0) is not the same as the hostname,
2631 * mtrace -i [if_addr] will have to be used.
2632 */
2633 if (addr.sin_addr.s_addr == 0) {
2634 char myhostname[MAXHOSTNAMELEN];
2635 struct hostent *hp;
2636 int error;
2637
2638 error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
2639 if (error == -1)
2640 err(1, "getting my hostname");
2641
2642 hp = gethostbyname(myhostname);
2643 if (hp == NULL || hp->h_addrtype != AF_INET ||
2644 hp->h_length != sizeof(addr.sin_addr))
2645 err(1, "finding IP address for my hostname");
2646
2647 memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr, hp->h_length);
2648 }
2649#endif
2650
2651 /*
2652 * Default destination for path to be queried is the local host.
2653 * When gateway specified, default destination is that gateway
2654 * and default source is local host.
2655 */
2656 if (qdst == 0) {
2657 qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2658 dst_netmask = get_netmask(udp, &qdst);
2659 if (gwy && (gwy & dst_netmask) != (qdst & dst_netmask) &&
2660 !IN_MULTICAST(ntohl(gwy)))
2661 qdst = gwy;
2662 }
2663 if (qsrc == 0 && gwy)
2664 qsrc = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2665 if (qsrc == 0)
2666 usage();
2667 if (!dst_netmask)
2668 dst_netmask = get_netmask(udp, &qdst);
2669 close(udp);
2670 if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
2671
2672 /*
2673 * Initialize the seed for random query identifiers.
2674 */
2675 gettimeofday(&tv, 0);
2676 seed = tv.tv_usec ^ lcl_addr;
2677#ifdef SYSV
2678 srand48(seed);
2679#endif
2680
2681 /*
2682 * Protect against unicast queries to mrouted versions that might crash.
2683 * Also use the obsolete "can mtrace" neighbor bit to warn about
2684 * older implementations.
2685 */
2686 if (gwy && !IN_MULTICAST(ntohl(gwy)))
2687 if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL)) {
2688 int flags = ntohl(incr[0].igmp.igmp_group.s_addr);
2689 int version = flags & 0xFFFF;
2690 int info = (flags & 0xFF0000) >> 16;
2691
2692 if (version == 0x0303 || version == 0x0503) {
2693 printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
2694 (version >> 8) & 0xFF);
2695 exit(0);
2696 }
2697 if ((info & 0x08) == 0) {
2698 printf("mtrace: ");
2699 print_host(gwy);
2700 printf(" probably doesn't support mtrace, trying anyway...\n");
2701 }
2702 }
2703
2704 printf("Mtrace from %s to %s via group %s\n",
2705 inet_fmt(qsrc, s1), inet_fmt(qdst, s2), inet_fmt(qgrp, s3));
2706
2707 if ((qdst & dst_netmask) == (qsrc & dst_netmask))
2708 fprintf(stderr, "mtrace: Source & receiver appear to be directly connected\n");
2709
2710 /*
2711 * If the response is to be a multicast address, make sure we
2712 * are listening on that multicast address.
2713 */
2714 if (raddr) {
2715 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
2716 } else k_join(resp_cast, lcl_addr);
2717
2718 memset(&base, 0, sizeof(base));
2719
2720 /*
2721 * If the destination is on the local net, the last-hop router can
2722 * be found by multicast to the all-routers multicast group.
2723 * Otherwise, use the group address that is the subject of the
2724 * query since by definition the last-hop router will be a member.
2725 * Set default TTLs for local remote multicasts.
2726 */
2727 if (gwy == 0)
2728 if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
2729 else tdst = qgrp;
2730 else tdst = gwy;
2731 if (tdst == 0 && qgrp == 0)
2732 errx(1, "mtrace: weak mtrace requires -g if destination is not local.\n");
2733
2734 if (IN_MULTICAST(ntohl(tdst))) {
2735 k_set_loop(1); /* If I am running on a router, I need to hear this */
2736 if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
2737 else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
2738 }
2739
2740 /*
2741 * Try a query at the requested number of hops or MAXHOPS if unspecified.
2742 */
2743 if (qno == 0) {
2744 hops = MAXHOPS;
2745 tries = 1;
2746 printf("Querying full reverse path... ");
2747 fflush(stdout);
2748 } else {
2749 hops = qno;
2750 tries = nqueries;
2751 if (fflag)
2752 printf("Querying full reverse path, starting at hop %d...", qno);
2753 else
2754 printf("Querying reverse path, maximum %d hops... ", qno);
2755 fflush(stdout);
2756 }
2757 base.rtime = 0;
2758 base.len = 0;
2759 hopbyhop = FALSE;
2760
2761 recvlen = send_recv(tdst, IGMP_MTRACE, hops, tries, &base, mtrace_callback);
2762
2763 /*
2764 * If the initial query was successful, print it. Otherwise, if
2765 * the query max hop count is the default of zero, loop starting
2766 * from one until there is no response for extrahops more hops. The
2767 * extra hops allow getting past an mtrace-capable mrouter that can't
2768 * send multicast packets because all phyints are disabled.
2769 */
2770 if (recvlen) {
2771 printf("\n 0 ");
2772 print_host(qdst);
2773 printf("\n");
2774 print_trace(1, &base, names);
2775 r = base.resps + base.len - 1;
2776 if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
2777 (qno != 0 && r->tr_rmtaddr != 0 && !fflag)) {
2778 printf("%3d ", -(base.len+1));
2779 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2780 "doesn't support mtrace"
2781 : "is the next hop");
2782 } else {
2783 if (fflag) {
2784 nexthop = hops = qno;
2785 goto continuehop;
2786 }
2787 VAL_TO_MASK(smask, r->tr_smask);
2788 if ((r->tr_inaddr & smask) == (qsrc & smask)) {
2789 printf("%3d ", -(base.len+1));
2790 print_host(qsrc);
2791 printf("\n");
2792 }
2793 }
2794 } else if (qno == 0) {
2795 hopbyhop = TRUE;
2796 printf("switching to hop-by-hop:\n 0 ");
2797 print_host(qdst);
2798 printf("\n");
2799
2800 for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
2801 printf("%3d ", -hops);
2802 fflush(stdout);
2803
2804 /*
2805 * After a successful first hop, try switching to the unicast
2806 * address of the last-hop router instead of multicasting the
2807 * trace query. This should be safe for mrouted versions 3.3
2808 * and 3.5 because there is a long route timeout with metric
2809 * infinity before a route disappears. Switching to unicast
2810 * reduces the amount of multicast traffic and avoids a bug
2811 * with duplicate suppression in mrouted 3.5.
2812 */
2813 if (hops == 2 && gwy == 0 && lastout != 0 &&
2814 (recvlen = send_recv(lastout, IGMP_MTRACE, hops, 1, &base, mtrace_callback)))
2815 tdst = lastout;
2816 else recvlen = send_recv(tdst, IGMP_MTRACE, hops, nqueries, &base, mtrace_callback);
2817
2818 if (recvlen == 0) {
2819 /*if (hops == 1) break;*/
2820 if (hops == nexthop) {
2821 if (hops == 1) {
2822 printf("\n");
2823 } else if (what_kind(&base, "didn't respond")) {
2824 /* the ask_neighbors determined that the
2825 * not-responding router is the first-hop. */
2826 break;
2827 }
2828 if (extrahops == 0)
2829 break;
2830 } else if (hops < nexthop + extrahops) {
2831 printf("\n");
2832 } else {
2833 printf("...giving up\n");
2834 break;
2835 }
2836 continue;
2837 }
2838 if (base.len == hops &&
2839 (hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
2840 if (hops == nexthop) {
2841 print_trace(-hops, &base, names);
2842 } else {
2843 printf("\nResuming...\n");
2844 print_trace(nexthop, &base, names);
2845 }
2846 } else {
2847 if (base.len < hops) {
2848 /*
2849 * A shorter trace than requested means a fatal error
2850 * occurred along the path, or that the route changed
2851 * to a shorter one.
2852 *
2853 * If the trace is longer than the last one we received,
2854 * then we are resuming from a skipped router (but there
2855 * is still probably a problem).
2856 *
2857 * If the trace is shorter than the last one we
2858 * received, then the route must have changed (and
2859 * there is still probably a problem).
2860 */
2861 if (nexthop <= base.len) {
2862 printf("\nResuming...\n");
2863 print_trace(nexthop, &base, names);
2864 } else if (nexthop > base.len + 1) {
2865 hops = base.len;
2866 printf("\nRoute must have changed...\n");
2867 print_trace(1, &base, names);
2868 }
2869 } else {
2870 /*
2871 * The last hop address is not the same as it was.
2872 * If we didn't know the last hop then we just
2873 * got the first response from a hop-by-hop trace;
2874 * if we did know the last hop then
2875 * the route probably changed underneath us.
2876 */
2877 hops = base.len;
2878 if (lastout != 0)
2879 printf("\nRoute must have changed...\n");
2880 else
2881 printf("\nResuming...\n");
2882 print_trace(1, &base, names);
2883 }
2884 }
2885continuehop:
2886 r = base.resps + base.len - 1;
2887 lastout = r->tr_outaddr;
2888
2889 if (base.len < hops ||
2890 r->tr_rmtaddr == 0 ||
2891 (r->tr_rflags & 0x80)) {
2892 VAL_TO_MASK(smask, r->tr_smask);
2893 if (r->tr_rmtaddr) {
2894 if (hops != nexthop) {
2895 printf("\n%3d ", -(base.len+1));
2896 }
2897 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2898 "doesn't support mtrace" :
2899 "would be the next hop");
2900 /* XXX could do segmented trace if TR_NO_SPACE */
2901 } else if (r->tr_rflags == TR_NO_ERR &&
2902 (r->tr_inaddr & smask) == (qsrc & smask)) {
2903 printf("%3d ", -(hops + 1));
2904 print_host(qsrc);
2905 printf("\n");
2906 }
2907 break;
2908 }
2909
2910 nexthop = hops + 1;
2911 }
2912 }
2913
2914 if (base.rtime == 0) {
2915 printf("Timed out receiving responses\n");
2916 if (IN_MULTICAST(ntohl(tdst)))
2917 if (tdst == query_cast)
2918 printf("Perhaps no local router has a route for source %s\n",
2919 inet_fmt(qsrc, s1));
2920 else
2921 printf("Perhaps receiver %s is not a member of group %s,\n\
2922or no router local to it has a route for source %s,\n\
2923or multicast at ttl %d doesn't reach its last-hop router for that source\n",
2924 inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
2925 qttl ? qttl : MULTICAST_TTL1);
2926 exit(1);
2927 }
2928
2929 printf("Round trip time %d ms; ", t_diff(base.rtime, base.qtime));
2930 {
2931 struct tr_resp *n = base.resps + base.len - 1;
2932 u_int ttl = n->tr_fttl + 1;
2933
2934 rno = base.len - 1;
2935 while (--rno > 0) {
2936 --n;
2937 ttl = MaX(ttl, MaX(1, n->tr_fttl) + base.len - rno);
2938 }
2939 printf("total ttl of %d required.\n\n",ttl);
2940 }
2941
2942 /*
2943 * Use the saved response which was the longest one received,
2944 * and make additional probes after delay to measure loss.
2945 */
2946 raddr = base.qhdr.tr_raddr;
2947 rttl = TR_GETTTL(base.qhdr.tr_rttlqid);
2948 gettimeofday(&tv, 0);
2949 waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
2950 prev = &base;
2951 new = &incr[numstats&1];
2952
2953 /*
2954 * Zero out bug-avoidance counters
2955 */
2956 memset(bugs, 0, sizeof(bugs));
2957
2958 if (!printstats)
2959 printf("Monitoring path..");
2960
2961 while (numstats--) {
2962 if (waittime < 1) printf("\n");
2963 else {
2964 if (printstats && (lossthresh == 0 || printed)) {
2965 printf("Waiting to accumulate statistics...");
2966 } else {
2967 printf(".");
2968 }
2969 fflush(stdout);
2970 sleep((unsigned)waittime);
2971 }
2972 printed = 0;
2973 rno = hopbyhop ? base.len : qno ? qno : MAXHOPS;
2974 recvlen = send_recv(tdst, IGMP_MTRACE, rno, nqueries, new, mtrace_callback);
2975
2976 if (recvlen == 0) {
2977 printf("Timed out.\n");
2978 if (numstats) {
2979 numstats++;
2980 continue;
2981 } else
2982 exit(1);
2983 }
2984
2985 if (base.len != new->len || path_changed(&base, new)) {
2986 printf("%s", base.len == new->len ? "Route changed" :
2987 "Trace length doesn't match");
2988 if (!printstats)
2989 printf(" after %d seconds",
2990 (int)((new->qtime - base.qtime) >> 16));
2991 printf(":\n");
2992printandcontinue:
2993 print_trace(1, new, names);
2994 numstats++;
2995 bcopy(new, &base, sizeof(base));
2996 nexthop = hops = new->len;
2997 printf("Continuing with hop-by-hop...\n");
2998 goto continuehop;
2999 }
3000
3001 if (printstats) {
3002 if (new->igmp.igmp_group.s_addr != qgrp ||
3003 new->qhdr.tr_src != qsrc || new->qhdr.tr_dst != qdst)
3004 printf("\nWARNING: trace modified en route; statistics may be incorrect\n");
3005 fixup_stats(&base, prev, new, bugs);
3006 if ((lossthresh == 0) || check_thresh(lossthresh, &base, prev, new)) {
3007 printf("Results after %d seconds",
3008 (int)((new->qtime - base.qtime) >> 16));
3009 if (lossthresh)
3010 printf(" (this trace %d seconds)",
3011 (int)((new->qtime - prev->qtime) >> 16));
3012 if (verbose) {
3013 time_t t = time(0);
3014 struct tm *qr = localtime(&t);
3015
3016 printf(" qid 0x%06x at %2d:%02d:%02d",
3017 TR_GETQID(base.qhdr.tr_rttlqid),
3018 qr->tm_hour, qr->tm_min, qr->tm_sec);
3019 }
3020 printf(":\n\n");
3021 printed = 1;
3022 if (print_stats(&base, prev, new, bugs, names)) {
3023 printf("This should have been detected earlier, but ");
3024 printf("Route changed:\n");
3025 goto printandcontinue;
3026 }
3027 }
3028 }
3029 prev = new;
3030 new = &incr[numstats&1];
3031 waittime = statint;
3032 }
3033
3034 /*
3035 * If the response was multicast back, leave the group
3036 */
3037 if (raddr) {
3038 if (IN_MULTICAST(ntohl(raddr))) k_leave(raddr, lcl_addr);
3039 } else k_leave(resp_cast, lcl_addr);
3040
3041 return (0);
3042}
3043
3044static void
33745200 3045usage(void)
984263bc
MD
3046{
3047 fprintf(stderr, "%s\n%s\n%s\n",
3048 "usage: mtrace [-MUOPTWVlnpvs] [-e extra_hops] [-f first_hop] [-i if_addr]",
3049 " [-g gateway] [-m max_hops] [-q nqueries] [-r resp_dest]",
3050 " [-S statint] [-t ttl] [-w wait] source [receiver] [group]");
3051 exit(1);
3052}
3053
3054void
33745200 3055check_vif_state(void)
984263bc
MD
3056{
3057 log(LOG_WARNING, errno, "sendto");
3058}
3059
3060/*
3061 * Log errors and other messages to stderr, according to the severity
3062 * of the message and the current debug level. For errors of severity
3063 * LOG_ERR or worse, terminate the program.
3064 */
984263bc
MD
3065void
3066log(int severity, int syserr, char *format, ...)
3067{
3068 va_list ap;
3069 char fmt[100];
3070
3071 va_start(ap, format);
984263bc
MD
3072
3073 switch (debug) {
3074 case 0: if (severity > LOG_WARNING) return;
3075 case 1: if (severity > LOG_NOTICE) return;
3076 case 2: if (severity > LOG_INFO ) return;
3077 default:
3078 fmt[0] = '\0';
3079 if (severity == LOG_WARNING)
3080 strcpy(fmt, "warning - ");
3081 strncat(fmt, format, sizeof(fmt)-strlen(fmt));
3082 fmt[sizeof(fmt)-1]='\0';
3083 vfprintf(stderr, fmt, ap);
3084 if (syserr == 0)
3085 fprintf(stderr, "\n");
3086 else if (syserr < sys_nerr)
3087 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
3088 else
3089 fprintf(stderr, ": errno %d\n", syserr);
3090 }
3091 if (severity <= LOG_ERR) exit(1);
3092}