mtrace.c revision 1.33 1 /* $NetBSD: mtrace.c,v 1.33 2003/09/06 12:45:01 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.33 2003/09/06 12:45:01 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 query->tr_qid = arc4random() >> 8;
446
447 /*
448 * Set timer to calculate delays, then send query
449 */
450 gettimeofday(&tq, 0);
451 send_igmp(local, dst, type, code, group, datalen);
452
453 /*
454 * Wait for response, discarding false alarms
455 */
456 set[0].fd = igmp_socket;
457 set[0].events = POLLIN;
458 while (TRUE) {
459 gettimeofday(&tv, 0);
460 tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
461 tv.tv_usec = tq.tv_usec - tv.tv_usec;
462 if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
463 if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;
464
465 count = poll(set, 1, tv.tv_sec * 1000 + tv.tv_usec / 1000);
466
467 if (count < 0) {
468 if (errno != EINTR) perror("select");
469 continue;
470 } else if (count == 0) {
471 printf("* ");
472 fflush(stdout);
473 break;
474 }
475
476 gettimeofday(&tr, 0);
477 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
478 0, (struct sockaddr *)0, &dummy);
479
480 if (recvlen <= 0) {
481 if (recvlen && errno != EINTR) perror("recvfrom");
482 continue;
483 }
484
485 if (recvlen < sizeof(struct ip)) {
486 fprintf(stderr,
487 "packet too short (%u bytes) for IP header", recvlen);
488 continue;
489 }
490 ip = (struct ip *) recv_buf;
491 if (ip->ip_p == 0) /* ignore cache creation requests */
492 continue;
493
494 iphdrlen = ip->ip_hl << 2;
495 ipdatalen = ip->ip_len;
496 if (iphdrlen + ipdatalen != recvlen) {
497 fprintf(stderr,
498 "packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
499 recvlen, iphdrlen, ipdatalen);
500 continue;
501 }
502
503 igmp = (struct igmp *) (recv_buf + iphdrlen);
504 igmpdatalen = ipdatalen - IGMP_MINLEN;
505 if (igmpdatalen < 0) {
506 fprintf(stderr,
507 "IP data field too short (%u bytes) for IGMP from %s\n",
508 ipdatalen, inet_fmt(ip->ip_src.s_addr));
509 continue;
510 }
511
512 switch (igmp->igmp_type) {
513
514 case IGMP_DVMRP:
515 if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
516 len = igmpdatalen;
517 /*
518 * Accept DVMRP_NEIGHBORS2 response if it comes from the
519 * address queried or if that address is one of the local
520 * addresses in the response.
521 */
522 if (ip->ip_src.s_addr != dst) {
523 u_int32_t *p = (u_int32_t *)(igmp + 1);
524 u_int32_t *ep = p + (len >> 2);
525 while (p < ep) {
526 u_int32_t laddr = *p++;
527 int n = ntohl(*p++) & 0xFF;
528 if (laddr == dst) {
529 ep = p + 1; /* ensure p < ep after loop */
530 break;
531 }
532 p += n;
533 }
534 if (p >= ep) continue;
535 }
536 break;
537
538 case IGMP_MTRACE_QUERY: /* For backward compatibility with 3.3 */
539 case IGMP_MTRACE_REPLY:
540 if (igmpdatalen <= QLEN) continue;
541 if ((igmpdatalen - QLEN)%RLEN) {
542 printf("packet with incorrect datalen\n");
543 continue;
544 }
545
546 /*
547 * Ignore responses that don't match query.
548 */
549 rquery = (struct tr_query *)(igmp + 1);
550 if (rquery->tr_qid != query->tr_qid) continue;
551 if (rquery->tr_src != qsrc) continue;
552 if (rquery->tr_dst != qdst) continue;
553 len = (igmpdatalen - QLEN)/RLEN;
554
555 /*
556 * Ignore trace queries passing through this node when
557 * mtrace is run on an mrouter that is in the path
558 * (needed only because IGMP_MTRACE_QUERY is accepted above
559 * for backward compatibility with multicast release 3.3).
560 */
561 if (igmp->igmp_type == IGMP_MTRACE_QUERY) {
562 struct tr_resp *r = (struct tr_resp *)(rquery+1) + len - 1;
563 u_int32_t smask;
564
565 VAL_TO_MASK(smask, r->tr_smask);
566 if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
567 && r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
568 continue;
569 }
570
571 /*
572 * A match, we'll keep this one.
573 */
574 if (len > code) {
575 fprintf(stderr,
576 "Num hops received (%d) exceeds request (%d)\n",
577 len, code);
578 }
579 rquery->tr_raddr = query->tr_raddr; /* Insure these are */
580 rquery->tr_rttl = query->tr_rttl; /* as we sent them */
581 break;
582
583 default:
584 continue;
585 }
586
587 /*
588 * Most of the sanity checking done at this point.
589 * Return this packet we have been waiting for.
590 */
591 if (save) {
592 save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
593 (tq.tv_usec << 10) / 15625;
594 save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
595 (tr.tv_usec << 10) / 15625;
596 save->len = len;
597 bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
598 }
599 return (recvlen);
600 }
601 }
602 return (0);
603 }
604
605 /*
606 * Most of this code is duplicated elsewhere. I'm not sure if
607 * the duplication is absolutely required or not.
608 *
609 * Ideally, this would keep track of ongoing statistics
610 * collection and print out statistics. (& keep track
611 * of h-b-h traces and only print the longest) For now,
612 * it just snoops on what traces it can.
613 */
614 void
615 passive_mode(void)
616 {
617 struct timeval tr;
618 struct ip *ip;
619 struct igmp *igmp;
620 struct tr_resp *r;
621 int ipdatalen, iphdrlen, igmpdatalen;
622 int len, recvlen, dummy = 0;
623 u_int32_t smask;
624
625 if (raddr) {
626 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, INADDR_ANY);
627 } else k_join(htonl(0xE0000120), INADDR_ANY);
628
629 while (1) {
630 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
631 0, (struct sockaddr *)0, &dummy);
632 gettimeofday(&tr,0);
633
634 if (recvlen <= 0) {
635 if (recvlen && errno != EINTR) perror("recvfrom");
636 continue;
637 }
638
639 if (recvlen < sizeof(struct ip)) {
640 fprintf(stderr,
641 "packet too short (%u bytes) for IP header", recvlen);
642 continue;
643 }
644 ip = (struct ip *) recv_buf;
645 if (ip->ip_p == 0) /* ignore cache creation requests */
646 continue;
647
648 iphdrlen = ip->ip_hl << 2;
649 ipdatalen = ip->ip_len;
650 if (iphdrlen + ipdatalen != recvlen) {
651 fprintf(stderr,
652 "packet shorter (%u bytes) than hdr+data len (%u+%u)\n",
653 recvlen, iphdrlen, ipdatalen);
654 continue;
655 }
656
657 igmp = (struct igmp *) (recv_buf + iphdrlen);
658 igmpdatalen = ipdatalen - IGMP_MINLEN;
659 if (igmpdatalen < 0) {
660 fprintf(stderr,
661 "IP data field too short (%u bytes) for IGMP from %s\n",
662 ipdatalen, inet_fmt(ip->ip_src.s_addr));
663 continue;
664 }
665
666 switch (igmp->igmp_type) {
667
668 case IGMP_MTRACE_QUERY: /* For backward compatibility with 3.3 */
669 case IGMP_MTRACE_REPLY:
670 if (igmpdatalen < QLEN) continue;
671 if ((igmpdatalen - QLEN)%RLEN) {
672 printf("packet with incorrect datalen\n");
673 continue;
674 }
675
676 len = (igmpdatalen - QLEN)/RLEN;
677
678 break;
679
680 default:
681 continue;
682 }
683
684 base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
685 (tr.tv_usec << 10) / 15625;
686 base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
687 (tr.tv_usec << 10) / 15625;
688 base.len = len;
689 bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
690 /*
691 * If the user specified which traces to monitor,
692 * only accept traces that correspond to the
693 * request
694 */
695 if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
696 (qdst != 0 && qdst != base.qhdr.tr_dst) ||
697 (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
698 continue;
699
700 printf("Mtrace from %s to %s via group %s (mxhop=%d)\n",
701 inet_fmt(base.qhdr.tr_dst),
702 inet_fmt(base.qhdr.tr_src),
703 inet_fmt(igmp->igmp_group.s_addr),
704 igmp->igmp_code);
705 if (len == 0)
706 continue;
707 printf(" 0 ");
708 print_host(base.qhdr.tr_dst);
709 printf("\n");
710 print_trace(1, &base);
711 r = base.resps + base.len - 1;
712 VAL_TO_MASK(smask, r->tr_smask);
713 if ((r->tr_inaddr & smask) == (base.qhdr.tr_src & smask)) {
714 printf("%3d ", -(base.len+1));
715 print_host(base.qhdr.tr_src);
716 printf("\n");
717 } else if (r->tr_rmtaddr != 0) {
718 printf("%3d ", -(base.len+1));
719 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
720 "doesn't support mtrace"
721 : "is the next hop");
722 }
723 printf("\n");
724 }
725 }
726
727 char *
728 print_host(u_int32_t addr)
729 {
730 return print_host2(addr, 0);
731 }
732
733 /*
734 * On some routers, one interface has a name and the other doesn't.
735 * We always print the address of the outgoing interface, but can
736 * sometimes get the name from the incoming interface. This might be
737 * confusing but should be slightly more helpful than just a "?".
738 */
739 char *
740 print_host2(u_int32_t addr1, u_int32_t addr2)
741 {
742 char *name;
743
744 if (numeric) {
745 printf("%s", inet_fmt(addr1));
746 return ("");
747 }
748 name = inet_name(addr1);
749 if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
750 name = inet_name(addr2);
751 printf("%s (%s)", name, inet_fmt(addr1));
752 return (name);
753 }
754
755 /*
756 * Print responses as received (reverse path from dst to src)
757 */
758 void
759 print_trace(int index, struct resp_buf *buf)
760 {
761 struct tr_resp *r;
762 char *name;
763 int i;
764 int hop;
765 char *ms, *ft;
766
767 i = abs(index);
768 r = buf->resps + i - 1;
769
770 for (; i <= buf->len; ++i, ++r) {
771 if (index > 0) printf("%3d ", -i);
772 name = print_host2(r->tr_outaddr, r->tr_inaddr);
773 printf(" %s thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
774 if (verbose) {
775 hop = t_diff(fixtime(ntohl(r->tr_qarr)), buf->qtime);
776 ms = scale(&hop);
777 printf(" %d%s", hop, ms);
778 }
779 ft = flag_type(r->tr_rflags);
780 if (strlen(ft) != 0)
781 printf(" %s", ft);
782 printf("\n");
783 memcpy(names[i-1], name, sizeof(names[0]) - 1);
784 names[i-1][sizeof(names[0])-1] = '\0';
785 }
786 }
787
788 /*
789 * See what kind of router is the next hop
790 */
791 int
792 what_kind(struct resp_buf *buf, char *why)
793 {
794 u_int32_t smask;
795 int retval;
796 int hops = buf->len;
797 struct tr_resp *r = buf->resps + hops - 1;
798 u_int32_t next = r->tr_rmtaddr;
799
800 retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0]);
801 print_host(next);
802 if (retval) {
803 u_int32_t version = ntohl(incr[0].igmp.igmp_group.s_addr);
804 u_int32_t *p = (u_int32_t *)incr[0].ndata;
805 u_int32_t *ep = p + (incr[0].len >> 2);
806 char *type = "";
807 retval = 0;
808 switch (version & 0xFF) {
809 case 1:
810 type = "proteon/mrouted ";
811 retval = 1;
812 break;
813
814 case 2:
815 case 3:
816 if (((version >> 8) & 0xFF) < 3) retval = 1;
817 /* Fall through */
818 case 4:
819 type = "mrouted ";
820 break;
821
822 case 10:
823 type = "cisco ";
824 }
825 printf(" [%s%d.%d] %s\n",
826 type, version & 0xFF, (version >> 8) & 0xFF,
827 why);
828 VAL_TO_MASK(smask, r->tr_smask);
829 while (p < ep) {
830 u_int32_t laddr = *p++;
831 int flags = (ntohl(*p) & 0xFF00) >> 8;
832 int n = ntohl(*p++) & 0xFF;
833 if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
834 (laddr & smask) == (qsrc & smask)) {
835 printf("%3d ", -(hops+2));
836 print_host(qsrc);
837 printf("\n");
838 return 1;
839 }
840 p += n;
841 }
842 return retval;
843 }
844 printf(" %s\n", why);
845 return 0;
846 }
847
848
849 char *
850 scale(int *hop)
851 {
852 if (*hop > -1000 && *hop < 10000) return (" ms");
853 *hop /= 1000;
854 if (*hop > -1000 && *hop < 10000) return (" s ");
855 return ("s ");
856 }
857
858 /*
859 * Calculate and print one line of packet loss and packet rate statistics.
860 * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
861 */
862 #define NEITHER 0
863 #define INS 1
864 #define OUTS 2
865 #define BOTH 3
866 void
867 stat_line(struct tr_resp *r, struct tr_resp *s, int have_next, int *rst)
868 {
869 int timediff = (fixtime(ntohl(s->tr_qarr)) -
870 fixtime(ntohl(r->tr_qarr))) >> 16;
871 int v_lost, v_pct;
872 int g_lost, g_pct;
873 int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
874 int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
875 int v_pps, g_pps;
876 char v_str[8], g_str[8];
877 int have = NEITHER;
878 int res = *rst;
879
880 if (timediff == 0) timediff = 1;
881 v_pps = v_out / timediff;
882 g_pps = g_out / timediff;
883
884 if ((v_out && (s->tr_vifout != 0xFFFFFFFF && s->tr_vifout != 0)) ||
885 (r->tr_vifout != 0xFFFFFFFF && r->tr_vifout != 0))
886 have |= OUTS;
887
888 if (have_next) {
889 --r, --s, --rst;
890 if ((s->tr_vifin != 0xFFFFFFFF && s->tr_vifin != 0) ||
891 (r->tr_vifin != 0xFFFFFFFF && r->tr_vifin != 0))
892 have |= INS;
893 if (*rst)
894 res = 1;
895 }
896
897 switch (have) {
898 case BOTH:
899 v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
900 if (v_out) v_pct = (v_lost * 100 + (v_out >> 1)) / v_out;
901 else v_pct = 0;
902 if (-100 < v_pct && v_pct < 101 && v_out > 10)
903 (void)snprintf(v_str, sizeof v_str, "%3d", v_pct);
904 else memcpy(v_str, " --", 4);
905
906 g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
907 if (g_out) g_pct = (g_lost * 100 + (g_out >> 1))/ g_out;
908 else g_pct = 0;
909 if (-100 < g_pct && g_pct < 101 && g_out > 10)
910 (void)snprintf(g_str, sizeof g_str, "%3d", g_pct);
911 else memcpy(g_str, " --", 4);
912
913 printf("%6d/%-5d=%s%%%4d pps",
914 v_lost, v_out, v_str, v_pps);
915 if (res)
916 printf("\n");
917 else
918 printf("%6d/%-5d=%s%%%4d pps\n",
919 g_lost, g_out, g_str, g_pps);
920 break;
921
922 case INS:
923 v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
924 v_pps = v_out / timediff;
925 /* Fall through */
926
927 case OUTS:
928 printf(" %-5d %4d pps",
929 v_out, v_pps);
930 if (res)
931 printf("\n");
932 else
933 printf(" %-5d %4d pps\n",
934 g_out, g_pps);
935 break;
936
937 case NEITHER:
938 printf("\n");
939 break;
940 }
941
942 if (debug > 2) {
943 printf("\t\t\t\tv_in: %ld ", (long)ntohl(s->tr_vifin));
944 printf("v_out: %ld ", (long)ntohl(s->tr_vifout));
945 printf("pkts: %ld\n", (long)ntohl(s->tr_pktcnt));
946 printf("\t\t\t\tv_in: %ld ", (long)ntohl(r->tr_vifin));
947 printf("v_out: %ld ", (long)ntohl(r->tr_vifout));
948 printf("pkts: %ld\n", (long)ntohl(r->tr_pktcnt));
949 printf("\t\t\t\tv_in: %ld ",
950 (long)ntohl(s->tr_vifin)-ntohl(r->tr_vifin));
951 printf("v_out: %ld ",
952 (long)(ntohl(s->tr_vifout) - ntohl(r->tr_vifout)));
953 printf("pkts: %ld ", (long)(ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt)));
954 printf("time: %d\n", timediff);
955 printf("\t\t\t\tres: %d\n", res);
956 }
957 }
958
959 /*
960 * A fixup to check if any pktcnt has been reset, and to fix the
961 * byteorder bugs in mrouted 3.6 on little-endian machines.
962 */
963 void
964 fixup_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new)
965 {
966 int rno = base->len;
967 struct tr_resp *b = base->resps + rno;
968 struct tr_resp *p = prev->resps + rno;
969 struct tr_resp *n = new->resps + rno;
970 int *r = reset + rno;
971 int *s = swaps + rno;
972 int res;
973
974 /* Check for byte-swappers */
975 while (--rno >= 0) {
976 --n; --p; --b; --s;
977 if (*s || abs(ntohl(n->tr_vifout) - ntohl(p->tr_vifout)) > 100000) {
978 /* This host sends byteswapped reports; swap 'em */
979 if (!*s) {
980 *s = 1;
981 b->tr_qarr = byteswap(b->tr_qarr);
982 b->tr_vifin = byteswap(b->tr_vifin);
983 b->tr_vifout = byteswap(b->tr_vifout);
984 b->tr_pktcnt = byteswap(b->tr_pktcnt);
985 }
986
987 n->tr_qarr = byteswap(n->tr_qarr);
988 n->tr_vifin = byteswap(n->tr_vifin);
989 n->tr_vifout = byteswap(n->tr_vifout);
990 n->tr_pktcnt = byteswap(n->tr_pktcnt);
991 }
992 }
993
994 rno = base->len;
995 b = base->resps + rno;
996 p = prev->resps + rno;
997 n = new->resps + rno;
998
999 while (--rno >= 0) {
1000 --n; --p; --b; --r;
1001 res = ((ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
1002 (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)));
1003 if (debug > 2)
1004 printf("\t\tr=%d, res=%d\n", *r, res);
1005 if (*r) {
1006 if (res || *r > 1) {
1007 /*
1008 * This router appears to be a 3.4 with that nasty ol'
1009 * neighbor version bug, which causes it to constantly
1010 * reset. Just nuke the statistics for this node, and
1011 * don't even bother giving it the benefit of the
1012 * doubt from now on.
1013 */
1014 p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
1015 r++;
1016 } else {
1017 /*
1018 * This is simply the situation that the original
1019 * fixup_stats was meant to deal with -- that a
1020 * 3.3 or 3.4 router deleted a cache entry while
1021 * traffic was still active.
1022 */
1023 *r = 0;
1024 break;
1025 }
1026 } else
1027 *r = res;
1028 }
1029
1030 if (rno < 0) return;
1031
1032 rno = base->len;
1033 b = base->resps + rno;
1034 p = prev->resps + rno;
1035
1036 while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
1037 }
1038
1039 /*
1040 * Print responses with statistics for forward path (from src to dst)
1041 */
1042 int
1043 print_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new)
1044 {
1045 int rtt, hop;
1046 char *ms;
1047 char *s1;
1048 u_int32_t smask;
1049 int rno = base->len - 1;
1050 struct tr_resp *b = base->resps + rno;
1051 struct tr_resp *p = prev->resps + rno;
1052 struct tr_resp *n = new->resps + rno;
1053 int *r = reset + rno;
1054 u_long resptime = new->rtime;
1055 u_long qarrtime = fixtime(ntohl(n->tr_qarr));
1056 u_int ttl = n->tr_fttl;
1057 int first = (base == prev);
1058
1059 VAL_TO_MASK(smask, b->tr_smask);
1060 printf(" Source Response Dest");
1061 printf(" Packet Statistics For Only For Traffic\n");
1062 s1 = inet_fmt(qsrc);
1063 printf("%-15s %-15s All Multicast Traffic From %s\n",
1064 ((b->tr_inaddr & smask) == (qsrc & smask)) ? s1 : " * * * ",
1065 inet_fmt(base->qhdr.tr_raddr), s1);
1066 rtt = t_diff(resptime, new->qtime);
1067 ms = scale(&rtt);
1068 printf(" %c __/ rtt%5d%s Lost/Sent = Pct Rate To %s\n",
1069 first ? 'v' : '|', rtt, ms, inet_fmt(qgrp));
1070 if (!first) {
1071 hop = t_diff(resptime, qarrtime);
1072 ms = scale(&hop);
1073 printf(" v / hop%5d%s", hop, ms);
1074 printf(" --------------------- --------------------\n");
1075 }
1076 if (debug > 2) {
1077 printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
1078 printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
1079 printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
1080 printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
1081 printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
1082 printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
1083 printf("\t\t\t\tv_in: %ld ",
1084 (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
1085 printf("v_out: %ld ",
1086 (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
1087 printf("pkts: %ld\n",
1088 (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
1089 printf("\t\t\t\treset: %d\n", *r);
1090 }
1091
1092 while (TRUE) {
1093 if ((n->tr_inaddr != b->tr_inaddr) || (n->tr_inaddr != b->tr_inaddr))
1094 return 1; /* Route changed */
1095
1096 if ((n->tr_inaddr != n->tr_outaddr))
1097 printf("%-15s\n", inet_fmt(n->tr_inaddr));
1098 printf("%-15s %-14s %s\n", inet_fmt(n->tr_outaddr), names[rno],
1099 flag_type(n->tr_rflags));
1100
1101 if (rno-- < 1) break;
1102
1103 printf(" %c ^ ttl%5d ", first ? 'v' : '|', ttl);
1104 stat_line(p, n, TRUE, r);
1105 if (!first) {
1106 resptime = qarrtime;
1107 qarrtime = fixtime(ntohl((n-1)->tr_qarr));
1108 hop = t_diff(resptime, qarrtime);
1109 ms = scale(&hop);
1110 printf(" v | hop%5d%s", hop, ms);
1111 stat_line(b, n, TRUE, r);
1112 }
1113
1114 --b, --p, --n, --r;
1115 if (ttl < n->tr_fttl) ttl = n->tr_fttl;
1116 else ++ttl;
1117 }
1118
1119 printf(" %c \\__ ttl%5d ", first ? 'v' : '|', ttl);
1120 stat_line(p, n, FALSE, r);
1121 if (!first) {
1122 hop = t_diff(qarrtime, new->qtime);
1123 ms = scale(&hop);
1124 printf(" v \\ hop%5d%s", hop, ms);
1125 stat_line(b, n, FALSE, r);
1126 }
1127 printf("%-15s %s\n", inet_fmt(qdst), inet_fmt(lcl_addr));
1128 printf(" Receiver Query Source\n\n");
1129 return 0;
1130 }
1131
1132
1133 /***************************************************************************
1134 * main
1135 ***************************************************************************/
1136
1137 int
1138 main(int argc, char **argv)
1139 {
1140 int udp;
1141 struct sockaddr_in addr;
1142 int addrlen = sizeof(addr);
1143 int recvlen;
1144 struct timeval tv;
1145 struct resp_buf *prev, *new;
1146 struct tr_resp *r;
1147 u_int32_t smask;
1148 int rno;
1149 int hops, nexthop, tries;
1150 u_int32_t lastout = 0;
1151 int numstats = 1;
1152 int waittime;
1153
1154 if (geteuid() != 0) {
1155 fprintf(stderr, "mtrace: must be root\n");
1156 exit(1);
1157 }
1158 init_igmp();
1159 if (setuid(getuid()) == -1)
1160 logit(LOG_ERR, errno, "setuid");
1161
1162 argv++, argc--;
1163 if (argc == 0) goto usage;
1164
1165 while (argc > 0 && *argv[0] == '-') {
1166 char *p = *argv++; argc--;
1167 p++;
1168 do {
1169 char c = *p++;
1170 char *arg = (char *) 0;
1171 if (isdigit(*p)) {
1172 arg = p;
1173 p = "";
1174 } else if (argc > 0) arg = argv[0];
1175 switch (c) {
1176 case 'd': /* Unlisted debug print option */
1177 if (arg && isdigit(*arg)) {
1178 debug = atoi(arg);
1179 if (debug < 0) debug = 0;
1180 if (debug > 3) debug = 3;
1181 if (arg == argv[0]) argv++, argc--;
1182 break;
1183 } else
1184 goto usage;
1185 case 'M': /* Use multicast for reponse */
1186 multicast = TRUE;
1187 break;
1188 case 'l': /* Loop updating stats indefinitely */
1189 numstats = 3153600;
1190 break;
1191 case 'n': /* Don't reverse map host addresses */
1192 numeric = TRUE;
1193 break;
1194 case 'p': /* Passive listen for traces */
1195 passive = TRUE;
1196 break;
1197 case 'v': /* Verbosity */
1198 verbose = TRUE;
1199 break;
1200 case 's': /* Short form, don't wait for stats */
1201 numstats = 0;
1202 break;
1203 case 'w': /* Time to wait for packet arrival */
1204 if (arg && isdigit(*arg)) {
1205 timeout = atoi(arg);
1206 if (timeout < 1) timeout = 1;
1207 if (arg == argv[0]) argv++, argc--;
1208 break;
1209 } else
1210 goto usage;
1211 case 'm': /* Max number of hops to trace */
1212 if (arg && isdigit(*arg)) {
1213 qno = atoi(arg);
1214 if (qno > MAXHOPS) qno = MAXHOPS;
1215 else if (qno < 1) qno = 0;
1216 if (arg == argv[0]) argv++, argc--;
1217 break;
1218 } else
1219 goto usage;
1220 case 'q': /* Number of query retries */
1221 if (arg && isdigit(*arg)) {
1222 nqueries = atoi(arg);
1223 if (nqueries < 1) nqueries = 1;
1224 if (arg == argv[0]) argv++, argc--;
1225 break;
1226 } else
1227 goto usage;
1228 case 'g': /* Last-hop gateway (dest of query) */
1229 if (arg && (gwy = host_addr(arg))) {
1230 if (arg == argv[0]) argv++, argc--;
1231 break;
1232 } else
1233 goto usage;
1234 case 't': /* TTL for query packet */
1235 if (arg && isdigit(*arg)) {
1236 qttl = atoi(arg);
1237 if (qttl < 1) qttl = 1;
1238 rttl = qttl;
1239 if (arg == argv[0]) argv++, argc--;
1240 break;
1241 } else
1242 goto usage;
1243 case 'r': /* Dest for response packet */
1244 if (arg && (raddr = host_addr(arg))) {
1245 if (arg == argv[0]) argv++, argc--;
1246 break;
1247 } else
1248 goto usage;
1249 case 'i': /* Local interface address */
1250 if (arg && (lcl_addr = host_addr(arg))) {
1251 if (arg == argv[0]) argv++, argc--;
1252 break;
1253 } else
1254 goto usage;
1255 case 'S': /* Stat accumulation interval */
1256 if (arg && isdigit(*arg)) {
1257 statint = atoi(arg);
1258 if (statint < 1) statint = 1;
1259 if (arg == argv[0]) argv++, argc--;
1260 break;
1261 } else
1262 goto usage;
1263 default:
1264 goto usage;
1265 }
1266 } while (*p);
1267 }
1268
1269 if (argc > 0 && (qsrc = host_addr(argv[0]))) { /* Source of path */
1270 if (IN_MULTICAST(ntohl(qsrc))) goto usage;
1271 argv++, argc--;
1272 if (argc > 0 && (qdst = host_addr(argv[0]))) { /* Dest of path */
1273 argv++, argc--;
1274 if (argc > 0 && (qgrp = host_addr(argv[0]))) { /* Path via group */
1275 argv++, argc--;
1276 }
1277 if (IN_MULTICAST(ntohl(qdst))) {
1278 u_int32_t temp = qdst;
1279 qdst = qgrp;
1280 qgrp = temp;
1281 if (IN_MULTICAST(ntohl(qdst))) goto usage;
1282 } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) goto usage;
1283 }
1284 }
1285
1286 if (passive) {
1287 passive_mode();
1288 return(0);
1289 }
1290
1291 if (argc > 0 || qsrc == 0) {
1292 usage: printf("\
1293 Usage: mtrace [-Mlnps] [-w wait] [-m max_hops] [-q nqueries] [-g gateway]\n\
1294 [-S statint] [-t ttl] [-r resp_dest] [-i if_addr] source [receiver] [group]\n");
1295 exit(1);
1296 }
1297
1298 /*
1299 * Set useful defaults for as many parameters as possible.
1300 */
1301
1302 defgrp = htonl(0xE0020001); /* MBone Audio (224.2.0.1) */
1303 query_cast = htonl(0xE0000002); /* All routers multicast addr */
1304 resp_cast = htonl(0xE0000120); /* Mtrace response multicast addr */
1305 if (qgrp == 0) qgrp = defgrp;
1306
1307 /*
1308 * Get default local address for multicasts to use in setting defaults.
1309 */
1310 memset(&addr, 0, sizeof(addr));
1311 addr.sin_family = AF_INET;
1312 #if (defined(BSD) && (BSD >= 199103))
1313 addr.sin_len = sizeof(addr);
1314 #endif
1315 addr.sin_addr.s_addr = qgrp;
1316 addr.sin_port = htons(2000); /* Any port above 1024 will do */
1317
1318 if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
1319 (connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
1320 getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0) {
1321 perror("Determining local address");
1322 exit(1);
1323 }
1324
1325 #ifdef SUNOS5
1326 /*
1327 * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
1328 * This call to sysinfo will return the hostname.
1329 * If the default multicast interfface (set with the route
1330 * for 224.0.0.0) is not the same as the hostname,
1331 * mtrace -i [if_addr] will have to be used.
1332 */
1333 if (addr.sin_addr.s_addr == 0) {
1334 char myhostname[MAXHOSTNAMELEN];
1335 struct hostent *hp;
1336 int error;
1337
1338 error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
1339 if (error == -1) {
1340 perror("Getting my hostname");
1341 exit(1);
1342 }
1343
1344 hp = gethostbyname(myhostname);
1345 if (hp == NULL || hp->h_addrtype != AF_INET ||
1346 hp->h_length != sizeof(addr.sin_addr)) {
1347 perror("Finding IP address for my hostname");
1348 exit(1);
1349 }
1350
1351 memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr,
1352 sizeof(addr.sin_addr.s_addr));
1353 }
1354 #endif
1355
1356 /*
1357 * Default destination for path to be queried is the local host.
1358 */
1359 if (qdst == 0) qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
1360 dst_netmask = get_netmask(udp, qdst);
1361 close(udp);
1362 if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
1363
1364 /*
1365 * Protect against unicast queries to mrouted versions that might crash.
1366 */
1367 if (gwy && !IN_MULTICAST(ntohl(gwy)))
1368 if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0])) {
1369 int version = ntohl(incr[0].igmp.igmp_group.s_addr) & 0xFFFF;
1370 if (version == 0x0303 || version == 0x0503) {
1371 printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
1372 (version >> 8) & 0xFF);
1373 exit(0);
1374 }
1375 }
1376
1377 printf("Mtrace from %s to %s via group %s\n",
1378 inet_fmt(qsrc), inet_fmt(qdst),
1379 inet_fmt(qgrp));
1380
1381 if ((qdst & dst_netmask) == (qsrc & dst_netmask)) {
1382 printf("Source & receiver are directly connected, no path to trace\n");
1383 exit(0);
1384 }
1385
1386 /*
1387 * If the response is to be a multicast address, make sure we
1388 * are listening on that multicast address.
1389 */
1390 if (raddr) {
1391 if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1392 } else k_join(resp_cast, lcl_addr);
1393
1394 /*
1395 * If the destination is on the local net, the last-hop router can
1396 * be found by multicast to the all-routers multicast group.
1397 * Otherwise, use the group address that is the subject of the
1398 * query since by definition the last-hop router will be a member.
1399 * Set default TTLs for local remote multicasts.
1400 */
1401 restart:
1402
1403 if (gwy == 0)
1404 if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
1405 else tdst = qgrp;
1406 else tdst = gwy;
1407
1408 if (IN_MULTICAST(ntohl(tdst))) {
1409 k_set_loop(1); /* If I am running on a router, I need to hear this */
1410 if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
1411 else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
1412 }
1413
1414 /*
1415 * Try a query at the requested number of hops or MAXHOPS if unspecified.
1416 */
1417 if (qno == 0) {
1418 hops = MAXHOPS;
1419 tries = 1;
1420 printf("Querying full reverse path... ");
1421 fflush(stdout);
1422 } else {
1423 hops = qno;
1424 tries = nqueries;
1425 printf("Querying reverse path, maximum %d hops... ", qno);
1426 fflush(stdout);
1427 }
1428 base.rtime = 0;
1429 base.len = 0;
1430
1431 recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, tries, &base);
1432
1433 /*
1434 * If the initial query was successful, print it. Otherwise, if
1435 * the query max hop count is the default of zero, loop starting
1436 * from one until there is no response for four hops. The extra
1437 * hops allow getting past an mtrace-capable mrouter that can't
1438 * send multicast packets because all phyints are disabled.
1439 */
1440 if (recvlen) {
1441 printf("\n 0 ");
1442 print_host(qdst);
1443 printf("\n");
1444 print_trace(1, &base);
1445 r = base.resps + base.len - 1;
1446 if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
1447 qno != 0) {
1448 printf("%3d ", -(base.len+1));
1449 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1450 "doesn't support mtrace"
1451 : "is the next hop");
1452 } else {
1453 VAL_TO_MASK(smask, r->tr_smask);
1454 if ((r->tr_inaddr & smask) == (qsrc & smask)) {
1455 printf("%3d ", -(base.len+1));
1456 print_host(qsrc);
1457 printf("\n");
1458 }
1459 }
1460 } else if (qno == 0) {
1461 printf("switching to hop-by-hop:\n 0 ");
1462 print_host(qdst);
1463 printf("\n");
1464
1465 for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
1466 printf("%3d ", -hops);
1467 fflush(stdout);
1468
1469 /*
1470 * After a successful first hop, try switching to the unicast
1471 * address of the last-hop router instead of multicasting the
1472 * trace query. This should be safe for mrouted versions 3.3
1473 * and 3.5 because there is a long route timeout with metric
1474 * infinity before a route disappears. Switching to unicast
1475 * reduces the amount of multicast traffic and avoids a bug
1476 * with duplicate suppression in mrouted 3.5.
1477 */
1478 if (hops == 2 && gwy == 0 &&
1479 (recvlen = send_recv(lastout, IGMP_MTRACE_QUERY, hops, 1, &base)))
1480 tdst = lastout;
1481 else recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, hops, nqueries, &base);
1482
1483 if (recvlen == 0) {
1484 if (hops == 1) break;
1485 if (hops == nexthop) {
1486 if (what_kind(&base, "didn't respond")) {
1487 /* the ask_neighbors determined that the
1488 * not-responding router is the first-hop. */
1489 break;
1490 }
1491 } else if (hops < nexthop + 3) {
1492 printf("\n");
1493 } else {
1494 printf("...giving up\n");
1495 break;
1496 }
1497 continue;
1498 }
1499 r = base.resps + base.len - 1;
1500 if (base.len == hops &&
1501 (hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
1502 if (hops == nexthop) {
1503 print_trace(-hops, &base);
1504 } else {
1505 printf("\nResuming...\n");
1506 print_trace(nexthop, &base);
1507 }
1508 } else {
1509 if (base.len < hops) {
1510 /*
1511 * A shorter trace than requested means a fatal error
1512 * occurred along the path, or that the route changed
1513 * to a shorter one.
1514 *
1515 * If the trace is longer than the last one we received,
1516 * then we are resuming from a skipped router (but there
1517 * is still probably a problem).
1518 *
1519 * If the trace is shorter than the last one we
1520 * received, then the route must have changed (and
1521 * there is still probably a problem).
1522 */
1523 if (nexthop <= base.len) {
1524 printf("\nResuming...\n");
1525 print_trace(nexthop, &base);
1526 } else if (nexthop > base.len + 1) {
1527 hops = base.len;
1528 printf("\nRoute must have changed...\n");
1529 print_trace(1, &base);
1530 }
1531 } else {
1532 /*
1533 * The last hop address is not the same as it was;
1534 * the route probably changed underneath us.
1535 */
1536 hops = base.len;
1537 printf("\nRoute must have changed...\n");
1538 print_trace(1, &base);
1539 }
1540 }
1541 lastout = r->tr_outaddr;
1542
1543 if (base.len < hops ||
1544 r->tr_rmtaddr == 0 ||
1545 (r->tr_rflags & 0x80)) {
1546 VAL_TO_MASK(smask, r->tr_smask);
1547 if (r->tr_rmtaddr) {
1548 if (hops != nexthop) {
1549 printf("\n%3d ", -(base.len+1));
1550 }
1551 what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
1552 "doesn't support mtrace" :
1553 "would be the next hop");
1554 /* XXX could do segmented trace if TR_NO_SPACE */
1555 } else if (r->tr_rflags == TR_NO_ERR &&
1556 (r->tr_inaddr & smask) == (qsrc & smask)) {
1557 printf("%3d ", -(hops + 1));
1558 print_host(qsrc);
1559 printf("\n");
1560 }
1561 break;
1562 }
1563
1564 nexthop = hops + 1;
1565 }
1566 }
1567
1568 if (base.rtime == 0) {
1569 printf("Timed out receiving responses\n");
1570 if (IN_MULTICAST(ntohl(tdst))) {
1571 if (tdst == query_cast)
1572 printf("Perhaps no local router has a route for source %s\n",
1573 inet_fmt(qsrc));
1574 else
1575 printf("Perhaps receiver %s is not a member of group %s,\n"
1576 "or no router local to it has a route for source %s,\n"
1577 "or multicast at ttl %d doesn't reach its last-hop router"
1578 " for that source\n",
1579 inet_fmt(qdst), inet_fmt(qgrp), inet_fmt(qsrc),
1580 qttl ? qttl : MULTICAST_TTL1);
1581 }
1582 exit(1);
1583 }
1584
1585 printf("Round trip time %d ms\n\n", t_diff(base.rtime, base.qtime));
1586
1587 /*
1588 * Use the saved response which was the longest one received,
1589 * and make additional probes after delay to measure loss.
1590 */
1591 raddr = base.qhdr.tr_raddr;
1592 rttl = base.qhdr.tr_rttl;
1593 gettimeofday(&tv, 0);
1594 waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
1595 prev = &base;
1596 new = &incr[numstats&1];
1597
1598 while (numstats--) {
1599 if (waittime < 1) printf("\n");
1600 else {
1601 printf("Waiting to accumulate statistics... ");
1602 fflush(stdout);
1603 sleep((unsigned)waittime);
1604 }
1605 rno = base.len;
1606 recvlen = send_recv(tdst, IGMP_MTRACE_QUERY, rno, nqueries, new);
1607
1608 if (recvlen == 0) {
1609 printf("Timed out.\n");
1610 exit(1);
1611 }
1612
1613 if (rno != new->len) {
1614 printf("Trace length doesn't match:\n");
1615 /*
1616 * XXX Should this trace result be printed, or is that
1617 * too verbose? Perhaps it should just say restarting.
1618 * But if the path is changing quickly, this may be the
1619 * only snapshot of the current path. But, if the path
1620 * is changing that quickly, does the current path really
1621 * matter?
1622 */
1623 print_trace(1, new);
1624 printf("Restarting.\n\n");
1625 numstats++;
1626 goto restart;
1627 }
1628
1629 printf("Results after %d seconds:\n\n",
1630 (int)((new->qtime - base.qtime) >> 16));
1631 fixup_stats(&base, prev, new);
1632 if (print_stats(&base, prev, new)) {
1633 printf("Route changed:\n");
1634 print_trace(1, new);
1635 printf("Restarting.\n\n");
1636 goto restart;
1637 }
1638 prev = new;
1639 new = &incr[numstats&1];
1640 waittime = statint;
1641 }
1642
1643 /*
1644 * If the response was multicast back, leave the group
1645 */
1646 if (raddr) {
1647 if (IN_MULTICAST(ntohl(raddr))) k_leave(raddr, lcl_addr);
1648 } else k_leave(resp_cast, lcl_addr);
1649
1650 return (0);
1651 }
1652
1653 void
1654 check_vif_state(void)
1655 {
1656 logit(LOG_WARNING, errno, "sendto");
1657 }
1658
1659 /*
1660 * Log errors and other messages to stderr, according to the severity
1661 * of the message and the current debug level. For errors of severity
1662 * LOG_ERR or worse, terminate the program.
1663 */
1664 void
1665 logit(int severity, int syserr, const char *format, ...)
1666 {
1667 va_list ap;
1668
1669 switch (debug) {
1670 case 0: if (severity > LOG_WARNING) return;
1671 case 1: if (severity > LOG_NOTICE) return;
1672 case 2: if (severity > LOG_INFO ) return;
1673 default:
1674 if (severity == LOG_WARNING)
1675 fprintf(stderr, "warning - ");
1676 va_start(ap, format);
1677 vfprintf(stderr, format, ap);
1678 va_end(ap);
1679 if (syserr == 0)
1680 fprintf(stderr, "\n");
1681 else
1682 fprintf(stderr, ": %s\n", strerror(syserr));
1683 }
1684 if (severity <= LOG_ERR) exit(1);
1685 }
1686
1687 /* dummies */
1688 void accept_probe(u_int32_t src, u_int32_t dst, char *p, int datalen,
1689 u_int32_t level)
1690 {
1691 }
1692 void accept_group_report(u_int32_t src, u_int32_t dst, u_int32_t group,
1693 int r_type)
1694 {
1695 }
1696 void accept_neighbor_request2(u_int32_t src, u_int32_t dst)
1697 {
1698 }
1699 void accept_report(u_int32_t src, u_int32_t dst, char *p, int datalen,
1700 u_int32_t level)
1701 {
1702 }
1703 void accept_neighbor_request(u_int32_t src, u_int32_t dst)
1704 {
1705 }
1706 void accept_prune(u_int32_t src, u_int32_t dst, char *p, int datalen)
1707 {
1708 }
1709 void accept_graft(u_int32_t src, u_int32_t dst, char *p, int datalen)
1710 {
1711 }
1712 void accept_g_ack(u_int32_t src, u_int32_t dst, char *p, int datalen)
1713 {
1714 }
1715 void add_table_entry(u_int32_t origin, u_int32_t mcastgrp)
1716 {
1717 }
1718 void accept_leave_message(u_int32_t src, u_int32_t dst, u_int32_t group)
1719 {
1720 }
1721 void accept_mtrace(u_int32_t src, u_int32_t dst, u_int32_t group, char *data,
1722 u_int no, int datalen)
1723 {
1724 }
1725 void accept_membership_query(u_int32_t src, u_int32_t dst, u_int32_t group,
1726 int tmo)
1727 {
1728 }
1729 void accept_neighbors(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1730 u_int32_t level)
1731 {
1732 }
1733 void accept_neighbors2(u_int32_t src, u_int32_t dst, u_char *p, int datalen,
1734 u_int32_t level)
1735 {
1736 }
1737 void accept_info_request(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1738 {
1739 }
1740 void accept_info_reply(u_int32_t src, u_int32_t dst, u_char *p, int datalen)
1741 {
1742 }
1743