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.4 2003/11/06 19:46:42 eirikn 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>
146 #include <sys/systeminfo.h>
149 typedef unsigned int u_int32; /* XXX */
152 const char version[] = "$DragonFly: src/usr.sbin/mrouted/mtrace.c,v 1.4 2003/11/06 19:46:42 eirikn Exp $";
154 #define DEFAULT_TIMEOUT 3 /* How long to wait before retrying requests */
155 #define DEFAULT_RETRIES 3 /* How many times to try */
156 #define DEFAULT_EXTRAHOPS 3 /* How many hops past a non-responding rtr */
157 #define MAXHOPS 60 /* Don't need more hops than this */
158 #define UNICAST_TTL 255 /* TTL for unicast response */
159 #define MULTICAST_TTL1 127 /* Default TTL for multicast query/response */
160 #define MULTICAST_TTL_INC 32 /* TTL increment for increase after timeout */
161 #define MULTICAST_TTL_MAX 192 /* Maximum TTL allowed (protect low-BW links */
165 #define DVMRP_ASK_NEIGHBORS2 5 /* DVMRP msg requesting neighbors */
166 #define DVMRP_NEIGHBORS2 6 /* reply to above */
167 #define DVMRP_NF_DOWN 0x10 /* kernel state of interface */
168 #define DVMRP_NF_DISABLED 0x20 /* administratively disabled */
169 #define MAX_IP_PACKET_LEN 576
170 #define MIN_IP_HEADER_LEN 20
171 #define MAX_IP_HEADER_LEN 60
172 #define MAX_DVMRP_DATA_LEN \
173 ( MAX_IP_PACKET_LEN - MAX_IP_HEADER_LEN - IGMP_MINLEN )
176 u_long qtime; /* Time query was issued */
177 u_long rtime; /* Time response was received */
178 int len; /* Number of reports or length of data */
179 struct igmp igmp; /* IGMP header */
182 struct tr_query q; /* Query/response header */
183 struct tr_resp r[MAXHOPS]; /* Per-hop reports */
185 char d[MAX_DVMRP_DATA_LEN]; /* Neighbor data */
193 char *names[MAXHOPS];
196 * In mrouted 3.3 and 3.4 (and in some Cisco IOS releases),
197 * cache entries can get deleted even if there is traffic
198 * flowing, which will reset the per-source/group counters.
200 #define BUG_RESET 0x01
203 * Also in mrouted 3.3 and 3.4, there's a bug in neighbor
204 * version processing which can cause them to believe that
205 * the neighbor is constantly resetting. This causes them
206 * to constantly delete all their state.
208 #define BUG_RESET2X 0x02
211 * Pre-3.7 mrouted's forget to byte-swap their reports.
213 #define BUG_SWAP 0x04
216 * Pre-3.9 mrouted's forgot a parenthesis in the htonl()
217 * on the time calculation so supply bogus times.
219 #define BUG_BOGUSTIME 0x08
221 #define BUG_NOPRINT (BUG_RESET | BUG_RESET2X)
223 int bugs[MAXHOPS]; /* List of bugs noticed at each hop */
227 struct resp_buf base, incr[2];
228 struct resp_buf *new, *prev;
232 char *names[MAXHOPS];
236 int timeout = DEFAULT_TIMEOUT;
237 int nqueries = DEFAULT_RETRIES;
241 int multicast = FALSE;
245 int tunstats = FALSE;
247 int extrahops = DEFAULT_EXTRAHOPS;
248 int printstats = TRUE;
254 u_int32 defgrp; /* Default group if not specified */
255 u_int32 query_cast; /* All routers multicast addr */
256 u_int32 resp_cast; /* Mtrace response multicast addr */
258 u_int32 lcl_addr = 0; /* This host address, in NET order */
259 u_int32 dst_netmask = 0; /* netmask to go with qdst */
262 * Query/response parameters, all initialized to zero and set later
263 * to default values or from options.
265 u_int32 qsrc = 0; /* Source address in the query */
266 u_int32 qgrp = 0; /* Group address in the query */
267 u_int32 qdst = 0; /* Destination (receiver) address in query */
268 u_char qno = 0; /* Max number of hops to query */
269 u_int32 raddr = 0; /* Address where response should be sent */
270 int qttl = 0; /* TTL for the query packet */
271 u_char rttl = 0; /* TTL for the response packet */
272 u_int32 gwy = 0; /* User-supplied last-hop router address */
273 u_int32 tdst = 0; /* Address where trace is sent (last-hop) */
275 char s1[19]; /* buffers to hold the string representations */
276 char s2[19]; /* of IP addresses, to be passed to inet_fmt() */
277 char s3[19]; /* or inet_fmts(). */
279 #if !(defined(BSD) && (BSD >= 199103))
282 extern char * sys_errlist[];
285 #define RECV_BUF_SIZE 8192
286 char *send_buf, *recv_buf;
288 u_int32 allrtrs_group;
289 char router_alert[4]; /* Router Alert IP Option */
294 char eol[4]; /* EOL IP Option */
295 int ip_addlen = 0; /* Workaround for Option bug #2 */
299 * max macro, with weird case to avoid conflicts
301 #define MaX(a,b) ((a) > (b) ? (a) : (b))
303 typedef int (*callback_t)(int, u_char *, int, struct igmp *, int,
304 struct sockaddr *, int *, struct timeval *);
306 void init_igmp(void);
307 void send_igmp(u_int32 src, u_int32 dst, int type,
308 int code, u_int32 group,
310 int inet_cksum(u_short *addr, u_int len);
311 void k_set_rcvbuf(int bufsize);
312 void k_hdr_include(int bool);
313 void k_set_ttl(int t);
314 void k_set_loop(int l);
315 void k_set_if(u_int32 ifa);
316 void k_join(u_int32 grp, u_int32 ifa);
317 void k_leave(u_int32 grp, u_int32 ifa);
318 char * inet_fmt(u_int32 addr, char *s);
319 char * inet_fmts(u_int32 addr, u_int32 mask, char *s);
320 char * inet_name(u_int32 addr);
321 u_int32 host_addr(char *name);
322 /* u_int is promoted u_char */
323 char * proto_type(u_int type);
324 char * flag_type(u_int type);
326 u_int32 get_netmask(int s, u_int32 *dst);
327 int get_ttl(struct resp_buf *buf);
328 int t_diff(u_long a, u_long b);
329 u_long byteswap(u_long v);
330 int mtrace_callback(int, u_char *, int, struct igmp *,
331 int, struct sockaddr *, int *,
333 int send_recv(u_int32 dst, int type, int code,
334 int tries, struct resp_buf *save,
335 callback_t callback);
336 void passive_mode(void);
337 char * print_host(u_int32 addr);
338 char * print_host2(u_int32 addr1, u_int32 addr2);
339 void print_trace(int idx, struct resp_buf *buf,
341 int what_kind(struct resp_buf *buf, char *why);
342 char * scale(int *hop);
343 void stat_line(struct tr_resp *r, struct tr_resp *s,
344 int have_next, int *res);
345 void fixup_stats(struct resp_buf *base,
346 struct resp_buf *prev,
347 struct resp_buf *new,
349 int check_thresh(int thresh,
350 struct resp_buf *base,
351 struct resp_buf *prev,
352 struct resp_buf *new);
353 int print_stats(struct resp_buf *base,
354 struct resp_buf *prev,
355 struct resp_buf *new,
358 int path_changed(struct resp_buf *base,
359 struct resp_buf *new);
360 void check_vif_state(void);
362 int main(int argc, char *argv[]);
363 void log(int, int, char *, ...);
364 static void usage(void);
368 * Open and initialize the igmp socket, and fill in the non-changing
369 * IP header fields in the output packet buffer.
376 recv_buf = (char *)malloc(RECV_BUF_SIZE);
378 log(LOG_ERR, 0, "Out of memory allocating recv_buf!");
379 send_buf = (char *)malloc(RECV_BUF_SIZE);
381 log(LOG_ERR, 0, "Out of memory allocating send_buf!");
383 if ((igmp_socket = socket(AF_INET, SOCK_RAW, IPPROTO_IGMP)) < 0)
384 log(LOG_ERR, errno, "IGMP socket");
386 k_hdr_include(TRUE); /* include IP header when sending */
387 k_set_rcvbuf(48*1024); /* lots of input buffering */
388 k_set_ttl(1); /* restrict multicasts to one hop */
389 k_set_loop(FALSE); /* disable multicast loopback */
391 ip = (struct ip *)send_buf;
392 ip->ip_hl = sizeof(struct ip) >> 2;
393 ip->ip_v = IPVERSION;
396 ip->ip_p = IPPROTO_IGMP;
397 ip->ip_ttl = MAXTTL; /* applies to unicasts only */
399 #ifndef INADDR_ALLRTRS_GROUP
400 #define INADDR_ALLRTRS_GROUP 0xe0000002 /* 224.0.0.2 */
402 allrtrs_group = htonl(INADDR_ALLRTRS_GROUP);
404 router_alert[0] = IPOPT_RA; /* Router Alert */
405 router_alert[1] = 4; /* 4 bytes */
414 u_int32 localhost = htonl(0x7f000001);
421 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS, eol, sizeof(eol));
423 * Check if the kernel adds the options length to the packet
424 * length. Send myself an IGMP packet of type 0 (illegal),
425 * with 4 IPOPT_EOL options, my PID (for collision detection)
426 * and 4 bytes of zero (so that the checksum works whether
427 * the 4 bytes of zero get truncated or not).
429 bzero(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN, 8);
430 *(int *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN) = getpid();
431 send_igmp(localhost, localhost, 0, 0, 0, 8);
433 int recvlen, dummy = 0;
435 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
437 /* 8 == 4 bytes of options and 4 bytes of PID */
438 if (recvlen >= MIN_IP_HEADER_LEN + IGMP_MINLEN + 8) {
439 struct ip *ip = (struct ip *)recv_buf;
443 if (ip->ip_hl != 6 ||
444 ip->ip_p != IPPROTO_IGMP ||
445 ip->ip_src.s_addr != localhost ||
446 ip->ip_dst.s_addr != localhost)
449 igmp = (struct igmp *)(recv_buf + (ip->ip_hl << 2));
450 if (igmp->igmp_group.s_addr != 0)
452 if (igmp->igmp_type != 0 || igmp->igmp_code != 0)
455 p = (int *)((char *)igmp + IGMP_MINLEN);
459 #ifdef RAW_INPUT_IS_RAW
460 ip->ip_len = ntohs(ip->ip_len);
462 if (ip->ip_len == IGMP_MINLEN + 4)
464 else if (ip->ip_len == IGMP_MINLEN + 8)
467 log(LOG_ERR, 0, "while checking for Solaris bug: Sent %d bytes and got back %d!", IGMP_MINLEN + 8, ip->ip_len);
476 * Construct an IGMP message in the output packet buffer. The caller may
477 * have already placed data in that buffer, of length 'datalen'. Then send
478 * the message from the interface with IP address 'src' to destination 'dst'.
481 send_igmp(src, dst, type, code, group, datalen)
487 struct sockaddr_in sdst;
491 static int raset = 0;
495 ip = (struct ip *)send_buf;
496 ip->ip_src.s_addr = src;
497 ip->ip_dst.s_addr = dst;
498 ip->ip_len = MIN_IP_HEADER_LEN + IGMP_MINLEN + datalen;
499 sendlen = ip->ip_len;
501 ip->ip_len += ip_addlen;
503 #ifdef RAW_OUTPUT_IS_RAW
504 ip->ip_len = htons(ip->ip_len);
507 igmp = (struct igmp *)(send_buf + MIN_IP_HEADER_LEN);
508 igmp->igmp_type = type;
509 igmp->igmp_code = code;
510 igmp->igmp_group.s_addr = group;
511 igmp->igmp_cksum = 0;
512 igmp->igmp_cksum = inet_cksum((u_short *)igmp,
513 IGMP_MINLEN + datalen);
515 if (IN_MULTICAST(ntohl(dst))) {
519 if (dst != allrtrs_group)
523 if (sendopts && sendra && !raset) {
524 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
525 router_alert, sizeof(router_alert));
527 } else if (!sendra && raset) {
530 * SunOS5 < 5.6 cannot properly reset the IP_OPTIONS "socket"
531 * option. Instead, set up a string of 4 EOL's.
533 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
536 setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
542 bzero(&sdst, sizeof(sdst));
543 sdst.sin_family = AF_INET;
544 #if (defined(BSD) && (BSD >= 199103))
545 sdst.sin_len = sizeof(sdst);
547 sdst.sin_addr.s_addr = dst;
548 if (sendto(igmp_socket, send_buf, sendlen, 0,
549 (struct sockaddr *)&sdst, sizeof(sdst)) < 0) {
550 log(LOG_WARNING, errno, "sendto to %s on %s",
551 inet_fmt(dst, s1), inet_fmt(src, s2));
557 log(LOG_DEBUG, 0, "SENT %s from %-15s to %s",
558 type == IGMP_MTRACE ? "mtrace request" : "ask_neighbors",
559 src == INADDR_ANY ? "INADDR_ANY" : inet_fmt(src, s1),
564 * inet_cksum extracted from:
569 * U. S. Army Ballistic Research Laboratory
571 * Modified at Uc Berkeley
574 * Public Domain. Distribution Unlimited.
578 * Checksum routine for Internet Protocol family headers (C Version)
582 inet_cksum(addr, len)
586 register int nleft = (int)len;
587 register u_short *w = addr;
589 register int sum = 0;
592 * Our algorithm is simple, using a 32 bit accumulator (sum),
593 * we add sequential 16 bit words to it, and at the end, fold
594 * back all the carry bits from the top 16 bits into the lower
602 /* mop up an odd byte, if necessary */
604 *(u_char *) (&answer) = *(u_char *)w ;
609 * add back carry outs from top 16 bits to low 16 bits
611 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
612 sum += (sum >> 16); /* add carry */
613 answer = ~sum; /* truncate to 16 bits */
618 k_set_rcvbuf(bufsize)
621 if (setsockopt(igmp_socket, SOL_SOCKET, SO_RCVBUF,
622 (char *)&bufsize, sizeof(bufsize)) < 0)
623 log(LOG_ERR, errno, "setsockopt SO_RCVBUF %u", bufsize);
632 if (setsockopt(igmp_socket, IPPROTO_IP, IP_HDRINCL,
633 (char *)&bool, sizeof(bool)) < 0)
634 log(LOG_ERR, errno, "setsockopt IP_HDRINCL %u", bool);
645 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_TTL,
646 (char *)&ttl, sizeof(ttl)) < 0)
647 log(LOG_ERR, errno, "setsockopt IP_MULTICAST_TTL %u", ttl);
658 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_LOOP,
659 (char *)&loop, sizeof(loop)) < 0)
660 log(LOG_ERR, errno, "setsockopt IP_MULTICAST_LOOP %u", loop);
670 if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_IF,
671 (char *)&adr, sizeof(adr)) < 0)
672 log(LOG_ERR, errno, "setsockopt IP_MULTICAST_IF %s",
683 mreq.imr_multiaddr.s_addr = grp;
684 mreq.imr_interface.s_addr = ifa;
686 if (setsockopt(igmp_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
687 (char *)&mreq, sizeof(mreq)) < 0)
688 log(LOG_WARNING, errno, "can't join group %s on interface %s",
689 inet_fmt(grp, s1), inet_fmt(ifa, s2));
700 mreq.imr_multiaddr.s_addr = grp;
701 mreq.imr_interface.s_addr = ifa;
703 if (setsockopt(igmp_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
704 (char *)&mreq, sizeof(mreq)) < 0)
705 log(LOG_WARNING, errno, "can't leave group %s on interface %s",
706 inet_fmt(grp, s1), inet_fmt(ifa, s2));
710 * Convert an IP address in u_long (network) format into a printable string.
720 sprintf(s, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
726 * Convert an IP subnet number in u_long (network) format into a printable
727 * string including the netmask as a number of bits.
730 inet_fmts(addr, mask, s)
734 register u_char *a, *m;
737 if ((addr == 0) && (mask == 0)) {
738 sprintf(s, "default");
743 bits = 33 - ffs(ntohl(mask));
745 if (m[3] != 0) sprintf(s, "%u.%u.%u.%u/%d", a[0], a[1], a[2], a[3],
747 else if (m[2] != 0) sprintf(s, "%u.%u.%u/%d", a[0], a[1], a[2], bits);
748 else if (m[1] != 0) sprintf(s, "%u.%u/%d", a[0], a[1], bits);
749 else sprintf(s, "%u/%d", a[0], bits);
760 e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
762 return e ? e->h_name : "?";
770 struct hostent *e = (struct hostent *)0;
778 * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
779 * if the name is all numeric.
781 for (i = sizeof(buf) - 7; i > 0; --i) {
782 if (*ip == '.') --dots;
783 else if (*ip == '\0') break;
784 else if (!isdigit(*ip)) dots = 0; /* Not numeric, don't add zeroes */
787 for (i = 0; i < dots; ++i) {
794 e = gethostbyname(name);
795 if (e && (e->h_length == sizeof(addr))) {
796 memcpy((char *)&addr, e->h_addr_list[0], e->h_length);
797 if (e->h_addr_list[1])
798 fprintf(stderr, "Warning: %s has multiple addresses, using %s\n",
799 name, inet_fmt(addr, s1));
801 addr = inet_addr(buf);
802 if (addr == -1 || (IN_MULTICAST(addr) && dots)) {
804 printf("Could not parse %s as host name or address\n", name);
826 case PROTO_PIM_SPECIAL:
827 return ("PIM/Special");
828 case PROTO_PIM_STATIC:
829 return ("PIM/Static");
830 case PROTO_DVMRP_STATIC:
831 return ("DVMRP/Static");
832 case PROTO_PIM_BGP4PLUS:
833 return ("PIM/BGP4+");
834 case PROTO_CBT_SPECIAL:
835 return ("CBT/Special");
836 case PROTO_CBT_STATIC:
837 return ("CBT/Static");
838 case PROTO_PIM_ASSERT:
839 return ("PIM/Assert");
843 (void) sprintf(buf, "Unknown protocol code %d", type);
859 return ("Wrong interface");
861 return ("Prune sent upstream");
863 return ("Output pruned");
865 return ("Hit scope boundary");
869 return ("Not forwarding");
871 return ("Reached RP/Core");
873 return ("RPF Interface");
875 return ("Multicast disabled");
877 return ("Next router no mtrace");
879 return ("No space in packet");
880 case TR_ADMIN_PROHIB:
881 return ("Admin. Prohibited");
883 (void) sprintf(buf, "Unknown error code %d", type);
889 * If destination is on a local net, get the netmask, else set the
890 * netmask to all ones. There are two side effects: if the local
891 * address was not explicitly set, and if the destination is on a
892 * local net, use that one; in either case, verify that the local
902 struct ifreq *ifrp, *ifend;
903 u_int32 if_addr, if_mask;
904 u_int32 retval = 0xFFFFFFFF;
908 ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
909 ifc.ifc_buf = malloc(ifc.ifc_len);
910 while (ifc.ifc_buf) {
911 if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) {
912 perror("ioctl SIOCGIFCONF");
917 * If the buffer was large enough to hold all the addresses
918 * then break out, otherwise increase the buffer size and
921 * The only way to know that we definitely had enough space
922 * is to know that there was enough space for at least one
923 * more struct ifreq. ???
925 if ((num_ifreq * sizeof(struct ifreq)) >=
926 ifc.ifc_len + sizeof(struct ifreq))
930 ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
931 ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
933 if (ifc.ifc_buf == NULL) {
934 fprintf(stderr, "getting interface list: ran out of memory");
938 ifrp = (struct ifreq *)ifc.ifc_buf;
939 ifend = (struct ifreq *)(ifc.ifc_buf + ifc.ifc_len);
941 * Loop through all of the interfaces.
943 for (; ifrp < ifend && !found; ifrp = (struct ifreq *)((char *)ifrp + n)) {
945 n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
946 if (n < sizeof(*ifrp))
952 * Ignore any interface for an address family other than IP.
954 if (ifrp->ifr_addr.sa_family != AF_INET)
957 if_addr = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
958 if (ioctl(s, SIOCGIFFLAGS, (char *)ifrp) < 0) {
959 fprintf(stderr, "SIOCGIFFLAGS on ");
960 perror(ifrp->ifr_name);
963 if ((ifrp->ifr_flags & (IFF_MULTICAST|IFF_UP|IFF_LOOPBACK)) !=
964 (IFF_MULTICAST|IFF_UP))
968 if (ioctl(s, SIOCGIFNETMASK, (char *)ifrp) >= 0) {
969 if_mask = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
970 if (if_mask != 0 && (*dst & if_mask) == (if_addr & if_mask)) {
972 if (lcl_addr == 0) lcl_addr = if_addr; /* XXX what about aliases? */
975 if (lcl_addr == if_addr) found = TRUE;
977 if (!found && lcl_addr != 0) {
978 printf("Interface address is not valid\n");
986 * Try to pick a TTL that will get past all the thresholds in the path.
990 struct resp_buf *buf;
996 if (buf && (rno = buf->len) > 0) {
997 b = buf->resps + rno - 1;
1002 if (ttl < b->tr_fttl) ttl = b->tr_fttl;
1005 ttl += MULTICAST_TTL_INC;
1006 if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
1007 if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
1009 } else return(MULTICAST_TTL1);
1013 * Calculate the difference between two 32-bit NTP timestamps and return
1014 * the result in milliseconds.
1022 return ((d * 125) >> 13);
1026 * Swap bytes for poor little-endian machines that don't byte-swap
1032 return ((v << 24) | ((v & 0xff00) << 8) |
1033 ((v >> 8) & 0xff00) | (v >> 24));
1038 * XXX incomplete - need private callback data, too?
1039 * XXX since dst doesn't get passed through?
1042 neighbors_callback(tmo, buf, buflen, igmp, igmplen, addr, addrlen, ts)
1048 struct sockaddr *addr;
1054 struct ip *ip = (struct ip *)buf;
1059 if (igmp->igmp_code != DVMRP_NEIGHBORS2)
1063 * Accept DVMRP_NEIGHBORS2 response if it comes from the
1064 * address queried or if that address is one of the local
1065 * addresses in the response.
1067 if (ip->ip_src.s_addr != dst) {
1068 u_int32 *p = (u_int32 *)(igmp + 1);
1069 u_int32 *ep = p + (len >> 2);
1071 u_int32 laddr = *p++;
1072 int n = ntohl(*p++) & 0xFF;
1074 ep = p + 1; /* ensure p < ep after loop */
1087 mtrace_callback(tmo, buf, buflen, igmp, igmplen, addr, addrlen, ts)
1093 struct sockaddr *addr;
1097 static u_char *savbuf = NULL;
1098 static int savbuflen;
1099 static struct sockaddr *savaddr;
1100 static int savaddrlen;
1101 static struct timeval savts;
1103 int len = (igmplen - QLEN) / RLEN;
1104 struct tr_resp *r = (struct tr_resp *)((struct tr_query *)(igmp + 1) + 1);
1108 * If we timed out with a packet saved, then return that packet.
1109 * send_recv won't send this same packet to the callback again.
1112 bcopy(savbuf, buf, savbuflen);
1115 bcopy(savaddr, addr, savaddrlen);
1117 *addrlen = savaddrlen;
1118 bcopy(&savts, ts, sizeof(savts));
1129 * Check for IOS bug described in CSCdi68628, where a router that does
1130 * not have multicast enabled responds to an mtrace request with a 1-hop
1133 * If there is only one hop reported in the packet,
1134 * And the protocol code is 0,
1135 * And there is no previous hop,
1136 * And the forwarding information is "Not Forwarding",
1137 * And the router is not on the same subnet as the destination of the
1139 * then drop this packet. The "#if 0"'d code saves it and returns
1140 * it on timeout, but timeouts are too common (e.g. routers with
1141 * limited unicast routing tables, etc).
1143 if (len == 1 && r->tr_rproto == 0 && r->tr_rmtaddr == 0 &&
1144 r->tr_rflags == TR_NO_FWD) {
1147 VAL_TO_MASK(smask, r->tr_smask);
1148 if ((r->tr_outaddr & smask) != (qdst & smask)) {
1150 /* XXX should do this silently? */
1151 fprintf(stderr, "mtrace: probably IOS-buggy packet from %s\n",
1152 inet_fmt(((struct sockaddr_in *)addr)->sin_addr.s_addr, s1));
1153 /* Save the packet to return if a timeout occurs. */
1154 savbuf = (u_char *)malloc(buflen);
1155 if (savbuf != NULL) {
1156 bcopy(buf, savbuf, buflen);
1158 savaddr = (struct sockaddr *)malloc(*addrlen);
1159 if (savaddr != NULL) {
1160 bcopy(addr, savaddr, *addrlen);
1161 savaddrlen = *addrlen;
1162 bcopy(ts, &savts, sizeof(savts));
1176 send_recv(dst, type, code, tries, save, callback)
1178 int type, code, tries;
1179 struct resp_buf *save;
1180 callback_t callback;
1183 struct timeval tq, tr, tv;
1186 struct tr_query *query, *rquery;
1188 struct sockaddr_in recvaddr;
1189 u_int32 local, group;
1190 int ipdatalen, iphdrlen, igmpdatalen;
1192 int count, recvlen, socklen = sizeof(recvaddr);
1196 if (type == IGMP_MTRACE) {
1198 datalen = sizeof(struct tr_query);
1200 group = htonl(0xff03);
1203 if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
1204 else local = INADDR_ANY;
1207 * If the reply address was not explictly specified, start off
1208 * with the standard multicast reply address, or the unicast
1209 * address of this host if the unicast flag was specified.
1210 * Then, if there is no response after trying half the tries
1211 * with multicast, switch to the unicast address of this host
1212 * if the multicast flag was not specified. If the TTL was
1213 * also not specified, set a multicast TTL and increase it
1216 query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
1217 query->tr_raddr = raddr ? raddr : unicast ? lcl_addr : resp_cast;
1218 TR_SETTTL(query->tr_rttlqid, rttl ? rttl :
1219 IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL);
1220 query->tr_src = qsrc;
1221 query->tr_dst = qdst;
1223 for (i = tries ; i > 0; --i) {
1226 if (tries == nqueries && raddr == 0) {
1227 if (i == (nqueries >> 1)) {
1228 if (multicast && unicast) {
1229 query->tr_raddr = resp_cast;
1231 TR_SETTTL(query->tr_rttlqid, get_ttl(save));
1232 } else if (!multicast) {
1233 query->tr_raddr = lcl_addr;
1234 TR_SETTTL(query->tr_rttlqid, UNICAST_TTL);
1237 if (i < tries && IN_MULTICAST(ntohl(query->tr_raddr)) &&
1239 TR_SETTTL(query->tr_rttlqid,
1240 TR_GETTTL(query->tr_rttlqid) + MULTICAST_TTL_INC);
1241 if (TR_GETTTL(query->tr_rttlqid) > MULTICAST_TTL_MAX)
1242 TR_SETTTL(query->tr_rttlqid, MULTICAST_TTL_MAX);
1247 * Change the qid for each request sent to avoid being confused
1248 * by duplicate responses
1250 oqid = TR_GETQID(query->tr_rttlqid);
1252 TR_SETQID(query->tr_rttlqid, staticqid);
1255 TR_SETQID(query->tr_rttlqid, ((u_int32)lrand48() >> 8));
1257 TR_SETQID(query->tr_rttlqid, ((u_int32)arc4random() >> 8));
1261 * Set timer to calculate delays, then send query
1263 gettimeofday(&tq, 0);
1264 send_igmp(local, dst, type, code, group, datalen);
1267 * Wait for response, discarding false alarms
1270 if (igmp_socket >= FD_SETSIZE)
1271 log(LOG_ERR, 0, "descriptor too big");
1273 FD_SET(igmp_socket, &fds);
1274 gettimeofday(&tv, 0);
1275 tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
1276 tv.tv_usec = tq.tv_usec - tv.tv_usec;
1277 if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
1278 if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;
1280 count = select(igmp_socket + 1, &fds, (fd_set *)0, (fd_set *)0,
1284 if (errno != EINTR) warn("select");
1286 } else if (count == 0) {
1288 * Timed out. Notify the callback.
1290 if (!callback || (recvlen = (callback)(1, recv_buf, 0, NULL, 0, (struct sockaddr *)&recvaddr, &socklen, &tr)) == 0) {
1297 * Data is available on the socket, so read it.
1299 gettimeofday(&tr, 0);
1300 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1301 0, (struct sockaddr *)&recvaddr, &socklen);
1305 if (recvlen && errno != EINTR) warn("recvfrom");
1309 if (recvlen < sizeof(struct ip)) {
1310 warnx("packet too short (%u bytes) for IP header", recvlen);
1313 ip = (struct ip *) recv_buf;
1314 if (ip->ip_p == 0) /* ignore cache creation requests */
1317 iphdrlen = ip->ip_hl << 2;
1318 #ifdef RAW_INPUT_IS_RAW
1319 ipdatalen = ntohs(ip->ip_len);
1321 ipdatalen = ip->ip_len;
1323 if (iphdrlen + ipdatalen != recvlen) {
1324 warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1325 recvlen, iphdrlen, ipdatalen);
1329 igmp = (struct igmp *) (recv_buf + iphdrlen);
1330 igmpdatalen = ipdatalen - IGMP_MINLEN;
1331 if (igmpdatalen < 0) {
1332 warnx("IP data field too short (%u bytes) for IGMP from %s",
1333 ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1337 switch (igmp->igmp_type) {
1340 if (type != IGMP_DVMRP || code != DVMRP_ASK_NEIGHBORS2)
1342 if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
1345 * Accept DVMRP_NEIGHBORS2 response if it comes from the
1346 * address queried or if that address is one of the local
1347 * addresses in the response.
1349 if (ip->ip_src.s_addr != dst) {
1350 u_int32 *p = (u_int32 *)(igmp + 1);
1351 u_int32 *ep = p + (len >> 2);
1353 u_int32 laddr = *p++;
1354 int n = ntohl(*p++) & 0xFF;
1356 ep = p + 1; /* ensure p < ep after loop */
1361 if (p >= ep) continue;
1365 case IGMP_MTRACE: /* For backward compatibility with 3.3 */
1366 case IGMP_MTRACE_RESP:
1367 if (type != IGMP_MTRACE) continue;
1368 if (igmpdatalen <= QLEN) continue;
1369 if ((igmpdatalen - QLEN)%RLEN) {
1370 printf("packet with incomplete responses (%d bytes)\n",
1376 * Ignore responses that don't match query.
1378 rquery = (struct tr_query *)(igmp + 1);
1379 if (rquery->tr_src != qsrc || rquery->tr_dst != qdst)
1381 if (TR_GETQID(rquery->tr_rttlqid) !=
1382 TR_GETQID(query->tr_rttlqid)) {
1383 if (verbose && TR_GETQID(rquery->tr_rttlqid) == oqid)
1387 len = (igmpdatalen - QLEN)/RLEN;
1388 r = (struct tr_resp *)(rquery+1) + len - 1;
1391 * Ignore trace queries passing through this node when
1392 * mtrace is run on an mrouter that is in the path
1393 * (needed only because IGMP_MTRACE is accepted above
1394 * for backward compatibility with multicast release 3.3).
1396 if (igmp->igmp_type == IGMP_MTRACE) {
1399 VAL_TO_MASK(smask, r->tr_smask);
1400 if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
1401 && r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
1405 * Some routers will return error messages without
1406 * filling in their addresses. We fill in the address
1409 if (r->tr_outaddr == 0)
1410 r->tr_outaddr = recvaddr.sin_addr.s_addr;
1413 * A match, we'll keep this one.
1416 warnx("num hops received (%d) exceeds request (%d)",
1419 rquery->tr_raddr = query->tr_raddr; /* Insure these are */
1420 TR_SETTTL(rquery->tr_rttlqid, TR_GETTTL(query->tr_rttlqid));
1421 /* as we sent them */
1429 * We're pretty sure we want to use this packet now,
1430 * but if the caller gave a callback function, it might
1431 * want to handle it instead. Give the callback a chance,
1432 * unless the select timed out (in which case the only way
1433 * to get here is because the callback returned a packet).
1435 if (callback && (count != 0) && ((callback)(0, recv_buf, recvlen, igmp, igmpdatalen, (struct sockaddr*)&recvaddr, &socklen, &tr)) == 0) {
1437 * The callback function didn't like this packet.
1438 * Go try receiving another one.
1444 * Most of the sanity checking done at this point.
1445 * Return this packet we have been waiting for.
1448 save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
1449 (tq.tv_usec << 10) / 15625;
1450 save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
1451 (tr.tv_usec << 10) / 15625;
1453 bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
1462 * Most of this code is duplicated elsewhere. I'm not sure if
1463 * the duplication is absolutely required or not.
1465 * Ideally, this would keep track of ongoing statistics
1466 * collection and print out statistics. (& keep track
1467 * of h-b-h traces and only print the longest) For now,
1468 * it just snoops on what traces it can.
1478 struct sockaddr_in recvaddr;
1482 int ipdatalen, iphdrlen, igmpdatalen;
1486 struct mtrace *remembered = NULL, *m, *n, **nn;
1490 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1491 } else k_join(htonl(0xE0000120), lcl_addr);
1494 fflush(stdout); /* make sure previous trace is flushed */
1496 socklen = sizeof(recvaddr);
1497 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1498 0, (struct sockaddr *)&recvaddr, &socklen);
1499 gettimeofday(&tr,0);
1502 if (recvlen && errno != EINTR) warn("recvfrom");
1506 if (recvlen < sizeof(struct ip)) {
1507 warnx("packet too short (%u bytes) for IP header", recvlen);
1510 ip = (struct ip *) recv_buf;
1511 if (ip->ip_p == 0) /* ignore cache creation requests */
1514 iphdrlen = ip->ip_hl << 2;
1515 #ifdef RAW_INPUT_IS_RAW
1516 ipdatalen = ntohs(ip->ip_len);
1518 ipdatalen = ip->ip_len;
1520 if (iphdrlen + ipdatalen != recvlen) {
1521 warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1522 recvlen, iphdrlen, ipdatalen);
1526 igmp = (struct igmp *) (recv_buf + iphdrlen);
1527 igmpdatalen = ipdatalen - IGMP_MINLEN;
1528 if (igmpdatalen < 0) {
1529 warnx("IP data field too short (%u bytes) for IGMP from %s",
1530 ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1534 switch (igmp->igmp_type) {
1536 case IGMP_MTRACE: /* For backward compatibility with 3.3 */
1537 case IGMP_MTRACE_RESP:
1538 if (igmpdatalen < QLEN) continue;
1539 if ((igmpdatalen - QLEN)%RLEN) {
1540 printf("packet with incorrect datalen\n");
1544 len = (igmpdatalen - QLEN)/RLEN;
1552 base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
1553 (tr.tv_usec << 10) / 15625;
1554 base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
1555 (tr.tv_usec << 10) / 15625;
1557 bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
1559 * If the user specified which traces to monitor,
1560 * only accept traces that correspond to the
1563 if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
1564 (qdst != 0 && qdst != base.qhdr.tr_dst) ||
1565 (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
1568 /* XXX This should be a hash table */
1569 /* XXX garbage-collection should be more efficient */
1570 for (nn = &remembered, n = *nn, m = 0; n; n = *nn) {
1571 if ((n->base.qhdr.tr_src == base.qhdr.tr_src) &&
1572 (n->base.qhdr.tr_dst == base.qhdr.tr_dst) &&
1573 (n->base.igmp.igmp_group.s_addr == igmp->igmp_group.s_addr)) {
1577 if (tr.tv_sec - n->last.tv_sec > 500) { /* XXX don't hardcode */
1586 now = localtime(&tr_sec);
1587 strftime(timebuf, sizeof(timebuf) - 1, "%b %e %k:%M:%S", now);
1588 printf("Mtrace %s at %s",
1589 len == 0 ? "query" :
1590 igmp->igmp_type == IGMP_MTRACE_RESP ? "response" :
1594 printf(" by %s", inet_fmt(recvaddr.sin_addr.s_addr, s1));
1595 if (!IN_MULTICAST(base.qhdr.tr_raddr))
1596 printf(", resp to %s", (len == 0 && recvaddr.sin_addr.s_addr == base.qhdr.tr_raddr) ? "same" : inet_fmt(base.qhdr.tr_raddr, s1));
1598 printf(", respttl %d", TR_GETTTL(base.qhdr.tr_rttlqid));
1599 printf(", qid %06x\n", qid = TR_GETQID(base.qhdr.tr_rttlqid));
1600 printf("packet from %s to %s\n",
1601 inet_fmt(ip->ip_src.s_addr, s1),
1602 inet_fmt(ip->ip_dst.s_addr, s2));
1604 printf("from %s to %s via group %s (mxhop=%d)\n",
1605 inet_fmt(base.qhdr.tr_dst, s1), inet_fmt(base.qhdr.tr_src, s2),
1606 inet_fmt(igmp->igmp_group.s_addr, s3), igmp->igmp_code);
1611 r = base.resps + base.len - 1;
1613 * Some routers will return error messages without
1614 * filling in their addresses. We fill in the address
1617 if (r->tr_outaddr == 0)
1618 r->tr_outaddr = recvaddr.sin_addr.s_addr;
1621 * If there was a previous trace, it see if this is a
1622 * statistics candidate.
1624 if (m && base.len == m->base.len &&
1625 !(pc = path_changed(&m->base, &base))) {
1627 * Some mtrace responders send multiple copies of the same
1628 * reply. Skip this packet if it's got the same query-id
1631 if (m->lastqid == qid) {
1632 printf("Skipping duplicate reply\n");
1640 bcopy(&base, m->new, sizeof(base));
1642 printf("Results after %d seconds:\n\n",
1643 (int)((m->new->qtime - m->base.qtime) >> 16));
1644 fixup_stats(&m->base, m->prev, m->new, m->bugs);
1645 print_stats(&m->base, m->prev, m->new, m->bugs, m->names);
1647 m->new = &m->incr[(m->nresp & 1)];
1653 m = (struct mtrace *)malloc(sizeof(struct mtrace));
1655 fprintf(stderr, "Out of memory!\n");
1658 bzero(m, sizeof(struct mtrace));
1659 m->next = remembered;
1661 bcopy(&tr, &m->last, sizeof(tr));
1664 /* Either it's a hop-by-hop in progress, or the path changed. */
1666 printf("[Path Changed...]\n");
1667 bzero(m->bugs, sizeof(m->bugs));
1669 bcopy(&base, &m->base, sizeof(base));
1671 m->new = &m->incr[0];
1675 print_host(base.qhdr.tr_dst);
1677 print_trace(1, &base, m->names);
1678 VAL_TO_MASK(smask, r->tr_smask);
1679 if ((r->tr_inaddr & smask) == (base.qhdr.tr_src & smask)) {
1680 printf("%3d ", -(base.len+1));
1681 print_host(base.qhdr.tr_src);
1683 } else if (r->tr_rmtaddr != 0) {
1684 printf("%3d ", -(base.len+1));
1685 print_host(r->tr_rmtaddr);
1686 printf(" %s\n", r->tr_rflags == TR_OLD_ROUTER ?
1687 "doesn't support mtrace"
1688 : "is the next hop");
1698 return print_host2(addr, 0);
1702 * On some routers, one interface has a name and the other doesn't.
1703 * We always print the address of the outgoing interface, but can
1704 * sometimes get the name from the incoming interface. This might be
1705 * confusing but should be slightly more helpful than just a "?".
1708 print_host2(addr1, addr2)
1709 u_int32 addr1, addr2;
1714 printf("%s", inet_fmt(addr1, s1));
1717 name = inet_name(addr1);
1718 if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
1719 name = inet_name(addr2);
1720 printf("%s (%s)", name, inet_fmt(addr1, s1));
1725 * Print responses as received (reverse path from dst to src)
1728 print_trace(idx, buf, names)
1730 struct resp_buf *buf;
1740 r = buf->resps + i - 1;
1742 for (; i <= buf->len; ++i, ++r) {
1743 if (idx > 0) printf("%3d ", -i);
1744 name = print_host2(r->tr_outaddr, r->tr_inaddr);
1745 if (r->tr_rflags != TR_NO_RTE)
1746 printf(" %s thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
1748 hop = t_diff(ntohl(r->tr_qarr), buf->qtime);
1750 printf(" %d%s", hop, ms);
1752 printf(" %s", flag_type(r->tr_rflags));
1753 if (i > 1 && r->tr_outaddr != (r-1)->tr_rmtaddr) {
1755 print_host((r-1)->tr_rmtaddr);
1757 if (r->tr_rflags != TR_NO_RTE) {
1758 if (r->tr_smask <= 1) /* MASK_TO_VAL() returns 1 for default */
1759 printf(" [default]");
1763 VAL_TO_MASK(smask, r->tr_smask);
1764 printf(" [%s]", inet_fmts(buf->qhdr.tr_src & smask,
1771 names[i-1]=malloc(strlen(name) + 1);
1772 strcpy(names[i-1], name);
1777 * See what kind of router is the next hop
1781 struct resp_buf *buf;
1786 int hops = buf->len;
1787 struct tr_resp *r = buf->resps + hops - 1;
1788 u_int32 next = r->tr_rmtaddr;
1790 retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL);
1793 u_int32 version = ntohl(incr[0].igmp.igmp_group.s_addr);
1794 u_int32 *p = (u_int32 *)incr[0].ndata;
1795 u_int32 *ep = p + (incr[0].len >> 2);
1796 char *type = "version ";
1799 switch (version & 0xFF) {
1801 type = "proteon/mrouted ";
1809 printf(" [%s%d.%d] %s\n",
1810 type, version & 0xFF, (version >> 8) & 0xFF,
1812 VAL_TO_MASK(smask, r->tr_smask);
1814 u_int32 laddr = *p++;
1815 int flags = (ntohl(*p) & 0xFF00) >> 8;
1816 int n = ntohl(*p++) & 0xFF;
1817 if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
1818 (laddr & smask) == (qsrc & smask)) {
1819 printf("%3d ", -(hops+2));
1828 printf(" %s\n", why);
1837 if (*hop > -1000 && *hop < 10000) return (" ms");
1839 if (*hop > -1000 && *hop < 10000) return (" s ");
1844 * Calculate and print one line of packet loss and packet rate statistics.
1845 * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
1852 stat_line(r, s, have_next, rst)
1853 struct tr_resp *r, *s;
1857 int timediff = (ntohl(s->tr_qarr) - ntohl(r->tr_qarr)) >> 16;
1860 int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
1861 int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1863 char v_str[8], g_str[8];
1864 int vhave = NEITHER;
1865 int ghave = NEITHER;
1866 int gmissing = NEITHER;
1870 if (timediff == 0) {
1872 /* Might be 32 bits of int seconds instead of 16int+16frac */
1873 timediff = ntohl(s->tr_qarr) - ntohl(r->tr_qarr);
1874 if (timediff == 0 || abs(timediff - statint) > statint)
1877 v_pps = v_out / timediff;
1878 g_pps = g_out / timediff;
1880 #define STATS_MISSING(x) ((x) == 0xFFFFFFFF)
1882 if (!STATS_MISSING(s->tr_vifout) && !STATS_MISSING(r->tr_vifout))
1884 if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1886 if (!(*rst & BUG_NOPRINT))
1891 if (!STATS_MISSING(s->tr_vifin) && !STATS_MISSING(r->tr_vifin))
1893 if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1895 if (!(*rst & BUG_NOPRINT))
1900 * Stats can be missing for any number of reasons:
1901 * - The hop may not be capable of collecting stats
1902 * - Traffic may be getting dropped at the previous hop
1903 * and so this hop may not have any state
1905 * We need a stronger heuristic to tell between these
1906 * two cases; in case 1 we don't want to print the stats
1907 * and in case 2 we want to print 100% loss. We used to
1908 * err on the side of not printing, which is less useful
1909 * than printing 100% loss and dealing with it.
1913 * If both hops report as missing, then it's likely that there's just
1914 * no traffic flowing.
1916 * If just one hop is missing, then we really don't have it.
1918 if (gmissing != BOTH)
1922 whochar = have_next ? '^' : ' ';
1925 v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
1926 if (v_out) v_pct = v_lost * 100 / v_out;
1928 if (-20 < v_pct && v_pct < 101 && v_out > 10)
1929 sprintf(v_str, "%3d%%", v_pct);
1930 else if (v_pct < -900 && v_out > 10)
1931 sprintf(v_str, "%3dx", (int)(-v_pct / 100. + 1.));
1932 else if (v_pct <= -20 && v_out > 10)
1933 sprintf(v_str, "%1.1fx", -v_pct / 100. + 1.);
1935 memcpy(v_str, " -- ", 5);
1938 printf("%6d/%-5d=%s", v_lost, v_out, v_str);
1941 printf("%4d pps", v_pps);
1942 if (v_pps && badtime)
1948 v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
1949 v_pps = v_out / timediff;
1955 printf(" %c%-5d ", whochar, v_out);
1957 printf(" %c", whochar);
1958 printf("%4d pps", v_pps);
1959 if (v_pps && badtime)
1965 if (ghave != NEITHER)
1974 whochar = have_next ? '^' : ' ';
1977 g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
1978 if (g_out) g_pct = g_lost * 100 / g_out;
1980 if (-20 < g_pct && g_pct < 101 && g_out > 10)
1981 sprintf(g_str, "%3d%%", g_pct);
1982 else if (g_pct < -900 && g_out > 10)
1983 sprintf(g_str, "%3dx", (int)(-g_pct / 100. + 1.));
1984 else if (g_pct <= -20 && g_out > 10)
1985 sprintf(g_str, "%1.1fx", -g_pct / 100. + 1.);
1987 memcpy(g_str, " -- ", 5);
1989 printf("%s%6d/%-5d=%s%4d pps",
1990 tunstats ? "" : " ", g_lost, g_out, g_str, g_pps);
1991 if (g_pps && badtime)
1998 g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1999 g_pps = g_out / timediff;
2005 printf("%s ?/%-5d %4d pps",
2006 tunstats ? "" : " ", g_out, g_pps);
2020 printf("\t\t\t\tv_in: %ld ", (long)ntohl(s->tr_vifin));
2021 printf("v_out: %ld ", (long)ntohl(s->tr_vifout));
2022 printf("pkts: %ld\n", (long)ntohl(s->tr_pktcnt));
2023 printf("\t\t\t\tv_in: %ld ", (long)ntohl(r->tr_vifin));
2024 printf("v_out: %ld ", (long)ntohl(r->tr_vifout));
2025 printf("pkts: %ld\n", (long)ntohl(r->tr_pktcnt));
2026 printf("\t\t\t\tv_in: %ld ",
2027 (long)(ntohl(s->tr_vifin) - ntohl(r->tr_vifin)));
2028 printf("v_out: %ld ",
2029 (long)(ntohl(s->tr_vifout) - ntohl(r->tr_vifout)));
2030 printf("pkts: %ld ", (long)(ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt)));
2031 printf("time: %d\n", timediff);
2032 printf("\t\t\t\treset: %x hoptime: %lx\n", *rst, ntohl(s->tr_qarr));
2037 * A fixup to check if any pktcnt has been reset, and to fix the
2038 * byteorder bugs in mrouted 3.6 on little-endian machines.
2040 * XXX Since periodic traffic sources are likely to have their
2041 * pktcnt periodically reset, should we save old values when
2042 * the reset occurs to keep slightly better statistics over
2043 * the long term? (e.g. SAP)
2046 fixup_stats(base, prev, new, bugs)
2047 struct resp_buf *base, *prev, *new;
2050 int rno = base->len;
2051 struct tr_resp *b = base->resps + rno;
2052 struct tr_resp *p = prev->resps + rno;
2053 struct tr_resp *n = new->resps + rno;
2054 int *r = bugs + rno;
2058 /* Check for byte-swappers. Only check on the first trace,
2059 * since long-running traces can wrap around and falsely trigger. */
2060 while (--rno >= 0) {
2062 u_int32 nvifout = ntohl(n->tr_vifout);
2063 u_int32 pvifout = ntohl(p->tr_vifout);
2066 #ifdef TEST_ONLY /*XXX this is still buggy, so disable it for release */
2067 if ((*r & BUG_SWAP) ||
2069 (nvifout - pvifout) > (byteswap(nvifout) - byteswap(pvifout)))) {
2070 if (1 || debug > 2) {
2071 printf("ip %s swaps; b %08x p %08x n %08x\n",
2072 inet_fmt(n->tr_inaddr, s1),
2073 ntohl(b->tr_vifout), pvifout, nvifout);
2075 /* This host sends byteswapped reports; swap 'em */
2076 if (!(*r & BUG_SWAP)) {
2078 b->tr_qarr = byteswap(b->tr_qarr);
2079 b->tr_vifin = byteswap(b->tr_vifin);
2080 b->tr_vifout = byteswap(b->tr_vifout);
2081 b->tr_pktcnt = byteswap(b->tr_pktcnt);
2084 n->tr_qarr = byteswap(n->tr_qarr);
2085 n->tr_vifin = byteswap(n->tr_vifin);
2086 n->tr_vifout = byteswap(n->tr_vifout);
2087 n->tr_pktcnt = byteswap(n->tr_pktcnt);
2091 * A missing parenthesis in mrouted 3.5-3.8's prune.c
2092 * causes extremely bogus time diff's.
2093 * One half of the time calculation was
2094 * inside an htonl() and one half wasn't. Therefore, on
2095 * a little-endian machine, both halves of the calculation
2096 * would get added together in the little end. Thus, the
2097 * low-order 2 bytes are either 0000 (no overflow) or
2098 * 0100 (overflow from the addition).
2100 * Odds are against these particular bit patterns
2101 * happening in both prev and new for actual time values.
2103 if ((*r & BUG_BOGUSTIME) || (((ntohl(n->tr_qarr) & 0xfeff) == 0x0000) &&
2104 ((ntohl(p->tr_qarr) & 0xfeff) == 0x0000))) {
2105 *r |= BUG_BOGUSTIME;
2106 n->tr_qarr = new->rtime;
2107 p->tr_qarr = prev->rtime;
2108 b->tr_qarr = base->rtime;
2113 b = base->resps + rno;
2114 p = prev->resps + rno;
2115 n = new->resps + rno;
2118 while (--rno >= 0) {
2121 * This hop has reset if:
2122 * - There were statistics in the base AND previous pass, AND
2123 * - There are less packets this time than the first time and
2124 * we didn't reset last time, OR
2125 * - There are less packets this time than last time, OR
2126 * - There are no statistics on this pass.
2128 * The "and we didn't reset last time" is necessary in the
2129 * first branch of the OR because if the base is large and
2130 * we reset last time but the constant-resetter-avoidance
2131 * code kicked in so we delayed the copy of prev to base,
2132 * new could still be below base so we trigger the
2133 * constant-resetter code even though it was really only
2136 res = ((b->tr_pktcnt != 0xFFFFFFFF) && (p->tr_pktcnt != 0xFFFFFFFF) &&
2137 ((!(*r & BUG_RESET) && ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
2138 (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)) ||
2139 (n->tr_pktcnt == 0xFFFFFFFF)));
2141 printf("\t\tip=%s, r=%d, res=%d\n", inet_fmt(b->tr_inaddr, s1), *r, res);
2143 printf("\t\tbase=%ld, prev=%ld, new=%ld\n", ntohl(b->tr_pktcnt),
2144 ntohl(p->tr_pktcnt), ntohl(n->tr_pktcnt));
2146 if (*r & BUG_RESET) {
2147 if (res || (*r & BUG_RESET2X)) {
2149 * This router appears to be a 3.4 with that nasty ol'
2150 * neighbor version bug, which causes it to constantly
2151 * reset. Just nuke the statistics for this node, and
2152 * don't even bother giving it the benefit of the
2153 * doubt from now on.
2155 p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
2159 * This is simply the situation that the original
2160 * fixup_stats was meant to deal with -- that a
2161 * 3.3 or 3.4 router deleted a cache entry while
2162 * traffic was still active.
2172 if (cleanup == 0) return;
2175 * If some hop reset its counters and didn't continue to
2176 * reset, then we pretend that the previous
2177 * trace was the first one.
2180 b = base->resps + rno;
2181 p = prev->resps + rno;
2183 while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
2184 base->qtime = prev->qtime;
2185 base->rtime = prev->rtime;
2189 * Check per-source losses along path and compare with threshold.
2192 check_thresh(thresh, base, prev, new)
2194 struct resp_buf *base, *prev, *new;
2196 int rno = base->len - 1;
2197 struct tr_resp *b = base->resps + rno;
2198 struct tr_resp *p = prev->resps + rno;
2199 struct tr_resp *n = new->resps + rno;
2203 if ((n->tr_inaddr != b->tr_inaddr) ||
2204 (n->tr_outaddr != b->tr_outaddr) ||
2205 (n->tr_rmtaddr != b->tr_rmtaddr))
2206 return 1; /* Route changed */
2208 if (rno-- < 1) break;
2209 g_out = ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt);
2211 g_lost = g_out - (ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt));
2212 if (g_out && ((g_lost * 100 + (g_out >> 1))/ g_out) > thresh) {
2220 * Print responses with statistics for forward path (from src to dst)
2223 print_stats(base, prev, new, bugs, names)
2224 struct resp_buf *base, *prev, *new;
2231 int rno = base->len - 1;
2232 struct tr_resp *b = base->resps + rno;
2233 struct tr_resp *p = prev->resps + rno;
2234 struct tr_resp *n = new->resps + rno;
2235 int *r = bugs + rno;
2236 u_long resptime = new->rtime;
2237 u_long qarrtime = ntohl(n->tr_qarr);
2238 u_int ttl = MaX(1, n->tr_fttl) + 1;
2239 int first = (base == prev);
2241 VAL_TO_MASK(smask, b->tr_smask);
2242 printf(" Source Response Dest ");
2244 printf("Packet Statistics For Only For Traffic\n");
2246 printf("Overall Packet Statistics For Traffic From\n");
2247 (void)inet_fmt(base->qhdr.tr_src, s1);
2248 printf("%-15s %-15s ",
2249 ((b->tr_inaddr & smask) == (base->qhdr.tr_src & smask)) ?
2251 inet_fmt(base->qhdr.tr_raddr, s2));
2252 (void)inet_fmt(base->igmp.igmp_group.s_addr, s2);
2254 printf("All Multicast Traffic From %s\n", s1);
2256 printf("Packet %s To %s\n", s1, s2);
2257 rtt = t_diff(resptime, new->qtime);
2259 printf(" %c __/ rtt%5d%s ",
2260 (first && !verbose) ? 'v' : '|', rtt, ms);
2262 printf("Lost/Sent = Pct Rate To %s\n", s2);
2264 printf(" Rate Lost/Sent = Pct Rate\n");
2265 if (!first || verbose) {
2266 hop = t_diff(resptime, qarrtime);
2268 printf(" v / hop%5d%s ", hop, ms);
2270 printf("--------------------- --------------------\n");
2272 printf("------- ---------------------\n");
2274 if ((b->tr_inaddr & smask) != (base->qhdr.tr_src & smask) &&
2275 b->tr_rmtaddr != 0) {
2276 printf("%-15s %-14s is the previous hop\n", inet_fmt(b->tr_rmtaddr, s1),
2277 inet_name(b->tr_rmtaddr));
2281 printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
2282 printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
2283 printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
2284 printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
2285 printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
2286 printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
2287 printf("\t\t\t\tv_in: %ld ",
2288 (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
2289 printf("v_out: %ld ",
2290 (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
2291 printf("pkts: %ld\n",
2292 (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
2293 printf("\t\t\t\treset: %x hoptime: %lx\n", *r, (long)ntohl(n->tr_qarr));
2297 if ((n->tr_inaddr != b->tr_inaddr) ||
2298 (n->tr_outaddr != b->tr_outaddr) ||
2299 (n->tr_rmtaddr != b->tr_rmtaddr))
2300 return 1; /* Route changed */
2302 if ((n->tr_inaddr != n->tr_outaddr) && n->tr_inaddr)
2303 printf("%-15s\n", inet_fmt(n->tr_inaddr, s1));
2304 printf("%-15s %-14s %s%s\n", inet_fmt(n->tr_outaddr, s1), names[rno],
2305 flag_type(n->tr_rflags),
2306 (*r & BUG_NOPRINT) ? " [reset counters]" : "");
2308 if (rno-- < 1) break;
2310 printf(" %c ^ ttl%5d ", (first && !verbose) ? 'v' : '|',
2312 stat_line(p, n, TRUE, r);
2313 if (!first || verbose) {
2314 resptime = qarrtime;
2315 qarrtime = ntohl((n-1)->tr_qarr);
2316 hop = t_diff(resptime, qarrtime);
2318 printf(" v | hop%5d%s", hop, ms);
2322 stat_line(b, n, TRUE, r);
2326 ttl = MaX(ttl, MaX(1, n->tr_fttl) + base->len - rno);
2329 printf(" %c \\__ ttl%5d ", (first && !verbose) ? 'v' : '|',
2331 stat_line(p, n, FALSE, r);
2332 if (!first || verbose) {
2333 hop = t_diff(qarrtime, new->qtime);
2335 printf(" v \\ hop%5d%s", hop, ms);
2339 stat_line(b, n, FALSE, r);
2341 printf("%-15s %s\n", inet_fmt(base->qhdr.tr_dst, s1),
2342 !passive ? inet_fmt(lcl_addr, s2) : " * * * ");
2343 printf(" Receiver Query Source\n\n");
2348 * Determine whether or not the path has changed.
2351 path_changed(base, new)
2352 struct resp_buf *base, *new;
2354 int rno = base->len - 1;
2355 struct tr_resp *b = base->resps + rno;
2356 struct tr_resp *n = new->resps + rno;
2358 while (rno-- >= 0) {
2359 if ((n->tr_inaddr != b->tr_inaddr) ||
2360 (n->tr_outaddr != b->tr_outaddr) ||
2361 (n->tr_rmtaddr != b->tr_rmtaddr))
2362 return 1; /* Route changed */
2363 if ((b->tr_rflags == TR_NO_RTE) &&
2364 (n->tr_rflags != TR_NO_RTE))
2365 return 1; /* Route got longer? */
2373 /***************************************************************************
2375 ***************************************************************************/
2383 struct sockaddr_in addr;
2384 int addrlen = sizeof(addr);
2387 struct resp_buf *prev, *new;
2391 int hops, nexthop, tries;
2392 u_int32 lastout = 0;
2401 errx(1, "must be root");
2404 * We might get spawned by vat with the audio device open.
2405 * Close everything but stdin, stdout, stderr.
2407 for (i = 3; i < 255; i++)
2414 if (argc == 0) usage();
2416 while (argc > 0 && *argv[0] == '-') {
2417 char *p = *argv++; argc--;
2421 char *arg = (char *) 0;
2425 } else if (argc > 0) arg = argv[0];
2427 case 'd': /* Unlisted debug print option */
2428 if (arg && isdigit(*arg)) {
2430 if (debug < 0) debug = 0;
2431 if (debug > 3) debug = 3;
2432 if (arg == argv[0]) argv++, argc--;
2436 case 'M': /* Use multicast for reponse */
2439 case 'U': /* Use unicast for response */
2442 case 'L': /* Trace w/ loss threshold */
2443 if (arg && isdigit(*arg)) {
2444 lossthresh = atoi(arg);
2448 if (arg == argv[0]) argv++, argc--;
2453 case 'O': /* Don't use IP options */
2456 case 'P': /* Just watch the path */
2460 case 'Q': /* (undoc.) always use this QID */
2461 if (arg && isdigit(*arg)) {
2462 staticqid = atoi(arg);
2465 if (arg == argv[0]) argv++, argc--;
2470 case 'T': /* Print confusing tunnel stats */
2473 case 'W': /* Cisco's "weak" mtrace */
2476 case 'V': /* Print version and exit */
2478 * FreeBSD wants to have its own Id string, so
2479 * determination of the version number has to change.
2480 * XXX Note that this must be changed by hand on importing
2484 char *r = strdup(version);
2485 char *s = strchr(r, ',');
2487 while (s && *(s+1) != 'v')
2488 s = strchr(s + 1, ',');
2493 s += 3; /* , v sp */
2497 fprintf(stderr, "mtrace version 5.2/%s\n", s);
2499 fprintf(stderr, "mtrace could not determine version number!?\n");
2504 case 'l': /* Loop updating stats indefinitely */
2507 case 'n': /* Don't reverse map host addresses */
2510 case 'p': /* Passive listen for traces */
2513 case 'v': /* Verbosity */
2516 case 's': /* Short form, don't wait for stats */
2519 case 'w': /* Time to wait for packet arrival */
2520 if (arg && isdigit(*arg)) {
2521 timeout = atoi(arg);
2522 if (timeout < 1) timeout = 1;
2523 if (arg == argv[0]) argv++, argc--;
2527 case 'f': /* first hop */
2528 if (arg && isdigit(*arg)) {
2530 if (qno > MAXHOPS) qno = MAXHOPS;
2531 else if (qno < 1) qno = 0;
2532 if (arg == argv[0]) argv++, argc--;
2537 case 'm': /* Max number of hops to trace */
2538 if (arg && isdigit(*arg)) {
2540 if (qno > MAXHOPS) qno = MAXHOPS;
2541 else if (qno < 1) qno = 0;
2542 if (arg == argv[0]) argv++, argc--;
2546 case 'q': /* Number of query retries */
2547 if (arg && isdigit(*arg)) {
2548 nqueries = atoi(arg);
2549 if (nqueries < 1) nqueries = 1;
2550 if (arg == argv[0]) argv++, argc--;
2554 case 'g': /* Last-hop gateway (dest of query) */
2555 if (arg && (gwy = host_addr(arg))) {
2556 if (arg == argv[0]) argv++, argc--;
2560 case 't': /* TTL for query packet */
2561 if (arg && isdigit(*arg)) {
2563 if (qttl < 1) qttl = 1;
2565 if (arg == argv[0]) argv++, argc--;
2569 case 'e': /* Extra hops past non-responder */
2570 if (arg && isdigit(*arg)) {
2571 extrahops = atoi(arg);
2572 if (extrahops < 0) extrahops = 0;
2573 if (arg == argv[0]) argv++, argc--;
2577 case 'r': /* Dest for response packet */
2578 if (arg && (raddr = host_addr(arg))) {
2579 if (arg == argv[0]) argv++, argc--;
2583 case 'i': /* Local interface address */
2584 if (arg && (lcl_addr = host_addr(arg))) {
2585 if (arg == argv[0]) argv++, argc--;
2589 case 'S': /* Stat accumulation interval */
2590 if (arg && isdigit(*arg)) {
2591 statint = atoi(arg);
2592 if (statint < 1) statint = 1;
2593 if (arg == argv[0]) argv++, argc--;
2603 if (argc > 0 && (qsrc = host_addr(argv[0]))) { /* Source of path */
2604 if (IN_MULTICAST(ntohl(qsrc))) {
2606 /* Should probably rewrite arg parsing at some point, as
2607 * this makes "mtrace -g foo 224.1.2.3 224.2.3.4" valid!... */
2615 if (argc > 0 && (qdst = host_addr(argv[0]))) { /* Dest of path */
2617 if (argc > 0 && (qgrp = host_addr(argv[0]))) { /* Path via group */
2620 if (IN_MULTICAST(ntohl(qdst))) {
2621 u_int32 temp = qdst;
2624 if (IN_MULTICAST(ntohl(qdst))) usage();
2625 } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) usage();
2640 checkforsolarisbug();
2644 * Set useful defaults for as many parameters as possible.
2647 defgrp = 0; /* Default to no group */
2648 query_cast = htonl(0xE0000002); /* All routers multicast addr */
2649 resp_cast = htonl(0xE0000120); /* Mtrace response multicast addr */
2653 if (printstats && numstats != 0 && !tunstats) {
2654 /* Stats are useless without a group */
2656 "WARNING: no multicast group specified, so no statistics printed");
2662 "WARNING: group was specified so not performing \"weak\" mtrace");
2666 * Get default local address for multicasts to use in setting defaults.
2668 addr.sin_family = AF_INET;
2669 #if (defined(BSD) && (BSD >= 199103))
2670 addr.sin_len = sizeof(addr);
2672 addr.sin_addr.s_addr = qgrp ? qgrp : query_cast;
2673 addr.sin_port = htons(2000); /* Any port above 1024 will do */
2676 * Note that getsockname() can return 0 on some systems
2677 * (notably SunOS 5.x, x < 6). This is taken care of in
2678 * get_netmask(). If the default multicast interface (set
2679 * with the route for 224.0.0.0) is not the same as the
2680 * hostname, mtrace -i [if_addr] will have to be used.
2682 if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
2683 (connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
2684 getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0)
2685 err(-1, "determining local address");
2689 * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
2690 * This call to sysinfo will return the hostname.
2691 * If the default multicast interfface (set with the route
2692 * for 224.0.0.0) is not the same as the hostname,
2693 * mtrace -i [if_addr] will have to be used.
2695 if (addr.sin_addr.s_addr == 0) {
2696 char myhostname[MAXHOSTNAMELEN];
2700 error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
2702 err(1, "getting my hostname");
2704 hp = gethostbyname(myhostname);
2705 if (hp == NULL || hp->h_addrtype != AF_INET ||
2706 hp->h_length != sizeof(addr.sin_addr))
2707 err(1, "finding IP address for my hostname");
2709 memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr, hp->h_length);
2714 * Default destination for path to be queried is the local host.
2715 * When gateway specified, default destination is that gateway
2716 * and default source is local host.
2719 qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2720 dst_netmask = get_netmask(udp, &qdst);
2721 if (gwy && (gwy & dst_netmask) != (qdst & dst_netmask) &&
2722 !IN_MULTICAST(ntohl(gwy)))
2725 if (qsrc == 0 && gwy)
2726 qsrc = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2730 dst_netmask = get_netmask(udp, &qdst);
2732 if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
2735 * Initialize the seed for random query identifiers.
2737 gettimeofday(&tv, 0);
2738 seed = tv.tv_usec ^ lcl_addr;
2744 * Protect against unicast queries to mrouted versions that might crash.
2745 * Also use the obsolete "can mtrace" neighbor bit to warn about
2746 * older implementations.
2748 if (gwy && !IN_MULTICAST(ntohl(gwy)))
2749 if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL)) {
2750 int flags = ntohl(incr[0].igmp.igmp_group.s_addr);
2751 int version = flags & 0xFFFF;
2752 int info = (flags & 0xFF0000) >> 16;
2754 if (version == 0x0303 || version == 0x0503) {
2755 printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
2756 (version >> 8) & 0xFF);
2759 if ((info & 0x08) == 0) {
2762 printf(" probably doesn't support mtrace, trying anyway...\n");
2766 printf("Mtrace from %s to %s via group %s\n",
2767 inet_fmt(qsrc, s1), inet_fmt(qdst, s2), inet_fmt(qgrp, s3));
2769 if ((qdst & dst_netmask) == (qsrc & dst_netmask))
2770 fprintf(stderr, "mtrace: Source & receiver appear to be directly connected\n");
2773 * If the response is to be a multicast address, make sure we
2774 * are listening on that multicast address.
2777 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
2778 } else k_join(resp_cast, lcl_addr);
2780 memset(&base, 0, sizeof(base));
2783 * If the destination is on the local net, the last-hop router can
2784 * be found by multicast to the all-routers multicast group.
2785 * Otherwise, use the group address that is the subject of the
2786 * query since by definition the last-hop router will be a member.
2787 * Set default TTLs for local remote multicasts.
2790 if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
2793 if (tdst == 0 && qgrp == 0)
2794 errx(1, "mtrace: weak mtrace requires -g if destination is not local.\n");
2796 if (IN_MULTICAST(ntohl(tdst))) {
2797 k_set_loop(1); /* If I am running on a router, I need to hear this */
2798 if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
2799 else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
2803 * Try a query at the requested number of hops or MAXHOPS if unspecified.
2808 printf("Querying full reverse path... ");
2814 printf("Querying full reverse path, starting at hop %d...", qno);
2816 printf("Querying reverse path, maximum %d hops... ", qno);
2823 recvlen = send_recv(tdst, IGMP_MTRACE, hops, tries, &base, mtrace_callback);
2826 * If the initial query was successful, print it. Otherwise, if
2827 * the query max hop count is the default of zero, loop starting
2828 * from one until there is no response for extrahops more hops. The
2829 * extra hops allow getting past an mtrace-capable mrouter that can't
2830 * send multicast packets because all phyints are disabled.
2836 print_trace(1, &base, names);
2837 r = base.resps + base.len - 1;
2838 if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
2839 (qno != 0 && r->tr_rmtaddr != 0 && !fflag)) {
2840 printf("%3d ", -(base.len+1));
2841 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2842 "doesn't support mtrace"
2843 : "is the next hop");
2846 nexthop = hops = qno;
2849 VAL_TO_MASK(smask, r->tr_smask);
2850 if ((r->tr_inaddr & smask) == (qsrc & smask)) {
2851 printf("%3d ", -(base.len+1));
2856 } else if (qno == 0) {
2858 printf("switching to hop-by-hop:\n 0 ");
2862 for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
2863 printf("%3d ", -hops);
2867 * After a successful first hop, try switching to the unicast
2868 * address of the last-hop router instead of multicasting the
2869 * trace query. This should be safe for mrouted versions 3.3
2870 * and 3.5 because there is a long route timeout with metric
2871 * infinity before a route disappears. Switching to unicast
2872 * reduces the amount of multicast traffic and avoids a bug
2873 * with duplicate suppression in mrouted 3.5.
2875 if (hops == 2 && gwy == 0 && lastout != 0 &&
2876 (recvlen = send_recv(lastout, IGMP_MTRACE, hops, 1, &base, mtrace_callback)))
2878 else recvlen = send_recv(tdst, IGMP_MTRACE, hops, nqueries, &base, mtrace_callback);
2881 /*if (hops == 1) break;*/
2882 if (hops == nexthop) {
2885 } else if (what_kind(&base, "didn't respond")) {
2886 /* the ask_neighbors determined that the
2887 * not-responding router is the first-hop. */
2892 } else if (hops < nexthop + extrahops) {
2895 printf("...giving up\n");
2900 if (base.len == hops &&
2901 (hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
2902 if (hops == nexthop) {
2903 print_trace(-hops, &base, names);
2905 printf("\nResuming...\n");
2906 print_trace(nexthop, &base, names);
2909 if (base.len < hops) {
2911 * A shorter trace than requested means a fatal error
2912 * occurred along the path, or that the route changed
2915 * If the trace is longer than the last one we received,
2916 * then we are resuming from a skipped router (but there
2917 * is still probably a problem).
2919 * If the trace is shorter than the last one we
2920 * received, then the route must have changed (and
2921 * there is still probably a problem).
2923 if (nexthop <= base.len) {
2924 printf("\nResuming...\n");
2925 print_trace(nexthop, &base, names);
2926 } else if (nexthop > base.len + 1) {
2928 printf("\nRoute must have changed...\n");
2929 print_trace(1, &base, names);
2933 * The last hop address is not the same as it was.
2934 * If we didn't know the last hop then we just
2935 * got the first response from a hop-by-hop trace;
2936 * if we did know the last hop then
2937 * the route probably changed underneath us.
2941 printf("\nRoute must have changed...\n");
2943 printf("\nResuming...\n");
2944 print_trace(1, &base, names);
2948 r = base.resps + base.len - 1;
2949 lastout = r->tr_outaddr;
2951 if (base.len < hops ||
2952 r->tr_rmtaddr == 0 ||
2953 (r->tr_rflags & 0x80)) {
2954 VAL_TO_MASK(smask, r->tr_smask);
2955 if (r->tr_rmtaddr) {
2956 if (hops != nexthop) {
2957 printf("\n%3d ", -(base.len+1));
2959 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2960 "doesn't support mtrace" :
2961 "would be the next hop");
2962 /* XXX could do segmented trace if TR_NO_SPACE */
2963 } else if (r->tr_rflags == TR_NO_ERR &&
2964 (r->tr_inaddr & smask) == (qsrc & smask)) {
2965 printf("%3d ", -(hops + 1));
2976 if (base.rtime == 0) {
2977 printf("Timed out receiving responses\n");
2978 if (IN_MULTICAST(ntohl(tdst)))
2979 if (tdst == query_cast)
2980 printf("Perhaps no local router has a route for source %s\n",
2981 inet_fmt(qsrc, s1));
2983 printf("Perhaps receiver %s is not a member of group %s,\n\
2984 or no router local to it has a route for source %s,\n\
2985 or multicast at ttl %d doesn't reach its last-hop router for that source\n",
2986 inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
2987 qttl ? qttl : MULTICAST_TTL1);
2991 printf("Round trip time %d ms; ", t_diff(base.rtime, base.qtime));
2993 struct tr_resp *n = base.resps + base.len - 1;
2994 u_int ttl = n->tr_fttl + 1;
2999 ttl = MaX(ttl, MaX(1, n->tr_fttl) + base.len - rno);
3001 printf("total ttl of %d required.\n\n",ttl);
3005 * Use the saved response which was the longest one received,
3006 * and make additional probes after delay to measure loss.
3008 raddr = base.qhdr.tr_raddr;
3009 rttl = TR_GETTTL(base.qhdr.tr_rttlqid);
3010 gettimeofday(&tv, 0);
3011 waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
3013 new = &incr[numstats&1];
3016 * Zero out bug-avoidance counters
3018 memset(bugs, 0, sizeof(bugs));
3021 printf("Monitoring path..");
3023 while (numstats--) {
3024 if (waittime < 1) printf("\n");
3026 if (printstats && (lossthresh == 0 || printed)) {
3027 printf("Waiting to accumulate statistics...");
3032 sleep((unsigned)waittime);
3035 rno = hopbyhop ? base.len : qno ? qno : MAXHOPS;
3036 recvlen = send_recv(tdst, IGMP_MTRACE, rno, nqueries, new, mtrace_callback);
3039 printf("Timed out.\n");
3047 if (base.len != new->len || path_changed(&base, new)) {
3048 printf("%s", base.len == new->len ? "Route changed" :
3049 "Trace length doesn't match");
3051 printf(" after %d seconds",
3052 (int)((new->qtime - base.qtime) >> 16));
3055 print_trace(1, new, names);
3057 bcopy(new, &base, sizeof(base));
3058 nexthop = hops = new->len;
3059 printf("Continuing with hop-by-hop...\n");
3064 if (new->igmp.igmp_group.s_addr != qgrp ||
3065 new->qhdr.tr_src != qsrc || new->qhdr.tr_dst != qdst)
3066 printf("\nWARNING: trace modified en route; statistics may be incorrect\n");
3067 fixup_stats(&base, prev, new, bugs);
3068 if ((lossthresh == 0) || check_thresh(lossthresh, &base, prev, new)) {
3069 printf("Results after %d seconds",
3070 (int)((new->qtime - base.qtime) >> 16));
3072 printf(" (this trace %d seconds)",
3073 (int)((new->qtime - prev->qtime) >> 16));
3076 struct tm *qr = localtime(&t);
3078 printf(" qid 0x%06x at %2d:%02d:%02d",
3079 TR_GETQID(base.qhdr.tr_rttlqid),
3080 qr->tm_hour, qr->tm_min, qr->tm_sec);
3084 if (print_stats(&base, prev, new, bugs, names)) {
3085 printf("This should have been detected earlier, but ");
3086 printf("Route changed:\n");
3087 goto printandcontinue;
3092 new = &incr[numstats&1];
3097 * If the response was multicast back, leave the group
3100 if (IN_MULTICAST(ntohl(raddr))) k_leave(raddr, lcl_addr);
3101 } else k_leave(resp_cast, lcl_addr);
3109 fprintf(stderr, "%s\n%s\n%s\n",
3110 "usage: mtrace [-MUOPTWVlnpvs] [-e extra_hops] [-f first_hop] [-i if_addr]",
3111 " [-g gateway] [-m max_hops] [-q nqueries] [-r resp_dest]",
3112 " [-S statint] [-t ttl] [-w wait] source [receiver] [group]");
3119 log(LOG_WARNING, errno, "sendto");
3123 * Log errors and other messages to stderr, according to the severity
3124 * of the message and the current debug level. For errors of severity
3125 * LOG_ERR or worse, terminate the program.
3129 log(int severity, int syserr, char *format, ...)
3134 va_start(ap, format);
3138 log(severity, syserr, format, va_alist)
3139 int severity, syserr;
3150 case 0: if (severity > LOG_WARNING) return;
3151 case 1: if (severity > LOG_NOTICE) return;
3152 case 2: if (severity > LOG_INFO ) return;
3155 if (severity == LOG_WARNING)
3156 strcpy(fmt, "warning - ");
3157 strncat(fmt, format, sizeof(fmt)-strlen(fmt));
3158 fmt[sizeof(fmt)-1]='\0';
3159 vfprintf(stderr, fmt, ap);
3161 fprintf(stderr, "\n");
3162 else if (syserr < sys_nerr)
3163 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
3165 fprintf(stderr, ": errno %d\n", syserr);
3167 if (severity <= LOG_ERR) exit(1);