mtrace.c revision 1.32 1 /* $NetBSD: mtrace.c,v 1.32 2003/08/17 22:12:43 itojun Exp $ */
2
3 /*
4 * mtrace.c
5 *
6 * This tool traces the branch of a multicast tree from a source to a
7 * receiver for a particular multicast group and gives statistics
8 * about packet rate and loss for each hop along the path. It can
9 * usually be invoked just as
10 *
11 * mtrace source
12 *
13 * to trace the route from that source to the local host for a default
14 * group when only the route is desired and not group-specific packet
15 * counts. See the usage line for more complex forms.
16 *
17 *
18 * Released 4 Apr 1995. This program was adapted by Steve Casner
19 * (USC/ISI) from a prototype written by Ajit Thyagarajan (UDel and
20 * Xerox PARC). It attempts to parallel in command syntax and output
21 * format the unicast traceroute program written by Van Jacobson (LBL)
22 * for the parts where that makes sense.
23 *
24 * Copyright (c) 1998-2001.
25 * The University of Southern California/Information Sciences Institute.
26 * All rights reserved.
27 *
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
30 * are met:
31 * 1. Redistributions of source code must retain the above copyright
32 * notice, this list of conditions and the following disclaimer.
33 * 2. Redistributions in binary form must reproduce the above copyright
34 * notice, this list of conditions and the following disclaimer in the
35 * documentation and/or other materials provided with the distribution.
36 * 3. Neither the name of the project nor the names of its contributors
37 * may be used to endorse or promote products derived from this software
38 * without specific prior written permission.
39 *
40 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 */
52
53 #include <sys/cdefs.h>
54 #ifndef lint
55 __RCSID("$NetBSD: mtrace.c,v 1.32 2003/08/17 22:12:43 itojun Exp $");
56 #endif
57
58 #include <sys/types.h>
59 #include <sys/ioctl.h>
60 #include <sys/time.h>
61 #include <poll.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 #include <ctype.h>
65 #include <memory.h>
66 #include <netdb.h>
67 #include <string.h>
68 #include <ifaddrs.h>
69 #include "defs.h"
70
71 #include <stdarg.h>
72 #ifdef SUNOS5
73 #include <sys/systeminfo.h>
74 #endif
75
76 #define DEFAULT_TIMEOUT 3 /* How long to wait before retrying requests */
77 #define DEFAULT_RETRIES 3 /* How many times to try */
78 #define MAXHOPS UNREACHABLE /* Don't need more hops than max metric */
79 #define UNICAST_TTL 255 /* TTL for unicast response */
80 #define MULTICAST_TTL1 64 /* Default TTL for multicast query/response */
81 #define MULTICAST_TTL_INC 32 /* TTL increment for increase after timeout */
82 #define MULTICAST_TTL_MAX 192 /* Maximum TTL allowed (protect low-BW links */
83
84 struct resp_buf {
85 u_long qtime; /* Time query was issued */
86 u_long rtime; /* Time response was received */
87 int len; /* Number of reports or length of data */
88 struct igmp igmp; /* IGMP header */
89 union {
90 struct {
91 struct tr_query q; /* Query/response header */
92 struct tr_resp r[MAXHOPS]; /* Per-hop reports */
93 } t;
94 char d[MAX_DVMRP_DATA_LEN]; /* Neighbor data */
95 } u;
96 } base, incr[2];
97
98 #define qhdr u.t.q
99 #define resps u.t.r
100 #define ndata u.d
101
102 char names[MAXHOPS][40];
103 int reset[MAXHOPS]; /* To get around 3.4 bug, ... */
104 int swaps[MAXHOPS]; /* To get around 3.6 bug, ... */
105
106 int timeout = DEFAULT_TIMEOUT;
107 int nqueries = DEFAULT_RETRIES;
108 int numeric = FALSE;
109 int debug = 0;
110 int passive = FALSE;
111 int multicast = FALSE;
112 int statint = 10;
113 int verbose = 0;
114
115 u_int32_t defgrp; /* Default group if not specified */
116 u_int32_t query_cast; /* All routers multicast addr */
117 u_int32_t resp_cast; /* Mtrace response multicast addr */
118
119 u_int32_t lcl_addr = 0; /* This host address, in NET order */
120 u_int32_t dst_netmask; /* netmask to go with qdst */
121
122 /*
123 * Query/response parameters, all initialized to zero and set later
124 * to default values or from options.
125 */
126 u_int32_t qsrc = 0; /* Source address in the query */
127 u_int32_t qgrp = 0; /* Group address in the query */
128 u_int32_t qdst = 0; /* Destination (receiver) address in query */
129 u_char qno = 0; /* Max number of hops to query */
130 u_int32_t raddr = 0; /* Address where response should be sent */
131 int qttl = 0; /* TTL for the query packet */
132 u_char rttl = 0; /* TTL for the response packet */
133 u_int32_t gwy = 0; /* User-supplied last-hop router address */
134 u_int32_t tdst = 0; /* Address where trace is sent (last-hop) */
135
136 vifi_t numvifs; /* to keep loader happy */
137 /* (see kern.c) */
138
139 u_long byteswap(u_long);
140 char * inet_name(u_int32_t addr);
141 u_int32_t host_addr(char *name);
142 /* u_int is promoted u_char */
143 char * proto_type(u_int type);
144 char * flag_type(u_int type);
145
146 u_int32_t get_netmask(int s, u_int32_t dst);
147 int get_ttl(struct resp_buf *buf);
148 int t_diff(u_long a, u_long b);
149 u_long fixtime(u_long time);
150 int send_recv(u_int32_t dst, int type, int code,
151 int tries, struct resp_buf *save);
152 char * print_host(u_int32_t addr);
153 char * print_host2(u_int32_t addr1, u_int32_t addr2);
154 void print_trace(int index, struct resp_buf *buf);
155 int what_kind(struct resp_buf *buf, char *why);
156 char * scale(int *hop);
157 void stat_line(struct tr_resp *r, struct tr_resp *s,
158 int have_next, int *res);
159 void fixup_stats(struct resp_buf *base,
160 struct resp_buf *prev,
161 struct resp_buf *new);
162 int print_stats(struct resp_buf *base,
163 struct resp_buf *prev,
164 struct resp_buf *new);
165 void check_vif_state(void);
166 void passive_mode(void);
167
168 int main(int argc, char *argv[]);
169 /* logit() prototyped in defs.h */
170
171
172 char *
173 inet_name(u_int32_t addr)
174 {
175 struct hostent *e;
176
177 e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
178
179 return e ? e->h_name : "?";
180 }
181
182
183 u_int32_t
184 host_addr(char *name)
185 {
186 struct hostent *e = (struct hostent *)0;
187 u_int32_t addr;
188 int i, dots = 3;
189 char buf[40];
190 char *ip = name;
191 char *op = buf;
192
193 /*
194 * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
195 * if the name is all numeric.
196 */
197 for (i = sizeof(buf) - 7; i > 0; --i) {
198 if (*ip == '.') --dots;
199 else if (*ip == '\0') break;
200 else if (!isdigit(*ip)) dots = 0; /* Not numeric, don't add zeroes */
201 *op++ = *ip++;
202 }
203 for (i = 0; i < dots; ++i) {
204 *op++ = '.';
205 *op++ = '0';
206 }
207 *op = '\0';
208
209 if (dots <= 0) e = gethostbyname(name);
210 if (e) memcpy((char *)&addr, e->h_addr_list[0], sizeof(addr));
211 else {
212 addr = inet_addr(buf);
213 if (addr == -1) {
214 addr = 0;
215 printf("Could not parse %s as host name or address\n", name);
216 }
217 }
218 return addr;
219 }
220
221
222 char *
223 proto_type(u_int type)
224 {
225 static char buf[80];
226
227 switch (type) {
228 case PROTO_DVMRP:
229 return ("DVMRP");
230 case PROTO_MOSPF:
231 return ("MOSPF");
232 case PROTO_PIM:
233 return ("PIM");
234 case PROTO_CBT:
235 return ("CBT");
236 case PROTO_PIM_SPEC:
237 return ("PIM-special");
238 case PROTO_PIM_STAT:
239 return ("PIM-static");
240 case PROTO_DVMRP_STAT:
241 return ("DVMRP-static");
242 case PROTO_PIM_MBGP:
243 return ("PIM/MBGP");
244 default:
245 (void)snprintf(buf, sizeof buf, "Unknown protocol code %d", type);
246 return (buf);
247 }
248 }
249
250
251 char *
252 flag_type(u_int type)
253 {
254 static char buf[80];
255
256 switch (type) {
257 case TR_NO_ERR:
258 return ("");
259 case TR_WRONG_IF:
260 return ("Wrong interface");
261 case TR_PRUNED:
262 return ("Prune sent upstream");
263 case TR_OPRUNED:
264 return ("Output pruned");
265 case TR_SCOPED:
266 return ("Hit scope boundary");
267 case TR_NO_RTE:
268 return ("No route");
269 case TR_OLD_ROUTER:
270 return ("Next router no mtrace");
271 case TR_NO_FWD:
272 return ("Not forwarding");
273 case TR_NO_SPACE:
274 return ("No space in packet");
275 case TR_RP_OR_CORE:
276 return ("RP/Core");
277 case TR_RPF_INT:
278 return ("Trace packet on RPT interface");
279 case TR_NO_MULTICAST:
280 return ("Trace packet on non-MC interface");
281 case TR_ADMIN_DENY:
282 return ("Trace admin-denied");
283 default:
284 (void)snprintf(buf, sizeof buf, "Unknown error code %d", type);
285 return (buf);
286 }
287 }
288
289 /*
290 * If destination is on a local net, get the netmask, else set the
291 * netmask to all ones. There are two side effects: if the local
292 * address was not explicitly set, and if the destination is on a
293 * local net, use that one; in either case, verify that the local
294 * address is valid.
295 */
296
297 u_int32_t
298 get_netmask(int s, u_int32_t dst)
299 {
300 u_int32_t if_addr, if_mask;
301 u_int32_t retval = 0xFFFFFFFF;
302 int found = FALSE;
303 struct ifaddrs *ifap, *ifa;
304
305 if (getifaddrs(&ifap) != 0) {
306 perror("getifaddrs");
307 return (retval);
308 }
309 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
310 if_addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr;
311 if_mask = ((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr.s_addr;
312 if ((dst & if_mask) == (if_addr & if_mask)) {
313 retval = if_mask;
314 if (lcl_addr == 0)
315 lcl_addr = if_addr;
316 }
317 if (lcl_addr == if_addr)
318 found = TRUE;
319 }
320 if (!found && lcl_addr != 0) {
321 printf("Interface address is not valid\n");
322 exit(1);
323 }
324 freeifaddrs(ifap);
325 return (retval);
326 }
327
328
329 int
330 get_ttl(struct resp_buf *buf)
331 {
332 int rno;
333 struct tr_resp *b;
334 u_int ttl;
335
336 if (buf && (rno = buf->len) > 0) {
337 b = buf->resps + rno - 1;
338 ttl = b->tr_fttl;
339
340 while (--rno > 0) {
341 --b;
342 if (ttl < b->tr_fttl) ttl = b->tr_fttl;
343 else ++ttl;
344 }
345 ttl += MULTICAST_TTL_INC;
346 if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
347 if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
348 return (ttl);
349 } else return(MULTICAST_TTL1);
350 }
351
352 /*
353 * Calculate the difference between two 32-bit NTP timestamps and return
354 * the result in milliseconds.
355 */
356 int
357 t_diff(u_long a, u_long b)
358 {
359 int d = a - b;
360
361 return ((d * 125) >> 13);
362 }
363
364 /*
365 * Fixup for incorrect time format in 3.3 mrouted.
366 * This is possible because (JAN_1970 mod 64K) is quite close to 32K,
367 * so correct and incorrect times will be far apart.
368 */
369 u_long
370 fixtime(u_long time)
371 {
372 if (abs((int)(time-base.qtime)) > 0x3FFFFFFF)
373 time = ((time & 0xFFFF0000) + (JAN_1970 << 16)) +
374 ((time & 0xFFFF) << 14) / 15625;
375 return (time);
376 }
377
378 /*
379 * Swap bytes for poor little-endian machines that don't byte-swap
380 */
381 u_long
382 byteswap(u_long v)
383 {
384 return ((v << 24) | ((v & 0xff00) << 8) |
385 ((v >> 8) & 0xff00) | (v >> 24));
386 }
387
388 int
389 send_recv(u_int32_t dst, int type, int code, int tries, struct resp_buf *save)
390 {
391 struct pollfd set[1];
392 struct timeval tq, tr, tv;
393 struct ip *ip;
394 struct igmp *igmp;
395 struct tr_query *query, *rquery;
396 int ipdatalen, iphdrlen, igmpdatalen;
397 u_int32_t local, group;
398 int datalen;
399 int count, recvlen, dummy = 0;
400 int len;
401 int i;
402
403 if (type == IGMP_MTRACE_QUERY) {
404 group = qgrp;
405 datalen = sizeof(struct tr_query);
406 } else {
407 group = htonl(MROUTED_LEVEL);
408 datalen = 0;
409 }
410 if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
411 else local = INADDR_ANY;
412
413 /*
414 * If the reply address was not explictly specified, start off
415 * with the unicast address of this host. Then, if there is no
416 * response after trying half the tries with unicast, switch to
417 * the standard multicast reply address. If the TTL was also not
418 * specified, set a multicast TTL and if needed increase it for the
419 * last quarter of the tries.
420 */
421 query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
422 query->tr_raddr = raddr ? raddr : multicast ? resp_cast : lcl_addr;
423 query->tr_rttl = rttl ? rttl :
424 IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL;
425 query->tr_src = qsrc;
426 query->tr_dst = qdst;
427
428 for (i = tries ; i > 0; --i) {
429 if (tries == nqueries && raddr == 0) {
430 if (i == ((nqueries + 1) >> 1)) {
431 query->tr_raddr = resp_cast;
432 if (rttl == 0) query->tr_rttl = get_ttl(save);
433 }
434 if (i <= ((nqueries + 3) >> 2) && rttl == 0) {
435 query->tr_rttl += MULTICAST_TTL_INC;
436 if (query->tr_rttl > MULTICAST_TTL_MAX)
437 query->tr_rttl = MULTICAST_TTL_MAX;
438 }
439 }
440
441 /*
442 * Change the qid for each request sent to avoid being confused
443 * by duplicate responses
444 */
445 #ifdef SYSV
446 query->tr_qid = ((u_int32_t)lrand48() >> 8);
447 #else
448 query->tr_qid = ((u_int32_t)random() >> 8);
449 #endif
450
451 /*
452 * Set timer to calculate delays, then send query
453 */
454 gettimeofday(&tq, 0);
455 send_igmp(local, dst, type, code, group, datalen);
456
457 /*
458 * Wait for response, discarding false alarms
459 */
460 set[0].fd = igmp_socket;
461 set[0].events = POLLIN;
462 while (TRUE) {
463 gettimeofday(&tv, 0);
464 tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
465 tv.tv_usec = tq.tv_usec - tv.tv_usec;
466 if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
467 if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;
468
469 count = poll(set, 1, tv.tv_sec * 1000 + tv.tv_usec / 1000);
470
471 if (count < 0) {
472 if (errno != EINTR) perror("select");
473 continue;
474 } else if (count == 0) {
475 printf("* ");
476 fflush(stdout);
477 break;
478 }
479
480 gettimeofday(&tr, 0);
481 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
482 0, (struct sockaddr *)0, &dummy);
483
484 if (recvlen <= 0) {
485 if (recvlen && errno != EINTR) perror("recvfrom");
486 continue;
487 }
488
489 if (recvlen < sizeof(struct ip)) {
490 fprintf(stderr,
491 "packet too short (%u bytes) for IP header", recvlen);
492 continue;
493 }
494 ip = (struct ip *) recv_buf;
495 if (ip->ip_p == 0) /* ignore cache creation requests */
496 continue;
497
498 iphdrlen = ip->ip_hl << 2;
499 ipdatalen = ip->ip_len;
500 if (iphdrlen + ipdatalen != recvlen) {
501 fprintf(stderr,
502 "packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
503 recvlen, iphdrlen, ipdatalen);
504 continue;
505 }
506
507 igmp = (struct igmp *) (recv_buf + iphdrlen);
508 igmpdatalen = ipdatalen - IGMP_MINLEN;
509 if (igmpdatalen < 0) {
510 fprintf(stderr,
511 "IP data field too short (%u bytes) for IGMP from %s\n",
512 ipdatalen, inet_fmt(ip->ip_src.s_addr));
513 continue;
514 }
515
516 switch (igmp->igmp_type) {
517
518 case IGMP_DVMRP:
519 if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
520 len = igmpdatalen;
521 /*
522 * Accept DVMRP_NEIGHBORS2 response if it comes from the
523 * address queried or if that address is one of the local
524 * addresses in the response.
525 */
526 if (ip->ip_src.s_addr != dst) {
527 u_int32_t *p = (u_int32_t *)(igmp + 1);
528 u_int32_t *ep = p + (len >> 2);
529 while (p < ep) {
530 u_int32_t laddr = *p++;
531 int n = ntohl(*p++) & 0xFF;
532 if (laddr == dst) {
533 ep = p + 1; /* ensure p < ep after loop */
534 break;
535 }
536 p += n;
537 }
538 if (p >= ep) continue;
539 }
540 break;
541
542 case IGMP_MTRACE_QUERY: /* For backward compatibility with 3.3 */
543 case IGMP_MTRACE_REPLY:
544 if (igmpdatalen <= QLEN) continue;
545 if ((igmpdatalen - QLEN)%RLEN) {
546 printf("packet with incorrect datalen\n");
547 continue;
548 }
549
550 /*
551 * Ignore responses that don't match query.
552 */
553 rquery = (struct tr_query *)(igmp + 1);
554 if (rquery->tr_qid != query->tr_qid) continue;
555 if (rquery->tr_src != qsrc) continue;
556 if (rquery->tr_dst != qdst) continue;
557 len = (igmpdatalen - QLEN)/RLEN;
558
559 /*
560 * Ignore trace queries passing through this node when
561 * mtrace is run on an mrouter that is in the path
562 * (needed only because IGMP_MTRACE_QUERY is accepted above
563 * for backward compatibility with multicast release 3.3).
564 */
565 if (igmp->igmp_type == IGMP_MTRACE_QUERY) {
566 struct tr_resp *r = (struct tr_resp *)(rquery+1) + len - 1;
567 u_int32_t smask;
568
569 VAL_TO_MASK(smask, r->tr_smask);
570 if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
571 && r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
572 continue;
573 }
574
575 /*
576 * A match, we'll keep this one.
577 */
578 if (len > code) {
579 fprintf(stderr,
580 "Num hops received (%d) exceeds request (%d)\n",
581 len, code);
582 }
583 rquery->tr_raddr = query->tr_raddr; /* Insure these are */
584 rquery->tr_rttl = query->tr_rttl; /* as we sent them */
585 break;
586
587 default:
588 continue;
589 }
590
591 /*
592 * Most of the sanity checking done at this point.
593 * Return this packet we have been waiting for.
594 */
595 if (save) {
596 save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
597 (tq.tv_usec << 10) / 15625;
598 save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
599 (tr.tv_usec << 10) / 15625;
600 save->len = len;
601 bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
602 }
603 return (recvlen);
604 }
605 }
606 return (0);
607 }
608
609 /*
610 * Most of this code is duplicated elsewhere. I'm not sure if
611 * the duplication is absolutely required or not.
612 *
613 * Ideally, this would keep track of ongoing statistics
614 * collection and print out statistics. (& keep track
615 * of h-b-h traces and only print the longest) For now,
616 * it just snoops on what traces it can.
617 */
618 void
619 passive_mode(void)
620 {
621 struct timeval tr;
622 struct ip *ip;
623 struct igmp *igmp;
624 struct tr_resp *r;
625 int ipdatalen, iphdrlen, igmpdatalen;
626 int len, recvlen, dummy = 0;
627 u_int32_t smask;
628
629 if (raddr) {
630 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, INADDR_ANY);
631 } else k_join(htonl(0xE0000120), INADDR_ANY);
632
633 while (1) {
634 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
635 0, (struct sockaddr *)0, &dummy);
636 gettimeofday(&tr,0);
637
638 if (recvlen <= 0) {
639 if (recvlen && errno != EINTR) perror("recvfrom");
640 continue;
641 }
642
643 if (recvlen < sizeof(struct ip)) {
644 fprintf(stderr,
645 "packet too short (%u bytes) for IP header", recvlen);
646 continue;
647 }
648 ip = (struct ip *) recv_buf;
649 if (ip->ip_p == 0) /* ignore cache creation requests */
650 continue;
651
652 iphdrlen = ip->ip_hl << 2;
653 ipdatalen = ip->ip_len;
654 if (iphdrlen + ipdatalen != recvlen) {
655 fprintf(stderr,
656 "packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
657 recvlen, iphdrlen, ipdatalen);
658 continue;
659 }
660
661 igmp = (struct igmp *) (recv_buf + iphdrlen);
662 igmpdatalen = ipdatalen - IGMP_MINLEN;
663 if (igmpdatalen < 0) {
664 fprintf(stderr,
665 "IP data field too short (%u bytes) for IGMP from %s\n",
666 ipdatalen, inet_fmt(ip->ip_src.s_addr));
667 continue;
668 }
669
670 switch (igmp->igmp_type) {
671
672 case IGMP_MTRACE_QUERY: /* For backward compatibility with 3.3 */
673 case IGMP_MTRACE_REPLY:
674 if (igmpdatalen < QLEN) continue;
675 if ((igmpdatalen - QLEN)%RLEN) {
676 printf("packet with incorrect datalen\n");
677 continue;
678 }
679
680 len = (igmpdatalen - QLEN)/RLEN;
681
682 break;
683
684 default:
685 continue;
686 }
687
688 base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
689 (tr.tv_usec << 10) / 15625;
690 base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
691 (tr.tv_usec << 10) / 15625;
692 base.len = len;
693 bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
694 /*
695 * If the user specified which traces to monitor,
696 * only accept traces that correspond to the
697 * request
698 */
699 if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
700 (qdst != 0 && qdst != base.qhdr.tr_dst) ||
701 (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
702 continue;
703
704 printf("Mtrace from %s to %s via group %s (mxhop=%d)\n",
705 inet_fmt(base.qhdr.tr_dst),
706 inet_fmt(base.qhdr.tr_src),
707 inet_fmt(igmp->igmp_group.s_addr),
708 igmp->igmp_code);
709 if (len == 0)
710 continue;
711 printf(" 0 ");
712 print_host(base.qhdr.tr_dst);
713 printf("\n");
714 print_trace(1, &base);
715 r = base.resps + base.len - 1;
716 VAL_TO_MASK(smask, r->tr_smask);
717 if ((r->tr_inaddr & smask) == (base.qhdr.tr_src & smask)) {
718 printf("%3d ", -(base.len+1));
719 print_host(base.qhdr.tr_src);
720 printf("\n");
721 } else if (r->tr_rmtaddr != 0) {
722 printf("%3d ", -(base.len+1));
723 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
724 "doesn't support mtrace"
725 : "is the next hop");
726 }
727 printf("\n");
728 }
729 }
730
731 char *
732 print_host(u_int32_t addr)
733 {
734 return print_host2(addr, 0);
735 }
736
737 /*
738 * On some routers, one interface has a name and the other doesn't.
739 * We always print the address of the outgoing interface, but can
740 * sometimes get the name from the incoming interface. This might be
741 * confusing but should be slightly more helpful than just a "?".
742 */
743 char *
744 print_host2(u_int32_t addr1, u_int32_t addr2)
745 {
746 char *name;
747
748 if (numeric) {
749 printf("%s", inet_fmt(addr1));
750 return ("");
751 }
752 name = inet_name(addr1);
753 if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
754 name = inet_name(addr2);
755 printf("%s (%s)", name, inet_fmt(addr1));
756 return (name);
757 }
758
759 /*
760 * Print responses as received (reverse path from dst to src)
761 */
762 void
763 print_trace(int index, struct resp_buf *buf)
764 {
765 struct tr_resp *r;
766 char *name;
767 int i;
768 int hop;
769 char *ms, *ft;
770
771 i = abs(index);
772 r = buf->resps + i - 1;
773
774 for (; i <= buf->len; ++i, ++r) {
775 if (index > 0) printf("%3d ", -i);
776 name = print_host2(r->tr_outaddr, r->tr_inaddr);
777 printf(" %s thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
778 if (verbose) {
779 hop = t_diff(fixtime(ntohl(r->tr_qarr)), buf->qtime);
780 ms = scale(&hop);
781 printf(" %d%s", hop, ms);
782 }
783 ft = flag_type(r->tr_rflags);
784 if (strlen(ft) != 0)
785 printf(" %s", ft);
786 printf("\n");
787 memcpy(names[i-1], name, sizeof(names[0]) - 1);
788 names[i-1][sizeof(names[0])-1] = '\0';
789 }
790 }
791
792 /*
793 * See what kind of router is the next hop
794 */
795 int
796 what_kind(struct resp_buf *buf, char *why)
797 {
798 u_int32_t smask;
799 int retval;
800 int hops = buf->len;
801 struct tr_resp *r = buf->resps + hops - 1;
802 u_int32_t next = r->tr_rmtaddr;
803
804 retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0]);
805 print_host(next);
806 if (retval) {
807 u_int32_t version = ntohl(incr[0].igmp.igmp_group.s_addr);
808 u_int32_t *p = (u_int32_t *)incr[0].ndata;
809 u_int32_t *ep = p + (incr[0].len >> 2);
810 char *type = "";
811 retval = 0;
812 switch (version & 0xFF) {
813 case 1:
814 type = "proteon/mrouted ";
815 retval = 1;
816 break;
817
818 case 2:
819 case 3:
820 if (((version >> 8) & 0xFF) < 3) retval = 1;
821 /* Fall through */
822 case 4:
823 type = "mrouted ";
824 break;
825
826 case 10:
827 type = "cisco ";
828 }
829 printf(" [%s%d.%d] %s\n",
830 type, version & 0xFF, (version >> 8) & 0xFF,
831 why);
832 VAL_TO_MASK(smask, r->tr_smask);
833 while (p < ep) {
834 u_int32_t laddr = *p++;
835 int flags = (ntohl(*p) & 0xFF00) >> 8;
836 int n = ntohl(*p++) & 0xFF;
837 if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
838 (laddr & smask) == (qsrc & smask)) {
839 printf("%3d ", -(hops+2));
840 print_host(qsrc);
841 printf("\n");
842 return 1;
843 }
844 p += n;
845 }
846 return retval;
847 }
848 printf(" %s\n", why);
849 return 0;
850 }
851
852
853 char *
854 scale(int *hop)
855 {
856 if (*hop > -1000 && *hop < 10000) return (" ms");
857 *hop /= 1000;
858 if (*hop > -1000 && *hop < 10000) return (" s ");
859 return ("s ");
860 }
861
862 /*
863 * Calculate and print one line of packet loss and packet rate statistics.
864 * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
865 */
866 #define NEITHER 0
867 #define INS 1
868 #define OUTS 2
869 #define BOTH 3
870 void
871 stat_line(struct tr_resp *r, struct tr_resp *s, int have_next, int *rst)
872 {
873 int timediff = (fixtime(ntohl(s->tr_qarr)) -
874 fixtime(ntohl(r->tr_qarr))) >> 16;
875 int v_lost, v_pct;
876 int g_lost, g_pct;
877 int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
878 int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
879 int v_pps, g_pps;
880 char v_str[8], g_str[8];
881 int have = NEITHER;
882 int res = *rst;
883
884 if (timediff == 0) timediff = 1;
885 v_pps = v_out / timediff;
886 g_pps = g_out / timediff;
887
888 if ((v_out && (s->tr_vifout != 0xFFFFFFFF && s->tr_vifout != 0)) ||
889 (r->tr_vifout != 0xFFFFFFFF && r->tr_vifout != 0))
890 have |= OUTS;
891
892 if (have_next) {
893 --r, --s, --rst;
894 if ((s->tr_vifin != 0xFFFFFFFF && s->tr_vifin != 0) ||
895 (r->tr_vifin != 0xFFFFFFFF && r->tr_vifin != 0))
896 have |= INS;
897 if (*rst)
898 res = 1;
899 }
900
901 switch (have) {
902 case BOTH:
903 v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
904 if (v_out) v_pct = (v_lost * 100 + (v_out >> 1)) / v_out;
905 else v_pct = 0;
906 if (-100 < v_pct && v_pct < 101 && v_out > 10)
907 (void)snprintf(v_str, sizeof v_str, "%3d", v_pct);
908 else memcpy(v_str, " --", 4);
909
910 g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
911 if (g_out) g_pct = (g_lost * 100 + (g_out >> 1))/ g_out;
912 else g_pct = 0;
913 if (-100 < g_pct && g_pct < 101 && g_out > 10)
914 (void)snprintf(g_str, sizeof g_str, "%3d", g_pct);
915 else memcpy(g_str, " --", 4);
916
917 printf("%6d/%-5d=%s%%%4d pps",
918 v_lost, v_out, v_str, v_pps);
919 if (res)
920 printf("\n");
921 else
922 printf("%6d/%-5d=%s%%%4d pps\n",
923 g_lost, g_out, g_str, g_pps);
924 break;
925
926 case INS:
927 v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
928 v_pps = v_out / timediff;
929 /* Fall through */
930
931 case OUTS:
932 printf(" %-5d %4d pps",
933 v_out, v_pps);
934 if (res)
935 printf("\n");
936 else
937 printf(" %-5d %4d pps\n",
938 g_out, g_pps);
939 break;
940
941 case NEITHER:
942 printf("\n");
943 break;
944 }
945
946 if (debug > 2) {
947 printf("\t\t\t\tv_in: %ld ", (long)ntohl(s->tr_vifin));
948 printf("v_out: %ld ", (long)ntohl(s->tr_vifout));
949 printf("pkts: %ld\n", (long)ntohl(s->tr_pktcnt));
950 printf("\t\t\t\tv_in: %ld ", (long)ntohl(r->tr_vifin));
951 printf("v_out: %ld ", (long)ntohl(r->tr_vifout));
952 printf("pkts: %ld\n", (long)ntohl(r->tr_pktcnt));
953 printf("\t\t\t\tv_in: %ld ",
954 (long)ntohl(s->tr_vifin)-ntohl(r->tr_vifin));
955 printf("v_out: %ld ",
956 (long)(ntohl(s->tr_vifout) - ntohl(r->tr_vifout)));
957 printf("pkts: %ld ", (long)(ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt)));
958 printf("time: %d\n", timediff);
959 printf("\t\t\t\tres: %d\n", res);
960 }
961 }
962
963 /*
964 * A fixup to check if any pktcnt has been reset, and to fix the
965 * byteorder bugs in mrouted 3.6 on little-endian machines.
966 */
967 void
968 fixup_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new)
969 {
970 int rno = base->len;
971 struct tr_resp *b = base->resps + rno;
972 struct tr_resp *p = prev->resps + rno;
973 struct tr_resp *n = new->resps + rno;
974 int *r = reset + rno;
975 int *s = swaps + rno;
976 int res;
977
978 /* Check for byte-swappers */
979 while (--rno >= 0) {
980 --n; --p; --b; --s;
981 if (*s || abs(ntohl(n->tr_vifout) - ntohl(p->tr_vifout)) > 100000) {
982 /* This host sends byteswapped reports; swap 'em */
983 if (!*s) {
984 *s = 1;
985 b->tr_qarr = byteswap(b->tr_qarr);
986 b->tr_vifin = byteswap(b->tr_vifin);
987 b->tr_vifout = byteswap(b->tr_vifout);
988 b->tr_pktcnt = byteswap(b->tr_pktcnt);
989 }
990
991 n->tr_qarr = byteswap(n->tr_qarr);
992 n->tr_vifin = byteswap(n->tr_vifin);
993 n->tr_vifout = byteswap(n->tr_vifout);
994 n->tr_pktcnt = byteswap(n->tr_pktcnt);
995 }
996 }
997
998 rno = base->len;
999 b = base->resps + rno;
1000 p = prev->resps + rno;
1001 n = new->resps + rno;
1002
1003 while (--rno >= 0) {
1004 --n; --p; --b; --r;
1005 res = ((ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
1006 (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)));
1007 if (debug > 2)
1008 printf("\t\tr=%d, res=%d\n", *r, res);
1009 if (*r) {
1010 if (res || *r > 1) {
1011 /*
1012 * This router appears to be a 3.4 with that nasty ol'
1013 * neighbor version bug, which causes it to constantly
1014 * reset. Just nuke the statistics for this node, and
1015 * don't even bother giving it the benefit of the
1016 * doubt from now on.
1017 */
1018 p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
1019 r++;
1020 } else {
1021 /*
1022 * This is simply the situation that the original
1023 * fixup_stats was meant to deal with -- that a
1024 * 3.3 or 3.4 router deleted a cache entry while
1025 * traffic was still active.
1026 */
1027 *r = 0;
1028 break;
1029 }
1030 } else
1031 *r = res;
1032 }
1033
1034 if (rno < 0) return;
1035
1036 rno = base->len;
1037 b = base->resps + rno;
1038 p = prev->resps + rno;
1039
1040 while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
1041 }
1042
1043 /*
1044 * Print responses with statistics for forward path (from src to dst)
1045 */
1046 int
1047 print_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new)
1048 {
1049 int rtt, hop;
1050 char *ms;
1051 char *s1;
1052 u_int32_t smask;
1053 int rno = base->len - 1;
1054 struct tr_resp *b = base->resps + rno;
1055 struct tr_resp *p = prev->resps + rno;
1056 struct tr_resp *n = new->resps + rno;
1057 int *r = reset + rno;
1058 u_long resptime = new->rtime;
1059 u_long qarrtime = fixtime(ntohl(n->tr_qarr));
1060 u_int ttl = n->tr_fttl;
1061 int first = (base == prev);
1062
1063 VAL_TO_MASK(smask, b->tr_smask);
1064 printf(" Source Response Dest");
1065 printf(" Packet Statistics For Only For Traffic\n");
1066 s1 = inet_fmt(qsrc);
1067 printf("%-15s %-15s All Multicast Traffic From %s\n",
1068 ((b->tr_inaddr & smask) == (qsrc & smask)) ? s1 : " * * * ",
1069 inet_fmt(base->qhdr.tr_raddr), s1);
1070 rtt = t_diff(resptime, new->qtime);
1071 ms = scale(&rtt);
1072 printf(" %c __/ rtt%5d%s Lost/Sent = Pct Rate To %s\n",
1073 first ? 'v' : '|', rtt, ms, inet_fmt(qgrp));
1074 if (!first) {
1075 hop = t_diff(resptime, qarrtime);
1076 ms = scale(&hop);
1077 printf(" v / hop%5d%s", hop, ms);
1078 printf(" --------------------- --------------------\n");
1079 }
1080 if (debug > 2) {
1081 printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
1082 printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
1083 printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
1084 printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
1085 printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
1086 printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
1087 printf("\t\t\t\tv_in: %ld ",
1088 (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
1089 printf("v_out: %ld ",
1090 (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
1091 printf("pkts: %ld\n",
1092 (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
1093 printf("\t\t\t\treset: %d\n", *r);
1094 }
1095
1096 while (TRUE) {
1097 if ((n->tr_inaddr != b->tr_inaddr) || (n->tr_inaddr != b->tr_inaddr))
1098 return 1; /* Route changed */
1099
1100 if ((n->tr_inaddr != n->tr_outaddr))
1101 printf("%-15s\n", inet_fmt(n->tr_inaddr));
1102 printf("%-15s %-14s %s\n", inet_fmt(n->tr_outaddr), names[rno],
1103 flag_type(n->tr_rflags));
1104
1105 if (rno-- < 1) break;
1106
1107 printf(" %c ^ ttl%5d ", first ? 'v' : '|', ttl);
1108 stat_line(p, n, TRUE, r);
1109 if (!first) {
1110 resptime = qarrtime;
1111 qarrtime = fixtime(ntohl((n-1)->tr_qarr));
1112 hop = t_diff(resptime, qarrtime);
1113 ms = scale(&hop);
1114 printf(" v | hop%5d%s", hop, ms);
1115 stat_line(b, n, TRUE, r);
1116 }
1117
1118 --b, --p, --n, --r;
1119 if (ttl < n->tr_fttl) ttl = n->tr_fttl;
1120 else ++ttl;
1121 }
1122
1123 printf(" %c \\__ ttl%5d ", first ? 'v' : '|', ttl);
1124 stat_line(p, n, FALSE, r);
1125 if (!first) {
1126 hop = t_diff(qarrtime, new->qtime);
1127 ms = scale(&hop);
1128 printf(" v \\ hop%5d%s", hop, ms);
1129 stat_line(b, n, FALSE, r);
1130 }
1131 printf("%-15s %s\n", inet_fmt(qdst), inet_fmt(lcl_addr));
1132 printf(" Receiver Query Source\n\n");
1133 return 0;
1134 }
1135
1136
1137 /***************************************************************************
1138 * main
1139 ***************************************************************************/
1140
1141 int
1142 main(int argc, char **argv)
1143 {
1144 int udp;
1145 struct sockaddr_in addr;
1146 int addrlen = sizeof(addr);
1147 int recvlen;
1148 struct timeval tv;
1149 struct resp_buf *prev, *new;
1150 struct tr_resp *r;
1151 u_int32_t smask;
1152 int rno;
1153 int hops, nexthop, tries;
1154 u_int32_t lastout = 0;
1155 int numstats = 1;
1156 int waittime;
1157 int seed;
1158
1159 if (geteuid() != 0) {
1160 fprintf(stderr, "mtrace: must be root\n");
1161 exit(1);
1162 }
1163 init_igmp();
1164 if (setuid(getuid()) == -1)
1165 logit(LOG_ERR, errno, "setuid");
1166
1167 argv++, argc--;
1168 if (argc == 0) goto usage;
1169
1170 while (argc > 0 && *argv[0] == '-') {
1171 char *p = *argv++; argc--;
1172 p++;
1173 do {
1174 char c = *p++;
1175 char *arg = (char *) 0;
1176 if (isdigit(*p)) {
1177 arg = p;
1178 p = "";
1179 } else if (argc > 0) arg = argv[0];
1180 switch (c) {
1181 case 'd': /* Unlisted debug print option */
1182 if (arg && isdigit(*arg)) {
1183 debug = atoi(arg);
1184 if (debug < 0) debug = 0;
1185 if (debug > 3) debug = 3;
1186 if (arg == argv[0]) argv++, argc--;
1187 break;
1188 } else
1189 goto usage;
1190 case 'M': /* Use multicast for reponse */
1191 multicast = TRUE;
1192 break;
1193 case 'l': /* Loop updating stats indefinitely */
1194 numstats = 3153600;
1195 break;
1196 case 'n': /* Don't reverse map host addresses */
1197 numeric = TRUE;
1198 break;
1199 case 'p': /* Passive listen for traces */
1200 passive = TRUE;
1201 break;
1202 case 'v': /* Verbosity */
1203 verbose = TRUE;
1204 break;
1205 case 's': /* Short form, don't wait for stats */
1206 numstats = 0;
1207 break;
1208 case 'w': /* Time to wait for packet arrival */
1209 if (arg && isdigit(*arg)) {
1210 timeout = atoi(arg);
1211 if (timeout < 1) timeout = 1;
1212 if (arg == argv[0]) argv++, argc--;
1213 break;
1214 } else
1215 goto usage;
1216 case 'm': /* Max number of hops to trace */
1217 if (arg && isdigit(*arg)) {
1218 qno = atoi(arg);
1219 if (qno > MAXHOPS) qno = MAXHOPS;
1220 else if (qno < 1) qno = 0;
1221 if (arg == argv[0]) argv++, argc--;
1222 break;
1223 } else
1224 goto usage;
1225 case 'q': /* Number of query retries */
1226 if (arg && isdigit(*arg)) {
1227 nqueries = atoi(arg);
1228 if (nqueries < 1) nqueries = 1;
1229 if (arg == argv[0]) argv++, argc--;
1230 break;
1231 } else
1232 goto usage;
1233 case 'g': /* Last-hop gateway (dest of query) */
1234 if (arg && (gwy = host_addr(arg))) {
1235 if (arg == argv[0]) argv++, argc--;
1236 break;
1237 } else
1238 goto usage;
1239 case 't': /* TTL for query packet */
1240 if (arg && isdigit(*arg)) {
1241 qttl = atoi(arg);
1242 if (qttl < 1) qttl = 1;
1243 rttl = qttl;
1244 if (arg == argv[0]) argv++, argc--;
1245 break;
1246 } else
1247 goto usage;
1248 case 'r': /* Dest for response packet */
1249 if (arg && (raddr = host_addr(arg))) {
1250 if (arg == argv[0]) argv++, argc--;
1251 break;
1252 } else
1253 goto usage;
1254 case 'i': /* Local interface address */
1255 if (arg && (lcl_addr = host_addr(arg))) {
1256 if (arg == argv[0]) argv++, argc--;
1257 break;
1258 } else
1259 goto usage;
1260 case 'S': /* Stat accumulation interval */
1261 if (arg && isdigit(*arg)) {
1262 statint = atoi(arg);
1263 if (statint < 1) statint = 1;
1264 if (arg == argv[0]) argv++, argc--;
1265 break;
1266 } else
1267 goto usage;
1268 default:
1269 goto usage;
1270 }
1271 } while (*p);
1272 }
1273
1274 if (argc > 0 && (qsrc = host_addr(argv[0]))) { /* Source of path */
1275 if (IN_MULTICAST(ntohl(qsrc))) goto usage;
1276 argv++, argc--;
1277 if (argc > 0 && (qdst = host_addr(argv[0]))) { /* Dest of path */
1278 argv++, argc--;
1279 if (argc > 0 && (qgrp = host_addr(argv[0]))) { /* Path via group */
1280 argv++, argc--;
1281 }
1282 if (IN_MULTICAST(ntohl(qdst))) {
1283 u_int32_t temp = qdst;
1284 qdst = qgrp;
1285 qgrp = temp;
1286 if (IN_MULTICAST(ntohl(qdst))) goto usage;
1287 } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) goto usage;
1288 }
1289 }
1290
1291 if (passive) {
1292 passive_mode();
1293 return(0);
1294 }
1295
1296 if (argc > 0 || qsrc == 0) {
1297 usage: printf("\
1298 Usage: mtrace [-Mlnps] [-w wait] [-m max_hops] [-q nqueries] [-g gateway]\n\
1299 [-S statint] [-t ttl] [-r resp_dest] [-i if_addr] source [receiver] [group]\n");
1300 exit(1);
1301 }
1302
1303 /*
1304 * Set useful defaults for as many parameters as possible.
1305 */
1306
1307 defgrp = htonl(0xE0020001); /* MBone Audio (224.2.0.1) */
1308 query_cast = htonl(0xE0000002); /* All routers multicast addr */
1309 resp_cast = htonl(0xE0000120); /* Mtrace response multicast addr */
1310 if (qgrp == 0) qgrp = defgrp;
1311
1312 /*
1313 * Get default local address for multicasts to use in setting defaults.
1314 */
1315 memset(&addr, 0, sizeof(addr));
1316 addr.sin_family = AF_INET;
1317 #if (defined(BSD) && (BSD >= 199103))
1318 addr.sin_len = sizeof(addr);
1319 #endif
1320 addr.sin_addr.s_addr = qgrp;
1321 addr.sin_port = htons(2000); /* Any port above 1024 will do */
1322
1323 if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
1324 (connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
1325 getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0) {
1326 perror("Determining local address");
1327 exit(1);
1328 }
1329
1330 #ifdef SUNOS5
1331 /*
1332 * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
1333 * This call to sysinfo will return the hostname.
1334 * If the default multicast interfface (set with the route
1335 * for 224.0.0.0) is not the same as the hostname,
1336 * mtrace -i [if_addr] will have to be used.
1337 */
1338 if (addr.sin_addr.s_addr == 0) {
1339 char myhostname[MAXHOSTNAMELEN];
1340 struct hostent *hp;
1341 int error;
1342
1343 error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
1344 if (error == -1) {
1345 perror("Getting my hostname");
1346 exit(1);
1347 }
1348
1349 hp = gethostbyname(myhostname);
1350 if (hp == NULL || hp->h_addrtype != AF_INET ||
1351 hp->h_length != sizeof(addr.sin_addr)) {
1352 perror("Finding IP address for my hostname");
1353 exit(1);
1354 }
1355
1356 memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr,
1357 sizeof(addr.sin_addr.s_addr));
1358 }
1359 #endif
1360
1361 /*
1362 * Default destination for path to be queried is the local host.
1363 */
1364 if (qdst == 0) qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
1365 dst_netmask = get_netmask(udp, qdst);
1366 close(udp);
1367 if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
1368
1369 /*
1370 * Initialize the seed for random query identifiers.
1371 */
1372 gettimeofday(&tv, 0);
1373 seed = tv.tv_usec ^ lcl_addr;
1374 #ifdef SYSV
1375 srand48(seed);
1376 #else
1377 srandom(seed);
1378 #endif
1379
1380 /*
1381 * Protect against unicast queries to mrouted versions that might crash.
1382 */
1383 if (gwy && !IN_MULTICAST(ntohl(gwy)))
1384 if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0])) {
1385 int version = ntohl(incr[0].igmp.igmp_group.s_addr) & 0xFFFF;
1386 if (version == 0x0303 || version == 0x0503) {
1387 printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
1388 (version >> 8) & 0xFF);
1389 exit(0);
1390 }
1391 }
1392
1393 printf("Mtrace from %s to %s via group %s\n",
1394 inet_fmt(qsrc), inet_fmt(qdst),
1395 inet_fmt(qgrp));
1396
1397 if ((qdst & dst_netmask) == (qsrc & dst_netmask)) {
1398 printf("Source & receiver are directly connected, no path to trace\n");
1399 exit(0);
1400 }
1401
1402 /*
1403 * If the response is to be a multicast address, make sure we
1404 * are listening on that multicast address.
1405 */
1406 if (raddr) {
1407 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1408 } else k_join(resp_cast, lcl_addr);
1409
1410 /*
1411 * If the destination is on the local net, the last-hop router can
1412 * be found by multicast to the all-routers multicast group.
1413 * Otherwise, use the group address that is the subject of the
1414 * query since by definition the last-hop router will be a member.
1415 * Set default TTLs for local remote multicasts.
1416 */
1417 restart:
1418
1419 if (gwy == 0)
1420 if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
1421 else tdst = qgrp;
1422 else tdst = gwy;
1423
1424 if (IN_MULTICAST(ntohl(tdst))) {
1425 k_set_loop(1); /* If I am running on a router, I need to hear this */
1426 if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
1427 else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
1428 }
1429
1430 /*
1431 * Try a query at the requested number of hops or MAXHOPS if unspecified.
1432 */
1433 if (qno == 0) {
1434 hops = MAXHOPS;
1435 tries = 1;
1436 printf("Querying full reverse path... ");
1437 fflush(stdout);
1438 } else {
1439 hops = qno;
1440 tries = nqueries;
1441 printf("Querying reverse path, maximum %d hops... ", qno);
1442 fflush(stdout);
1443 }
1444 base.rtime = 0;
1445 base.len = 0;
1446
1447 recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, tries, &base);
1448
1449 /*
1450 * If the initial query was successful, print it. Otherwise, if
1451 * the query max hop count is the default of zero, loop starting
1452 * from one until there is no response for four hops. The extra
1453 * hops allow getting past an mtrace-capable mrouter that can't
1454 * send multicast packets because all phyints are disabled.
1455 */
1456 if (recvlen) {
1457 printf("\n 0 ");
1458 print_host(qdst);
1459 printf("\n");
1460 print_trace(1, &base);
1461 r = base.resps + base.len - 1;
1462 if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
1463 qno != 0) {
1464 printf("%3d ", -(base.len+1));
1465 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1466 "doesn't support mtrace"
1467 : "is the next hop");
1468 } else {
1469 VAL_TO_MASK(smask, r->tr_smask);
1470 if ((r->tr_inaddr & smask) == (qsrc & smask)) {
1471 printf("%3d ", -(base.len+1));
1472 print_host(qsrc);
1473 printf("\n");
1474 }
1475 }
1476 } else if (qno == 0) {
1477 printf("switching to hop-by-hop:\n 0 ");
1478 print_host(qdst);
1479 printf("\n");
1480
1481 for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
1482 printf("%3d ", -hops);
1483 fflush(stdout);
1484
1485 /*
1486 * After a successful first hop, try switching to the unicast
1487 * address of the last-hop router instead of multicasting the
1488 * trace query. This should be safe for mrouted versions 3.3
1489 * and 3.5 because there is a long route timeout with metric
1490 * infinity before a route disappears. Switching to unicast
1491 * reduces the amount of multicast traffic and avoids a bug
1492 * with duplicate suppression in mrouted 3.5.
1493 */
1494 if (hops == 2 && gwy == 0 &&
1495 (recvlen = send_recv(lastout, IGMP_MTRACE_QUERY, hops, 1, &base)))
1496 tdst = lastout;
1497 else recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, nqueries, &base);
1498
1499 if (recvlen == 0) {
1500 if (hops == 1) break;
1501 if (hops == nexthop) {
1502 if (what_kind(&base, "didn't respond")) {
1503 /* the ask_neighbors determined that the
1504 * not-responding router is the first-hop. */
1505 break;
1506 }
1507 } else if (hops < nexthop + 3) {
1508 printf("\n");
1509 } else {
1510 printf("...giving up\n");
1511 break;
1512 }
1513 continue;
1514 }
1515 r = base.resps + base.len - 1;
1516 if (base.len == hops &&
1517 (hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
1518 if (hops == nexthop) {
1519 print_trace(-hops, &base);
1520 } else {
1521 printf("\nResuming...\n");
1522 print_trace(nexthop, &base);
1523 }
1524 } else {
1525 if (base.len < hops) {
1526 /*
1527 * A shorter trace than requested means a fatal error
1528 * occurred along the path, or that the route changed
1529 * to a shorter one.
1530 *
1531 * If the trace is longer than the last one we received,
1532 * then we are resuming from a skipped router (but there
1533 * is still probably a problem).
1534 *
1535 * If the trace is shorter than the last one we
1536 * received, then the route must have changed (and
1537 * there is still probably a problem).
1538 */
1539 if (nexthop <= base.len) {
1540 printf("\nResuming...\n");
1541 print_trace(nexthop, &base);
1542 } else if (nexthop > base.len + 1) {
1543 hops = base.len;
1544 printf("\nRoute must have changed...\n");
1545 print_trace(1, &base);
1546 }
1547 } else {
1548 /*
1549 * The last hop address is not the same as it was;
1550 * the route probably changed underneath us.
1551 */
1552 hops = base.len;
1553 printf("\nRoute must have changed...\n");
1554 print_trace(1, &base);
1555 }
1556 }
1557 lastout = r->tr_outaddr;
1558
1559 if (base.len < hops ||
1560 r->tr_rmtaddr == 0 ||
1561 (r->tr_rflags & 0x80)) {
1562 VAL_TO_MASK(smask, r->tr_smask);
1563 if (r->tr_rmtaddr) {
1564 if (hops != nexthop) {
1565 printf("\n%3d ", -(base.len+1));
1566 }
1567 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1568 "doesn't support mtrace" :
1569 "would be the next hop");
1570 /* XXX could do segmented trace if TR_NO_SPACE */
1571 } else if (r->tr_rflags == TR_NO_ERR &&
1572 (r->tr_inaddr & smask) == (qsrc & smask)) {
1573 printf("%3d ", -(hops + 1));
1574 print_host(qsrc);
1575 printf("\n");
1576 }
1577 break;
1578 }
1579
1580 nexthop = hops + 1;
1581 }
1582 }
1583
1584 if (base.rtime == 0) {
1585 printf("Timed out receiving responses\n");
1586 if (IN_MULTICAST(ntohl(tdst))) {
1587 if (tdst == query_cast)
1588 printf("Perhaps no local router has a route for source %s\n",
1589 inet_fmt(qsrc));
1590 else
1591 printf("Perhaps receiver %s is not a member of group %s,\n"
1592 "or no router local to it has a route for source %s,\n"
1593 "or multicast at ttl %d doesn't reach its last-hop router"
1594 " for that source\n",
1595 inet_fmt(qdst), inet_fmt(qgrp), inet_fmt(qsrc),
1596 qttl ? qttl : MULTICAST_TTL1);
1597 }
1598 exit(1);
1599 }
1600
1601 printf("Round trip time %d ms\n\n", t_diff(base.rtime, base.qtime));
1602
1603 /*
1604 * Use the saved response which was the longest one received,
1605 * and make additional probes after delay to measure loss.
1606 */
1607 raddr = base.qhdr.tr_raddr;
1608 rttl = base.qhdr.tr_rttl;
1609 gettimeofday(&tv, 0);
1610 waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
1611 prev = &base;
1612 new = &incr[numstats&1];
1613
1614 while (numstats--) {
1615 if (waittime < 1) printf("\n");
1616 else {
1617 printf("Waiting to accumulate statistics... ");
1618 fflush(stdout);
1619 sleep((unsigned)waittime);
1620 }
1621 rno = base.len;
1622 recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, rno, nqueries, new);
1623
1624 if (recvlen == 0) {
1625 printf("Timed out.\n");
1626 exit(1);
1627 }
1628
1629 if (rno != new->len) {
1630 printf("Trace length doesn't match:\n");
1631 /*
1632 * XXX Should this trace result be printed, or is that
1633 * too verbose? Perhaps it should just say restarting.
1634 * But if the path is changing quickly, this may be the
1635 * only snapshot of the current path. But, if the path
1636 * is changing that quickly, does the current path really
1637 * matter?
1638 */
1639 print_trace(1, new);
1640 printf("Restarting.\n\n");
1641 numstats++;
1642 goto restart;
1643 }
1644
1645 printf("Results after %d seconds:\n\n",
1646 (int)((new->qtime - base.qtime) >> 16));
1647 fixup_stats(&base, prev, new);
1648 if (print_stats(&base, prev, new)) {
1649 printf("Route changed:\n");
1650 print_trace(1, new);
1651 printf("Restarting.\n\n");
1652 goto restart;
1653 }
1654 prev = new;
1655 new = &incr[numstats&1];
1656 waittime = statint;
1657 }
1658
1659 /*
1660 * If the response was multicast back, leave the group
1661 */
1662 if (raddr) {
1663 if (IN_MULTICAST(ntohl(raddr))) k_leave(raddr, lcl_addr);
1664 } else k_leave(resp_cast, lcl_addr);
1665
1666 return (0);
1667 }
1668
1669 void
1670 check_vif_state(void)
1671 {
1672 logit(LOG_WARNING, errno, "sendto");
1673 }
1674
1675 /*
1676 * Log errors and other messages to stderr, according to the severity
1677 * of the message and the current debug level. For errors of severity
1678 * LOG_ERR or worse, terminate the program.
1679 */
1680 void
1681 logit(int severity, int syserr, const char *format, ...)
1682 {
1683 va_list ap;
1684
1685 switch (debug) {
1686 case 0: if (severity > LOG_WARNING) return;
1687 case 1: if (severity > LOG_NOTICE) return;
1688 case 2: if (severity > LOG_INFO ) return;
1689 default:
1690 if (severity == LOG_WARNING)
1691 fprintf(stderr, "warning - ");
1692 va_start(ap, format);
1693 vfprintf(stderr, format, ap);
1694 va_end(ap);
1695 if (syserr == 0)
1696 fprintf(stderr, "\n");
1697 else
1698 fprintf(stderr, ": %s\n", strerror(syserr));
1699 }
1700 if (severity <= LOG_ERR) exit(1);
1701 }
1702
1703 /* dummies */
1704 void accept_probe(u_int32_t src, u_int32_t dst, char *p, int datalen,
1705 u_int32_t level)
1706 {
1707 }
1708 void accept_group_report(u_int32_t src, u_int32_t dst, u_int32_t group,
1709 int r_type)
1710 {
1711 }
1712 void accept_neighbor_request2(u_int32_t src, u_int32_t dst)
1713 {
1714 }
1715 void accept_report(u_int32_t src, u_int32_t dst, char *p, int datalen,
1716 u_int32_t level)
1717 {
1718 }
1719 void accept_neighbor_request(u_int32_t src, u_int32_t dst)
1720 {
1721 }
1722 void accept_prune(u_int32_t src, u_int32_t dst, char *p, int datalen)
1723 {
1724 }
1725 void accept_graft(u_int32_t src, u_int32_t dst, char *p, int datalen)
1726 {
1727 }
1728 void accept_g_ack(u_int32_t src, u_int32_t dst, char *p, int datalen)
1729 {
1730 }
1731 void add_table_entry(u_int32_t origin, u_int32_t mcastgrp)
1732 {
1733 }
1734 void accept_leave_message(u_int32_t src, u_int32_t dst, u_int32_t group)
1735 {
1736 }
1737 void accept_mtrace(u_int32_t src, u_int32_t dst, u_int32_t group, char *data,
1738 u_int no, int datalen)
1739 {
1740 }
1741 void accept_membership_query(u_int32_t src, u_int32_t dst, u_int32_t group,
1742 int tmo)
1743 {
1744 }
1745 void accept_neighbors(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1746 u_int32_t level)
1747 {
1748 }
1749 void accept_neighbors2(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1750 u_int32_t level)
1751 {
1752 }
1753 void accept_info_request(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1754 {
1755 }
1756 void accept_info_reply(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1757 {
1758 }
1759