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
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.
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.
22 * Copyright (c) 1995 by the University of Southern California
23 * All rights reserved.
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
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.
43 * Other copyrights might apply to parts of this software and are so
44 * noted when applicable.
46 * Parts of this software are derived from mrouted, which has the
49 * The mrouted program is covered by the following license. Use of the
50 * mrouted program represents acceptance of these terms and conditions.
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
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.
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.
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.
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
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.
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
96 * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of
97 * Leland Stanford Junior University.
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.
110 * The mtrace program is COPYRIGHT 1998 by Xerox Corporation.
112 * $FreeBSD: src/usr.sbin/mrouted/mtrace.c,v 1.17.2.3 2002/09/12 16:27:49 nectar Exp $
113 * $DragonFly: src/usr.sbin/mrouted/mtrace.c,v 1.8 2005/12/05 00:58:50 swildner Exp $
126 #include <sys/param.h>
127 #include <sys/types.h>
128 #include <sys/socket.h>
129 #include <sys/time.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>
137 #include <sys/sockio.h>
139 #include <arpa/inet.h>
142 #include <sys/systeminfo.h>
145 typedef unsigned int u_int32; /* XXX */
148 const char version[] = "$DragonFly: src/usr.sbin/mrouted/mtrace.c,v 1.8 2005/12/05 00:58:50 swildner Exp $";
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 */
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 )
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 */
178 struct tr_query q; /* Query/response header */
179 struct tr_resp r[MAXHOPS]; /* Per-hop reports */
181 char d[MAX_DVMRP_DATA_LEN]; /* Neighbor data */
189 char *names[MAXHOPS];
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.
196 #define BUG_RESET 0x01
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.
204 #define BUG_RESET2X 0x02
207 * Pre-3.7 mrouted's forget to byte-swap their reports.
209 #define BUG_SWAP 0x04
212 * Pre-3.9 mrouted's forgot a parenthesis in the htonl()
213 * on the time calculation so supply bogus times.
215 #define BUG_BOGUSTIME 0x08
217 #define BUG_NOPRINT (BUG_RESET | BUG_RESET2X)
219 int bugs[MAXHOPS]; /* List of bugs noticed at each hop */
223 struct resp_buf base, incr[2];
224 struct resp_buf *new, *prev;
228 char *names[MAXHOPS];
232 int timeout = DEFAULT_TIMEOUT;
233 int nqueries = DEFAULT_RETRIES;
237 int multicast = FALSE;
241 int tunstats = FALSE;
243 int extrahops = DEFAULT_EXTRAHOPS;
244 int printstats = TRUE;
250 u_int32 defgrp; /* Default group if not specified */
251 u_int32 query_cast; /* All routers multicast addr */
252 u_int32 resp_cast; /* Mtrace response multicast addr */
254 u_int32 lcl_addr = 0; /* This host address, in NET order */
255 u_int32 dst_netmask = 0; /* netmask to go with qdst */
258 * Query/response parameters, all initialized to zero and set later
259 * to default values or from options.
261 u_int32 qsrc = 0; /* Source address in the query */
262 u_int32 qgrp = 0; /* Group address in the query */
263 u_int32 qdst = 0; /* Destination (receiver) address in query */
264 u_char qno = 0; /* Max number of hops to query */
265 u_int32 raddr = 0; /* Address where response should be sent */
266 int qttl = 0; /* TTL for the query packet */
267 u_char rttl = 0; /* TTL for the response packet */
268 u_int32 gwy = 0; /* User-supplied last-hop router address */
269 u_int32 tdst = 0; /* Address where trace is sent (last-hop) */
271 char s1[19]; /* buffers to hold the string representations */
272 char s2[19]; /* of IP addresses, to be passed to inet_fmt() */
273 char s3[19]; /* or inet_fmts(). */
275 #if !(defined(BSD) && (BSD >= 199103))
278 extern char * sys_errlist[];
281 #define RECV_BUF_SIZE 8192
282 char *send_buf, *recv_buf;
284 u_int32 allrtrs_group;
285 char router_alert[4]; /* Router Alert IP Option */
290 char eol[4]; /* EOL IP Option */
291 int ip_addlen = 0; /* Workaround for Option bug #2 */
295 * max macro, with weird case to avoid conflicts
297 #define MaX(a,b) ((a) > (b) ? (a) : (b))
299 typedef int (*callback_t)(int, u_char *, int, struct igmp *, int,
300 struct sockaddr *, int *, struct timeval *);
302 void init_igmp(void);
303 void send_igmp(u_int32 src, u_int32 dst, int type,
304 int code, u_int32 group,
306 int inet_cksum(u_short *addr, u_int len);
307 void k_set_rcvbuf(int bufsize);
308 void k_hdr_include(int boolv);
309 void k_set_ttl(int t);
310 void k_set_loop(int l);
311 void k_set_if(u_int32 ifa);
312 void k_join(u_int32 grp, u_int32 ifa);
313 void k_leave(u_int32 grp, u_int32 ifa);
314 char * inet_fmt(u_int32 addr, char *s);
315 char * inet_fmts(u_int32 addr, u_int32 mask, char *s);
316 char * inet_name(u_int32 addr);
317 u_int32 host_addr(char *name);
318 /* u_int is promoted u_char */
319 char * proto_type(u_int type);
320 char * flag_type(u_int type);
322 u_int32 get_netmask(int s, u_int32 *dst);
323 int get_ttl(struct resp_buf *buf);
324 int t_diff(u_long a, u_long b);
325 u_long byteswap(u_long v);
326 int mtrace_callback(int, u_char *, int, struct igmp *,
327 int, struct sockaddr *, int *,
329 int send_recv(u_int32 dst, int type, int code,
330 int tries, struct resp_buf *save,
331 callback_t callback);
332 void passive_mode(void);
333 char * print_host(u_int32 addr);
334 char * print_host2(u_int32 addr1, u_int32 addr2);
335 void print_trace(int idx, struct resp_buf *buf,
337 int what_kind(struct resp_buf *buf, char *why);
338 char * scale(int *hop);
339 void stat_line(struct tr_resp *r, struct tr_resp *s,
340 int have_next, int *res);
341 void fixup_stats(struct resp_buf *base,
342 struct resp_buf *prev,
343 struct resp_buf *new,
345 int check_thresh(int thresh,
346 struct resp_buf *base,
347 struct resp_buf *prev,
348 struct resp_buf *new);
349 int print_stats(struct resp_buf *base,
350 struct resp_buf *prev,
351 struct resp_buf *new,
354 int path_changed(struct resp_buf *base,
355 struct resp_buf *new);
356 void check_vif_state(void);
358 int main(int argc, char **argv);
359 void dolog(int, int, char *, ...);
360 static void usage(void);
364 * Open and initialize the igmp socket, and fill in the non-changing
365 * IP header fields in the output packet buffer.
372 recv_buf = (char *)malloc(RECV_BUF_SIZE);
374 dolog(LOG_ERR, 0, "Out of memory allocating recv_buf!");
375 send_buf = (char *)malloc(RECV_BUF_SIZE);
377 dolog(LOG_ERR, 0, "Out of memory allocating send_buf!");
379 if ((igmp_socket = socket(AF_INET, SOCK_RAW, IPPROTO_IGMP)) < 0)
380 dolog(LOG_ERR, errno, "IGMP socket");
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 */
387 ip = (struct ip *)send_buf;
388 ip->ip_hl = sizeof(struct ip) >> 2;
389 ip->ip_v = IPVERSION;
392 ip->ip_p = IPPROTO_IGMP;
393 ip->ip_ttl = MAXTTL; /* applies to unicasts only */
395 #ifndef INADDR_ALLRTRS_GROUP
396 #define INADDR_ALLRTRS_GROUP 0xe0000002 /* 224.0.0.2 */
398 allrtrs_group = htonl(INADDR_ALLRTRS_GROUP);
400 router_alert[0] = IPOPT_RA; /* Router Alert */
401 router_alert[1] = 4; /* 4 bytes */
408 checkforsolarisbug(void)
410 u_int32 localhost = htonl(0x7f000001);
417 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS, eol, sizeof(eol));
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).
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);
429 int recvlen, dummy = 0;
431 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
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;
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)
445 igmp = (struct igmp *)(recv_buf + (ip->ip_hl << 2));
446 if (igmp->igmp_group.s_addr != 0)
448 if (igmp->igmp_type != 0 || igmp->igmp_code != 0)
451 p = (int *)((char *)igmp + IGMP_MINLEN);
455 #ifdef RAW_INPUT_IS_RAW
456 ip->ip_len = ntohs(ip->ip_len);
458 if (ip->ip_len == IGMP_MINLEN + 4)
460 else if (ip->ip_len == IGMP_MINLEN + 8)
463 dolog(LOG_ERR, 0, "while checking for Solaris bug: Sent %d bytes and got back %d!", IGMP_MINLEN + 8, ip->ip_len);
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'.
477 send_igmp(u_int32 src, u_int32 dst, int type, int code, u_int32 group,
480 struct sockaddr_in sdst;
484 static int raset = 0;
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;
494 ip->ip_len += ip_addlen;
496 #ifdef RAW_OUTPUT_IS_RAW
497 ip->ip_len = htons(ip->ip_len);
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);
508 if (IN_MULTICAST(ntohl(dst))) {
512 if (dst != allrtrs_group)
516 if (sendopts && sendra && !raset) {
517 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
518 router_alert, sizeof(router_alert));
520 } else if (!sendra && raset) {
523 * SunOS5 < 5.6 cannot properly reset the IP_OPTIONS "socket"
524 * option. Instead, set up a string of 4 EOL's.
526 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
529 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
535 bzero(&sdst, sizeof(sdst));
536 sdst.sin_family = AF_INET;
537 #if (defined(BSD) && (BSD >= 199103))
538 sdst.sin_len = sizeof(sdst);
540 sdst.sin_addr.s_addr = dst;
541 if (sendto(igmp_socket, send_buf, sendlen, 0,
542 (struct sockaddr *)&sdst, sizeof(sdst)) < 0) {
543 dolog(LOG_WARNING, errno, "sendto to %s on %s",
544 inet_fmt(dst, s1), inet_fmt(src, s2));
550 dolog(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),
557 * inet_cksum extracted from:
562 * U. S. Army Ballistic Research Laboratory
564 * Modified at Uc Berkeley
567 * Public Domain. Distribution Unlimited.
571 * Checksum routine for Internet Protocol family headers (C Version)
575 inet_cksum(u_short *addr, u_int len)
577 int nleft = (int)len;
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
593 /* mop up an odd byte, if necessary */
595 *(u_char *) (&answer) = *(u_char *)w ;
600 * add back carry outs from top 16 bits to low 16 bits
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 */
609 k_set_rcvbuf(int bufsize)
611 if (setsockopt(igmp_socket, SOL_SOCKET, SO_RCVBUF,
612 (char *)&bufsize, sizeof(bufsize)) < 0)
613 dolog(LOG_ERR, errno, "setsockopt SO_RCVBUF %u", bufsize);
618 k_hdr_include(int boolv)
621 if (setsockopt(igmp_socket, IPPROTO_IP, IP_HDRINCL,
622 (char *)&boolv, sizeof(boolv)) < 0)
623 dolog(LOG_ERR, errno, "setsockopt IP_HDRINCL %u", boolv);
633 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_TTL,
634 (char *)&ttl, sizeof(ttl)) < 0)
635 dolog(LOG_ERR, errno, "setsockopt IP_MULTICAST_TTL %u", ttl);
645 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_LOOP,
646 (char *)&loop, sizeof(loop)) < 0)
647 dolog(LOG_ERR, errno, "setsockopt IP_MULTICAST_LOOP %u", loop);
651 k_set_if(u_int32 ifa)
656 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_IF,
657 (char *)&adr, sizeof(adr)) < 0)
658 dolog(LOG_ERR, errno, "setsockopt IP_MULTICAST_IF %s",
663 k_join(u_int32 grp, u_int32 ifa)
667 mreq.imr_multiaddr.s_addr = grp;
668 mreq.imr_interface.s_addr = ifa;
670 if (setsockopt(igmp_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
671 (char *)&mreq, sizeof(mreq)) < 0)
672 dolog(LOG_WARNING, errno, "can't join group %s on interface %s",
673 inet_fmt(grp, s1), inet_fmt(ifa, s2));
678 k_leave(u_int32 grp, u_int32 ifa)
682 mreq.imr_multiaddr.s_addr = grp;
683 mreq.imr_interface.s_addr = ifa;
685 if (setsockopt(igmp_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
686 (char *)&mreq, sizeof(mreq)) < 0)
687 dolog(LOG_WARNING, errno, "can't leave group %s on interface %s",
688 inet_fmt(grp, s1), inet_fmt(ifa, s2));
692 * Convert an IP address in u_long (network) format into a printable string.
695 inet_fmt(u_int32 addr, char *s)
700 sprintf(s, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
706 * Convert an IP subnet number in u_long (network) format into a printable
707 * string including the netmask as a number of bits.
710 inet_fmts(u_int32 addr, u_int32 mask, char *s)
715 if ((addr == 0) && (mask == 0)) {
716 sprintf(s, "default");
721 bits = 33 - ffs(ntohl(mask));
723 if (m[3] != 0) sprintf(s, "%u.%u.%u.%u/%d", a[0], a[1], a[2], a[3],
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);
733 inet_name(u_int32 addr)
737 e = gethostbyaddr(&addr, sizeof(addr), AF_INET);
739 return e ? e->h_name : "?";
744 host_addr(char *name)
746 struct hostent *e = NULL;
754 * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
755 * if the name is all numeric.
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 */
763 for (i = 0; i < dots; ++i) {
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));
777 addr = inet_addr(buf);
778 if (addr == -1 || (IN_MULTICAST(addr) && dots)) {
780 printf("Could not parse %s as host name or address\n", name);
788 proto_type(u_int type)
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");
818 sprintf(buf, "Unknown protocol code %d", type);
825 flag_type(u_int type)
833 return ("Wrong interface");
835 return ("Prune sent upstream");
837 return ("Output pruned");
839 return ("Hit scope boundary");
843 return ("Not forwarding");
845 return ("Reached RP/Core");
847 return ("RPF Interface");
849 return ("Multicast disabled");
851 return ("Next router no mtrace");
853 return ("No space in packet");
854 case TR_ADMIN_PROHIB:
855 return ("Admin. Prohibited");
857 sprintf(buf, "Unknown error code %d", type);
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
870 get_netmask(int s, u_int32 *dst)
874 struct ifreq *ifrp, *ifend;
875 u_int32 if_addr, if_mask;
876 u_int32 retval = 0xFFFFFFFF;
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");
889 * If the buffer was large enough to hold all the addresses
890 * then break out, otherwise increase the buffer size and
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. ???
897 if ((num_ifreq * sizeof(struct ifreq)) >=
898 ifc.ifc_len + sizeof(struct ifreq))
902 ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
903 ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
905 if (ifc.ifc_buf == NULL) {
906 fprintf(stderr, "getting interface list: ran out of memory");
910 ifrp = (struct ifreq *)ifc.ifc_buf;
911 ifend = (struct ifreq *)(ifc.ifc_buf + ifc.ifc_len);
913 * Loop through all of the interfaces.
915 for (; ifrp < ifend && !found; ifrp = (struct ifreq *)((char *)ifrp + n)) {
917 n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
918 if (n < sizeof(*ifrp))
924 * Ignore any interface for an address family other than IP.
926 if (ifrp->ifr_addr.sa_family != AF_INET)
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);
935 if ((ifrp->ifr_flags & (IFF_MULTICAST|IFF_UP|IFF_LOOPBACK)) !=
936 (IFF_MULTICAST|IFF_UP))
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)) {
944 if (lcl_addr == 0) lcl_addr = if_addr; /* XXX what about aliases? */
947 if (lcl_addr == if_addr) found = TRUE;
949 if (!found && lcl_addr != 0) {
950 printf("Interface address is not valid\n");
958 * Try to pick a TTL that will get past all the thresholds in the path.
961 get_ttl(struct resp_buf *buf)
967 if (buf && (rno = buf->len) > 0) {
968 b = buf->resps + rno - 1;
973 if (ttl < b->tr_fttl) ttl = b->tr_fttl;
976 ttl += MULTICAST_TTL_INC;
977 if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
978 if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
980 } else return(MULTICAST_TTL1);
984 * Calculate the difference between two 32-bit NTP timestamps and return
985 * the result in milliseconds.
988 t_diff(u_long a, u_long b)
992 return ((d * 125) >> 13);
996 * Swap bytes for poor little-endian machines that don't byte-swap
1001 return ((v << 24) | ((v & 0xff00) << 8) |
1002 ((v >> 8) & 0xff00) | (v >> 24));
1007 * XXX incomplete - need private callback data, too?
1008 * XXX since dst doesn't get passed through?
1011 neighbors_callback(int tmo, u_char *buf, int buflen, struct igmp *igmp,
1012 int igmplen, struct sockaddr *addr, int *addrlen,
1017 struct ip *ip = (struct ip *)buf;
1022 if (igmp->igmp_code != DVMRP_NEIGHBORS2)
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.
1030 if (ip->ip_src.s_addr != dst) {
1031 u_int32 *p = (u_int32 *)(igmp + 1);
1032 u_int32 *ep = p + (len >> 2);
1034 u_int32 laddr = *p++;
1035 int n = ntohl(*p++) & 0xFF;
1037 ep = p + 1; /* ensure p < ep after loop */
1050 mtrace_callback(int tmo, u_char *buf, int buflen, struct igmp *igmp,
1051 int igmplen, struct sockaddr *addr, int *addrlen,
1054 static u_char *savbuf = NULL;
1055 static int savbuflen;
1056 static struct sockaddr *savaddr;
1057 static int savaddrlen;
1058 static struct timeval savts;
1060 int len = (igmplen - QLEN) / RLEN;
1061 struct tr_resp *r = (struct tr_resp *)((struct tr_query *)(igmp + 1) + 1);
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.
1069 bcopy(savbuf, buf, savbuflen);
1072 bcopy(savaddr, addr, savaddrlen);
1074 *addrlen = savaddrlen;
1075 bcopy(&savts, ts, sizeof(savts));
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
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
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).
1100 if (len == 1 && r->tr_rproto == 0 && r->tr_rmtaddr == 0 &&
1101 r->tr_rflags == TR_NO_FWD) {
1104 VAL_TO_MASK(smask, r->tr_smask);
1105 if ((r->tr_outaddr & smask) != (qdst & smask)) {
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);
1115 savaddr = (struct sockaddr *)malloc(*addrlen);
1116 if (savaddr != NULL) {
1117 bcopy(addr, savaddr, *addrlen);
1118 savaddrlen = *addrlen;
1119 bcopy(ts, &savts, sizeof(savts));
1133 send_recv(u_int32 dst, int type, int code, int tries, struct resp_buf *save,
1134 callback_t callback)
1137 struct timeval tq, tr, tv;
1140 struct tr_query *query, *rquery;
1142 struct sockaddr_in recvaddr;
1143 u_int32 local, group;
1144 int ipdatalen, iphdrlen, igmpdatalen;
1146 int count, recvlen, socklen = sizeof(recvaddr);
1150 if (type == IGMP_MTRACE) {
1152 datalen = sizeof(struct tr_query);
1154 group = htonl(0xff03);
1157 if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
1158 else local = INADDR_ANY;
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
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;
1177 for (i = tries ; i > 0; --i) {
1180 if (tries == nqueries && raddr == 0) {
1181 if (i == (nqueries >> 1)) {
1182 if (multicast && unicast) {
1183 query->tr_raddr = resp_cast;
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);
1191 if (i < tries && IN_MULTICAST(ntohl(query->tr_raddr)) &&
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);
1201 * Change the qid for each request sent to avoid being confused
1202 * by duplicate responses
1204 oqid = TR_GETQID(query->tr_rttlqid);
1206 TR_SETQID(query->tr_rttlqid, staticqid);
1209 TR_SETQID(query->tr_rttlqid, ((u_int32)lrand48() >> 8));
1211 TR_SETQID(query->tr_rttlqid, ((u_int32)arc4random() >> 8));
1215 * Set timer to calculate delays, then send query
1217 gettimeofday(&tq, 0);
1218 send_igmp(local, dst, type, code, group, datalen);
1221 * Wait for response, discarding false alarms
1224 if (igmp_socket >= FD_SETSIZE)
1225 dolog(LOG_ERR, 0, "descriptor too big");
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;
1234 count = select(igmp_socket + 1, &fds, NULL, NULL, &tv);
1237 if (errno != EINTR) warn("select");
1239 } else if (count == 0) {
1241 * Timed out. Notify the callback.
1243 if (!callback || (recvlen = (callback)(1, recv_buf, 0, NULL, 0, (struct sockaddr *)&recvaddr, &socklen, &tr)) == 0) {
1250 * Data is available on the socket, so read it.
1252 gettimeofday(&tr, 0);
1253 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1254 0, (struct sockaddr *)&recvaddr, &socklen);
1258 if (recvlen && errno != EINTR) warn("recvfrom");
1262 if (recvlen < sizeof(struct ip)) {
1263 warnx("packet too short (%u bytes) for IP header", recvlen);
1266 ip = (struct ip *) recv_buf;
1267 if (ip->ip_p == 0) /* ignore cache creation requests */
1270 iphdrlen = ip->ip_hl << 2;
1271 #ifdef RAW_INPUT_IS_RAW
1272 ipdatalen = ntohs(ip->ip_len);
1274 ipdatalen = ip->ip_len;
1276 if (iphdrlen + ipdatalen != recvlen) {
1277 warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1278 recvlen, iphdrlen, ipdatalen);
1282 igmp = (struct igmp *) (recv_buf + iphdrlen);
1283 igmpdatalen = ipdatalen - IGMP_MINLEN;
1284 if (igmpdatalen < 0) {
1285 warnx("IP data field too short (%u bytes) for IGMP from %s",
1286 ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1290 switch (igmp->igmp_type) {
1293 if (type != IGMP_DVMRP || code != DVMRP_ASK_NEIGHBORS2)
1295 if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
1298 * Accept DVMRP_NEIGHBORS2 response if it comes from the
1299 * address queried or if that address is one of the local
1300 * addresses in the response.
1302 if (ip->ip_src.s_addr != dst) {
1303 u_int32 *p = (u_int32 *)(igmp + 1);
1304 u_int32 *ep = p + (len >> 2);
1306 u_int32 laddr = *p++;
1307 int n = ntohl(*p++) & 0xFF;
1309 ep = p + 1; /* ensure p < ep after loop */
1314 if (p >= ep) continue;
1318 case IGMP_MTRACE: /* For backward compatibility with 3.3 */
1319 case IGMP_MTRACE_RESP:
1320 if (type != IGMP_MTRACE) continue;
1321 if (igmpdatalen <= QLEN) continue;
1322 if ((igmpdatalen - QLEN)%RLEN) {
1323 printf("packet with incomplete responses (%d bytes)\n",
1329 * Ignore responses that don't match query.
1331 rquery = (struct tr_query *)(igmp + 1);
1332 if (rquery->tr_src != qsrc || rquery->tr_dst != qdst)
1334 if (TR_GETQID(rquery->tr_rttlqid) !=
1335 TR_GETQID(query->tr_rttlqid)) {
1336 if (verbose && TR_GETQID(rquery->tr_rttlqid) == oqid)
1340 len = (igmpdatalen - QLEN)/RLEN;
1341 r = (struct tr_resp *)(rquery+1) + len - 1;
1344 * Ignore trace queries passing through this node when
1345 * mtrace is run on an mrouter that is in the path
1346 * (needed only because IGMP_MTRACE is accepted above
1347 * for backward compatibility with multicast release 3.3).
1349 if (igmp->igmp_type == IGMP_MTRACE) {
1352 VAL_TO_MASK(smask, r->tr_smask);
1353 if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
1354 && r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
1358 * Some routers will return error messages without
1359 * filling in their addresses. We fill in the address
1362 if (r->tr_outaddr == 0)
1363 r->tr_outaddr = recvaddr.sin_addr.s_addr;
1366 * A match, we'll keep this one.
1369 warnx("num hops received (%d) exceeds request (%d)",
1372 rquery->tr_raddr = query->tr_raddr; /* Insure these are */
1373 TR_SETTTL(rquery->tr_rttlqid, TR_GETTTL(query->tr_rttlqid));
1374 /* as we sent them */
1382 * We're pretty sure we want to use this packet now,
1383 * but if the caller gave a callback function, it might
1384 * want to handle it instead. Give the callback a chance,
1385 * unless the select timed out (in which case the only way
1386 * to get here is because the callback returned a packet).
1388 if (callback && (count != 0) && ((callback)(0, recv_buf, recvlen, igmp, igmpdatalen, (struct sockaddr*)&recvaddr, &socklen, &tr)) == 0) {
1390 * The callback function didn't like this packet.
1391 * Go try receiving another one.
1397 * Most of the sanity checking done at this point.
1398 * Return this packet we have been waiting for.
1401 save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
1402 (tq.tv_usec << 10) / 15625;
1403 save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
1404 (tr.tv_usec << 10) / 15625;
1406 bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
1415 * Most of this code is duplicated elsewhere. I'm not sure if
1416 * the duplication is absolutely required or not.
1418 * Ideally, this would keep track of ongoing statistics
1419 * collection and print out statistics. (& keep track
1420 * of h-b-h traces and only print the longest) For now,
1421 * it just snoops on what traces it can.
1431 struct sockaddr_in recvaddr;
1435 int ipdatalen, iphdrlen, igmpdatalen;
1439 struct mtrace *remembered = NULL, *m, *n, **nn;
1443 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1444 } else k_join(htonl(0xE0000120), lcl_addr);
1447 fflush(stdout); /* make sure previous trace is flushed */
1449 socklen = sizeof(recvaddr);
1450 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1451 0, (struct sockaddr *)&recvaddr, &socklen);
1452 gettimeofday(&tr,0);
1455 if (recvlen && errno != EINTR) warn("recvfrom");
1459 if (recvlen < sizeof(struct ip)) {
1460 warnx("packet too short (%u bytes) for IP header", recvlen);
1463 ip = (struct ip *) recv_buf;
1464 if (ip->ip_p == 0) /* ignore cache creation requests */
1467 iphdrlen = ip->ip_hl << 2;
1468 #ifdef RAW_INPUT_IS_RAW
1469 ipdatalen = ntohs(ip->ip_len);
1471 ipdatalen = ip->ip_len;
1473 if (iphdrlen + ipdatalen != recvlen) {
1474 warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1475 recvlen, iphdrlen, ipdatalen);
1479 igmp = (struct igmp *) (recv_buf + iphdrlen);
1480 igmpdatalen = ipdatalen - IGMP_MINLEN;
1481 if (igmpdatalen < 0) {
1482 warnx("IP data field too short (%u bytes) for IGMP from %s",
1483 ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1487 switch (igmp->igmp_type) {
1489 case IGMP_MTRACE: /* For backward compatibility with 3.3 */
1490 case IGMP_MTRACE_RESP:
1491 if (igmpdatalen < QLEN) continue;
1492 if ((igmpdatalen - QLEN)%RLEN) {
1493 printf("packet with incorrect datalen\n");
1497 len = (igmpdatalen - QLEN)/RLEN;
1505 base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
1506 (tr.tv_usec << 10) / 15625;
1507 base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
1508 (tr.tv_usec << 10) / 15625;
1510 bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
1512 * If the user specified which traces to monitor,
1513 * only accept traces that correspond to the
1516 if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
1517 (qdst != 0 && qdst != base.qhdr.tr_dst) ||
1518 (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
1521 /* XXX This should be a hash table */
1522 /* XXX garbage-collection should be more efficient */
1523 for (nn = &remembered, n = *nn, m = 0; n; n = *nn) {
1524 if ((n->base.qhdr.tr_src == base.qhdr.tr_src) &&
1525 (n->base.qhdr.tr_dst == base.qhdr.tr_dst) &&
1526 (n->base.igmp.igmp_group.s_addr == igmp->igmp_group.s_addr)) {
1530 if (tr.tv_sec - n->last.tv_sec > 500) { /* XXX don't hardcode */
1539 now = localtime(&tr_sec);
1540 strftime(timebuf, sizeof(timebuf) - 1, "%b %e %k:%M:%S", now);
1541 printf("Mtrace %s at %s",
1542 len == 0 ? "query" :
1543 igmp->igmp_type == IGMP_MTRACE_RESP ? "response" :
1547 printf(" by %s", inet_fmt(recvaddr.sin_addr.s_addr, s1));
1548 if (!IN_MULTICAST(base.qhdr.tr_raddr))
1549 printf(", resp to %s", (len == 0 && recvaddr.sin_addr.s_addr == base.qhdr.tr_raddr) ? "same" : inet_fmt(base.qhdr.tr_raddr, s1));
1551 printf(", respttl %d", TR_GETTTL(base.qhdr.tr_rttlqid));
1552 printf(", qid %06x\n", qid = TR_GETQID(base.qhdr.tr_rttlqid));
1553 printf("packet from %s to %s\n",
1554 inet_fmt(ip->ip_src.s_addr, s1),
1555 inet_fmt(ip->ip_dst.s_addr, s2));
1557 printf("from %s to %s via group %s (mxhop=%d)\n",
1558 inet_fmt(base.qhdr.tr_dst, s1), inet_fmt(base.qhdr.tr_src, s2),
1559 inet_fmt(igmp->igmp_group.s_addr, s3), igmp->igmp_code);
1564 r = base.resps + base.len - 1;
1566 * Some routers will return error messages without
1567 * filling in their addresses. We fill in the address
1570 if (r->tr_outaddr == 0)
1571 r->tr_outaddr = recvaddr.sin_addr.s_addr;
1574 * If there was a previous trace, it see if this is a
1575 * statistics candidate.
1577 if (m && base.len == m->base.len &&
1578 !(pc = path_changed(&m->base, &base))) {
1580 * Some mtrace responders send multiple copies of the same
1581 * reply. Skip this packet if it's got the same query-id
1584 if (m->lastqid == qid) {
1585 printf("Skipping duplicate reply\n");
1593 bcopy(&base, m->new, sizeof(base));
1595 printf("Results after %d seconds:\n\n",
1596 (int)((m->new->qtime - m->base.qtime) >> 16));
1597 fixup_stats(&m->base, m->prev, m->new, m->bugs);
1598 print_stats(&m->base, m->prev, m->new, m->bugs, m->names);
1600 m->new = &m->incr[(m->nresp & 1)];
1606 m = (struct mtrace *)malloc(sizeof(struct mtrace));
1608 fprintf(stderr, "Out of memory!\n");
1611 bzero(m, sizeof(struct mtrace));
1612 m->next = remembered;
1614 bcopy(&tr, &m->last, sizeof(tr));
1617 /* Either it's a hop-by-hop in progress, or the path changed. */
1619 printf("[Path Changed...]\n");
1620 bzero(m->bugs, sizeof(m->bugs));
1622 bcopy(&base, &m->base, sizeof(base));
1624 m->new = &m->incr[0];
1628 print_host(base.qhdr.tr_dst);
1630 print_trace(1, &base, m->names);
1631 VAL_TO_MASK(smask, r->tr_smask);
1632 if ((r->tr_inaddr & smask) == (base.qhdr.tr_src & smask)) {
1633 printf("%3d ", -(base.len+1));
1634 print_host(base.qhdr.tr_src);
1636 } else if (r->tr_rmtaddr != 0) {
1637 printf("%3d ", -(base.len+1));
1638 print_host(r->tr_rmtaddr);
1639 printf(" %s\n", r->tr_rflags == TR_OLD_ROUTER ?
1640 "doesn't support mtrace"
1641 : "is the next hop");
1648 print_host(u_int32 addr)
1650 return print_host2(addr, 0);
1654 * On some routers, one interface has a name and the other doesn't.
1655 * We always print the address of the outgoing interface, but can
1656 * sometimes get the name from the incoming interface. This might be
1657 * confusing but should be slightly more helpful than just a "?".
1660 print_host2(u_int32 addr1, u_int32 addr2)
1665 printf("%s", inet_fmt(addr1, s1));
1668 name = inet_name(addr1);
1669 if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
1670 name = inet_name(addr2);
1671 printf("%s (%s)", name, inet_fmt(addr1, s1));
1676 * Print responses as received (reverse path from dst to src)
1679 print_trace(int idx, struct resp_buf *buf, char **names)
1688 r = buf->resps + i - 1;
1690 for (; i <= buf->len; ++i, ++r) {
1691 if (idx > 0) printf("%3d ", -i);
1692 name = print_host2(r->tr_outaddr, r->tr_inaddr);
1693 if (r->tr_rflags != TR_NO_RTE)
1694 printf(" %s thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
1696 hop = t_diff(ntohl(r->tr_qarr), buf->qtime);
1698 printf(" %d%s", hop, ms);
1700 printf(" %s", flag_type(r->tr_rflags));
1701 if (i > 1 && r->tr_outaddr != (r-1)->tr_rmtaddr) {
1703 print_host((r-1)->tr_rmtaddr);
1705 if (r->tr_rflags != TR_NO_RTE) {
1706 if (r->tr_smask <= 1) /* MASK_TO_VAL() returns 1 for default */
1707 printf(" [default]");
1711 VAL_TO_MASK(smask, r->tr_smask);
1712 printf(" [%s]", inet_fmts(buf->qhdr.tr_src & smask,
1719 names[i-1]=malloc(strlen(name) + 1);
1720 strcpy(names[i-1], name);
1725 * See what kind of router is the next hop
1728 what_kind(struct resp_buf *buf, char *why)
1732 int hops = buf->len;
1733 struct tr_resp *r = buf->resps + hops - 1;
1734 u_int32 next = r->tr_rmtaddr;
1736 retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL);
1739 u_int32 version = ntohl(incr[0].igmp.igmp_group.s_addr);
1740 u_int32 *p = (u_int32 *)incr[0].ndata;
1741 u_int32 *ep = p + (incr[0].len >> 2);
1742 char *type = "version ";
1745 switch (version & 0xFF) {
1747 type = "proteon/mrouted ";
1755 printf(" [%s%d.%d] %s\n",
1756 type, version & 0xFF, (version >> 8) & 0xFF,
1758 VAL_TO_MASK(smask, r->tr_smask);
1760 u_int32 laddr = *p++;
1761 int flags = (ntohl(*p) & 0xFF00) >> 8;
1762 int n = ntohl(*p++) & 0xFF;
1763 if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
1764 (laddr & smask) == (qsrc & smask)) {
1765 printf("%3d ", -(hops+2));
1774 printf(" %s\n", why);
1782 if (*hop > -1000 && *hop < 10000)
1785 if (*hop > -1000 && *hop < 10000)
1791 * Calculate and print one line of packet loss and packet rate statistics.
1792 * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
1799 stat_line(struct tr_resp *r, struct tr_resp *s, int have_next, int *rst)
1801 int timediff = (ntohl(s->tr_qarr) - ntohl(r->tr_qarr)) >> 16;
1804 int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
1805 int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1807 char v_str[8], g_str[8];
1808 int vhave = NEITHER;
1809 int ghave = NEITHER;
1810 int gmissing = NEITHER;
1814 if (timediff == 0) {
1816 /* Might be 32 bits of int seconds instead of 16int+16frac */
1817 timediff = ntohl(s->tr_qarr) - ntohl(r->tr_qarr);
1818 if (timediff == 0 || abs(timediff - statint) > statint)
1821 v_pps = v_out / timediff;
1822 g_pps = g_out / timediff;
1824 #define STATS_MISSING(x) ((x) == 0xFFFFFFFF)
1826 if (!STATS_MISSING(s->tr_vifout) && !STATS_MISSING(r->tr_vifout))
1828 if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1830 if (!(*rst & BUG_NOPRINT))
1835 if (!STATS_MISSING(s->tr_vifin) && !STATS_MISSING(r->tr_vifin))
1837 if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1839 if (!(*rst & BUG_NOPRINT))
1844 * Stats can be missing for any number of reasons:
1845 * - The hop may not be capable of collecting stats
1846 * - Traffic may be getting dropped at the previous hop
1847 * and so this hop may not have any state
1849 * We need a stronger heuristic to tell between these
1850 * two cases; in case 1 we don't want to print the stats
1851 * and in case 2 we want to print 100% loss. We used to
1852 * err on the side of not printing, which is less useful
1853 * than printing 100% loss and dealing with it.
1857 * If both hops report as missing, then it's likely that there's just
1858 * no traffic flowing.
1860 * If just one hop is missing, then we really don't have it.
1862 if (gmissing != BOTH)
1866 whochar = have_next ? '^' : ' ';
1869 v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
1870 if (v_out) v_pct = v_lost * 100 / v_out;
1872 if (-20 < v_pct && v_pct < 101 && v_out > 10)
1873 sprintf(v_str, "%3d%%", v_pct);
1874 else if (v_pct < -900 && v_out > 10)
1875 sprintf(v_str, "%3dx", (int)(-v_pct / 100. + 1.));
1876 else if (v_pct <= -20 && v_out > 10)
1877 sprintf(v_str, "%1.1fx", -v_pct / 100. + 1.);
1879 memcpy(v_str, " -- ", 5);
1882 printf("%6d/%-5d=%s", v_lost, v_out, v_str);
1885 printf("%4d pps", v_pps);
1886 if (v_pps && badtime)
1892 v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
1893 v_pps = v_out / timediff;
1899 printf(" %c%-5d ", whochar, v_out);
1901 printf(" %c", whochar);
1902 printf("%4d pps", v_pps);
1903 if (v_pps && badtime)
1909 if (ghave != NEITHER)
1918 whochar = have_next ? '^' : ' ';
1921 g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
1922 if (g_out) g_pct = g_lost * 100 / g_out;
1924 if (-20 < g_pct && g_pct < 101 && g_out > 10)
1925 sprintf(g_str, "%3d%%", g_pct);
1926 else if (g_pct < -900 && g_out > 10)
1927 sprintf(g_str, "%3dx", (int)(-g_pct / 100. + 1.));
1928 else if (g_pct <= -20 && g_out > 10)
1929 sprintf(g_str, "%1.1fx", -g_pct / 100. + 1.);
1931 memcpy(g_str, " -- ", 5);
1933 printf("%s%6d/%-5d=%s%4d pps",
1934 tunstats ? "" : " ", g_lost, g_out, g_str, g_pps);
1935 if (g_pps && badtime)
1942 g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1943 g_pps = g_out / timediff;
1949 printf("%s ?/%-5d %4d pps",
1950 tunstats ? "" : " ", g_out, g_pps);
1964 printf("\t\t\t\tv_in: %ld ", (long)ntohl(s->tr_vifin));
1965 printf("v_out: %ld ", (long)ntohl(s->tr_vifout));
1966 printf("pkts: %ld\n", (long)ntohl(s->tr_pktcnt));
1967 printf("\t\t\t\tv_in: %ld ", (long)ntohl(r->tr_vifin));
1968 printf("v_out: %ld ", (long)ntohl(r->tr_vifout));
1969 printf("pkts: %ld\n", (long)ntohl(r->tr_pktcnt));
1970 printf("\t\t\t\tv_in: %ld ",
1971 (long)(ntohl(s->tr_vifin) - ntohl(r->tr_vifin)));
1972 printf("v_out: %ld ",
1973 (long)(ntohl(s->tr_vifout) - ntohl(r->tr_vifout)));
1974 printf("pkts: %ld ", (long)(ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt)));
1975 printf("time: %d\n", timediff);
1976 printf("\t\t\t\treset: %x hoptime: %lx\n", *rst, ntohl(s->tr_qarr));
1981 * A fixup to check if any pktcnt has been reset, and to fix the
1982 * byteorder bugs in mrouted 3.6 on little-endian machines.
1984 * XXX Since periodic traffic sources are likely to have their
1985 * pktcnt periodically reset, should we save old values when
1986 * the reset occurs to keep slightly better statistics over
1987 * the long term? (e.g. SAP)
1990 fixup_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new,
1993 int rno = base->len;
1994 struct tr_resp *b = base->resps + rno;
1995 struct tr_resp *p = prev->resps + rno;
1996 struct tr_resp *n = new->resps + rno;
1997 int *r = bugs + rno;
2001 /* Check for byte-swappers. Only check on the first trace,
2002 * since long-running traces can wrap around and falsely trigger. */
2003 while (--rno >= 0) {
2005 u_int32 nvifout = ntohl(n->tr_vifout);
2006 u_int32 pvifout = ntohl(p->tr_vifout);
2009 #ifdef TEST_ONLY /*XXX this is still buggy, so disable it for release */
2010 if ((*r & BUG_SWAP) ||
2012 (nvifout - pvifout) > (byteswap(nvifout) - byteswap(pvifout)))) {
2013 if (1 || debug > 2) {
2014 printf("ip %s swaps; b %08x p %08x n %08x\n",
2015 inet_fmt(n->tr_inaddr, s1),
2016 ntohl(b->tr_vifout), pvifout, nvifout);
2018 /* This host sends byteswapped reports; swap 'em */
2019 if (!(*r & BUG_SWAP)) {
2021 b->tr_qarr = byteswap(b->tr_qarr);
2022 b->tr_vifin = byteswap(b->tr_vifin);
2023 b->tr_vifout = byteswap(b->tr_vifout);
2024 b->tr_pktcnt = byteswap(b->tr_pktcnt);
2027 n->tr_qarr = byteswap(n->tr_qarr);
2028 n->tr_vifin = byteswap(n->tr_vifin);
2029 n->tr_vifout = byteswap(n->tr_vifout);
2030 n->tr_pktcnt = byteswap(n->tr_pktcnt);
2034 * A missing parenthesis in mrouted 3.5-3.8's prune.c
2035 * causes extremely bogus time diff's.
2036 * One half of the time calculation was
2037 * inside an htonl() and one half wasn't. Therefore, on
2038 * a little-endian machine, both halves of the calculation
2039 * would get added together in the little end. Thus, the
2040 * low-order 2 bytes are either 0000 (no overflow) or
2041 * 0100 (overflow from the addition).
2043 * Odds are against these particular bit patterns
2044 * happening in both prev and new for actual time values.
2046 if ((*r & BUG_BOGUSTIME) || (((ntohl(n->tr_qarr) & 0xfeff) == 0x0000) &&
2047 ((ntohl(p->tr_qarr) & 0xfeff) == 0x0000))) {
2048 *r |= BUG_BOGUSTIME;
2049 n->tr_qarr = new->rtime;
2050 p->tr_qarr = prev->rtime;
2051 b->tr_qarr = base->rtime;
2056 b = base->resps + rno;
2057 p = prev->resps + rno;
2058 n = new->resps + rno;
2061 while (--rno >= 0) {
2064 * This hop has reset if:
2065 * - There were statistics in the base AND previous pass, AND
2066 * - There are less packets this time than the first time and
2067 * we didn't reset last time, OR
2068 * - There are less packets this time than last time, OR
2069 * - There are no statistics on this pass.
2071 * The "and we didn't reset last time" is necessary in the
2072 * first branch of the OR because if the base is large and
2073 * we reset last time but the constant-resetter-avoidance
2074 * code kicked in so we delayed the copy of prev to base,
2075 * new could still be below base so we trigger the
2076 * constant-resetter code even though it was really only
2079 res = ((b->tr_pktcnt != 0xFFFFFFFF) && (p->tr_pktcnt != 0xFFFFFFFF) &&
2080 ((!(*r & BUG_RESET) && ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
2081 (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)) ||
2082 (n->tr_pktcnt == 0xFFFFFFFF)));
2084 printf("\t\tip=%s, r=%d, res=%d\n", inet_fmt(b->tr_inaddr, s1), *r, res);
2086 printf("\t\tbase=%ld, prev=%ld, new=%ld\n", ntohl(b->tr_pktcnt),
2087 ntohl(p->tr_pktcnt), ntohl(n->tr_pktcnt));
2089 if (*r & BUG_RESET) {
2090 if (res || (*r & BUG_RESET2X)) {
2092 * This router appears to be a 3.4 with that nasty ol'
2093 * neighbor version bug, which causes it to constantly
2094 * reset. Just nuke the statistics for this node, and
2095 * don't even bother giving it the benefit of the
2096 * doubt from now on.
2098 p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
2102 * This is simply the situation that the original
2103 * fixup_stats was meant to deal with -- that a
2104 * 3.3 or 3.4 router deleted a cache entry while
2105 * traffic was still active.
2115 if (cleanup == 0) return;
2118 * If some hop reset its counters and didn't continue to
2119 * reset, then we pretend that the previous
2120 * trace was the first one.
2123 b = base->resps + rno;
2124 p = prev->resps + rno;
2126 while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
2127 base->qtime = prev->qtime;
2128 base->rtime = prev->rtime;
2132 * Check per-source losses along path and compare with threshold.
2135 check_thresh(int thresh, struct resp_buf *base, struct resp_buf *prev,
2136 struct resp_buf *new)
2138 int rno = base->len - 1;
2139 struct tr_resp *b = base->resps + rno;
2140 struct tr_resp *p = prev->resps + rno;
2141 struct tr_resp *n = new->resps + rno;
2145 if ((n->tr_inaddr != b->tr_inaddr) ||
2146 (n->tr_outaddr != b->tr_outaddr) ||
2147 (n->tr_rmtaddr != b->tr_rmtaddr))
2148 return 1; /* Route changed */
2150 if (rno-- < 1) break;
2151 g_out = ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt);
2153 g_lost = g_out - (ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt));
2154 if (g_out && ((g_lost * 100 + (g_out >> 1))/ g_out) > thresh) {
2162 * Print responses with statistics for forward path (from src to dst)
2165 print_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new,
2166 int *bugs, char **names)
2171 int rno = base->len - 1;
2172 struct tr_resp *b = base->resps + rno;
2173 struct tr_resp *p = prev->resps + rno;
2174 struct tr_resp *n = new->resps + rno;
2175 int *r = bugs + rno;
2176 u_long resptime = new->rtime;
2177 u_long qarrtime = ntohl(n->tr_qarr);
2178 u_int ttl = MaX(1, n->tr_fttl) + 1;
2179 int first = (base == prev);
2181 VAL_TO_MASK(smask, b->tr_smask);
2182 printf(" Source Response Dest ");
2184 printf("Packet Statistics For Only For Traffic\n");
2186 printf("Overall Packet Statistics For Traffic From\n");
2187 inet_fmt(base->qhdr.tr_src, s1);
2188 printf("%-15s %-15s ",
2189 ((b->tr_inaddr & smask) == (base->qhdr.tr_src & smask)) ?
2191 inet_fmt(base->qhdr.tr_raddr, s2));
2192 inet_fmt(base->igmp.igmp_group.s_addr, s2);
2194 printf("All Multicast Traffic From %s\n", s1);
2196 printf("Packet %s To %s\n", s1, s2);
2197 rtt = t_diff(resptime, new->qtime);
2199 printf(" %c __/ rtt%5d%s ",
2200 (first && !verbose) ? 'v' : '|', rtt, ms);
2202 printf("Lost/Sent = Pct Rate To %s\n", s2);
2204 printf(" Rate Lost/Sent = Pct Rate\n");
2205 if (!first || verbose) {
2206 hop = t_diff(resptime, qarrtime);
2208 printf(" v / hop%5d%s ", hop, ms);
2210 printf("--------------------- --------------------\n");
2212 printf("------- ---------------------\n");
2214 if ((b->tr_inaddr & smask) != (base->qhdr.tr_src & smask) &&
2215 b->tr_rmtaddr != 0) {
2216 printf("%-15s %-14s is the previous hop\n", inet_fmt(b->tr_rmtaddr, s1),
2217 inet_name(b->tr_rmtaddr));
2221 printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
2222 printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
2223 printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
2224 printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
2225 printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
2226 printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
2227 printf("\t\t\t\tv_in: %ld ",
2228 (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
2229 printf("v_out: %ld ",
2230 (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
2231 printf("pkts: %ld\n",
2232 (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
2233 printf("\t\t\t\treset: %x hoptime: %lx\n", *r, (long)ntohl(n->tr_qarr));
2237 if ((n->tr_inaddr != b->tr_inaddr) ||
2238 (n->tr_outaddr != b->tr_outaddr) ||
2239 (n->tr_rmtaddr != b->tr_rmtaddr))
2240 return 1; /* Route changed */
2242 if ((n->tr_inaddr != n->tr_outaddr) && n->tr_inaddr)
2243 printf("%-15s\n", inet_fmt(n->tr_inaddr, s1));
2244 printf("%-15s %-14s %s%s\n", inet_fmt(n->tr_outaddr, s1), names[rno],
2245 flag_type(n->tr_rflags),
2246 (*r & BUG_NOPRINT) ? " [reset counters]" : "");
2248 if (rno-- < 1) break;
2250 printf(" %c ^ ttl%5d ", (first && !verbose) ? 'v' : '|',
2252 stat_line(p, n, TRUE, r);
2253 if (!first || verbose) {
2254 resptime = qarrtime;
2255 qarrtime = ntohl((n-1)->tr_qarr);
2256 hop = t_diff(resptime, qarrtime);
2258 printf(" v | hop%5d%s", hop, ms);
2262 stat_line(b, n, TRUE, r);
2266 ttl = MaX(ttl, MaX(1, n->tr_fttl) + base->len - rno);
2269 printf(" %c \\__ ttl%5d ", (first && !verbose) ? 'v' : '|',
2271 stat_line(p, n, FALSE, r);
2272 if (!first || verbose) {
2273 hop = t_diff(qarrtime, new->qtime);
2275 printf(" v \\ hop%5d%s", hop, ms);
2279 stat_line(b, n, FALSE, r);
2281 printf("%-15s %s\n", inet_fmt(base->qhdr.tr_dst, s1),
2282 !passive ? inet_fmt(lcl_addr, s2) : " * * * ");
2283 printf(" Receiver Query Source\n\n");
2288 * Determine whether or not the path has changed.
2291 path_changed(struct resp_buf *base, struct resp_buf *new)
2293 int rno = base->len - 1;
2294 struct tr_resp *b = base->resps + rno;
2295 struct tr_resp *n = new->resps + rno;
2297 while (rno-- >= 0) {
2298 if ((n->tr_inaddr != b->tr_inaddr) ||
2299 (n->tr_outaddr != b->tr_outaddr) ||
2300 (n->tr_rmtaddr != b->tr_rmtaddr))
2301 return 1; /* Route changed */
2302 if ((b->tr_rflags == TR_NO_RTE) &&
2303 (n->tr_rflags != TR_NO_RTE))
2304 return 1; /* Route got longer? */
2312 /***************************************************************************
2314 ***************************************************************************/
2317 main(int argc, char **argv)
2320 struct sockaddr_in addr;
2321 int addrlen = sizeof(addr);
2324 struct resp_buf *prev, *new;
2328 int hops, nexthop, tries;
2329 u_int32 lastout = 0;
2338 errx(1, "must be root");
2341 * We might get spawned by vat with the audio device open.
2342 * Close everything but stdin, stdout, stderr.
2344 for (i = 3; i < 255; i++)
2351 if (argc == 0) usage();
2353 while (argc > 0 && *argv[0] == '-') {
2354 char *p = *argv++; argc--;
2358 char *arg = (char *) 0;
2362 } else if (argc > 0) arg = argv[0];
2364 case 'd': /* Unlisted debug print option */
2365 if (arg && isdigit(*arg)) {
2367 if (debug < 0) debug = 0;
2368 if (debug > 3) debug = 3;
2369 if (arg == argv[0]) argv++, argc--;
2373 case 'M': /* Use multicast for reponse */
2376 case 'U': /* Use unicast for response */
2379 case 'L': /* Trace w/ loss threshold */
2380 if (arg && isdigit(*arg)) {
2381 lossthresh = atoi(arg);
2385 if (arg == argv[0]) argv++, argc--;
2390 case 'O': /* Don't use IP options */
2393 case 'P': /* Just watch the path */
2397 case 'Q': /* (undoc.) always use this QID */
2398 if (arg && isdigit(*arg)) {
2399 staticqid = atoi(arg);
2402 if (arg == argv[0]) argv++, argc--;
2407 case 'T': /* Print confusing tunnel stats */
2410 case 'W': /* Cisco's "weak" mtrace */
2413 case 'V': /* Print version and exit */
2415 * FreeBSD wants to have its own Id string, so
2416 * determination of the version number has to change.
2417 * XXX Note that this must be changed by hand on importing
2421 char *r = strdup(version);
2422 char *s = strchr(r, ',');
2424 while (s && *(s+1) != 'v')
2425 s = strchr(s + 1, ',');
2430 s += 3; /* , v sp */
2434 fprintf(stderr, "mtrace version 5.2/%s\n", s);
2436 fprintf(stderr, "mtrace could not determine version number!?\n");
2441 case 'l': /* Loop updating stats indefinitely */
2444 case 'n': /* Don't reverse map host addresses */
2447 case 'p': /* Passive listen for traces */
2450 case 'v': /* Verbosity */
2453 case 's': /* Short form, don't wait for stats */
2456 case 'w': /* Time to wait for packet arrival */
2457 if (arg && isdigit(*arg)) {
2458 timeout = atoi(arg);
2459 if (timeout < 1) timeout = 1;
2460 if (arg == argv[0]) argv++, argc--;
2464 case 'f': /* first hop */
2465 if (arg && isdigit(*arg)) {
2467 if (qno > MAXHOPS) qno = MAXHOPS;
2468 else if (qno < 1) qno = 0;
2469 if (arg == argv[0]) argv++, argc--;
2474 case 'm': /* Max number of hops to trace */
2475 if (arg && isdigit(*arg)) {
2477 if (qno > MAXHOPS) qno = MAXHOPS;
2478 else if (qno < 1) qno = 0;
2479 if (arg == argv[0]) argv++, argc--;
2483 case 'q': /* Number of query retries */
2484 if (arg && isdigit(*arg)) {
2485 nqueries = atoi(arg);
2486 if (nqueries < 1) nqueries = 1;
2487 if (arg == argv[0]) argv++, argc--;
2491 case 'g': /* Last-hop gateway (dest of query) */
2492 if (arg && (gwy = host_addr(arg))) {
2493 if (arg == argv[0]) argv++, argc--;
2497 case 't': /* TTL for query packet */
2498 if (arg && isdigit(*arg)) {
2500 if (qttl < 1) qttl = 1;
2502 if (arg == argv[0]) argv++, argc--;
2506 case 'e': /* Extra hops past non-responder */
2507 if (arg && isdigit(*arg)) {
2508 extrahops = atoi(arg);
2509 if (extrahops < 0) extrahops = 0;
2510 if (arg == argv[0]) argv++, argc--;
2514 case 'r': /* Dest for response packet */
2515 if (arg && (raddr = host_addr(arg))) {
2516 if (arg == argv[0]) argv++, argc--;
2520 case 'i': /* Local interface address */
2521 if (arg && (lcl_addr = host_addr(arg))) {
2522 if (arg == argv[0]) argv++, argc--;
2526 case 'S': /* Stat accumulation interval */
2527 if (arg && isdigit(*arg)) {
2528 statint = atoi(arg);
2529 if (statint < 1) statint = 1;
2530 if (arg == argv[0]) argv++, argc--;
2540 if (argc > 0 && (qsrc = host_addr(argv[0]))) { /* Source of path */
2541 if (IN_MULTICAST(ntohl(qsrc))) {
2543 /* Should probably rewrite arg parsing at some point, as
2544 * this makes "mtrace -g foo 224.1.2.3 224.2.3.4" valid!... */
2552 if (argc > 0 && (qdst = host_addr(argv[0]))) { /* Dest of path */
2554 if (argc > 0 && (qgrp = host_addr(argv[0]))) { /* Path via group */
2557 if (IN_MULTICAST(ntohl(qdst))) {
2558 u_int32 temp = qdst;
2561 if (IN_MULTICAST(ntohl(qdst))) usage();
2562 } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) usage();
2577 checkforsolarisbug();
2581 * Set useful defaults for as many parameters as possible.
2584 defgrp = 0; /* Default to no group */
2585 query_cast = htonl(0xE0000002); /* All routers multicast addr */
2586 resp_cast = htonl(0xE0000120); /* Mtrace response multicast addr */
2590 if (printstats && numstats != 0 && !tunstats) {
2591 /* Stats are useless without a group */
2593 "WARNING: no multicast group specified, so no statistics printed");
2599 "WARNING: group was specified so not performing \"weak\" mtrace");
2603 * Get default local address for multicasts to use in setting defaults.
2605 addr.sin_family = AF_INET;
2606 #if (defined(BSD) && (BSD >= 199103))
2607 addr.sin_len = sizeof(addr);
2609 addr.sin_addr.s_addr = qgrp ? qgrp : query_cast;
2610 addr.sin_port = htons(2000); /* Any port above 1024 will do */
2613 * Note that getsockname() can return 0 on some systems
2614 * (notably SunOS 5.x, x < 6). This is taken care of in
2615 * get_netmask(). If the default multicast interface (set
2616 * with the route for 224.0.0.0) is not the same as the
2617 * hostname, mtrace -i [if_addr] will have to be used.
2619 if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
2620 (connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
2621 getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0)
2622 err(-1, "determining local address");
2626 * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
2627 * This call to sysinfo will return the hostname.
2628 * If the default multicast interfface (set with the route
2629 * for 224.0.0.0) is not the same as the hostname,
2630 * mtrace -i [if_addr] will have to be used.
2632 if (addr.sin_addr.s_addr == 0) {
2633 char myhostname[MAXHOSTNAMELEN];
2637 error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
2639 err(1, "getting my hostname");
2641 hp = gethostbyname(myhostname);
2642 if (hp == NULL || hp->h_addrtype != AF_INET ||
2643 hp->h_length != sizeof(addr.sin_addr))
2644 err(1, "finding IP address for my hostname");
2646 memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr, hp->h_length);
2651 * Default destination for path to be queried is the local host.
2652 * When gateway specified, default destination is that gateway
2653 * and default source is local host.
2656 qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2657 dst_netmask = get_netmask(udp, &qdst);
2658 if (gwy && (gwy & dst_netmask) != (qdst & dst_netmask) &&
2659 !IN_MULTICAST(ntohl(gwy)))
2662 if (qsrc == 0 && gwy)
2663 qsrc = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2667 dst_netmask = get_netmask(udp, &qdst);
2669 if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
2672 * Initialize the seed for random query identifiers.
2674 gettimeofday(&tv, 0);
2675 seed = tv.tv_usec ^ lcl_addr;
2681 * Protect against unicast queries to mrouted versions that might crash.
2682 * Also use the obsolete "can mtrace" neighbor bit to warn about
2683 * older implementations.
2685 if (gwy && !IN_MULTICAST(ntohl(gwy)))
2686 if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL)) {
2687 int flags = ntohl(incr[0].igmp.igmp_group.s_addr);
2688 int version = flags & 0xFFFF;
2689 int info = (flags & 0xFF0000) >> 16;
2691 if (version == 0x0303 || version == 0x0503) {
2692 printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
2693 (version >> 8) & 0xFF);
2696 if ((info & 0x08) == 0) {
2699 printf(" probably doesn't support mtrace, trying anyway...\n");
2703 printf("Mtrace from %s to %s via group %s\n",
2704 inet_fmt(qsrc, s1), inet_fmt(qdst, s2), inet_fmt(qgrp, s3));
2706 if ((qdst & dst_netmask) == (qsrc & dst_netmask))
2707 fprintf(stderr, "mtrace: Source & receiver appear to be directly connected\n");
2710 * If the response is to be a multicast address, make sure we
2711 * are listening on that multicast address.
2714 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
2715 } else k_join(resp_cast, lcl_addr);
2717 memset(&base, 0, sizeof(base));
2720 * If the destination is on the local net, the last-hop router can
2721 * be found by multicast to the all-routers multicast group.
2722 * Otherwise, use the group address that is the subject of the
2723 * query since by definition the last-hop router will be a member.
2724 * Set default TTLs for local remote multicasts.
2727 if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
2730 if (tdst == 0 && qgrp == 0)
2731 errx(1, "mtrace: weak mtrace requires -g if destination is not local.\n");
2733 if (IN_MULTICAST(ntohl(tdst))) {
2734 k_set_loop(1); /* If I am running on a router, I need to hear this */
2735 if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
2736 else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
2740 * Try a query at the requested number of hops or MAXHOPS if unspecified.
2745 printf("Querying full reverse path... ");
2751 printf("Querying full reverse path, starting at hop %d...", qno);
2753 printf("Querying reverse path, maximum %d hops... ", qno);
2760 recvlen = send_recv(tdst, IGMP_MTRACE, hops, tries, &base, mtrace_callback);
2763 * If the initial query was successful, print it. Otherwise, if
2764 * the query max hop count is the default of zero, loop starting
2765 * from one until there is no response for extrahops more hops. The
2766 * extra hops allow getting past an mtrace-capable mrouter that can't
2767 * send multicast packets because all phyints are disabled.
2773 print_trace(1, &base, names);
2774 r = base.resps + base.len - 1;
2775 if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
2776 (qno != 0 && r->tr_rmtaddr != 0 && !fflag)) {
2777 printf("%3d ", -(base.len+1));
2778 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2779 "doesn't support mtrace"
2780 : "is the next hop");
2783 nexthop = hops = qno;
2786 VAL_TO_MASK(smask, r->tr_smask);
2787 if ((r->tr_inaddr & smask) == (qsrc & smask)) {
2788 printf("%3d ", -(base.len+1));
2793 } else if (qno == 0) {
2795 printf("switching to hop-by-hop:\n 0 ");
2799 for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
2800 printf("%3d ", -hops);
2804 * After a successful first hop, try switching to the unicast
2805 * address of the last-hop router instead of multicasting the
2806 * trace query. This should be safe for mrouted versions 3.3
2807 * and 3.5 because there is a long route timeout with metric
2808 * infinity before a route disappears. Switching to unicast
2809 * reduces the amount of multicast traffic and avoids a bug
2810 * with duplicate suppression in mrouted 3.5.
2812 if (hops == 2 && gwy == 0 && lastout != 0 &&
2813 (recvlen = send_recv(lastout, IGMP_MTRACE, hops, 1, &base, mtrace_callback)))
2815 else recvlen = send_recv(tdst, IGMP_MTRACE, hops, nqueries, &base, mtrace_callback);
2818 /*if (hops == 1) break;*/
2819 if (hops == nexthop) {
2822 } else if (what_kind(&base, "didn't respond")) {
2823 /* the ask_neighbors determined that the
2824 * not-responding router is the first-hop. */
2829 } else if (hops < nexthop + extrahops) {
2832 printf("...giving up\n");
2837 if (base.len == hops &&
2838 (hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
2839 if (hops == nexthop) {
2840 print_trace(-hops, &base, names);
2842 printf("\nResuming...\n");
2843 print_trace(nexthop, &base, names);
2846 if (base.len < hops) {
2848 * A shorter trace than requested means a fatal error
2849 * occurred along the path, or that the route changed
2852 * If the trace is longer than the last one we received,
2853 * then we are resuming from a skipped router (but there
2854 * is still probably a problem).
2856 * If the trace is shorter than the last one we
2857 * received, then the route must have changed (and
2858 * there is still probably a problem).
2860 if (nexthop <= base.len) {
2861 printf("\nResuming...\n");
2862 print_trace(nexthop, &base, names);
2863 } else if (nexthop > base.len + 1) {
2865 printf("\nRoute must have changed...\n");
2866 print_trace(1, &base, names);
2870 * The last hop address is not the same as it was.
2871 * If we didn't know the last hop then we just
2872 * got the first response from a hop-by-hop trace;
2873 * if we did know the last hop then
2874 * the route probably changed underneath us.
2878 printf("\nRoute must have changed...\n");
2880 printf("\nResuming...\n");
2881 print_trace(1, &base, names);
2885 r = base.resps + base.len - 1;
2886 lastout = r->tr_outaddr;
2888 if (base.len < hops ||
2889 r->tr_rmtaddr == 0 ||
2890 (r->tr_rflags & 0x80)) {
2891 VAL_TO_MASK(smask, r->tr_smask);
2892 if (r->tr_rmtaddr) {
2893 if (hops != nexthop) {
2894 printf("\n%3d ", -(base.len+1));
2896 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2897 "doesn't support mtrace" :
2898 "would be the next hop");
2899 /* XXX could do segmented trace if TR_NO_SPACE */
2900 } else if (r->tr_rflags == TR_NO_ERR &&
2901 (r->tr_inaddr & smask) == (qsrc & smask)) {
2902 printf("%3d ", -(hops + 1));
2913 if (base.rtime == 0) {
2914 printf("Timed out receiving responses\n");
2915 if (IN_MULTICAST(ntohl(tdst)))
2916 if (tdst == query_cast)
2917 printf("Perhaps no local router has a route for source %s\n",
2918 inet_fmt(qsrc, s1));
2920 printf("Perhaps receiver %s is not a member of group %s,\n\
2921 or no router local to it has a route for source %s,\n\
2922 or multicast at ttl %d doesn't reach its last-hop router for that source\n",
2923 inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
2924 qttl ? qttl : MULTICAST_TTL1);
2928 printf("Round trip time %d ms; ", t_diff(base.rtime, base.qtime));
2930 struct tr_resp *n = base.resps + base.len - 1;
2931 u_int ttl = n->tr_fttl + 1;
2936 ttl = MaX(ttl, MaX(1, n->tr_fttl) + base.len - rno);
2938 printf("total ttl of %d required.\n\n",ttl);
2942 * Use the saved response which was the longest one received,
2943 * and make additional probes after delay to measure loss.
2945 raddr = base.qhdr.tr_raddr;
2946 rttl = TR_GETTTL(base.qhdr.tr_rttlqid);
2947 gettimeofday(&tv, 0);
2948 waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
2950 new = &incr[numstats&1];
2953 * Zero out bug-avoidance counters
2955 memset(bugs, 0, sizeof(bugs));
2958 printf("Monitoring path..");
2960 while (numstats--) {
2961 if (waittime < 1) printf("\n");
2963 if (printstats && (lossthresh == 0 || printed)) {
2964 printf("Waiting to accumulate statistics...");
2969 sleep((unsigned)waittime);
2972 rno = hopbyhop ? base.len : qno ? qno : MAXHOPS;
2973 recvlen = send_recv(tdst, IGMP_MTRACE, rno, nqueries, new, mtrace_callback);
2976 printf("Timed out.\n");
2984 if (base.len != new->len || path_changed(&base, new)) {
2985 printf("%s", base.len == new->len ? "Route changed" :
2986 "Trace length doesn't match");
2988 printf(" after %d seconds",
2989 (int)((new->qtime - base.qtime) >> 16));
2992 print_trace(1, new, names);
2994 bcopy(new, &base, sizeof(base));
2995 nexthop = hops = new->len;
2996 printf("Continuing with hop-by-hop...\n");
3001 if (new->igmp.igmp_group.s_addr != qgrp ||
3002 new->qhdr.tr_src != qsrc || new->qhdr.tr_dst != qdst)
3003 printf("\nWARNING: trace modified en route; statistics may be incorrect\n");
3004 fixup_stats(&base, prev, new, bugs);
3005 if ((lossthresh == 0) || check_thresh(lossthresh, &base, prev, new)) {
3006 printf("Results after %d seconds",
3007 (int)((new->qtime - base.qtime) >> 16));
3009 printf(" (this trace %d seconds)",
3010 (int)((new->qtime - prev->qtime) >> 16));
3013 struct tm *qr = localtime(&t);
3015 printf(" qid 0x%06x at %2d:%02d:%02d",
3016 TR_GETQID(base.qhdr.tr_rttlqid),
3017 qr->tm_hour, qr->tm_min, qr->tm_sec);
3021 if (print_stats(&base, prev, new, bugs, names)) {
3022 printf("This should have been detected earlier, but ");
3023 printf("Route changed:\n");
3024 goto printandcontinue;
3029 new = &incr[numstats&1];
3034 * If the response was multicast back, leave the group
3037 if (IN_MULTICAST(ntohl(raddr))) k_leave(raddr, lcl_addr);
3038 } else k_leave(resp_cast, lcl_addr);
3046 fprintf(stderr, "%s\n%s\n%s\n",
3047 "usage: mtrace [-MUOPTWVlnpvs] [-e extra_hops] [-f first_hop] [-i if_addr]",
3048 " [-g gateway] [-m max_hops] [-q nqueries] [-r resp_dest]",
3049 " [-S statint] [-t ttl] [-w wait] source [receiver] [group]");
3054 check_vif_state(void)
3056 dolog(LOG_WARNING, errno, "sendto");
3060 * Log errors and other messages to stderr, according to the severity
3061 * of the message and the current debug level. For errors of severity
3062 * LOG_ERR or worse, terminate the program.
3065 dolog(int severity, int syserr, char *format, ...)
3070 va_start(ap, format);
3073 case 0: if (severity > LOG_WARNING) return;
3074 case 1: if (severity > LOG_NOTICE) return;
3075 case 2: if (severity > LOG_INFO ) return;
3078 if (severity == LOG_WARNING)
3079 strcpy(fmt, "warning - ");
3080 strncat(fmt, format, sizeof(fmt)-strlen(fmt));
3081 fmt[sizeof(fmt)-1]='\0';
3082 vfprintf(stderr, fmt, ap);
3084 fprintf(stderr, "\n");
3085 else if (syserr < sys_nerr)
3086 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
3088 fprintf(stderr, ": errno %d\n", syserr);
3090 if (severity <= LOG_ERR) exit(1);