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