mtrace.c revision 1.4 1 /* $NetBSD: mtrace.c,v 1.4 1995/10/04 03:47:57 thorpej 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) 1995 by the University of Southern California
25 * All rights reserved.
26 *
27 * Permission to use, copy, modify, and distribute this software and its
28 * documentation in source and binary forms for non-commercial purposes
29 * and without fee is hereby granted, provided that the above copyright
30 * notice appear in all copies and that both the copyright notice and
31 * this permission notice appear in supporting documentation, and that
32 * any documentation, advertising materials, and other materials related
33 * to such distribution and use acknowledge that the software was
34 * developed by the University of Southern California, Information
35 * Sciences Institute. The name of the University may not be used to
36 * endorse or promote products derived from this software without
37 * specific prior written permission.
38 *
39 * THE UNIVERSITY OF SOUTHERN CALIFORNIA makes no representations about
40 * the suitability of this software for any purpose. THIS SOFTWARE IS
41 * PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
42 * INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
43 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
44 *
45 * Other copyrights might apply to parts of this software and are so
46 * noted when applicable.
47 *
48 * In particular, parts of the prototype version of this program may
49 * have been derived from mrouted programs sources covered by the
50 * license in the accompanying file named "LICENSE".
51 */
52
53 #include <sys/filio.h>
54 #include <sys/time.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57 #include <ctype.h>
58 #include <memory.h>
59 #include <netdb.h>
60 #include <string.h>
61 #include <stdlib.h>
62 #include <unistd.h>
63
64 extern int optind;
65 extern char *optarg;
66
67 #include "defs.h"
68
69 #define DEFAULT_TIMEOUT 3 /* How long to wait before retrying requests */
70 #define DEFAULT_RETRIES 3 /* How many times to try */
71 #define MAXHOPS UNREACHABLE /* Don't need more hops than max metric */
72 #define UNICAST_TTL 255 /* TTL for unicast response */
73 #define MULTICAST_TTL1 64 /* Default TTL for multicast query/response */
74 #define MULTICAST_TTL_INC 32 /* TTL increment for increase after timeout */
75 #define MULTICAST_TTL_MAX 192 /* Maximum TTL allowed (protect low-BW links */
76
77 struct resp_buf {
78 u_long qtime; /* Time query was issued */
79 u_long rtime; /* Time response was received */
80 int len; /* Number of reports or length of data */
81 struct igmp igmp; /* IGMP header */
82 union {
83 struct {
84 struct tr_query q; /* Query/response header */
85 struct tr_resp r[MAXHOPS]; /* Per-hop reports */
86 } t;
87 char d[MAX_DVMRP_DATA_LEN]; /* Neighbor data */
88 } u;
89 } base, incr[2];
90
91 #define qhdr u.t.q
92 #define resps u.t.r
93 #define ndata u.d
94
95 char names[MAXHOPS][40];
96
97 int timeout = DEFAULT_TIMEOUT;
98 int nqueries = DEFAULT_RETRIES;
99 int numeric = FALSE;
100 int debug = 0;
101 int passive = FALSE;
102 int multicast = FALSE;
103
104 u_int32_t defgrp; /* Default group if not specified */
105 u_int32_t query_cast; /* All routers multicast addr */
106 u_int32_t resp_cast; /* Mtrace response multicast addr */
107
108 u_int32_t lcl_addr = 0; /* This host address, in NET order */
109 u_int32_t dst_netmask; /* netmask to go with qdst */
110
111 /*
112 * Query/response parameters, all initialized to zero and set later
113 * to default values or from options.
114 */
115 u_int32_t qsrc = 0;
116 u_int32_t qgrp = 0;
117 u_int32_t qdst = 0;
118 u_char qno = 0;
119 u_int32_t raddr = 0;
120 int qttl = 0;
121 u_char rttl = 0;
122 u_int32_t gwy = 0;
123
124 vifi_t numvifs; /* to keep loader happy */
125 /* (see kern.c) */
126 extern void k_join();
127 extern void k_leave();
128 extern void k_set_ttl();
129 extern void exit();
130 #ifndef SYSV
131 extern long random();
132 #endif
133 extern int errno;
134
135 void
136 usage()
137 {
138
139 printf("\
140 Usage: mtrace [-Mlnps] [-w wait] [-m max_hops] [-q nqueries] [-g gateway]\n\
141 [-t ttl] [-r resp_dest] [-i if_addr] source [receiver] [group]\n");
142 exit(1);
143 }
144
145
146 char *
147 inet_name(addr)
148 u_int32_t addr;
149 {
150 struct hostent *e;
151
152 e = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
153
154 return e ? e->h_name : "?";
155 }
156
157
158 u_int32_t
159 host_addr(name)
160 char *name;
161 {
162 struct hostent *e;
163 struct in_addr ina;
164 int i, dots = 3;
165 char buf[40];
166 char *ip = name;
167 char *op = buf;
168
169 /*
170 * Undo the BSD-ism `127.1' == `127.0.0.1'. We change this to
171 * `127.1' == `127.1.0.0'.
172 */
173
174 for (i = sizeof(buf) - 7; i > 0; --i) {
175 if (*ip == '.')
176 --dots;
177 if (*ip == '\0')
178 break;
179 *op++ = *ip++;
180 }
181 for (i = 0; i < dots; ++i) {
182 *op++ = '.';
183 *op++ = '0';
184 }
185 *op = '\0';
186
187 if (inet_aton(buf, &ina) == 0) {
188 if ((e = gethostbyname(name)) == NULL) {
189 ina.s_addr = 0;
190 printf("Could not parse %s as host name or address\n", name);
191 } else
192 memcpy((char *)&ina.s_addr, e->h_addr_list[0], e->h_length);
193 }
194
195 return (ina.s_addr);
196 }
197
198
199 char *
200 proto_type(type)
201 u_char type;
202 {
203 static char buf[80];
204
205 switch (type) {
206 case PROTO_DVMRP:
207 return ("DVMRP");
208 case PROTO_MOSPF:
209 return ("MOSPF");
210 case PROTO_PIM:
211 return ("PIM");
212 case PROTO_CBT:
213 return ("CBT");
214 default:
215 (void) sprintf(buf, "Unknown protocol code %d", type);
216 return (buf);
217 }
218 }
219
220
221 char *
222 flag_type(type)
223 u_char type;
224 {
225 static char buf[80];
226
227 switch (type) {
228 case TR_NO_ERR:
229 return ("");
230 case TR_WRONG_IF:
231 return ("Wrong interface");
232 case TR_PRUNED:
233 return ("Prune sent upstream");
234 case TR_OPRUNED:
235 return ("Output pruned");
236 case TR_SCOPED:
237 return ("Hit scope boundary");
238 case TR_NO_RTE:
239 return ("No route");
240 case TR_OLD_ROUTER:
241 return ("Next router no mtrace");
242 case TR_NO_FWD:
243 return ("Not forwarding");
244 case TR_NO_SPACE:
245 return ("No space in packet");
246 default:
247 (void) sprintf(buf, "Unknown error code %d", type);
248 return (buf);
249 }
250 }
251
252 /*
253 * If destination is on a local net, get the netmask, else set the
254 * netmask to all ones. There are two side effects: if the local
255 * address was not explicitly set, and if the destination is on a
256 * local net, use that one; in either case, verify that the local
257 * address is valid.
258 */
259
260 u_int32_t
261 get_netmask(s, dst)
262 int s;
263 u_int32_t dst;
264 {
265 char inbuf[8192];
266 struct ifconf ifc;
267 struct ifreq *ifr;
268 int i;
269 u_int32_t if_addr, if_mask;
270 u_int32_t retval = 0xFFFFFFFF;
271 int found = FALSE;
272
273 ifc.ifc_len = sizeof(inbuf);
274 ifc.ifc_buf = inbuf;
275 if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) {
276 perror("ioctl (SIOCGIFCONF)");
277 return (retval);
278 }
279
280 for (i = 0; i < ifc.ifc_len; ) {
281 ifr = (struct ifreq *)((char *)ifc.ifc_req + i);
282 i += sizeof(ifr->ifr_name) + ifr->ifr_addr.sa_len;
283 if_addr = ((struct sockaddr_in *)&(ifr->ifr_addr))->sin_addr.s_addr;
284 if (ioctl(s, SIOCGIFNETMASK, (char *)ifr) >= 0) {
285 if_mask = ((struct sockaddr_in *)&(ifr->ifr_addr))->sin_addr.s_addr;
286 if ((dst & if_mask) == (if_addr & if_mask)) {
287 retval = if_mask;
288 if (lcl_addr == 0)
289 lcl_addr = if_addr;
290 }
291 }
292 if (lcl_addr == if_addr)
293 found = TRUE;
294 }
295 if (!found && lcl_addr != 0) {
296 printf("Interface address is not valid\n");
297 exit(1);
298 }
299 return (retval);
300 }
301
302
303 int
304 get_ttl(buf)
305 struct resp_buf *buf;
306 {
307 register rno;
308 register struct tr_resp *b;
309 register ttl;
310
311 if (buf && (rno = buf->len) > 0) {
312 b = buf->resps + rno - 1;
313 ttl = b->tr_fttl;
314
315 while (--rno > 0) {
316 --b;
317 if (ttl < b->tr_fttl)
318 ttl = b->tr_fttl;
319 else
320 ++ttl;
321 }
322 ttl += MULTICAST_TTL_INC;
323 if (ttl < MULTICAST_TTL1)
324 ttl = MULTICAST_TTL1;
325 if (ttl > MULTICAST_TTL_MAX)
326 ttl = MULTICAST_TTL_MAX;
327 return (ttl);
328 } else
329 return(MULTICAST_TTL1);
330 }
331
332 /*
333 * Calculate the difference between two 32-bit NTP timestamps and return
334 * the result in milliseconds.
335 */
336 int
337 t_diff(a, b)
338 u_long a, b;
339 {
340 int d = a - b;
341
342 return ((d * 125) >> 13);
343 }
344
345 /*
346 * Fixup for incorrect time format in 3.3 mrouted.
347 * This is possible because (JAN_1970 mod 64K) is quite close to 32K,
348 * so correct and incorrect times will be far apart.
349 */
350 u_long
351 fixtime(time)
352 u_long time;
353 {
354 if (abs((int)(time-base.qtime)) > 0x3FFFFFFF)
355 time = ((time & 0xFFFF0000) + (JAN_1970 << 16)) +
356 ((time & 0xFFFF) << 14) / 15625;
357 return (time);
358 }
359
360 int
361 send_recv(dst, type, code, tries, save)
362 u_int32_t dst;
363 int type, code, tries;
364 struct resp_buf *save;
365 {
366 fd_set fds;
367 struct timeval tq, tr, tv;
368 struct ip *ip;
369 struct igmp *igmp;
370 struct tr_query *query, *rquery;
371 int ipdatalen, iphdrlen, igmpdatalen;
372 u_int32_t local, group;
373 int datalen;
374 int count, recvlen, dummy = 0;
375 int len;
376 int i;
377
378 if (type == IGMP_MTRACE_QUERY) {
379 group = qgrp;
380 datalen = sizeof(struct tr_query);
381 } else {
382 group = htonl(MROUTED_LEVEL);
383 datalen = 0;
384 }
385 if (IN_MULTICAST(ntohl(dst)))
386 local = lcl_addr;
387 else
388 local = INADDR_ANY;
389
390 /*
391 * If the reply address was not explictly specified, start off
392 * with the unicast address of this host. Then, if there is no
393 * response after trying half the tries with unicast, switch to
394 * the standard multicast reply address. If the TTL was also not
395 * specified, set a multicast TTL and if needed increase it for the
396 * last quarter of the tries.
397 */
398 query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
399 query->tr_raddr = raddr ? raddr : multicast ? resp_cast : lcl_addr;
400 query->tr_rttl = rttl ? rttl :
401 IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL;
402
403 for (i = tries ; i > 0; --i) {
404 if (tries == nqueries && raddr == 0) {
405 if (i == ((nqueries + 1) >> 1)) {
406 query->tr_raddr = resp_cast;
407 if (rttl == 0) query->tr_rttl = get_ttl(save);
408 }
409 if (i <= ((nqueries + 3) >> 2) && rttl == 0) {
410 query->tr_rttl += MULTICAST_TTL_INC;
411 if (query->tr_rttl > MULTICAST_TTL_MAX)
412 query->tr_rttl = MULTICAST_TTL_MAX;
413 }
414 }
415
416 /*
417 * Change the qid for each request sent to avoid being confused
418 * by duplicate responses
419 */
420 query->tr_qid = ((u_int32_t)random() >> 8);
421
422 /*
423 * Set timer to calculate delays, then send query
424 */
425 gettimeofday(&tq, 0);
426 send_igmp(local, dst, type, code, group, datalen);
427
428 /*
429 * Wait for response, discarding false alarms
430 */
431 while (TRUE) {
432 FD_ZERO(&fds);
433 FD_SET(igmp_socket, &fds);
434 gettimeofday(&tv, 0);
435 tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
436 tv.tv_usec = tq.tv_usec - tv.tv_usec;
437 if (tv.tv_usec < 0)
438 tv.tv_usec += 1000000L, --tv.tv_sec;
439 if (tv.tv_sec < 0)
440 tv.tv_sec = tv.tv_usec = 0;
441
442 count = select(igmp_socket + 1, &fds, (fd_set *)0, (fd_set *)0,
443 &tv);
444
445 if (count < 0) {
446 if (errno != EINTR)
447 perror("select");
448 continue;
449 } else if (count == 0) {
450 printf("* ");
451 fflush(stdout);
452 break;
453 }
454
455 gettimeofday(&tr, 0);
456 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
457 0, (struct sockaddr *)0, &dummy);
458
459 if (recvlen <= 0) {
460 if (recvlen && errno != EINTR)
461 perror("recvfrom");
462 continue;
463 }
464
465 if (recvlen < sizeof(struct ip)) {
466 fprintf(stderr,
467 "packet too short (%u bytes) for IP header", recvlen);
468 continue;
469 }
470 ip = (struct ip *) recv_buf;
471 if (ip->ip_p == 0) /* ignore cache creation requests */
472 continue;
473
474 iphdrlen = ip->ip_hl << 2;
475 ipdatalen = ip->ip_len;
476 if (iphdrlen + ipdatalen != recvlen) {
477 fprintf(stderr,
478 "packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
479 recvlen, iphdrlen, ipdatalen);
480 continue;
481 }
482
483 igmp = (struct igmp *) (recv_buf + iphdrlen);
484 igmpdatalen = ipdatalen - IGMP_MINLEN;
485 if (igmpdatalen < 0) {
486 fprintf(stderr,
487 "IP data field too short (%u bytes) for IGMP from %s\n",
488 ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
489 continue;
490 }
491
492 switch (igmp->igmp_type) {
493
494 case IGMP_DVMRP:
495 if (igmp->igmp_code != DVMRP_NEIGHBORS2)
496 continue;
497 if (ip->ip_src.s_addr != dst)
498 continue;
499 len = igmpdatalen;
500 break;
501
502 case IGMP_MTRACE_QUERY: /* For backward compatibility with 3.3 */
503 case IGMP_MTRACE_REPLY:
504 if (igmpdatalen <= QLEN)
505 continue;
506 if ((igmpdatalen - QLEN)%RLEN) {
507 printf("packet with incorrect datalen\n");
508 continue;
509 }
510
511 /*
512 * Ignore responses that don't match query.
513 */
514 rquery = (struct tr_query *)(igmp + 1);
515 if (rquery->tr_qid != query->tr_qid)
516 continue;
517 if (rquery->tr_src != qsrc)
518 continue;
519 if (rquery->tr_dst != qdst)
520 continue;
521 len = (igmpdatalen - QLEN)/RLEN;
522
523 /*
524 * Ignore trace queries passing through this node when
525 * mtrace is run on an mrouter that is in the path
526 * (needed only because IGMP_MTRACE is accepted above
527 * for backward compatibility with multicast release 3.3).
528 */
529 if (igmp->igmp_type == IGMP_MTRACE_QUERY) {
530 struct tr_resp *r = (struct tr_resp *)(rquery+1) + len - 1;
531 u_int32_t smask;
532
533 VAL_TO_MASK(smask, r->tr_smask);
534 if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
535 && r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
536 continue;
537 }
538
539 /*
540 * A match, we'll keep this one.
541 */
542 if (len > code) {
543 fprintf(stderr,
544 "Num hops received (%d) exceeds request (%d)\n",
545 len, code);
546 }
547 rquery->tr_raddr = query->tr_raddr; /* Insure these are */
548 rquery->tr_rttl = query->tr_rttl; /* as we sent them */
549 break;
550
551 default:
552 continue;
553 }
554
555 /*
556 * Most of the sanity checking done at this point.
557 * Return this packet we have been waiting for.
558 */
559 if (save) {
560 save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
561 (tq.tv_usec << 10) / 15625;
562 save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
563 (tr.tv_usec << 10) / 15625;
564 save->len = len;
565 bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
566 }
567 return (recvlen);
568 }
569 }
570 return (0);
571 }
572
573
574 char *
575 print_host(addr)
576 u_int32_t addr;
577 {
578 char *name;
579
580 if (numeric) {
581 printf("%s", inet_fmt(addr, s1));
582 return ("");
583 }
584 name = inet_name(addr);
585 printf("%s (%s)", name, inet_fmt(addr, s1));
586 return (name);
587 }
588
589 /*
590 * Print responses as received (reverse path from dst to src)
591 */
592 void
593 print_trace(index, buf)
594 int index;
595 struct resp_buf *buf;
596 {
597 struct tr_resp *r;
598 char *name;
599 int i;
600
601 i = abs(index);
602 r = buf->resps + i - 1;
603
604 for (; i <= buf->len; ++i, ++r) {
605 if (index > 0) printf("%3d ", -i);
606 name = print_host(r->tr_outaddr);
607 printf(" %s thresh^ %d %d ms %s\n", proto_type(r->tr_rproto),
608 r->tr_fttl, t_diff(fixtime(ntohl(r->tr_qarr)), buf->qtime),
609 flag_type(r->tr_rflags));
610 memcpy(names[i-1], name, sizeof(names[0]) - 1);
611 names[i-1][sizeof(names[0])-1] = '\0';
612 }
613 }
614
615 /*
616 * See what kind of router is the next hop
617 */
618 void
619 what_kind(buf)
620 struct resp_buf *buf;
621 {
622 u_int32_t smask;
623 int recvlen;
624 int hops = buf->len;
625 struct tr_resp *r = buf->resps + hops - 1;
626 u_int32_t next = r->tr_rmtaddr;
627
628 recvlen = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0]);
629 print_host(next);
630 if (recvlen) {
631 u_int32_t version = ntohl(incr[0].igmp.igmp_group.s_addr);
632 u_int32_t *p = (u_int32_t *)incr[0].ndata;
633 u_int32_t *ep = p + (incr[0].len >> 2);
634 printf(" [%s%d.%d] didn't respond\n",
635 (version == 1) ? "proteon/mrouted " :
636 ((version & 0xff) == 2) ? "mrouted " :
637 ((version & 0xff) == 3) ? "mrouted " :
638 ((version & 0xff) == 4) ? "mrouted " :
639 ((version & 0xff) == 10) ? "cisco " : "",
640 version & 0xff, (version >> 8) & 0xff);
641 VAL_TO_MASK(smask, r->tr_smask);
642 while (p < ep) {
643 register u_int32_t laddr = *p++;
644 register int n = ntohl(*p++) & 0xFF;
645 if ((laddr & smask) == (qsrc & smask)) {
646 printf("%3d ", -(hops+2));
647 print_host(qsrc);
648 printf("\n");
649 break;
650 }
651 p += n;
652 }
653 return;
654 }
655 printf(" didn't respond\n");
656 }
657
658
659 char *
660 scale(hop)
661 int *hop;
662 {
663 if (*hop > -1000 && *hop < 10000) return (" ms");
664 *hop /= 1000;
665 if (*hop > -1000 && *hop < 10000) return (" s ");
666 return ("s ");
667 }
668
669 /*
670 * Calculate and print one line of packet loss and packet rate statistics.
671 * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
672 */
673 #define NEITHER 0
674 #define INS 1
675 #define OUTS 2
676 #define BOTH 3
677 void
678 stat_line(r, s, have_next)
679 struct tr_resp *r, *s;
680 int have_next;
681 {
682 register timediff = (fixtime(ntohl(s->tr_qarr)) -
683 fixtime(ntohl(r->tr_qarr))) >> 16;
684 register v_lost, v_pct;
685 register g_lost, g_pct;
686 register v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
687 register g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
688 register v_pps, g_pps;
689 char v_str[8], g_str[8];
690 register have = NEITHER;
691
692 if (timediff == 0)
693 timediff = 1;
694 v_pps = v_out / timediff;
695 g_pps = g_out / timediff;
696
697 if (v_out || s->tr_vifout != 0xFFFFFFFF)
698 have |= OUTS;
699
700 if (have_next) {
701 --r, --s;
702 if (s->tr_vifin != 0xFFFFFFFF || r->tr_vifin != 0xFFFFFFFF)
703 have |= INS;
704 }
705
706 switch (have) {
707 case BOTH:
708 v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
709 if (v_out)
710 v_pct = (v_lost * 100 + (v_out >> 1)) / v_out;
711 else
712 v_pct = 0;
713 if (-100 < v_pct && v_pct < 101 && v_out > 10)
714 sprintf(v_str, "%3d", v_pct);
715 else
716 memcpy(v_str, " --", 4);
717
718 g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
719 if (g_out)
720 g_pct = (g_lost * 100 + (g_out >> 1))/ g_out;
721 else
722 g_pct = 0;
723 if (-100 < g_pct && g_pct < 101 && g_out > 10)
724 sprintf(g_str, "%3d", g_pct);
725 else
726 memcpy(g_str, " --", 4);
727
728 printf("%6d/%-5d=%s%%%4d pps%6d/%-5d=%s%%%4d pps\n",
729 v_lost, v_out, v_str, v_pps, g_lost, g_out, g_str, g_pps);
730 if (debug > 2) {
731 printf("\t\t\t\tv_in: %ld ", ntohl(s->tr_vifin));
732 printf("v_out: %ld ", ntohl(s->tr_vifout));
733 printf("pkts: %ld\n", ntohl(s->tr_pktcnt));
734 printf("\t\t\t\tv_in: %ld ", ntohl(r->tr_vifin));
735 printf("v_out: %ld ", ntohl(r->tr_vifout));
736 printf("pkts: %ld\n", ntohl(r->tr_pktcnt));
737 printf("\t\t\t\tv_in: %ld ",ntohl(s->tr_vifin)-ntohl(r->tr_vifin));
738 printf("v_out: %ld ", ntohl(s->tr_vifout) - ntohl(r->tr_vifout));
739 printf("pkts: %ld ", ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
740 printf("time: %d\n", timediff);
741 }
742 break;
743
744 case INS:
745 v_out = (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
746 g_out = (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
747 v_pps = v_out / timediff;
748 g_pps = g_out / timediff;
749 /* Fall through */
750
751 case OUTS:
752 printf(" %-5d %4d pps %-5d %4d pps\n",
753 v_out, v_pps, g_out, g_pps);
754 break;
755
756 case NEITHER:
757 printf("\n");
758 break;
759 }
760 }
761
762 /*
763 * A fixup to check if any pktcnt has been reset.
764 */
765 void
766 fixup_stats(base, new)
767 struct resp_buf *base, *new;
768 {
769 register rno = base->len;
770 register struct tr_resp *b = base->resps + rno;
771 register struct tr_resp *n = new->resps + rno;
772
773 while (--rno >= 0)
774 if (ntohl((--n)->tr_pktcnt) < ntohl((--b)->tr_pktcnt))
775 break;
776
777 if (rno < 0)
778 return;
779
780 rno = base->len;
781 b = base->resps + rno;
782 n = new->resps + rno;
783
784 while (--rno >= 0)
785 (--b)->tr_pktcnt = (--n)->tr_pktcnt;
786 }
787
788 /*
789 * Print responses with statistics for forward path (from src to dst)
790 */
791 void
792 print_stats(base, prev, new)
793 struct resp_buf *base, *prev, *new;
794 {
795 int rtt, hop;
796 register char *ms;
797 register u_int32_t smask;
798 register rno = base->len - 1;
799 register struct tr_resp *b = base->resps + rno;
800 register struct tr_resp *p = prev->resps + rno;
801 register struct tr_resp *n = new->resps + rno;
802 register u_long resptime = new->rtime;
803 register u_long qarrtime = fixtime(ntohl(n->tr_qarr));
804 register ttl = n->tr_fttl;
805
806 VAL_TO_MASK(smask, b->tr_smask);
807 printf(" Source Response Dest");
808 printf(" Packet Statistics For Only For Traffic\n");
809 printf("%-15s %-15s All Multicast Traffic From %s\n",
810 ((b->tr_inaddr & smask) == (qsrc & smask)) ? s1 : " * * * ",
811 inet_fmt(base->qhdr.tr_raddr, s2), inet_fmt(qsrc, s1));
812 rtt = t_diff(resptime, new->qtime);
813 ms = scale(&rtt);
814 printf(" | __/ rtt%5d%s Lost/Sent = Pct Rate To %s\n",
815 rtt, ms, inet_fmt(qgrp, s2));
816 hop = t_diff(resptime, qarrtime);
817 ms = scale(&hop);
818 printf(" v / hop%5d%s", hop, ms);
819 printf(" --------------------- --------------------\n");
820 if (debug > 2) {
821 printf("\t\t\t\tv_in: %ld ", ntohl(n->tr_vifin));
822 printf("v_out: %ld ", ntohl(n->tr_vifout));
823 printf("pkts: %ld\n", ntohl(n->tr_pktcnt));
824 printf("\t\t\t\tv_in: %ld ", ntohl(b->tr_vifin));
825 printf("v_out: %ld ", ntohl(b->tr_vifout));
826 printf("pkts: %ld\n", ntohl(b->tr_pktcnt));
827 printf("\t\t\t\tv_in: %ld ", ntohl(n->tr_vifin) - ntohl(b->tr_vifin));
828 printf("v_out: %ld ", ntohl(n->tr_vifout) - ntohl(b->tr_vifout));
829 printf("pkts: %ld\n", ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt));
830 }
831
832 while (TRUE) {
833 if ((n->tr_inaddr != b->tr_inaddr) || (n->tr_inaddr != b->tr_inaddr)) {
834 printf("Route changed, start again.\n");
835 exit(1);
836 }
837 if ((n->tr_inaddr != n->tr_outaddr))
838 printf("%-15s\n", inet_fmt(n->tr_inaddr, s1));
839 printf("%-15s %-14s %s\n", inet_fmt(n->tr_outaddr, s1), names[rno],
840 flag_type(n->tr_rflags));
841
842 if (rno-- < 1) break;
843
844 printf(" | ^ ttl%5d ", ttl);
845 if (prev == new)
846 printf("\n");
847 else
848 stat_line(p, n, TRUE);
849 resptime = qarrtime;
850 qarrtime = fixtime(ntohl((n-1)->tr_qarr));
851 hop = t_diff(resptime, qarrtime);
852 ms = scale(&hop);
853 printf(" v | hop%5d%s", hop, ms);
854 stat_line(b, n, TRUE);
855
856 --b, --p, --n;
857 if (ttl < n->tr_fttl)
858 ttl = n->tr_fttl;
859 else
860 ++ttl;
861 }
862
863 printf(" | \\__ ttl%5d ", ttl);
864 if (prev == new)
865 printf("\n");
866 else
867 stat_line(p, n, FALSE);
868 hop = t_diff(qarrtime, new->qtime);
869 ms = scale(&hop);
870 printf(" v \\ hop%5d%s", hop, ms);
871 stat_line(b, n, FALSE);
872 printf("%-15s %s\n", inet_fmt(qdst, s1), inet_fmt(lcl_addr, s2));
873 printf(" Receiver Query Source\n\n");
874 }
875
876
877 /***************************************************************************
878 * main
879 ***************************************************************************/
880
881 int
882 main(argc, argv)
883 int argc;
884 char *argv[];
885 {
886 int udp;
887 struct sockaddr_in addr;
888 int addrlen = sizeof(addr);
889 int recvlen;
890 struct timeval tv;
891 struct resp_buf *prev, *new;
892 struct tr_query *query;
893 struct tr_resp *r;
894 u_int32_t smask;
895 int rno;
896 int hops, tries;
897 int numstats = 1;
898 int waittime;
899 int seed;
900 int ch;
901
902 if (geteuid() != 0) {
903 fprintf(stderr, "mtrace: must be root\n");
904 exit(1);
905 }
906
907 while ((ch = getopt(argc, argv, "d:g:i:lMm:npq:r:st:w:")) != -1) {
908 switch (ch) {
909 case 'd': /* Unlisted debug print option */
910 if (!isdigit(*optarg))
911 usage();
912 debug = atoi(optarg);
913 if (debug < 0)
914 debug = 0;
915 else if (debug > 3)
916 debug = 3;
917 break;
918
919 case 'M': /* Use multicast for reponse */
920 multicast = TRUE;
921 break;
922
923 case 'l': /* Loop updating stats indefinitely */
924 numstats = 3153600;
925 break;
926
927 case 'n': /* Don't reverse map host addresses */
928 numeric = TRUE;
929 break;
930
931 case 'p': /* Passive listen for traces */
932 passive = TRUE;
933 break;
934
935 case 's': /* Short form, don't wait for stats */
936 numstats = 0;
937 break;
938
939 case 'w': /* Time to wait for packet arrival */
940 if (!isdigit(*optarg))
941 usage();
942 timeout = atoi(optarg);
943 if (timeout < 1)
944 timeout = 1;
945 break;
946
947 case 'm': /* Max number of hops to trace */
948 if (!isdigit(*optarg))
949 usage();
950 qno = atoi(optarg);
951 if (qno > MAXHOPS)
952 qno = MAXHOPS;
953 else if (qno < 1)
954 qno = 0;
955 break;
956
957 case 'q': /* Number of query retries */
958 if (!isdigit(*optarg))
959 usage();
960 nqueries = atoi(optarg);
961 if (nqueries < 1)
962 nqueries = 1;
963 break;
964
965 case 'g': /* Last-hop gateway (dest of query) */
966 if ((gwy = host_addr(optarg)) == 0)
967 usage();
968 break;
969
970 case 't': /* TTL for query packet */
971 if (!isdigit(*optarg))
972 usage();
973 qttl = atoi(optarg);
974 if (qttl < 1)
975 qttl = 1;
976 rttl = qttl;
977 break;
978
979 case 'r': /* Dest for response packet */
980 if ((raddr = host_addr(optarg)) == 0)
981 usage();
982 break;
983
984 case 'i': /* Local interface address */
985 if ((lcl_addr = host_addr(optarg)) == 0)
986 usage();
987 break;
988
989 default:
990 usage();
991 } /* switch */
992 } /* while */
993 argv += optind;
994 argc -= optind;
995
996 switch (argc) {
997 case 3: /* Path via group */
998 if ((qgrp = host_addr(argv[2])) == 0)
999 usage();
1000 /* FALLTHROUGH */
1001 case 2: /* dest of path */
1002 if ((qdst = host_addr(argv[1])) == 0)
1003 usage();
1004 /* FALLTHROUGH */
1005 case 1: /* source of path */
1006 if ((qsrc = host_addr(argv[0])) == 0 || IN_MULTICAST(ntohl(qsrc)))
1007 usage();
1008 break;
1009
1010 default:
1011 usage();
1012 }
1013
1014 /*
1015 * If argc is > 1 and the second argument is a multicast address,
1016 * assume that the second argument is actually qgrp and the third
1017 * (if any) is qdst; in this case, the third argument is not allowed
1018 * to be a multicast address.
1019 */
1020 if (argc > 1) {
1021 if (IN_MULTICAST(ntohl(qdst))) {
1022 u_int32_t temp = qdst;
1023 qdst = qgrp;
1024 qgrp = temp;
1025 if (IN_MULTICAST(ntohl(qdst)))
1026 usage();
1027 } else if (qgrp != 0 && !IN_MULTICAST(ntohl(qgrp)))
1028 usage();
1029 }
1030
1031 if (qsrc == 0)
1032 usage();
1033
1034 init_igmp();
1035
1036 /*
1037 * Set useful defaults for as many parameters as possible.
1038 */
1039
1040 defgrp = htonl(0xE0020001); /* MBone Audio (224.2.0.1) */
1041 query_cast = htonl(0xE0000002); /* All routers multicast addr */
1042 resp_cast = htonl(0xE0000120); /* Mtrace response multicast addr */
1043 if (qgrp == 0)
1044 qgrp = defgrp;
1045
1046 /*
1047 * Get default local address for multicasts to use in setting defaults.
1048 */
1049 addr.sin_family = AF_INET;
1050 #if (defined(BSD) && (BSD >= 199103))
1051 addr.sin_len = sizeof(addr);
1052 #endif
1053 addr.sin_addr.s_addr = qgrp;
1054 addr.sin_port = htons(2000); /* Any port above 1024 will do */
1055
1056 if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
1057 (connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
1058 getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0) {
1059 perror("Determining local address");
1060 exit(-1);
1061 }
1062
1063 /*
1064 * Default destination for path to be queried is the local host.
1065 */
1066 if (qdst == 0)
1067 qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
1068
1069 /*
1070 * If the destination is on the local net, the last-hop router can
1071 * be found by multicast to the all-routers multicast group.
1072 * Otherwise, use the group address that is the subject of the
1073 * query since by definition the last hop router will be a member.
1074 * Set default TTLs for local remote multicasts.
1075 */
1076 dst_netmask = get_netmask(udp, qdst);
1077 close(udp);
1078 if (lcl_addr == 0)
1079 lcl_addr = addr.sin_addr.s_addr;
1080 if (gwy == 0)
1081 if ((qdst & dst_netmask) == (lcl_addr & dst_netmask))
1082 gwy = query_cast;
1083 else
1084 gwy = qgrp;
1085
1086 if (IN_MULTICAST(ntohl(gwy))) {
1087 k_set_loop(1); /* If I am running on a router, I need to hear this */
1088 if (gwy == query_cast)
1089 k_set_ttl(qttl ? qttl : 1);
1090 else
1091 k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
1092 } else
1093 if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0]))
1094 if (ntohl(incr[0].igmp.igmp_group.s_addr) == 0x0303) {
1095 printf("Don't use -g to address an mrouted 3.3, it might crash\n");
1096 exit(0);
1097 }
1098
1099 printf("Mtrace from %s to %s via group %s\n",
1100 inet_fmt(qsrc, s1), inet_fmt(qdst, s2), inet_fmt(qgrp, s3));
1101
1102 if ((qdst & dst_netmask) == (qsrc & dst_netmask)) {
1103 printf("Source & receiver are directly connected, no path to trace\n");
1104 exit(0);
1105 }
1106
1107 /*
1108 * Make up the IGMP_MTRACE_QUERY query packet to send (some parameters
1109 * are set later), including initializing the seed for random
1110 * query identifiers.
1111 */
1112 query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
1113 query->tr_src = qsrc;
1114 query->tr_dst = qdst;
1115
1116 gettimeofday(&tv, 0);
1117 seed = tv.tv_usec ^ lcl_addr;
1118 srandom(seed);
1119
1120 /*
1121 * If the response is to be a multicast address, make sure we
1122 * are listening on that multicast address.
1123 */
1124 if (raddr && IN_MULTICAST(ntohl(raddr)))
1125 k_join(raddr, lcl_addr);
1126 else
1127 k_join(resp_cast, lcl_addr);
1128
1129 /*
1130 * Try a query at the requested number of hops or MAXOPS if unspecified.
1131 */
1132 if (qno == 0) {
1133 hops = MAXHOPS;
1134 tries = 1;
1135 printf("Querying full reverse path... ");
1136 fflush(stdout);
1137 } else {
1138 hops = qno;
1139 tries = nqueries;
1140 printf("Querying reverse path, maximum %d hops... ", qno);
1141 fflush(stdout);
1142 }
1143 base.rtime = 0;
1144 base.len = 0;
1145
1146 recvlen = send_recv(gwy, IGMP_MTRACE_QUERY, hops, tries, &base);
1147
1148 /*
1149 * If the initial query was successful, print it. Otherwise, if
1150 * the query max hop count is the default of zero, loop starting
1151 * from one until a timeout occurs.
1152 */
1153 if (recvlen) {
1154 printf("\n 0 ");
1155 print_host(qdst);
1156 printf("\n");
1157 print_trace(1, &base);
1158 r = base.resps + base.len - 1;
1159 if (r->tr_rflags == TR_OLD_ROUTER) {
1160 printf("%3d ", -(base.len+1));
1161 fflush(stdout);
1162 what_kind(&base);
1163 } else {
1164 VAL_TO_MASK(smask, r->tr_smask);
1165 if ((r->tr_inaddr & smask) == (qsrc & smask)) {
1166 printf("%3d ", -(base.len+1));
1167 print_host(qsrc);
1168 printf("\n");
1169 }
1170 }
1171 } else if (qno == 0) {
1172 printf("switching to hop-by-hop:\n 0 ");
1173 print_host(qdst);
1174 printf("\n");
1175
1176 for (hops = 1; hops <= MAXHOPS; ++hops) {
1177 printf("%3d ", -hops);
1178 fflush(stdout);
1179
1180 recvlen = send_recv(gwy, IGMP_MTRACE_QUERY, hops, nqueries, &base);
1181
1182 if (recvlen == 0) {
1183 if (--hops == 0) break;
1184 what_kind(&base);
1185 break;
1186 }
1187 r = base.resps + base.len - 1;
1188 if (base.len == hops)
1189 print_trace(-hops, &base);
1190 else {
1191 hops = base.len;
1192 if (r->tr_rflags == TR_OLD_ROUTER) {
1193 what_kind(&base);
1194 break;
1195 }
1196 if (r->tr_rflags == TR_NO_SPACE) {
1197 printf("No space left in trace packet for further hops\n");
1198 break; /* XXX could do segmented trace */
1199 }
1200 printf("Route must have changed...\n\n");
1201 print_trace(1, &base);
1202 }
1203
1204 VAL_TO_MASK(smask, r->tr_smask);
1205 if ((r->tr_inaddr & smask) == (qsrc & smask)) {
1206 printf("%3d ", -(hops+1));
1207 print_host(qsrc);
1208 printf("\n");
1209 break;
1210 }
1211 if (r->tr_rmtaddr == 0 || (r->tr_rflags & 0x80))
1212 break;
1213 }
1214 }
1215
1216 if (base.rtime == 0) {
1217 printf("Timed out receiving responses\n");
1218 if (IN_MULTICAST(ntohl(gwy)))
1219 if (gwy == query_cast)
1220 printf("Perhaps no local router has a route for source %s\n",
1221 inet_fmt(qsrc, s1));
1222 else
1223 printf("Perhaps receiver %s is not a member of group %s,\n\
1224 or no router local to it has a route for source %s,\n\
1225 or multicast at ttl %d doesn't reach its last-hop router for that source\n",
1226 inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
1227 qttl ? qttl : MULTICAST_TTL1);
1228 exit(1);
1229 }
1230
1231 printf("Round trip time %d ms\n\n", t_diff(base.rtime, base.qtime));
1232
1233 /*
1234 * Use the saved response which was the longest one received,
1235 * and make additional probes after delay to measure loss.
1236 */
1237 raddr = base.qhdr.tr_raddr;
1238 rttl = base.qhdr.tr_rttl;
1239 gettimeofday(&tv, 0);
1240 waittime = 10 - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
1241 prev = new = &incr[numstats&1];
1242
1243 while (numstats--) {
1244 if (waittime < 1) printf("\n");
1245 else {
1246 printf("Waiting to accumulate statistics... ");
1247 fflush(stdout);
1248 sleep((unsigned)waittime);
1249 }
1250 rno = base.len;
1251 recvlen = send_recv(gwy, IGMP_MTRACE_QUERY, rno, nqueries, new);
1252
1253 if (recvlen == 0) {
1254 printf("Timed out.\n");
1255 exit(1);
1256 }
1257
1258 if (rno != new->len) {
1259 printf("Trace length doesn't match.\n");
1260 exit(1);
1261 }
1262
1263 printf("Results after %d seconds:\n\n",
1264 (new->qtime - base.qtime) >> 16);
1265 fixup_stats(&base, new);
1266 print_stats(&base, prev, new);
1267 prev = new;
1268 new = &incr[numstats&1];
1269 waittime = 10;
1270 }
1271
1272 /*
1273 * If the response was multicast back, leave the group
1274 */
1275 if (raddr && IN_MULTICAST(ntohl(raddr))) k_leave(raddr, lcl_addr);
1276 else k_leave(resp_cast, lcl_addr);
1277
1278 return (0);
1279 }
1280
1281 void
1282 check_vif_state()
1283 {
1284 log(LOG_WARNING, errno, "sendto");
1285 }
1286
1287 /*
1288 * Log errors and other messages to stderr, according to the severity
1289 * of the message and the current debug level. For errors of severity
1290 * LOG_ERR or worse, terminate the program.
1291 */
1292 /*VARARGS3*/
1293 void
1294 log(severity, syserr, format, a, b, c, d, e)
1295 int severity, syserr;
1296 char *format;
1297 int a, b, c, d, e;
1298 {
1299 char fmt[100];
1300
1301 switch (debug) {
1302 case 0:
1303 if (severity > LOG_WARNING)
1304 return;
1305 case 1:
1306 if (severity > LOG_NOTICE)
1307 return;
1308 case 2:
1309 if (severity > LOG_INFO)
1310 return;
1311 default:
1312 fmt[0] = '\0';
1313 if (severity == LOG_WARNING) strcat(fmt, "warning - ");
1314 strncat(fmt, format, 80);
1315 fprintf(stderr, fmt, a, b, c, d, e);
1316 if (syserr == 0)
1317 fprintf(stderr, "\n");
1318 else if(syserr < sys_nerr)
1319 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
1320 else
1321 fprintf(stderr, ": errno %d\n", syserr);
1322 }
1323 if (severity <= LOG_ERR)
1324 exit(-1);
1325 }
1326
1327 /* dummies */
1328
1329 /*VARARGS*/
1330 void accept_probe() {} /*VARARGS*/
1331 void accept_group_report() {} /*VARARGS*/
1332 void accept_neighbors() {} /*VARARGS*/
1333 void accept_neighbors2() {} /*VARARGS*/
1334 void accept_neighbor_request() {} /*VARARGS*/
1335 void accept_neighbor_request2() {} /*VARARGS*/
1336 void accept_report() {} /*VARARGS*/
1337 void accept_prune() {} /*VARARGS*/
1338 void accept_graft() {} /*VARARGS*/
1339 void accept_g_ack() {} /*VARARGS*/
1340 void add_table_entry() {} /*VARARGS*/
1341 void accept_mtrace() {} /*VARARGS*/
1342 void accept_leave_message() {} /*VARARGS*/
1343 void accept_membership_query() {} /*VARARGS*/
1344