Remove main() prototypes.
[dragonfly.git] / usr.sbin / mrouted / mtrace.c
1 /*
2  * mtrace.c
3  *
4  * This tool traces the branch of a multicast tree from a source to a
5  * receiver for a particular multicast group and gives statistics
6  * about packet rate and loss for each hop along the path.  It can
7  * usually be invoked just as
8  *
9  *      mtrace source
10  *
11  * to trace the route from that source to the local host for a default
12  * group when only the route is desired and not group-specific packet
13  * counts.  See the usage line for more complex forms.
14  *
15  *
16  * Released 4 Apr 1995.  This program was adapted by Steve Casner
17  * (USC/ISI) from a prototype written by Ajit Thyagarajan (UDel and
18  * Xerox PARC).  It attempts to parallel in command syntax and output
19  * format the unicast traceroute program written by Van Jacobson (LBL)
20  * for the parts where that makes sense.
21  * 
22  * Copyright (c) 1995 by the University of Southern California
23  * All rights reserved.
24  *
25  * Permission to use, copy, modify, and distribute this software and its
26  * documentation in source and binary forms for any purposes and without
27  * fee is hereby granted, provided that the above copyright notice
28  * appear in all copies and that both the copyright notice and this
29  * permission notice appear in supporting documentation, and that any
30  * documentation, advertising materials, and other materials related to
31  * such distribution and use acknowledge that the software was developed
32  * by the University of Southern California, Information Sciences
33  * Institute.  The name of the University may not be used to endorse or
34  * promote products derived from this software without specific prior
35  * written permission.
36  *
37  * THE UNIVERSITY OF SOUTHERN CALIFORNIA makes no representations about
38  * the suitability of this software for any purpose.  THIS SOFTWARE IS
39  * PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
40  * INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
41  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
42  *
43  * Other copyrights might apply to parts of this software and are so
44  * noted when applicable.
45  *
46  * Parts of this software are derived from mrouted, which has the
47  * following license:
48  * 
49  * The mrouted program is covered by the following license.  Use of the
50  * mrouted program represents acceptance of these terms and conditions.
51  * 
52  * 1. STANFORD grants to LICENSEE a nonexclusive and nontransferable
53  * license to use, copy and modify the computer software ``mrouted''
54  * (hereinafter called the ``Program''), upon the terms and conditions
55  * hereinafter set out and until Licensee discontinues use of the Licensed
56  * Program.
57  * 
58  * 2. LICENSEE acknowledges that the Program is a research tool still in
59  * the development state, that it is being supplied ``as is,'' without any
60  * accompanying services from STANFORD, and that this license is entered
61  * into in order to encourage scientific collaboration aimed at further
62  * development and application of the Program.
63  * 
64  * 3. LICENSEE may copy the Program and may sublicense others to use
65  * object code copies of the Program or any derivative version of the
66  * Program.  All copies must contain all copyright and other proprietary
67  * notices found in the Program as provided by STANFORD.  Title to
68  * copyright to the Program remains with STANFORD.
69  * 
70  * 4. LICENSEE may create derivative versions of the Program.  LICENSEE
71  * hereby grants STANFORD a royalty-free license to use, copy, modify,
72  * distribute and sublicense any such derivative works.  At the time
73  * LICENSEE provides a copy of a derivative version of the Program to a
74  * third party, LICENSEE shall provide STANFORD with one copy of the
75  * source code of the derivative version at no charge to STANFORD.
76  * 
77  * 5. STANFORD MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
78  * IMPLIED.  By way of example, but not limitation, STANFORD MAKES NO
79  * REPRESENTATION OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
80  * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED PROGRAM WILL NOT
81  * INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. STANFORD
82  * shall not be held liable for any liability nor for any direct, indirect
83  * or consequential damages with respect to any claim by LICENSEE or any
84  * third party on account of or arising from this Agreement or use of the
85  * Program.
86  * 
87  * 6. This agreement shall be construed, interpreted and applied in
88  * accordance with the State of California and any legal action arising
89  * out of this Agreement or use of the Program shall be filed in a court
90  * in the State of California.
91  * 
92  * 7. Nothing in this Agreement shall be construed as conferring rights to
93  * use in advertising, publicity or otherwise any trademark or the name
94  * of ``Stanford''.
95  * 
96  * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of
97  * Leland Stanford Junior University.
98  *
99  *
100  * The mtrace program has been modified and improved by Xerox
101  * Corporation.  Xerox grants to LICENSEE a non-exclusive and
102  * non-transferable license to use, copy, and modify the Xerox modified
103  * and improved mrouted software on the same terms and conditions which
104  * govern the license Stanford and ISI grant with respect to the mtrace
105  * program.  These terms and conditions are incorporated in this grant
106  * by reference and shall be deemed to have been accepted by LICENSEE
107  * to cover its relationship with Xerox Corporation with respect to any
108  * use of the Xerox improved program.
109  * 
110  * The mtrace program is COPYRIGHT 1998 by Xerox Corporation.
111  *
112  * $FreeBSD: src/usr.sbin/mrouted/mtrace.c,v 1.17.2.3 2002/09/12 16:27:49 nectar Exp $
113  */
114
115 #include <ctype.h>
116 #include <err.h>
117 #include <errno.h>
118 #include <memory.h>
119 #include <netdb.h>
120 #include <stdio.h>
121 #include <stdlib.h>
122 #include <string.h>
123 #include <syslog.h>
124 #include <unistd.h>
125 #include <sys/param.h>
126 #include <sys/types.h>
127 #include <sys/socket.h>
128 #include <sys/time.h>
129 #include <net/if.h>
130 #include <netinet/in.h>
131 #include <netinet/in_systm.h>
132 #include <netinet/ip.h>
133 #include <netinet/igmp.h>
134 #include <sys/ioctl.h>
135 #ifdef SYSV
136 #include <sys/sockio.h>
137 #endif
138 #include <arpa/inet.h>
139 #include <stdarg.h>
140 #ifdef SUNOS5
141 #include <sys/systeminfo.h>
142 #endif
143
144 typedef unsigned int u_int32;   /* XXX */
145 #include "mtrace.h"
146
147 #define DEFAULT_TIMEOUT 3       /* How long to wait before retrying requests */
148 #define DEFAULT_RETRIES 3       /* How many times to try */
149 #define DEFAULT_EXTRAHOPS 3     /* How many hops past a non-responding rtr */
150 #define MAXHOPS 60              /* Don't need more hops than this */
151 #define UNICAST_TTL 255         /* TTL for unicast response */
152 #define MULTICAST_TTL1 127      /* Default TTL for multicast query/response */
153 #define MULTICAST_TTL_INC 32    /* TTL increment for increase after timeout */
154 #define MULTICAST_TTL_MAX 192   /* Maximum TTL allowed (protect low-BW links */
155
156 #define TRUE 1
157 #define FALSE 0
158 #define DVMRP_ASK_NEIGHBORS2    5       /* DVMRP msg requesting neighbors */
159 #define DVMRP_NEIGHBORS2        6       /* reply to above */
160 #define DVMRP_NF_DOWN           0x10    /* kernel state of interface */
161 #define DVMRP_NF_DISABLED       0x20    /* administratively disabled */
162 #define MAX_IP_PACKET_LEN       576
163 #define MIN_IP_HEADER_LEN       20
164 #define MAX_IP_HEADER_LEN       60
165 #define MAX_DVMRP_DATA_LEN \
166                 ( MAX_IP_PACKET_LEN - MAX_IP_HEADER_LEN - IGMP_MINLEN )
167
168 struct resp_buf {
169     u_long qtime;               /* Time query was issued */
170     u_long rtime;               /* Time response was received */
171     int len;                    /* Number of reports or length of data */
172     struct igmp igmp;           /* IGMP header */
173     union {
174         struct {
175             struct tr_query q;          /* Query/response header */
176             struct tr_resp r[MAXHOPS];  /* Per-hop reports */
177         } t;
178         char d[MAX_DVMRP_DATA_LEN];     /* Neighbor data */
179     } u;
180 } base, incr[2];
181
182 #define qhdr u.t.q
183 #define resps u.t.r
184 #define ndata u.d
185
186 char *names[MAXHOPS];
187
188 /*
189  * In mrouted 3.3 and 3.4 (and in some Cisco IOS releases),
190  * cache entries can get deleted even if there is traffic
191  * flowing, which will reset the per-source/group counters.
192  */
193 #define         BUG_RESET       0x01
194
195 /*
196  * Also in mrouted 3.3 and 3.4, there's a bug in neighbor
197  * version processing which can cause them to believe that
198  * the neighbor is constantly resetting.  This causes them
199  * to constantly delete all their state.
200  */
201 #define         BUG_RESET2X     0x02
202
203 /*
204  * Pre-3.7 mrouted's forget to byte-swap their reports.
205  */
206 #define         BUG_SWAP        0x04
207
208 /*
209  * Pre-3.9 mrouted's forgot a parenthesis in the htonl()
210  * on the time calculation so supply bogus times.
211  */
212 #define         BUG_BOGUSTIME   0x08
213
214 #define BUG_NOPRINT     (BUG_RESET | BUG_RESET2X)
215
216 int bugs[MAXHOPS];                      /* List of bugs noticed at each hop */
217
218 struct mtrace {
219         struct mtrace   *next;
220         struct resp_buf  base, incr[2];
221         struct resp_buf *new, *prev;
222         int              nresp;
223         struct timeval   last;
224         int              bugs[MAXHOPS];
225         char            *names[MAXHOPS];
226         int              lastqid;
227 };
228
229 int timeout = DEFAULT_TIMEOUT;
230 int nqueries = DEFAULT_RETRIES;
231 int numeric = FALSE;
232 int debug = 0;
233 int passive = FALSE;
234 int multicast = FALSE;
235 int unicast = FALSE;
236 int statint = 10;
237 int verbose = FALSE;
238 int tunstats = FALSE;
239 int weak = FALSE;
240 int extrahops = DEFAULT_EXTRAHOPS;
241 int printstats = TRUE;
242 int sendopts = TRUE;
243 int lossthresh = 0;
244 int fflag = FALSE;
245 int staticqid = 0;
246
247 u_int32 defgrp;                         /* Default group if not specified */
248 u_int32 query_cast;                     /* All routers multicast addr */
249 u_int32 resp_cast;                      /* Mtrace response multicast addr */
250
251 u_int32 lcl_addr = 0;                   /* This host address, in NET order */
252 u_int32 dst_netmask = 0;                /* netmask to go with qdst */
253
254 /*
255  * Query/response parameters, all initialized to zero and set later
256  * to default values or from options.
257  */
258 u_int32 qsrc = 0;               /* Source address in the query */
259 u_int32 qgrp = 0;               /* Group address in the query */
260 u_int32 qdst = 0;               /* Destination (receiver) address in query */
261 u_char qno  = 0;                /* Max number of hops to query */
262 u_int32 raddr = 0;              /* Address where response should be sent */
263 int    qttl = 0;                /* TTL for the query packet */
264 u_char rttl = 0;                /* TTL for the response packet */
265 u_int32 gwy = 0;                /* User-supplied last-hop router address */
266 u_int32 tdst = 0;               /* Address where trace is sent (last-hop) */
267
268 char s1[19];            /* buffers to hold the string representations  */
269 char s2[19];            /* of IP addresses, to be passed to inet_fmt() */
270 char s3[19];            /* or inet_fmts().                             */
271
272 #if !(defined(BSD) && (BSD >= 199103))
273 extern int              errno;
274 extern int              sys_nerr;
275 extern char *           sys_errlist[];
276 #endif
277
278 #define RECV_BUF_SIZE 8192
279 char    *send_buf, *recv_buf;
280 int     igmp_socket;
281 u_int32 allrtrs_group;
282 char    router_alert[4];                /* Router Alert IP Option           */
283 #ifndef IPOPT_RA
284 #define IPOPT_RA                148
285 #endif
286 #ifdef SUNOS5
287 char    eol[4];                         /* EOL IP Option                    */
288 int ip_addlen = 0;                      /* Workaround for Option bug #2     */
289 #endif
290
291 /*
292  * max macro, with weird case to avoid conflicts
293  */
294 #define MaX(a,b)        ((a) > (b) ? (a) : (b))
295
296 typedef int (*callback_t)(int, u_char *, int, struct igmp *, int,
297                         struct sockaddr *, int *, struct timeval *);
298
299 void                    init_igmp(void);
300 void                    send_igmp(u_int32 src, u_int32 dst, int type,
301                                                 int code, u_int32 group,
302                                                 int datalen);
303 int                     inet_cksum(u_short *addr, u_int len);
304 void                    k_set_rcvbuf(int bufsize);
305 void                    k_hdr_include(int boolv);
306 void                    k_set_ttl(int t);
307 void                    k_set_loop(int l);
308 void                    k_set_if(u_int32 ifa);
309 void                    k_join(u_int32 grp, u_int32 ifa);
310 void                    k_leave(u_int32 grp, u_int32 ifa);
311 char *                  inet_fmt(u_int32 addr, char *s);
312 char *                  inet_fmts(u_int32 addr, u_int32 mask, char *s);
313 char *                  inet_name(u_int32 addr);
314 u_int32                 host_addr(char *name);
315 /* u_int is promoted u_char */
316 char *                  proto_type(u_int type);
317 char *                  flag_type(u_int type);
318
319 u_int32                 get_netmask(int s, u_int32 *dst);
320 int                     get_ttl(struct resp_buf *buf);
321 int                     t_diff(u_long a, u_long b);
322 u_long                  byteswap(u_long v);
323 int                     mtrace_callback(int, u_char *, int, struct igmp *,
324                                         int, struct sockaddr *, int *,
325                                         struct timeval *);
326 int                     send_recv(u_int32 dst, int type, int code,
327                                         int tries, struct resp_buf *save,
328                                         callback_t callback);
329 void                    passive_mode(void);
330 char *                  print_host(u_int32 addr);
331 char *                  print_host2(u_int32 addr1, u_int32 addr2);
332 void                    print_trace(int idx, struct resp_buf *buf,
333                                         char **names);
334 int                     what_kind(struct resp_buf *buf, char *why);
335 char *                  scale(int *hop);
336 void                    stat_line(struct tr_resp *r, struct tr_resp *s,
337                                         int have_next, int *res);
338 void                    fixup_stats(struct resp_buf *base,
339                                         struct resp_buf *prev,
340                                         struct resp_buf *new,
341                                         int *bugs);
342 int                     check_thresh(int thresh,
343                                         struct resp_buf *base,
344                                         struct resp_buf *prev,
345                                         struct resp_buf *new);
346 int                     print_stats(struct resp_buf *base,
347                                         struct resp_buf *prev,
348                                         struct resp_buf *new,
349                                         int *bugs,
350                                         char **names);
351 int                     path_changed(struct resp_buf *base,
352                                         struct resp_buf *new);
353 void                    check_vif_state(void);
354
355 void                    dolog(int, int, char *, ...) __printflike(3, 4);
356 static void             usage(void);
357
358
359 /*
360  * Open and initialize the igmp socket, and fill in the non-changing
361  * IP header fields in the output packet buffer.
362  */
363 void
364 init_igmp(void)
365 {
366     struct ip *ip;
367
368     recv_buf = (char *)malloc(RECV_BUF_SIZE);
369     if (recv_buf == NULL)
370         dolog(LOG_ERR, 0, "Out of memory allocating recv_buf!");
371     send_buf = (char *)malloc(RECV_BUF_SIZE);
372     if (send_buf == NULL)
373         dolog(LOG_ERR, 0, "Out of memory allocating send_buf!");
374
375     if ((igmp_socket = socket(AF_INET, SOCK_RAW, IPPROTO_IGMP)) < 0) 
376         dolog(LOG_ERR, errno, "IGMP socket");
377
378     k_hdr_include(TRUE);        /* include IP header when sending */
379     k_set_rcvbuf(48*1024);      /* lots of input buffering        */
380     k_set_ttl(1);               /* restrict multicasts to one hop */
381     k_set_loop(FALSE);          /* disable multicast loopback     */
382
383     ip         = (struct ip *)send_buf;
384     ip->ip_hl  = sizeof(struct ip) >> 2;
385     ip->ip_v   = IPVERSION;
386     ip->ip_tos = 0;
387     ip->ip_off = 0;
388     ip->ip_p   = IPPROTO_IGMP;
389     ip->ip_ttl = MAXTTL;        /* applies to unicasts only */
390
391 #ifndef INADDR_ALLRTRS_GROUP
392 #define INADDR_ALLRTRS_GROUP    0xe0000002      /* 224.0.0.2 */
393 #endif
394     allrtrs_group  = htonl(INADDR_ALLRTRS_GROUP);
395
396     router_alert[0] = IPOPT_RA; /* Router Alert */
397     router_alert[1] = 4;        /* 4 bytes */
398     router_alert[2] = 0;
399     router_alert[3] = 0;
400 }
401
402 #ifdef SUNOS5
403 void
404 checkforsolarisbug(void)
405 {
406     u_int32 localhost = htonl(0x7f000001);
407
408     eol[0] = IPOPT_EOL;
409     eol[1] = IPOPT_EOL;
410     eol[2] = IPOPT_EOL;
411     eol[3] = IPOPT_EOL;
412
413     setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS, eol, sizeof(eol));
414     /*
415      * Check if the kernel adds the options length to the packet
416      * length.  Send myself an IGMP packet of type 0 (illegal),
417      * with 4 IPOPT_EOL options, my PID (for collision detection)
418      * and 4 bytes of zero (so that the checksum works whether
419      * the 4 bytes of zero get truncated or not).
420      */
421     bzero(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN, 8);
422     *(int *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN) = getpid();
423     send_igmp(localhost, localhost, 0, 0, 0, 8);
424     while (1) {
425         int recvlen, dummy = 0;
426
427         recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
428                                 0, NULL, &dummy);
429         /* 8 == 4 bytes of options and 4 bytes of PID */
430         if (recvlen >= MIN_IP_HEADER_LEN + IGMP_MINLEN + 8) {
431             struct ip *ip = (struct ip *)recv_buf;
432             struct igmp *igmp;
433             int *p;
434
435             if (ip->ip_hl != 6 ||
436                 ip->ip_p != IPPROTO_IGMP ||
437                 ip->ip_src.s_addr != localhost ||
438                 ip->ip_dst.s_addr != localhost)
439                 continue;
440
441             igmp = (struct igmp *)(recv_buf + (ip->ip_hl << 2));
442             if (igmp->igmp_group.s_addr != 0)
443                 continue;
444             if (igmp->igmp_type != 0 || igmp->igmp_code != 0)
445                 continue;
446
447             p = (int *)((char *)igmp + IGMP_MINLEN);
448             if (*p != getpid())
449                 continue;
450
451 #ifdef RAW_INPUT_IS_RAW
452             ip->ip_len = ntohs(ip->ip_len);
453 #endif
454             if (ip->ip_len == IGMP_MINLEN + 4)
455                 ip_addlen = 4;
456             else if (ip->ip_len == IGMP_MINLEN + 8)
457                 ip_addlen = 0;
458             else
459                 dolog(LOG_ERR, 0, "while checking for Solaris bug: Sent %d bytes and got back %d!", IGMP_MINLEN + 8, ip->ip_len);
460
461             break;
462         }
463     }
464 }
465 #endif
466
467 /*
468  * Construct an IGMP message in the output packet buffer.  The caller may
469  * have already placed data in that buffer, of length 'datalen'.  Then send
470  * the message from the interface with IP address 'src' to destination 'dst'.
471  */
472 void
473 send_igmp(u_int32 src, u_int32 dst, int type, int code, u_int32 group,
474           int datalen)
475 {
476     struct sockaddr_in sdst;
477     struct ip *ip;
478     struct igmp *igmp;
479     int setloop = 0;
480     static int raset = 0;
481     int sendra = 0;
482     int sendlen;
483
484     ip                      = (struct ip *)send_buf;
485     ip->ip_src.s_addr       = src;
486     ip->ip_dst.s_addr       = dst;
487     ip->ip_len              = MIN_IP_HEADER_LEN + IGMP_MINLEN + datalen;
488     sendlen                 = ip->ip_len;
489 #ifdef SUNOS5
490     ip->ip_len             += ip_addlen;
491 #endif
492 #ifdef RAW_OUTPUT_IS_RAW
493     ip->ip_len              = htons(ip->ip_len);
494 #endif
495
496     igmp                    = (struct igmp *)(send_buf + MIN_IP_HEADER_LEN);
497     igmp->igmp_type         = type;
498     igmp->igmp_code         = code;
499     igmp->igmp_group.s_addr = group;
500     igmp->igmp_cksum        = 0;
501     igmp->igmp_cksum        = inet_cksum((u_short *)igmp,
502                                          IGMP_MINLEN + datalen);
503
504     if (IN_MULTICAST(ntohl(dst))) {
505         k_set_if(src);
506         setloop = 1;
507         k_set_loop(TRUE);
508         if (dst != allrtrs_group)
509             sendra = 1;
510     }
511
512     if (sendopts && sendra && !raset) {
513         setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
514                         router_alert, sizeof(router_alert));
515         raset = 1;
516     } else if (!sendra && raset) {
517 #ifdef SUNOS5
518         /*
519          * SunOS5 < 5.6 cannot properly reset the IP_OPTIONS "socket"
520          * option.  Instead, set up a string of 4 EOL's.
521          */
522         setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
523                         eol, sizeof(eol));
524 #else
525         setsockopt(igmp_socket, IPPROTO_IP, IP_OPTIONS,
526                         NULL, 0);
527 #endif
528         raset = 0;
529     }
530
531     bzero(&sdst, sizeof(sdst));
532     sdst.sin_family = AF_INET;
533 #if (defined(BSD) && (BSD >= 199103))
534     sdst.sin_len = sizeof(sdst);
535 #endif
536     sdst.sin_addr.s_addr = dst;
537     if (sendto(igmp_socket, send_buf, sendlen, 0,
538                         (struct sockaddr *)&sdst, sizeof(sdst)) < 0) {
539             dolog(LOG_WARNING, errno, "sendto to %s on %s",
540                 inet_fmt(dst, s1), inet_fmt(src, s2));
541     }
542
543     if (setloop)
544             k_set_loop(FALSE);
545
546     dolog(LOG_DEBUG, 0, "SENT %s from %-15s to %s",
547         type == IGMP_MTRACE ? "mtrace request" : "ask_neighbors",
548         src == INADDR_ANY ? "INADDR_ANY" : inet_fmt(src, s1),
549         inet_fmt(dst, s2));
550 }
551
552 /*
553  * inet_cksum extracted from:
554  *                      P I N G . C
555  *
556  * Author -
557  *      Mike Muuss
558  *      U. S. Army Ballistic Research Laboratory
559  *      December, 1983
560  * Modified at Uc Berkeley
561  *
562  * (ping.c) Status -
563  *      Public Domain.  Distribution Unlimited.
564  *
565  *                      I N _ C K S U M
566  *
567  * Checksum routine for Internet Protocol family headers (C Version)
568  *
569  */
570 int
571 inet_cksum(u_short *addr, u_int len)
572 {
573         int nleft = (int)len;
574         u_short *w = addr;
575         u_short answer = 0;
576         int sum = 0;
577
578         /*
579          *  Our algorithm is simple, using a 32 bit accumulator (sum),
580          *  we add sequential 16 bit words to it, and at the end, fold
581          *  back all the carry bits from the top 16 bits into the lower
582          *  16 bits.
583          */
584         while (nleft > 1)  {
585                 sum += *w++;
586                 nleft -= 2;
587         }
588
589         /* mop up an odd byte, if necessary */
590         if (nleft == 1) {
591                 *(u_char *) (&answer) = *(u_char *)w ;
592                 sum += answer;
593         }
594
595         /*
596          * add back carry outs from top 16 bits to low 16 bits
597          */
598         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
599         sum += (sum >> 16);                     /* add carry */
600         answer = ~sum;                          /* truncate to 16 bits */
601         return (answer);
602 }
603
604 void
605 k_set_rcvbuf(int bufsize)
606 {
607     if (setsockopt(igmp_socket, SOL_SOCKET, SO_RCVBUF,
608                    (char *)&bufsize, sizeof(bufsize)) < 0)
609         dolog(LOG_ERR, errno, "setsockopt SO_RCVBUF %u", bufsize);
610 }
611
612
613 void
614 k_hdr_include(int boolv)
615 {
616 #ifdef IP_HDRINCL
617     if (setsockopt(igmp_socket, IPPROTO_IP, IP_HDRINCL,
618                    (char *)&boolv, sizeof(boolv)) < 0)
619         dolog(LOG_ERR, errno, "setsockopt IP_HDRINCL %u", boolv);
620 #endif
621 }
622
623 void
624 k_set_ttl(int t)
625 {
626     u_char ttl;
627
628     ttl = t;
629     if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_TTL,
630                    (char *)&ttl, sizeof(ttl)) < 0)
631         dolog(LOG_ERR, errno, "setsockopt IP_MULTICAST_TTL %u", ttl);
632 }
633
634
635 void
636 k_set_loop(int l)
637 {
638     u_char loop;
639
640     loop = l;
641     if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_LOOP,
642                    (char *)&loop, sizeof(loop)) < 0)
643         dolog(LOG_ERR, errno, "setsockopt IP_MULTICAST_LOOP %u", loop);
644 }
645
646 void
647 k_set_if(u_int32 ifa)
648 {
649     struct in_addr adr;
650
651     adr.s_addr = ifa;
652     if (setsockopt(igmp_socket, IPPROTO_IP, IP_MULTICAST_IF,
653                    (char *)&adr, sizeof(adr)) < 0)
654         dolog(LOG_ERR, errno, "setsockopt IP_MULTICAST_IF %s",
655                             inet_fmt(ifa, s1));
656 }
657
658 void
659 k_join(u_int32 grp, u_int32 ifa)
660 {
661     struct ip_mreq mreq;
662
663     mreq.imr_multiaddr.s_addr = grp;
664     mreq.imr_interface.s_addr = ifa;
665
666     if (setsockopt(igmp_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
667                    (char *)&mreq, sizeof(mreq)) < 0)
668         dolog(LOG_WARNING, errno, "can't join group %s on interface %s",
669                                 inet_fmt(grp, s1), inet_fmt(ifa, s2));
670 }
671
672
673 void
674 k_leave(u_int32 grp, u_int32 ifa)
675 {
676     struct ip_mreq mreq;
677
678     mreq.imr_multiaddr.s_addr = grp;
679     mreq.imr_interface.s_addr = ifa;
680
681     if (setsockopt(igmp_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
682                    (char *)&mreq, sizeof(mreq)) < 0)
683         dolog(LOG_WARNING, errno, "can't leave group %s on interface %s",
684                                 inet_fmt(grp, s1), inet_fmt(ifa, s2));
685 }
686
687 /*
688  * Convert an IP address in u_long (network) format into a printable string.
689  */
690 char *
691 inet_fmt(u_int32 addr, char *s)
692 {
693     u_char *a;
694
695     a = (u_char *)&addr;
696     sprintf(s, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
697     return (s);
698 }
699
700
701 /*
702  * Convert an IP subnet number in u_long (network) format into a printable
703  * string including the netmask as a number of bits.
704  */
705 char *
706 inet_fmts(u_int32 addr, u_int32 mask, char *s)
707 {
708     u_char *a, *m;
709     int bits;
710
711     if ((addr == 0) && (mask == 0)) {
712         sprintf(s, "default");
713         return (s);
714     }
715     a = (u_char *)&addr;
716     m = (u_char *)&mask;
717     bits = 33 - ffs(ntohl(mask));
718
719     if      (m[3] != 0) sprintf(s, "%u.%u.%u.%u/%d", a[0], a[1], a[2], a[3],
720                                                 bits);
721     else if (m[2] != 0) sprintf(s, "%u.%u.%u/%d",    a[0], a[1], a[2], bits);
722     else if (m[1] != 0) sprintf(s, "%u.%u/%d",       a[0], a[1], bits);
723     else                sprintf(s, "%u/%d",          a[0], bits);
724
725     return (s);
726 }
727
728 char *
729 inet_name(u_int32 addr)
730 {
731     struct hostent *e;
732
733     e = gethostbyaddr(&addr, sizeof(addr), AF_INET);
734
735     return e ? e->h_name : "?";
736 }
737
738
739 u_int32 
740 host_addr(char *name)
741 {
742     struct hostent *e = NULL;
743     u_int32  addr;
744     int i, dots = 3;
745     char        buf[40];
746     char        *ip = name;
747     char        *op = buf;
748
749     /*
750      * Undo BSD's favor -- take fewer than 4 octets as net/subnet address
751      * if the name is all numeric.
752      */
753     for (i = sizeof(buf) - 7; i > 0; --i) {
754         if (*ip == '.') --dots;
755         else if (*ip == '\0') break;
756         else if (!isdigit(*ip)) dots = 0;  /* Not numeric, don't add zeroes */
757         *op++ = *ip++;
758     }
759     for (i = 0; i < dots; ++i) {
760         *op++ = '.';
761         *op++ = '0';
762     }
763     *op = '\0';
764
765     if (dots <= 0)
766         e = gethostbyname(name);
767     if (e && (e->h_length == sizeof(addr))) {
768         memcpy((char *)&addr, e->h_addr_list[0], e->h_length);
769         if (e->h_addr_list[1])
770             fprintf(stderr, "Warning: %s has multiple addresses, using %s\n",
771                         name, inet_fmt(addr, s1));
772     } else {
773         addr = inet_addr(buf);
774         if (addr == -1 || (IN_MULTICAST(addr) && dots)) {
775             addr = 0;
776             printf("Could not parse %s as host name or address\n", name);
777         }
778     }
779     return addr;
780 }
781
782
783 char *
784 proto_type(u_int type)
785 {
786     static char buf[80];
787
788     switch (type) {
789       case PROTO_DVMRP:
790         return ("DVMRP");
791       case PROTO_MOSPF:
792         return ("MOSPF");
793       case PROTO_PIM:
794         return ("PIM");
795       case PROTO_CBT:
796         return ("CBT");
797       case PROTO_PIM_SPECIAL:
798         return ("PIM/Special");
799       case PROTO_PIM_STATIC:
800         return ("PIM/Static");
801       case PROTO_DVMRP_STATIC:
802         return ("DVMRP/Static");
803       case PROTO_PIM_BGP4PLUS:
804         return ("PIM/BGP4+");
805       case PROTO_CBT_SPECIAL:
806         return ("CBT/Special");
807       case PROTO_CBT_STATIC:
808         return ("CBT/Static");
809       case PROTO_PIM_ASSERT:
810         return ("PIM/Assert");
811       case 0:
812         return ("None");
813       default:
814         sprintf(buf, "Unknown protocol code %d", type);
815         return (buf);
816     }
817 }
818
819
820 char *
821 flag_type(u_int type)
822 {
823     static char buf[80];
824
825     switch (type) {
826       case TR_NO_ERR:
827         return ("");
828       case TR_WRONG_IF:
829         return ("Wrong interface");
830       case TR_PRUNED:
831         return ("Prune sent upstream");
832       case TR_OPRUNED:
833         return ("Output pruned");
834       case TR_SCOPED:
835         return ("Hit scope boundary");
836       case TR_NO_RTE:
837         return ("No route");
838       case TR_NO_FWD:
839         return ("Not forwarding");
840       case TR_HIT_RP:
841         return ("Reached RP/Core");
842       case TR_RPF_IF:
843         return ("RPF Interface");
844       case TR_NO_MULTI:
845         return ("Multicast disabled");
846       case TR_OLD_ROUTER:
847         return ("Next router no mtrace");
848       case TR_NO_SPACE:
849         return ("No space in packet");
850       case TR_ADMIN_PROHIB:
851         return ("Admin. Prohibited");
852       default:
853         sprintf(buf, "Unknown error code %d", type);
854         return (buf);
855     }
856 }    
857
858 /*
859  * If destination is on a local net, get the netmask, else set the
860  * netmask to all ones.  There are two side effects: if the local
861  * address was not explicitly set, and if the destination is on a
862  * local net, use that one; in either case, verify that the local
863  * address is valid.
864  */
865 u_int32
866 get_netmask(int s, u_int32 *dst)
867 {
868     unsigned int n;
869     struct ifconf ifc;
870     struct ifreq *ifrp, *ifend;
871     u_int32 if_addr, if_mask;
872     u_int32 retval = 0xFFFFFFFF;
873     int found = FALSE;
874     int num_ifreq = 32;
875
876     ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
877     ifc.ifc_buf = malloc(ifc.ifc_len);
878     while (ifc.ifc_buf) {
879         if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) {
880             perror("ioctl SIOCGIFCONF");
881             return retval;
882         }
883
884         /*
885          * If the buffer was large enough to hold all the addresses
886          * then break out, otherwise increase the buffer size and
887          * try again.
888          *
889          * The only way to know that we definitely had enough space
890          * is to know that there was enough space for at least one
891          * more struct ifreq. ???
892          */
893         if ((num_ifreq * sizeof(struct ifreq)) >=
894              ifc.ifc_len + sizeof(struct ifreq))
895              break;
896
897         num_ifreq *= 2;
898         ifc.ifc_len = num_ifreq * sizeof(struct ifreq);
899         ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
900     }
901     if (ifc.ifc_buf == NULL) {
902         fprintf(stderr, "getting interface list: ran out of memory");
903         exit(1);
904     }
905
906     ifrp = (struct ifreq *)ifc.ifc_buf;
907     ifend = (struct ifreq *)(ifc.ifc_buf + ifc.ifc_len);
908     /*
909      * Loop through all of the interfaces.
910      */
911     for (; ifrp < ifend && !found; ifrp = (struct ifreq *)((char *)ifrp + n)) {
912 #if BSD >= 199006
913         n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
914         if (n < sizeof(*ifrp))
915             n = sizeof(*ifrp);
916 #else
917         n = sizeof(*ifrp);
918 #endif
919         /*
920          * Ignore any interface for an address family other than IP.
921          */
922         if (ifrp->ifr_addr.sa_family != AF_INET)
923             continue;
924
925         if_addr = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
926         if (ioctl(s, SIOCGIFFLAGS, (char *)ifrp) < 0) {
927             fprintf(stderr, "SIOCGIFFLAGS on ");
928             perror(ifrp->ifr_name);
929             continue;
930         }
931         if ((ifrp->ifr_flags & (IFF_MULTICAST|IFF_UP|IFF_LOOPBACK)) !=
932                                 (IFF_MULTICAST|IFF_UP))
933             continue;
934         if (*dst == 0)
935             *dst = if_addr;
936         if (ioctl(s, SIOCGIFNETMASK, (char *)ifrp) >= 0) {
937             if_mask = ((struct sockaddr_in *)&(ifrp->ifr_addr))->sin_addr.s_addr;
938             if (if_mask != 0 && (*dst & if_mask) == (if_addr & if_mask)) {
939                 retval = if_mask;
940                 if (lcl_addr == 0) lcl_addr = if_addr;  /* XXX what about aliases? */
941             }
942         }
943         if (lcl_addr == if_addr) found = TRUE;
944     }
945     if (!found && lcl_addr != 0) {
946         printf("Interface address is not valid\n");
947         exit(1);
948     }
949     return (retval);
950 }
951
952
953 /*
954  * Try to pick a TTL that will get past all the thresholds in the path.
955  */
956 int
957 get_ttl(struct resp_buf *buf)
958 {
959     int rno;
960     struct tr_resp *b;
961     u_int ttl;
962
963     if (buf && (rno = buf->len) > 0) {
964         b = buf->resps + rno - 1;
965         ttl = b->tr_fttl;
966
967         while (--rno > 0) {
968             --b;
969             if (ttl < b->tr_fttl) ttl = b->tr_fttl;
970             else ++ttl;
971         }
972         ttl += MULTICAST_TTL_INC;
973         if (ttl < MULTICAST_TTL1) ttl = MULTICAST_TTL1;
974         if (ttl > MULTICAST_TTL_MAX) ttl = MULTICAST_TTL_MAX;
975         return (ttl);
976     } else return(MULTICAST_TTL1);
977 }
978
979 /*
980  * Calculate the difference between two 32-bit NTP timestamps and return
981  * the result in milliseconds.
982  */
983 int
984 t_diff(u_long a, u_long b)
985 {
986     int d = a - b;
987
988     return ((d * 125) >> 13);
989 }
990
991 /*
992  * Swap bytes for poor little-endian machines that don't byte-swap
993  */
994 u_long
995 byteswap(u_long v)
996 {
997     return ((v << 24) | ((v & 0xff00) << 8) |
998             ((v >> 8) & 0xff00) | (v >> 24));
999 }
1000
1001 #if 0
1002 /*
1003  * XXX incomplete - need private callback data, too?
1004  * XXX since dst doesn't get passed through?
1005  */
1006 int
1007 neighbors_callback(int tmo, u_char *buf, int buflen, struct igmp *igmp,
1008                    int igmplen, struct sockaddr *addr, int *addrlen,
1009                    struct timeval *ts)
1010 {
1011     int len;
1012     u_int32 dst;
1013     struct ip *ip = (struct ip *)buf;
1014
1015     if (tmo)
1016         return 0;
1017
1018     if (igmp->igmp_code != DVMRP_NEIGHBORS2)
1019         return 0;
1020     len = igmplen;
1021     /*
1022      * Accept DVMRP_NEIGHBORS2 response if it comes from the
1023      * address queried or if that address is one of the local
1024      * addresses in the response.
1025      */
1026     if (ip->ip_src.s_addr != dst) {
1027         u_int32 *p = (u_int32 *)(igmp + 1);
1028         u_int32 *ep = p + (len >> 2);
1029         while (p < ep) {
1030             u_int32 laddr = *p++;
1031             int n = ntohl(*p++) & 0xFF;
1032             if (laddr == dst) {
1033                 ep = p + 1;             /* ensure p < ep after loop */
1034                 break;
1035             }
1036             p += n;
1037         }
1038         if (p >= ep)
1039             return 0;
1040     }
1041     return buflen;
1042 }
1043 #endif
1044
1045 int
1046 mtrace_callback(int tmo, u_char *buf, int buflen, struct igmp *igmp,
1047                 int igmplen, struct sockaddr *addr, int *addrlen,
1048                 struct timeval *ts)
1049 {
1050     static u_char *savbuf = NULL;
1051     static int savbuflen;
1052     static struct sockaddr *savaddr;
1053     static int savaddrlen;
1054     static struct timeval savts;
1055
1056     int len = (igmplen - QLEN) / RLEN;
1057     struct tr_resp *r = (struct tr_resp *)((struct tr_query *)(igmp + 1) + 1);
1058
1059     if (tmo == 1) {
1060         /*
1061          * If we timed out with a packet saved, then return that packet.
1062          * send_recv won't send this same packet to the callback again.
1063          */
1064         if (savbuf) {
1065             bcopy(savbuf, buf, savbuflen);
1066             free(savbuf);
1067             savbuf = NULL;
1068             bcopy(savaddr, addr, savaddrlen);
1069             free(savaddr);
1070             *addrlen = savaddrlen;
1071             bcopy(&savts, ts, sizeof(savts));
1072             return savbuflen;
1073         }
1074         return 0;
1075     }
1076     if (savbuf) {
1077         free(savbuf);
1078         savbuf = NULL;
1079         free(savaddr);
1080     }
1081     /*
1082      * Check for IOS bug described in CSCdi68628, where a router that does
1083      *  not have multicast enabled responds to an mtrace request with a 1-hop
1084      *  error packet.
1085      * Heuristic is:
1086      *  If there is only one hop reported in the packet,
1087      *  And the protocol code is 0,
1088      *  And there is no previous hop,
1089      *  And the forwarding information is "Not Forwarding",
1090      *  And the router is not on the same subnet as the destination of the
1091      *          trace,
1092      *  then drop this packet.  The "#if 0"'d code saves it and returns
1093      *   it on timeout, but timeouts are too common (e.g. routers with
1094      *   limited unicast routing tables, etc).
1095      */
1096     if (len == 1 && r->tr_rproto == 0 && r->tr_rmtaddr == 0 &&
1097                                         r->tr_rflags == TR_NO_FWD) {
1098         u_int32 smask;
1099
1100         VAL_TO_MASK(smask, r->tr_smask);
1101         if ((r->tr_outaddr & smask) != (qdst & smask)) {
1102 #if 0
1103             /* XXX should do this silently? */
1104             fprintf(stderr, "mtrace: probably IOS-buggy packet from %s\n",
1105                 inet_fmt(((struct sockaddr_in *)addr)->sin_addr.s_addr, s1));
1106             /* Save the packet to return if a timeout occurs. */
1107             savbuf = (u_char *)malloc(buflen);
1108             if (savbuf != NULL) {
1109                 bcopy(buf, savbuf, buflen);
1110                 savbuflen = buflen;
1111                 savaddr = (struct sockaddr *)malloc(*addrlen);
1112                 if (savaddr != NULL) {
1113                     bcopy(addr, savaddr, *addrlen);
1114                     savaddrlen = *addrlen;
1115                     bcopy(ts, &savts, sizeof(savts));
1116                 } else {
1117                     free(savbuf);
1118                     savbuf = NULL;
1119                 }
1120             }
1121 #endif
1122             return 0;
1123         }
1124     }
1125     return buflen;
1126 }
1127
1128 int
1129 send_recv(u_int32 dst, int type, int code, int tries, struct resp_buf *save,
1130           callback_t callback)
1131 {
1132     fd_set  fds;
1133     struct timeval tq, tr, tv;
1134     struct ip *ip;
1135     struct igmp *igmp;
1136     struct tr_query *query, *rquery;
1137     struct tr_resp *r;
1138     struct sockaddr_in recvaddr;
1139     u_int32 local, group;
1140     int ipdatalen, iphdrlen, igmpdatalen;
1141     int datalen;
1142     int count, recvlen, socklen = sizeof(recvaddr);
1143     int len;
1144     int i;
1145
1146     if (type == IGMP_MTRACE) {
1147         group = qgrp;
1148         datalen = sizeof(struct tr_query);
1149     } else {
1150         group = htonl(0xff03);
1151         datalen = 0;
1152     }
1153     if (IN_MULTICAST(ntohl(dst))) local = lcl_addr;
1154     else local = INADDR_ANY;
1155
1156     /*
1157      * If the reply address was not explictly specified, start off
1158      * with the standard multicast reply address, or the unicast
1159      * address of this host if the unicast flag was specified.
1160      * Then, if there is no response after trying half the tries
1161      * with multicast, switch to the unicast address of this host
1162      * if the multicast flag was not specified.  If the TTL was
1163      * also not specified, set a multicast TTL and increase it
1164      * for every try.
1165      */
1166     query = (struct tr_query *)(send_buf + MIN_IP_HEADER_LEN + IGMP_MINLEN);
1167     query->tr_raddr = raddr ? raddr : unicast ? lcl_addr : resp_cast;
1168     TR_SETTTL(query->tr_rttlqid, rttl ? rttl :
1169       IN_MULTICAST(ntohl(query->tr_raddr)) ? get_ttl(save) : UNICAST_TTL);
1170     query->tr_src   = qsrc;
1171     query->tr_dst   = qdst;
1172
1173     for (i = tries ; i > 0; --i) {
1174         int oqid;
1175
1176         if (tries == nqueries && raddr == 0) {
1177             if (i == (nqueries >> 1)) {
1178                 if (multicast && unicast) {
1179                     query->tr_raddr = resp_cast;
1180                     if (!rttl)
1181                         TR_SETTTL(query->tr_rttlqid, get_ttl(save));
1182                 } else if (!multicast) {
1183                     query->tr_raddr = lcl_addr;
1184                     TR_SETTTL(query->tr_rttlqid, UNICAST_TTL);
1185                 }
1186             }
1187             if (i < tries && IN_MULTICAST(ntohl(query->tr_raddr)) &&
1188                                                                 rttl == 0) {
1189                 TR_SETTTL(query->tr_rttlqid,
1190                         TR_GETTTL(query->tr_rttlqid) + MULTICAST_TTL_INC);
1191                 if (TR_GETTTL(query->tr_rttlqid) > MULTICAST_TTL_MAX)
1192                   TR_SETTTL(query->tr_rttlqid, MULTICAST_TTL_MAX);
1193             }
1194         }
1195
1196         /*
1197          * Change the qid for each request sent to avoid being confused
1198          * by duplicate responses
1199          */
1200         oqid = TR_GETQID(query->tr_rttlqid);
1201         if (staticqid)
1202             TR_SETQID(query->tr_rttlqid, staticqid);
1203         else
1204 #ifdef SYSV    
1205             TR_SETQID(query->tr_rttlqid, ((u_int32)lrand48() >> 8));
1206 #else
1207             TR_SETQID(query->tr_rttlqid, ((u_int32)arc4random() >> 8));
1208 #endif
1209
1210         /*
1211          * Set timer to calculate delays, then send query
1212          */
1213         gettimeofday(&tq, 0);
1214         send_igmp(local, dst, type, code, group, datalen);
1215
1216         /*
1217          * Wait for response, discarding false alarms
1218          */
1219         while (TRUE) {
1220             if (igmp_socket >= FD_SETSIZE)
1221                     dolog(LOG_ERR, 0, "descriptor too big");
1222             FD_ZERO(&fds);
1223             FD_SET(igmp_socket, &fds);
1224             gettimeofday(&tv, 0);
1225             tv.tv_sec = tq.tv_sec + timeout - tv.tv_sec;
1226             tv.tv_usec = tq.tv_usec - tv.tv_usec;
1227             if (tv.tv_usec < 0) tv.tv_usec += 1000000L, --tv.tv_sec;
1228             if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0;
1229
1230             count = select(igmp_socket + 1, &fds, NULL, NULL, &tv);
1231
1232             if (count < 0) {
1233                 if (errno != EINTR) warn("select");
1234                 continue;
1235             } else if (count == 0) {
1236                 /*
1237                  * Timed out.  Notify the callback.
1238                  */
1239                 if (!callback || (recvlen = (callback)(1, recv_buf, 0, NULL, 0, (struct sockaddr *)&recvaddr, &socklen, &tr)) == 0) {
1240                     printf("* ");
1241                     fflush(stdout);
1242                     break;
1243                 }
1244             } else {
1245                 /*
1246                  * Data is available on the socket, so read it.
1247                  */
1248                 gettimeofday(&tr, 0);
1249                 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1250                                    0, (struct sockaddr *)&recvaddr, &socklen);
1251             }
1252
1253             if (recvlen <= 0) {
1254                 if (recvlen && errno != EINTR) warn("recvfrom");
1255                 continue;
1256             }
1257
1258             if (recvlen < sizeof(struct ip)) {
1259                 warnx("packet too short (%u bytes) for IP header", recvlen);
1260                 continue;
1261             }
1262             ip = (struct ip *) recv_buf;
1263             if (ip->ip_p == 0)  /* ignore cache creation requests */
1264                 continue;
1265
1266             iphdrlen = ip->ip_hl << 2;
1267 #ifdef RAW_INPUT_IS_RAW
1268             ipdatalen = ntohs(ip->ip_len);
1269 #else
1270             ipdatalen = ip->ip_len;
1271 #endif
1272             if (iphdrlen + ipdatalen != recvlen) {
1273                 warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1274                         recvlen, iphdrlen, ipdatalen);
1275                 continue;
1276             }
1277
1278             igmp = (struct igmp *) (recv_buf + iphdrlen);
1279             igmpdatalen = ipdatalen - IGMP_MINLEN;
1280             if (igmpdatalen < 0) {
1281                 warnx("IP data field too short (%u bytes) for IGMP from %s",
1282                         ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1283                 continue;
1284             }
1285
1286             switch (igmp->igmp_type) {
1287
1288               case IGMP_DVMRP:
1289                 if (type != IGMP_DVMRP || code != DVMRP_ASK_NEIGHBORS2)
1290                         continue;
1291                 if (igmp->igmp_code != DVMRP_NEIGHBORS2) continue;
1292                 len = igmpdatalen;
1293                 /*
1294                  * Accept DVMRP_NEIGHBORS2 response if it comes from the
1295                  * address queried or if that address is one of the local
1296                  * addresses in the response.
1297                  */
1298                 if (ip->ip_src.s_addr != dst) {
1299                     u_int32 *p = (u_int32 *)(igmp + 1);
1300                     u_int32 *ep = p + (len >> 2);
1301                     while (p < ep) {
1302                         u_int32 laddr = *p++;
1303                         int n = ntohl(*p++) & 0xFF;
1304                         if (laddr == dst) {
1305                             ep = p + 1;         /* ensure p < ep after loop */
1306                             break;
1307                         }
1308                         p += n;
1309                     }
1310                     if (p >= ep) continue;
1311                 }
1312                 break;
1313
1314               case IGMP_MTRACE:     /* For backward compatibility with 3.3 */
1315               case IGMP_MTRACE_RESP:
1316                 if (type != IGMP_MTRACE) continue;
1317                 if (igmpdatalen <= QLEN) continue;
1318                 if ((igmpdatalen - QLEN)%RLEN) {
1319                     printf("packet with incomplete responses (%d bytes)\n",
1320                         igmpdatalen);
1321                     continue;
1322                 }
1323
1324                 /*
1325                  * Ignore responses that don't match query.
1326                  */
1327                 rquery = (struct tr_query *)(igmp + 1);
1328                 if (rquery->tr_src != qsrc || rquery->tr_dst != qdst)
1329                     continue;
1330                 if (TR_GETQID(rquery->tr_rttlqid) !=
1331                         TR_GETQID(query->tr_rttlqid)) {
1332                     if (verbose && TR_GETQID(rquery->tr_rttlqid) == oqid)
1333                         printf("[D]");
1334                     continue;
1335                 }
1336                 len = (igmpdatalen - QLEN)/RLEN;
1337                 r = (struct tr_resp *)(rquery+1) + len - 1;
1338
1339                 /*
1340                  * Ignore trace queries passing through this node when
1341                  * mtrace is run on an mrouter that is in the path
1342                  * (needed only because IGMP_MTRACE is accepted above
1343                  * for backward compatibility with multicast release 3.3).
1344                  */
1345                 if (igmp->igmp_type == IGMP_MTRACE) {
1346                     u_int32 smask;
1347
1348                     VAL_TO_MASK(smask, r->tr_smask);
1349                     if (len < code && (r->tr_inaddr & smask) != (qsrc & smask)
1350                         && r->tr_rmtaddr != 0 && !(r->tr_rflags & 0x80))
1351                       continue;
1352                 }
1353                 /*
1354                  * Some routers will return error messages without
1355                  * filling in their addresses.  We fill in the address
1356                  * for them.
1357                  */
1358                 if (r->tr_outaddr == 0)
1359                     r->tr_outaddr = recvaddr.sin_addr.s_addr;
1360
1361                 /*
1362                  * A match, we'll keep this one.
1363                  */
1364                 if (len > code) {
1365                     warnx("num hops received (%d) exceeds request (%d)",
1366                             len, code);
1367                 }
1368                 rquery->tr_raddr = query->tr_raddr;     /* Insure these are */
1369                 TR_SETTTL(rquery->tr_rttlqid, TR_GETTTL(query->tr_rttlqid));
1370                                                         /* as we sent them */
1371                 break;
1372
1373               default:
1374                 continue;
1375             }
1376
1377             /*
1378              * We're pretty sure we want to use this packet now,
1379              * but if the caller gave a callback function, it might
1380              * want to handle it instead.  Give the callback a chance,
1381              * unless the select timed out (in which case the only way
1382              * to get here is because the callback returned a packet).
1383              */
1384             if (callback && (count != 0) && ((callback)(0, recv_buf, recvlen, igmp, igmpdatalen, (struct sockaddr*)&recvaddr, &socklen, &tr)) == 0) {
1385                 /*
1386                  * The callback function didn't like this packet.
1387                  * Go try receiving another one.
1388                  */
1389                 continue;
1390             }
1391
1392             /*
1393              * Most of the sanity checking done at this point.
1394              * Return this packet we have been waiting for.
1395              */
1396             if (save) {
1397                 save->qtime = ((tq.tv_sec + JAN_1970) << 16) +
1398                               (tq.tv_usec << 10) / 15625;
1399                 save->rtime = ((tr.tv_sec + JAN_1970) << 16) +
1400                               (tr.tv_usec << 10) / 15625;
1401                 save->len = len;
1402                 bcopy((char *)igmp, (char *)&save->igmp, ipdatalen);
1403             }
1404             return (recvlen);
1405         }
1406     }
1407     return (0);
1408 }
1409
1410 /*
1411  * Most of this code is duplicated elsewhere.  I'm not sure if
1412  * the duplication is absolutely required or not.
1413  *
1414  * Ideally, this would keep track of ongoing statistics
1415  * collection and print out statistics.  (& keep track
1416  * of h-b-h traces and only print the longest)  For now,
1417  * it just snoops on what traces it can.
1418  */
1419 void
1420 passive_mode(void)
1421 {
1422     struct timeval tr;
1423     time_t tr_sec;
1424     struct ip *ip;
1425     struct igmp *igmp;
1426     struct tr_resp *r;
1427     struct sockaddr_in recvaddr;
1428     struct tm *now;
1429     char timebuf[32];
1430     int socklen;
1431     int ipdatalen, iphdrlen, igmpdatalen;
1432     int len, recvlen;
1433     int qid;
1434     u_int32 smask;
1435     struct mtrace *remembered = NULL, *m, *n, **nn;
1436     int pc = 0;
1437
1438     if (raddr) {
1439         if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
1440     } else k_join(htonl(0xE0000120), lcl_addr);
1441
1442     while (1) {
1443         fflush(stdout);         /* make sure previous trace is flushed */
1444
1445         socklen = sizeof(recvaddr);
1446         recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
1447                            0, (struct sockaddr *)&recvaddr, &socklen);
1448         gettimeofday(&tr,0);
1449
1450         if (recvlen <= 0) {
1451             if (recvlen && errno != EINTR) warn("recvfrom");
1452             continue;
1453         }
1454
1455         if (recvlen < sizeof(struct ip)) {
1456             warnx("packet too short (%u bytes) for IP header", recvlen);
1457             continue;
1458         }
1459         ip = (struct ip *) recv_buf;
1460         if (ip->ip_p == 0)      /* ignore cache creation requests */
1461             continue;
1462
1463         iphdrlen = ip->ip_hl << 2;
1464 #ifdef RAW_INPUT_IS_RAW
1465         ipdatalen = ntohs(ip->ip_len);
1466 #else
1467         ipdatalen = ip->ip_len;
1468 #endif
1469         if (iphdrlen + ipdatalen != recvlen) {
1470             warnx("packet shorter (%u bytes) than hdr+data len (%u+%u)",
1471                     recvlen, iphdrlen, ipdatalen);
1472             continue;
1473         }
1474
1475         igmp = (struct igmp *) (recv_buf + iphdrlen);
1476         igmpdatalen = ipdatalen - IGMP_MINLEN;
1477         if (igmpdatalen < 0) {
1478             warnx("IP data field too short (%u bytes) for IGMP from %s",
1479                     ipdatalen, inet_fmt(ip->ip_src.s_addr, s1));
1480             continue;
1481         }
1482
1483         switch (igmp->igmp_type) {
1484
1485           case IGMP_MTRACE:         /* For backward compatibility with 3.3 */
1486           case IGMP_MTRACE_RESP:
1487             if (igmpdatalen < QLEN) continue;
1488             if ((igmpdatalen - QLEN)%RLEN) {
1489                 printf("packet with incorrect datalen\n");
1490                 continue;
1491             }
1492
1493             len = (igmpdatalen - QLEN)/RLEN;
1494
1495             break;
1496
1497           default:
1498             continue;
1499         }
1500
1501         base.qtime = ((tr.tv_sec + JAN_1970) << 16) +
1502                       (tr.tv_usec << 10) / 15625;
1503         base.rtime = ((tr.tv_sec + JAN_1970) << 16) +
1504                       (tr.tv_usec << 10) / 15625;
1505         base.len = len;
1506         bcopy((char *)igmp, (char *)&base.igmp, ipdatalen);
1507         /*
1508          * If the user specified which traces to monitor,
1509          * only accept traces that correspond to the
1510          * request
1511          */
1512         if ((qsrc != 0 && qsrc != base.qhdr.tr_src) ||
1513             (qdst != 0 && qdst != base.qhdr.tr_dst) ||
1514             (qgrp != 0 && qgrp != igmp->igmp_group.s_addr))
1515             continue;
1516
1517         /* XXX This should be a hash table */
1518         /* XXX garbage-collection should be more efficient */
1519         for (nn = &remembered, n = *nn, m = NULL; n; n = *nn) {
1520             if ((n->base.qhdr.tr_src == base.qhdr.tr_src) &&
1521                 (n->base.qhdr.tr_dst == base.qhdr.tr_dst) &&
1522                 (n->base.igmp.igmp_group.s_addr == igmp->igmp_group.s_addr)) {
1523                 m = n;
1524                 m->last = tr;
1525             }
1526             if (tr.tv_sec - n->last.tv_sec > 500) { /* XXX don't hardcode */
1527                 *nn = n->next;
1528                 free(n);
1529             } else {
1530                 nn = &n->next;
1531             }
1532         }
1533
1534         tr_sec = tr.tv_sec;
1535         now = localtime(&tr_sec);
1536         strftime(timebuf, sizeof(timebuf) - 1, "%b %e %k:%M:%S", now);
1537         printf("Mtrace %s at %s",
1538                 len == 0 ? "query" :
1539                            igmp->igmp_type == IGMP_MTRACE_RESP ? "response" :
1540                                                                  "in transit",
1541                 timebuf);
1542         if (len == 0)
1543                 printf(" by %s", inet_fmt(recvaddr.sin_addr.s_addr, s1));
1544         if (!IN_MULTICAST(base.qhdr.tr_raddr))
1545                 printf(", resp to %s", (len == 0 && recvaddr.sin_addr.s_addr == base.qhdr.tr_raddr) ? "same" : inet_fmt(base.qhdr.tr_raddr, s1));
1546         else
1547                 printf(", respttl %d", TR_GETTTL(base.qhdr.tr_rttlqid));
1548         printf(", qid %06x\n", qid = TR_GETQID(base.qhdr.tr_rttlqid));
1549         printf("packet from %s to %s\n",
1550                 inet_fmt(ip->ip_src.s_addr, s1),
1551                 inet_fmt(ip->ip_dst.s_addr, s2));
1552
1553         printf("from %s to %s via group %s (mxhop=%d)\n",
1554                 inet_fmt(base.qhdr.tr_dst, s1), inet_fmt(base.qhdr.tr_src, s2),
1555                 inet_fmt(igmp->igmp_group.s_addr, s3), igmp->igmp_code);
1556         if (len == 0) {
1557             printf("\n");
1558             continue;
1559         }
1560         r = base.resps + base.len - 1;
1561         /*
1562          * Some routers will return error messages without
1563          * filling in their addresses.  We fill in the address
1564          * for them.
1565          */
1566         if (r->tr_outaddr == 0)
1567             r->tr_outaddr = recvaddr.sin_addr.s_addr;
1568
1569         /*
1570          * If there was a previous trace, it see if this is a
1571          * statistics candidate.
1572          */
1573         if (m && base.len == m->base.len &&
1574                 !(pc = path_changed(&m->base, &base))) {
1575             /*
1576              * Some mtrace responders send multiple copies of the same
1577              * reply.  Skip this packet if it's got the same query-id
1578              * as the last one.
1579              */
1580             if (m->lastqid == qid) {
1581                 printf("Skipping duplicate reply\n");
1582                 continue;
1583             }
1584
1585             m->lastqid = qid;
1586
1587             ++m->nresp;
1588
1589             bcopy(&base, m->new, sizeof(base));
1590
1591             printf("Results after %d seconds:\n\n",
1592                    (int)((m->new->qtime - m->base.qtime) >> 16));
1593             fixup_stats(&m->base, m->prev, m->new, m->bugs);
1594             print_stats(&m->base, m->prev, m->new, m->bugs, m->names);
1595             m->prev = m->new;
1596             m->new = &m->incr[(m->nresp & 1)];
1597
1598             continue;
1599         }
1600
1601         if (m == NULL) {
1602             m = (struct mtrace *)malloc(sizeof(struct mtrace));
1603             if (m == NULL) {
1604                 fprintf(stderr, "Out of memory!\n");
1605                 continue;
1606             }
1607             bzero(m, sizeof(struct mtrace));
1608             m->next = remembered;
1609             remembered = m;
1610             bcopy(&tr, &m->last, sizeof(tr));
1611         }
1612
1613         /* Either it's a hop-by-hop in progress, or the path changed. */
1614         if (pc) {
1615             printf("[Path Changed...]\n");
1616             bzero(m->bugs, sizeof(m->bugs));
1617         }
1618         bcopy(&base, &m->base, sizeof(base));
1619         m->prev = &m->base;
1620         m->new = &m->incr[0];
1621         m->nresp = 0;
1622
1623         printf("  0  ");
1624         print_host(base.qhdr.tr_dst);
1625         printf("\n");
1626         print_trace(1, &base, m->names);
1627         VAL_TO_MASK(smask, r->tr_smask);
1628         if ((r->tr_inaddr & smask) == (base.qhdr.tr_src & smask)) {
1629             printf("%3d  ", -(base.len+1));
1630             print_host(base.qhdr.tr_src);
1631             printf("\n");
1632         } else if (r->tr_rmtaddr != 0) {
1633             printf("%3d  ", -(base.len+1));
1634             print_host(r->tr_rmtaddr);
1635             printf(" %s\n", r->tr_rflags == TR_OLD_ROUTER ?
1636                                    "doesn't support mtrace"
1637                                  : "is the next hop");
1638         }
1639         printf("\n");
1640     }
1641 }
1642
1643 char *
1644 print_host(u_int32 addr)
1645 {
1646     return print_host2(addr, 0);
1647 }
1648
1649 /*
1650  * On some routers, one interface has a name and the other doesn't.
1651  * We always print the address of the outgoing interface, but can
1652  * sometimes get the name from the incoming interface.  This might be
1653  * confusing but should be slightly more helpful than just a "?".
1654  */
1655 char *
1656 print_host2(u_int32 addr1, u_int32 addr2)
1657 {
1658     char *name;
1659
1660     if (numeric) {
1661         printf("%s", inet_fmt(addr1, s1));
1662         return ("");
1663     }
1664     name = inet_name(addr1);
1665     if (*name == '?' && *(name + 1) == '\0' && addr2 != 0)
1666         name = inet_name(addr2);
1667     printf("%s (%s)", name, inet_fmt(addr1, s1));
1668     return (name);
1669 }
1670
1671 /*
1672  * Print responses as received (reverse path from dst to src)
1673  */
1674 void
1675 print_trace(int idx, struct resp_buf *buf, char **names)
1676 {
1677     struct tr_resp *r;
1678     char *name;
1679     int i;
1680     int hop;
1681     char *ms;
1682
1683     i = abs(idx);
1684     r = buf->resps + i - 1;
1685
1686     for (; i <= buf->len; ++i, ++r) {
1687         if (idx > 0) printf("%3d  ", -i);
1688         name = print_host2(r->tr_outaddr, r->tr_inaddr);
1689         if (r->tr_rflags != TR_NO_RTE)
1690             printf("  %s  thresh^ %d", proto_type(r->tr_rproto), r->tr_fttl);
1691         if (verbose) {
1692             hop = t_diff(ntohl(r->tr_qarr), buf->qtime);
1693             ms = scale(&hop);
1694             printf("  %d%s", hop, ms);
1695         }
1696         printf("  %s", flag_type(r->tr_rflags));
1697         if (i > 1 && r->tr_outaddr != (r-1)->tr_rmtaddr) {
1698             printf(" !RPF!");
1699             print_host((r-1)->tr_rmtaddr);
1700         }
1701         if (r->tr_rflags != TR_NO_RTE) {
1702             if (r->tr_smask <= 1)    /* MASK_TO_VAL() returns 1 for default */
1703                 printf(" [default]");
1704             else if (verbose) {
1705                 u_int32 smask;
1706
1707                 VAL_TO_MASK(smask, r->tr_smask);
1708                 printf(" [%s]", inet_fmts(buf->qhdr.tr_src & smask,
1709                                                         smask, s1));
1710             }
1711         }
1712         printf("\n");
1713         if (names[i-1])
1714             free(names[i-1]);
1715         names[i-1]=malloc(strlen(name) + 1);
1716         strcpy(names[i-1], name);
1717     }
1718 }
1719
1720 /*
1721  * See what kind of router is the next hop
1722  */
1723 int
1724 what_kind(struct resp_buf *buf, char *why)
1725 {
1726     u_int32 smask;
1727     int retval;
1728     int hops = buf->len;
1729     struct tr_resp *r = buf->resps + hops - 1;
1730     u_int32 next = r->tr_rmtaddr;
1731
1732     retval = send_recv(next, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL);
1733     print_host(next);
1734     if (retval) {
1735         u_int32 version = ntohl(incr[0].igmp.igmp_group.s_addr);
1736         u_int32 *p = (u_int32 *)incr[0].ndata;
1737         u_int32 *ep = p + (incr[0].len >> 2);
1738         char *type = "version ";
1739
1740         retval = 0;
1741         switch (version & 0xFF) {
1742           case 1:
1743             type = "proteon/mrouted ";
1744             retval = 1;
1745             break;
1746
1747           case 10:
1748           case 11:
1749             type = "cisco ";
1750         }
1751         printf(" [%s%d.%d] %s\n",
1752                type, version & 0xFF, (version >> 8) & 0xFF,
1753                why);
1754         VAL_TO_MASK(smask, r->tr_smask);
1755         while (p < ep) {
1756             u_int32 laddr = *p++;
1757             int flags = (ntohl(*p) & 0xFF00) >> 8;
1758             int n = ntohl(*p++) & 0xFF;
1759             if (!(flags & (DVMRP_NF_DOWN | DVMRP_NF_DISABLED)) &&
1760                  (laddr & smask) == (qsrc & smask)) {
1761                 printf("%3d  ", -(hops+2));
1762                 print_host(qsrc);
1763                 printf("\n");
1764                 return 1;
1765             }
1766             p += n;
1767         }
1768         return retval;
1769     }
1770     printf(" %s\n", why);
1771     return 0;
1772 }
1773
1774
1775 char *
1776 scale(int *hop)
1777 {
1778     if (*hop > -1000 && *hop < 10000) 
1779             return (" ms");
1780     *hop /= 1000;
1781     if (*hop > -1000 && *hop < 10000) 
1782             return (" s ");
1783     return ("s ");
1784 }
1785
1786 /*
1787  * Calculate and print one line of packet loss and packet rate statistics.
1788  * Checks for count of all ones from mrouted 2.3 that doesn't have counters.
1789  */
1790 #define NEITHER 0
1791 #define INS     1
1792 #define OUTS    2
1793 #define BOTH    3
1794 void
1795 stat_line(struct tr_resp *r, struct tr_resp *s, int have_next, int *rst)
1796 {
1797     int timediff = (ntohl(s->tr_qarr) - ntohl(r->tr_qarr)) >> 16;
1798     int v_lost, v_pct;
1799     int g_lost, g_pct;
1800     int v_out = ntohl(s->tr_vifout) - ntohl(r->tr_vifout);
1801     int g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1802     int v_pps, g_pps;
1803     char v_str[8], g_str[8];
1804     int vhave = NEITHER;
1805     int ghave = NEITHER;
1806     int gmissing = NEITHER;
1807     char whochar;
1808     int badtime = 0;
1809
1810     if (timediff == 0) {
1811         badtime = 1;
1812         /* Might be 32 bits of int seconds instead of 16int+16frac */
1813         timediff = ntohl(s->tr_qarr) - ntohl(r->tr_qarr);
1814         if (timediff == 0 || abs(timediff - statint) > statint)
1815             timediff = 1;
1816     }
1817     v_pps = v_out / timediff;
1818     g_pps = g_out / timediff;
1819
1820 #define STATS_MISSING(x)        ((x) == 0xFFFFFFFF)
1821
1822     if (!STATS_MISSING(s->tr_vifout) && !STATS_MISSING(r->tr_vifout))
1823             vhave |= OUTS;
1824     if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1825             gmissing |= OUTS;
1826     if (!(*rst & BUG_NOPRINT))
1827             ghave |= OUTS;
1828
1829     if (have_next) {
1830         --r,  --s,  --rst;
1831         if (!STATS_MISSING(s->tr_vifin) && !STATS_MISSING(r->tr_vifin))
1832             vhave |= INS;
1833         if (STATS_MISSING(s->tr_pktcnt) || STATS_MISSING(r->tr_pktcnt))
1834             gmissing |= INS;
1835         if (!(*rst & BUG_NOPRINT))
1836             ghave |= INS;
1837     }
1838
1839     /*
1840      * Stats can be missing for any number of reasons:
1841      * - The hop may not be capable of collecting stats
1842      * - Traffic may be getting dropped at the previous hop
1843      *   and so this hop may not have any state
1844      *
1845      * We need a stronger heuristic to tell between these
1846      * two cases; in case 1 we don't want to print the stats
1847      * and in case 2 we want to print 100% loss.  We used to
1848      * err on the side of not printing, which is less useful
1849      * than printing 100% loss and dealing with it.
1850      */
1851 #if 0
1852     /*
1853      * If both hops report as missing, then it's likely that there's just
1854      * no traffic flowing.
1855      *
1856      * If just one hop is missing, then we really don't have it.
1857      */
1858     if (gmissing != BOTH)
1859         ghave &= ~gmissing;
1860 #endif
1861
1862     whochar = have_next ? '^' : ' ';
1863     switch (vhave) {
1864       case BOTH:
1865         v_lost = v_out - (ntohl(s->tr_vifin) - ntohl(r->tr_vifin));
1866         if (v_out) v_pct = v_lost * 100 / v_out;
1867         else v_pct = 0;
1868         if (-20 < v_pct && v_pct < 101 && v_out > 10)
1869           sprintf(v_str, "%3d%%", v_pct);
1870         else if (v_pct < -900 && v_out > 10)
1871           sprintf(v_str, "%3dx", (int)(-v_pct / 100. + 1.));
1872         else if (v_pct <= -20 && v_out > 10)
1873           sprintf(v_str, "%1.1fx", -v_pct / 100. + 1.);
1874         else
1875           memcpy(v_str, " -- ", 5);
1876
1877         if (tunstats)
1878             printf("%6d/%-5d=%s", v_lost, v_out, v_str);
1879         else
1880             printf("   ");
1881         printf("%4d pps", v_pps);
1882         if (v_pps && badtime)
1883             printf("?");
1884
1885         break;
1886
1887       case INS:
1888         v_out = ntohl(s->tr_vifin) - ntohl(r->tr_vifin);
1889         v_pps = v_out / timediff;
1890         whochar = 'v';
1891         /* FALLTHROUGH */
1892
1893       case OUTS:
1894         if (tunstats)
1895             printf("      %c%-5d     ", whochar, v_out);
1896         else
1897             printf("  %c", whochar);
1898         printf("%4d pps", v_pps);
1899         if (v_pps && badtime)
1900             printf("?");
1901
1902         break;
1903
1904       case NEITHER:
1905         if (ghave != NEITHER)
1906             if (tunstats)
1907                 printf("                         ");
1908             else
1909                 printf("           ");
1910
1911         break;
1912     }
1913
1914     whochar = have_next ? '^' : ' ';
1915     switch (ghave) {
1916       case BOTH:
1917         g_lost = g_out - (ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt));
1918         if (g_out) g_pct = g_lost * 100 / g_out;
1919         else g_pct = 0;
1920         if (-20 < g_pct && g_pct < 101 && g_out > 10)
1921           sprintf(g_str, "%3d%%", g_pct);
1922         else if (g_pct < -900 && g_out > 10)
1923           sprintf(g_str, "%3dx", (int)(-g_pct / 100. + 1.));
1924         else if (g_pct <= -20 && g_out > 10)
1925           sprintf(g_str, "%1.1fx", -g_pct / 100. + 1.);
1926         else
1927           memcpy(g_str, " -- ", 5);
1928
1929         printf("%s%6d/%-5d=%s%4d pps",
1930                tunstats ? "" : "   ", g_lost, g_out, g_str, g_pps);
1931         if (g_pps && badtime)
1932             printf("?");
1933         printf("\n");
1934         break;
1935
1936 #if 0
1937       case INS:
1938         g_out = ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt);
1939         g_pps = g_out / timediff;
1940         whochar = 'v';
1941         /* FALLTHROUGH */
1942 #endif
1943
1944       case OUTS:
1945         printf("%s     ?/%-5d     %4d pps",
1946                tunstats ? "" : "   ", g_out, g_pps);
1947         if (badtime)
1948             printf("?");
1949         printf("\n");
1950         break;
1951
1952       case INS:
1953       case NEITHER:
1954         printf("\n");
1955         break;
1956     }
1957
1958
1959     if (debug > 2) {
1960         printf("\t\t\t\tv_in: %ld ", (long)ntohl(s->tr_vifin));
1961         printf("v_out: %ld ", (long)ntohl(s->tr_vifout));
1962         printf("pkts: %ld\n", (long)ntohl(s->tr_pktcnt));
1963         printf("\t\t\t\tv_in: %ld ", (long)ntohl(r->tr_vifin));
1964         printf("v_out: %ld ", (long)ntohl(r->tr_vifout));
1965         printf("pkts: %ld\n", (long)ntohl(r->tr_pktcnt));
1966         printf("\t\t\t\tv_in: %ld ",
1967             (long)(ntohl(s->tr_vifin) - ntohl(r->tr_vifin)));
1968         printf("v_out: %ld ",
1969             (long)(ntohl(s->tr_vifout) - ntohl(r->tr_vifout)));
1970         printf("pkts: %ld ", (long)(ntohl(s->tr_pktcnt) - ntohl(r->tr_pktcnt)));
1971         printf("time: %d\n", timediff);
1972         printf("\t\t\t\treset: %x hoptime: %lx\n", *rst, ntohl(s->tr_qarr));
1973     }
1974 }
1975
1976 /*
1977  * A fixup to check if any pktcnt has been reset, and to fix the
1978  * byteorder bugs in mrouted 3.6 on little-endian machines.
1979  *
1980  * XXX Since periodic traffic sources are likely to have their
1981  *     pktcnt periodically reset, should we save old values when
1982  *     the reset occurs to keep slightly better statistics over
1983  *     the long term?  (e.g. SAP)
1984  */
1985 void
1986 fixup_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new,
1987             int *bugs)
1988 {
1989     int rno = base->len;
1990     struct tr_resp *b = base->resps + rno;
1991     struct tr_resp *p = prev->resps + rno;
1992     struct tr_resp *n = new->resps + rno;
1993     int *r = bugs + rno;
1994     int res;
1995     int cleanup = 0;
1996
1997     /* Check for byte-swappers.  Only check on the first trace,
1998      * since long-running traces can wrap around and falsely trigger. */
1999     while (--rno >= 0) {
2000 #ifdef TEST_ONLY
2001         u_int32 nvifout = ntohl(n->tr_vifout);
2002         u_int32 pvifout = ntohl(p->tr_vifout);
2003 #endif
2004         --n; --p; --b;
2005 #ifdef TEST_ONLY        /*XXX this is still buggy, so disable it for release */
2006         if ((*r & BUG_SWAP) ||
2007             ((base == prev) &&
2008              (nvifout - pvifout) > (byteswap(nvifout) - byteswap(pvifout)))) {
2009             if (1 || debug > 2) {
2010                 printf("ip %s swaps; b %08x p %08x n %08x\n",
2011                         inet_fmt(n->tr_inaddr, s1),
2012                         ntohl(b->tr_vifout), pvifout, nvifout);
2013             }
2014             /* This host sends byteswapped reports; swap 'em */
2015             if (!(*r & BUG_SWAP)) {
2016                 *r |= BUG_SWAP;
2017                 b->tr_qarr = byteswap(b->tr_qarr);
2018                 b->tr_vifin = byteswap(b->tr_vifin);
2019                 b->tr_vifout = byteswap(b->tr_vifout);
2020                 b->tr_pktcnt = byteswap(b->tr_pktcnt);
2021             }
2022
2023             n->tr_qarr = byteswap(n->tr_qarr);
2024             n->tr_vifin = byteswap(n->tr_vifin);
2025             n->tr_vifout = byteswap(n->tr_vifout);
2026             n->tr_pktcnt = byteswap(n->tr_pktcnt);
2027         }
2028 #endif
2029         /*
2030          * A missing parenthesis in mrouted 3.5-3.8's prune.c
2031          * causes extremely bogus time diff's.
2032          * One half of the time calculation was
2033          * inside an htonl() and one half wasn't.  Therefore, on
2034          * a little-endian machine, both halves of the calculation
2035          * would get added together in the little end.  Thus, the
2036          * low-order 2 bytes are either 0000 (no overflow) or
2037          * 0100 (overflow from the addition).
2038          *
2039          * Odds are against these particular bit patterns
2040          * happening in both prev and new for actual time values.
2041          */
2042         if ((*r & BUG_BOGUSTIME) || (((ntohl(n->tr_qarr) & 0xfeff) == 0x0000) &&
2043             ((ntohl(p->tr_qarr) & 0xfeff) == 0x0000))) {
2044             *r |= BUG_BOGUSTIME;
2045             n->tr_qarr = new->rtime;
2046             p->tr_qarr = prev->rtime;
2047             b->tr_qarr = base->rtime;
2048         }
2049     }
2050
2051     rno = base->len;
2052     b = base->resps + rno;
2053     p = prev->resps + rno;
2054     n = new->resps + rno;
2055     r = bugs + rno;
2056
2057     while (--rno >= 0) {
2058         --n; --p; --b; --r;
2059         /*
2060          * This hop has reset if:
2061          * - There were statistics in the base AND previous pass, AND
2062          *   - There are less packets this time than the first time and
2063          *     we didn't reset last time, OR
2064          *   - There are less packets this time than last time, OR
2065          *   - There are no statistics on this pass.
2066          *
2067          * The "and we didn't reset last time" is necessary in the
2068          * first branch of the OR because if the base is large and
2069          * we reset last time but the constant-resetter-avoidance
2070          * code kicked in so we delayed the copy of prev to base,
2071          * new could still be below base so we trigger the
2072          * constant-resetter code even though it was really only
2073          * a single reset.
2074          */
2075         res = ((b->tr_pktcnt != 0xFFFFFFFF) && (p->tr_pktcnt != 0xFFFFFFFF) &&
2076                ((!(*r & BUG_RESET) && ntohl(n->tr_pktcnt) < ntohl(b->tr_pktcnt)) ||
2077                 (ntohl(n->tr_pktcnt) < ntohl(p->tr_pktcnt)) ||
2078                 (n->tr_pktcnt == 0xFFFFFFFF)));
2079         if (debug > 2) {
2080             printf("\t\tip=%s, r=%d, res=%d\n", inet_fmt(b->tr_inaddr, s1), *r, res);
2081             if (res)
2082                 printf("\t\tbase=%ld, prev=%ld, new=%ld\n", ntohl(b->tr_pktcnt),
2083                             ntohl(p->tr_pktcnt), ntohl(n->tr_pktcnt));
2084         }
2085         if (*r & BUG_RESET) {
2086             if (res || (*r & BUG_RESET2X)) {
2087                 /*
2088                  * This router appears to be a 3.4 with that nasty ol'
2089                  * neighbor version bug, which causes it to constantly
2090                  * reset.  Just nuke the statistics for this node, and
2091                  * don't even bother giving it the benefit of the
2092                  * doubt from now on.
2093                  */
2094                 p->tr_pktcnt = b->tr_pktcnt = n->tr_pktcnt;
2095                 *r |= BUG_RESET2X;
2096             } else {
2097                 /*
2098                  * This is simply the situation that the original
2099                  * fixup_stats was meant to deal with -- that a
2100                  * 3.3 or 3.4 router deleted a cache entry while
2101                  * traffic was still active.
2102                  */
2103                 *r &= ~BUG_RESET;
2104                 cleanup = 1;
2105             }
2106         } else
2107             if (res)
2108                 *r |= BUG_RESET;
2109     }
2110
2111     if (cleanup == 0) return;
2112
2113     /*
2114      * If some hop reset its counters and didn't continue to
2115      * reset, then we pretend that the previous
2116      * trace was the first one.
2117      */
2118     rno = base->len;
2119     b = base->resps + rno;
2120     p = prev->resps + rno;
2121
2122     while (--rno >= 0) (--b)->tr_pktcnt = (--p)->tr_pktcnt;
2123     base->qtime = prev->qtime;
2124     base->rtime = prev->rtime;
2125 }
2126
2127 /*
2128  * Check per-source losses along path and compare with threshold.
2129  */
2130 int
2131 check_thresh(int thresh, struct resp_buf *base, struct resp_buf *prev,
2132              struct resp_buf *new)
2133 {
2134     int rno = base->len - 1;
2135     struct tr_resp *b = base->resps + rno;
2136     struct tr_resp *p = prev->resps + rno;
2137     struct tr_resp *n = new->resps + rno;
2138     int g_out, g_lost;
2139
2140     while (TRUE) {
2141         if ((n->tr_inaddr != b->tr_inaddr) ||
2142             (n->tr_outaddr != b->tr_outaddr) ||
2143             (n->tr_rmtaddr != b->tr_rmtaddr))
2144           return 1;             /* Route changed */
2145
2146         if (rno-- < 1) break;
2147         g_out = ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt);
2148         b--; n--; p--;
2149         g_lost = g_out - (ntohl(n->tr_pktcnt) - ntohl(p->tr_pktcnt));
2150         if (g_out && ((g_lost * 100 + (g_out >> 1))/ g_out) > thresh) {
2151             return TRUE;
2152         }
2153     }
2154     return FALSE;
2155 }
2156
2157 /*
2158  * Print responses with statistics for forward path (from src to dst)
2159  */
2160 int
2161 print_stats(struct resp_buf *base, struct resp_buf *prev, struct resp_buf *new,
2162             int *bugs, char **names)
2163 {
2164     int rtt, hop;
2165     char *ms;
2166     u_int32 smask;
2167     int rno = base->len - 1;
2168     struct tr_resp *b = base->resps + rno;
2169     struct tr_resp *p = prev->resps + rno;
2170     struct tr_resp *n = new->resps + rno;
2171     int *r = bugs + rno;
2172     u_long resptime = new->rtime;
2173     u_long qarrtime = ntohl(n->tr_qarr);
2174     u_int ttl = MaX(1, n->tr_fttl) + 1;
2175     int first = (base == prev);
2176
2177     VAL_TO_MASK(smask, b->tr_smask);
2178     printf("  Source        Response Dest    ");
2179     if (tunstats)
2180         printf("Packet Statistics For     Only For Traffic\n");
2181     else
2182         printf("Overall     Packet Statistics For Traffic From\n");
2183     inet_fmt(base->qhdr.tr_src, s1);
2184     printf("%-15s %-15s  ",
2185            ((b->tr_inaddr & smask) == (base->qhdr.tr_src & smask)) ?
2186                 s1 : "   * * *       ",
2187            inet_fmt(base->qhdr.tr_raddr, s2));
2188     inet_fmt(base->igmp.igmp_group.s_addr, s2);
2189     if (tunstats)
2190         printf("All Multicast Traffic     From %s\n", s1);
2191     else
2192         printf("Packet      %s To %s\n", s1, s2);
2193     rtt = t_diff(resptime, new->qtime);
2194     ms = scale(&rtt);
2195     printf("     %c       __/  rtt%5d%s    ",
2196            (first && !verbose) ? 'v' : '|', rtt, ms);
2197     if (tunstats)
2198         printf("Lost/Sent = Pct  Rate       To %s\n", s2);
2199     else
2200         printf(" Rate       Lost/Sent = Pct  Rate\n");
2201     if (!first || verbose) {
2202         hop = t_diff(resptime, qarrtime);
2203         ms = scale(&hop);
2204         printf("     v      /     hop%5d%s    ", hop, ms);
2205         if (tunstats)
2206             printf("---------------------     --------------------\n");
2207         else
2208             printf("-------     ---------------------\n");
2209     }
2210     if ((b->tr_inaddr & smask) != (base->qhdr.tr_src & smask) &&
2211             b->tr_rmtaddr != 0) {
2212         printf("%-15s %-14s is the previous hop\n", inet_fmt(b->tr_rmtaddr, s1),
2213                 inet_name(b->tr_rmtaddr));
2214         printf("     v     ^\n");
2215     }
2216     if (debug > 2) {
2217         printf("\t\t\t\tv_in: %ld ", (long)ntohl(n->tr_vifin));
2218         printf("v_out: %ld ", (long)ntohl(n->tr_vifout));
2219         printf("pkts: %ld\n", (long)ntohl(n->tr_pktcnt));
2220         printf("\t\t\t\tv_in: %ld ", (long)ntohl(b->tr_vifin));
2221         printf("v_out: %ld ", (long)ntohl(b->tr_vifout));
2222         printf("pkts: %ld\n", (long)ntohl(b->tr_pktcnt));
2223         printf("\t\t\t\tv_in: %ld ",
2224             (long)(ntohl(n->tr_vifin) - ntohl(b->tr_vifin)));
2225         printf("v_out: %ld ",
2226             (long)(ntohl(n->tr_vifout) - ntohl(b->tr_vifout)));
2227         printf("pkts: %ld\n",
2228             (long)(ntohl(n->tr_pktcnt) - ntohl(b->tr_pktcnt)));
2229         printf("\t\t\t\treset: %x hoptime: %lx\n", *r, (long)ntohl(n->tr_qarr));
2230     }
2231
2232     while (TRUE) {
2233         if ((n->tr_inaddr != b->tr_inaddr) ||
2234             (n->tr_outaddr != b->tr_outaddr) ||
2235             (n->tr_rmtaddr != b->tr_rmtaddr))
2236           return 1;             /* Route changed */
2237
2238         if ((n->tr_inaddr != n->tr_outaddr) && n->tr_inaddr)
2239           printf("%-15s\n", inet_fmt(n->tr_inaddr, s1));
2240         printf("%-15s %-14s %s%s\n", inet_fmt(n->tr_outaddr, s1), names[rno],
2241                  flag_type(n->tr_rflags),
2242                  (*r & BUG_NOPRINT) ? " [reset counters]" : "");
2243
2244         if (rno-- < 1) break;
2245
2246         printf("     %c     ^      ttl%5d   ", (first && !verbose) ? 'v' : '|',
2247                                                                 ttl);
2248         stat_line(p, n, TRUE, r);
2249         if (!first || verbose) {
2250             resptime = qarrtime;
2251             qarrtime = ntohl((n-1)->tr_qarr);
2252             hop = t_diff(resptime, qarrtime);
2253             ms = scale(&hop);
2254             printf("     v     |      hop%5d%s", hop, ms);
2255             if (first)
2256                 printf("\n");
2257             else
2258                 stat_line(b, n, TRUE, r);
2259         }
2260
2261         --b, --p, --n, --r;
2262         ttl = MaX(ttl, MaX(1, n->tr_fttl) + base->len - rno);
2263     }
2264            
2265     printf("     %c      \\__   ttl%5d   ", (first && !verbose) ? 'v' : '|',
2266                                                         ttl);
2267     stat_line(p, n, FALSE, r);
2268     if (!first || verbose) {
2269         hop = t_diff(qarrtime, new->qtime);
2270         ms = scale(&hop);
2271         printf("     v         \\  hop%5d%s", hop, ms);
2272         if (first)
2273             printf("\n");
2274         else
2275             stat_line(b, n, FALSE, r);
2276     }
2277     printf("%-15s %s\n", inet_fmt(base->qhdr.tr_dst, s1),
2278                         !passive ? inet_fmt(lcl_addr, s2) : "   * * *       ");
2279     printf("  Receiver      Query Source\n\n");
2280     return 0;
2281 }
2282
2283 /*
2284  * Determine whether or not the path has changed.
2285  */
2286 int
2287 path_changed(struct resp_buf *base, struct resp_buf *new)
2288 {
2289     int rno = base->len - 1;
2290     struct tr_resp *b = base->resps + rno;
2291     struct tr_resp *n = new->resps + rno;
2292
2293     while (rno-- >= 0) {
2294         if ((n->tr_inaddr != b->tr_inaddr) ||
2295             (n->tr_outaddr != b->tr_outaddr) ||
2296             (n->tr_rmtaddr != b->tr_rmtaddr))
2297           return 1;             /* Route changed */
2298         if ((b->tr_rflags == TR_NO_RTE) &&
2299             (n->tr_rflags != TR_NO_RTE))
2300           return 1;             /* Route got longer? */
2301         --n;
2302         --b;
2303     }
2304     return 0;
2305 }
2306
2307
2308 /***************************************************************************
2309  *      main
2310  ***************************************************************************/
2311
2312 int
2313 main(int argc, char **argv)
2314 {
2315     int udp;
2316     struct sockaddr_in addr;
2317     int addrlen = sizeof(addr);
2318     int recvlen;
2319     struct timeval tv;
2320     struct resp_buf *prev, *new;
2321     struct tr_resp *r;
2322     u_int32 smask;
2323     int rno;
2324     int hops, nexthop, tries;
2325     u_int32 lastout = 0;
2326     int numstats = 1;
2327     int waittime;
2328     int seed;
2329     int hopbyhop;
2330     int i;
2331     int printed = 1;
2332
2333     if (geteuid() != 0)
2334         errx(1, "must be root");
2335
2336     /*
2337      * We might get spawned by vat with the audio device open.
2338      * Close everything but stdin, stdout, stderr.
2339      */
2340     for (i = 3; i < 255; i++)
2341         close(i);
2342
2343     init_igmp();
2344     setuid(getuid());
2345
2346     argv++, argc--;
2347     if (argc == 0) usage();
2348
2349     while (argc > 0 && *argv[0] == '-') {
2350         char *p = *argv++;  argc--;
2351         p++;
2352         do {
2353             char c = *p++;
2354             char *arg = NULL;
2355             if (isdigit(*p)) {
2356                 arg = p;
2357                 p = "";
2358             } else if (argc > 0) arg = argv[0];
2359             switch (c) {
2360               case 'd':                 /* Unlisted debug print option */
2361                 if (arg && isdigit(*arg)) {
2362                     debug = atoi(arg);
2363                     if (debug < 0) debug = 0;
2364                     if (debug > 3) debug = 3;
2365                     if (arg == argv[0]) argv++, argc--;
2366                     break;
2367                 } else
2368                     usage();
2369               case 'M':                 /* Use multicast for reponse */
2370                 multicast = TRUE;
2371                 break;
2372               case 'U':                 /* Use unicast for response */
2373                 unicast = TRUE;
2374                 break;
2375               case 'L':                 /* Trace w/ loss threshold */
2376                 if (arg && isdigit(*arg)) {
2377                     lossthresh = atoi(arg);
2378                     if (lossthresh < 0)
2379                         lossthresh = 0;
2380                     numstats = 3153600;
2381                     if (arg == argv[0]) argv++, argc--;
2382                     break;
2383                 } else
2384                     usage();
2385                 break;
2386               case 'O':                 /* Don't use IP options */
2387                 sendopts = FALSE;
2388                 break;
2389               case 'P':                 /* Just watch the path */
2390                 printstats = FALSE;
2391                 numstats = 3153600;
2392                 break;
2393               case 'Q':                 /* (undoc.) always use this QID */
2394                 if (arg && isdigit(*arg)) {
2395                     staticqid = atoi(arg);
2396                     if (staticqid < 0)
2397                         staticqid = 0;
2398                     if (arg == argv[0]) argv++, argc--;
2399                     break;
2400                 } else
2401                     usage();
2402                 break;
2403               case 'T':                 /* Print confusing tunnel stats */
2404                 tunstats = TRUE;
2405                 break;
2406               case 'W':                 /* Cisco's "weak" mtrace */
2407                 weak = TRUE;
2408                 break;
2409               case 'V':                 /* Print version and exit */
2410                 fprintf(stderr, "mtrace version 5.2\n");
2411                 exit(1);
2412                 break;
2413               case 'l':                 /* Loop updating stats indefinitely */
2414                 numstats = 3153600;
2415                 break;
2416               case 'n':                 /* Don't reverse map host addresses */
2417                 numeric = TRUE;
2418                 break;
2419               case 'p':                 /* Passive listen for traces */
2420                 passive = TRUE;
2421                 break;
2422               case 'v':                 /* Verbosity */
2423                 verbose = TRUE;
2424                 break;
2425               case 's':                 /* Short form, don't wait for stats */
2426                 numstats = 0;
2427                 break;
2428               case 'w':                 /* Time to wait for packet arrival */
2429                 if (arg && isdigit(*arg)) {
2430                     timeout = atoi(arg);
2431                     if (timeout < 1) timeout = 1;
2432                     if (arg == argv[0]) argv++, argc--;
2433                     break;
2434                 } else
2435                     usage();
2436               case 'f':                 /* first hop */
2437                 if (arg && isdigit(*arg)) {
2438                     qno = atoi(arg);
2439                     if (qno > MAXHOPS) qno = MAXHOPS;
2440                     else if (qno < 1) qno = 0;
2441                     if (arg == argv[0]) argv++, argc--;
2442                     fflag++;
2443                     break;
2444                 } else
2445                     usage();
2446               case 'm':                 /* Max number of hops to trace */
2447                 if (arg && isdigit(*arg)) {
2448                     qno = atoi(arg);
2449                     if (qno > MAXHOPS) qno = MAXHOPS;
2450                     else if (qno < 1) qno = 0;
2451                     if (arg == argv[0]) argv++, argc--;
2452                     break;
2453                 } else
2454                     usage();
2455               case 'q':                 /* Number of query retries */
2456                 if (arg && isdigit(*arg)) {
2457                     nqueries = atoi(arg);
2458                     if (nqueries < 1) nqueries = 1;
2459                     if (arg == argv[0]) argv++, argc--;
2460                     break;
2461                 } else
2462                     usage();
2463               case 'g':                 /* Last-hop gateway (dest of query) */
2464                 if (arg && (gwy = host_addr(arg))) {
2465                     if (arg == argv[0]) argv++, argc--;
2466                     break;
2467                 } else
2468                     usage();
2469               case 't':                 /* TTL for query packet */
2470                 if (arg && isdigit(*arg)) {
2471                     qttl = atoi(arg);
2472                     if (qttl < 1) qttl = 1;
2473                     rttl = qttl;
2474                     if (arg == argv[0]) argv++, argc--;
2475                     break;
2476                 } else
2477                     usage();
2478               case 'e':                 /* Extra hops past non-responder */
2479                 if (arg && isdigit(*arg)) {
2480                     extrahops = atoi(arg);
2481                     if (extrahops < 0) extrahops = 0;
2482                     if (arg == argv[0]) argv++, argc--;
2483                     break;
2484                 } else
2485                     usage();
2486               case 'r':                 /* Dest for response packet */
2487                 if (arg && (raddr = host_addr(arg))) {
2488                     if (arg == argv[0]) argv++, argc--;
2489                     break;
2490                 } else
2491                     usage();
2492               case 'i':                 /* Local interface address */
2493                 if (arg && (lcl_addr = host_addr(arg))) {
2494                     if (arg == argv[0]) argv++, argc--;
2495                     break;
2496                 } else
2497                     usage();
2498               case 'S':                 /* Stat accumulation interval */
2499                 if (arg && isdigit(*arg)) {
2500                     statint = atoi(arg);
2501                     if (statint < 1) statint = 1;
2502                     if (arg == argv[0]) argv++, argc--;
2503                     break;
2504                 } else
2505                     usage();
2506               default:
2507                 usage();
2508             }
2509         } while (*p);
2510     }
2511
2512     if (argc > 0 && (qsrc = host_addr(argv[0]))) {          /* Source of path */
2513         if (IN_MULTICAST(ntohl(qsrc))) {
2514             if (gwy) {
2515                 /* Should probably rewrite arg parsing at some point, as
2516                  * this makes "mtrace -g foo 224.1.2.3 224.2.3.4" valid!... */
2517                 qgrp = qsrc;
2518                 qsrc = 0;
2519             } else {
2520                 usage();
2521             }
2522         }
2523         argv++, argc--;
2524         if (argc > 0 && (qdst = host_addr(argv[0]))) {      /* Dest of path */
2525             argv++, argc--;
2526             if (argc > 0 && (qgrp = host_addr(argv[0]))) {  /* Path via group */
2527                 argv++, argc--;
2528             }
2529             if (IN_MULTICAST(ntohl(qdst))) {
2530                 u_int32 temp = qdst;
2531                 qdst = qgrp;
2532                 qgrp = temp;
2533                 if (IN_MULTICAST(ntohl(qdst))) usage();
2534             } else if (qgrp && !IN_MULTICAST(ntohl(qgrp))) usage();
2535         }
2536     }
2537
2538     if (passive) {
2539         passive_mode();
2540         return(0);
2541     }
2542
2543     if (argc > 0) {
2544         usage();
2545     }
2546
2547 #ifdef SUNOS5
2548     if (sendopts)
2549         checkforsolarisbug();
2550 #endif
2551
2552     /*
2553      * Set useful defaults for as many parameters as possible.
2554      */
2555
2556     defgrp = 0;                         /* Default to no group */
2557     query_cast = htonl(0xE0000002);     /* All routers multicast addr */
2558     resp_cast = htonl(0xE0000120);      /* Mtrace response multicast addr */
2559     if (qgrp == 0) {
2560         if (!weak)
2561             qgrp = defgrp;
2562         if (printstats && numstats != 0 && !tunstats) {
2563             /* Stats are useless without a group */
2564             warnx(
2565         "WARNING: no multicast group specified, so no statistics printed");
2566             numstats = 0;
2567         }
2568     } else {
2569         if (weak)
2570             warnx(
2571         "WARNING: group was specified so not performing \"weak\" mtrace");
2572     }
2573
2574     /*
2575      * Get default local address for multicasts to use in setting defaults.
2576      */
2577     addr.sin_family = AF_INET;
2578 #if (defined(BSD) && (BSD >= 199103))
2579     addr.sin_len = sizeof(addr);
2580 #endif
2581     addr.sin_addr.s_addr = qgrp ? qgrp : query_cast;
2582     addr.sin_port = htons(2000);        /* Any port above 1024 will do */
2583
2584     /*
2585      * Note that getsockname() can return 0 on some systems
2586      * (notably SunOS 5.x, x < 6).  This is taken care of in
2587      * get_netmask().  If the default multicast interface (set
2588      * with the route for 224.0.0.0) is not the same as the
2589      * hostname, mtrace -i [if_addr] will have to be used.
2590      */
2591     if (((udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) ||
2592         (connect(udp, (struct sockaddr *) &addr, sizeof(addr)) < 0) ||
2593         getsockname(udp, (struct sockaddr *) &addr, &addrlen) < 0)
2594         err(-1, "determining local address");
2595
2596 #ifdef SUNOS5
2597     /*
2598      * SunOS 5.X prior to SunOS 2.6, getsockname returns 0 for udp socket.
2599      * This call to sysinfo will return the hostname.
2600      * If the default multicast interfface (set with the route
2601      * for 224.0.0.0) is not the same as the hostname,
2602      * mtrace -i [if_addr] will have to be used.
2603      */
2604     if (addr.sin_addr.s_addr == 0) {
2605         char myhostname[MAXHOSTNAMELEN];
2606         struct hostent *hp;
2607         int error;
2608     
2609         error = sysinfo(SI_HOSTNAME, myhostname, sizeof(myhostname));
2610         if (error == -1)
2611             err(1, "getting my hostname");
2612
2613         hp = gethostbyname(myhostname);
2614         if (hp == NULL || hp->h_addrtype != AF_INET ||
2615             hp->h_length != sizeof(addr.sin_addr))
2616             err(1, "finding IP address for my hostname");
2617
2618         memcpy((char *)&addr.sin_addr.s_addr, hp->h_addr, hp->h_length);
2619     }
2620 #endif
2621
2622     /*
2623      * Default destination for path to be queried is the local host.
2624      * When gateway specified, default destination is that gateway
2625      *  and default source is local host.
2626      */
2627     if (qdst == 0) {
2628         qdst = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2629         dst_netmask = get_netmask(udp, &qdst);
2630         if (gwy && (gwy & dst_netmask) != (qdst & dst_netmask) &&
2631                 !IN_MULTICAST(ntohl(gwy)))
2632             qdst = gwy;
2633     }
2634     if (qsrc == 0 && gwy)
2635         qsrc = lcl_addr ? lcl_addr : addr.sin_addr.s_addr;
2636     if (qsrc == 0)
2637         usage();
2638     if (!dst_netmask)
2639         dst_netmask = get_netmask(udp, &qdst);
2640     close(udp);
2641     if (lcl_addr == 0) lcl_addr = addr.sin_addr.s_addr;
2642
2643     /*
2644      * Initialize the seed for random query identifiers.
2645      */
2646     gettimeofday(&tv, 0);
2647     seed = tv.tv_usec ^ lcl_addr;
2648 #ifdef SYSV    
2649     srand48(seed);
2650 #endif
2651
2652     /*
2653      * Protect against unicast queries to mrouted versions that might crash.
2654      * Also use the obsolete "can mtrace" neighbor bit to warn about
2655      * older implementations.
2656      */
2657     if (gwy && !IN_MULTICAST(ntohl(gwy)))
2658       if (send_recv(gwy, IGMP_DVMRP, DVMRP_ASK_NEIGHBORS2, 1, &incr[0], NULL)) {
2659         int flags = ntohl(incr[0].igmp.igmp_group.s_addr);
2660         int version = flags & 0xFFFF;
2661         int info = (flags & 0xFF0000) >> 16;
2662
2663         if (version == 0x0303 || version == 0x0503) {
2664             printf("Don't use -g to address an mrouted 3.%d, it might crash\n",
2665                    (version >> 8) & 0xFF);
2666             exit(0);
2667         }
2668         if ((info & 0x08) == 0) {
2669             printf("mtrace: ");
2670             print_host(gwy);
2671             printf(" probably doesn't support mtrace, trying anyway...\n");
2672         }
2673       }
2674
2675     printf("Mtrace from %s to %s via group %s\n",
2676            inet_fmt(qsrc, s1), inet_fmt(qdst, s2), inet_fmt(qgrp, s3));
2677
2678     if ((qdst & dst_netmask) == (qsrc & dst_netmask))
2679         fprintf(stderr, "mtrace: Source & receiver appear to be directly connected\n");
2680
2681     /*
2682      * If the response is to be a multicast address, make sure we 
2683      * are listening on that multicast address.
2684      */
2685     if (raddr) {
2686         if (IN_MULTICAST(ntohl(raddr))) k_join(raddr, lcl_addr);
2687     } else k_join(resp_cast, lcl_addr);
2688
2689     memset(&base, 0, sizeof(base));
2690
2691     /*
2692      * If the destination is on the local net, the last-hop router can
2693      * be found by multicast to the all-routers multicast group.
2694      * Otherwise, use the group address that is the subject of the
2695      * query since by definition the last-hop router will be a member.
2696      * Set default TTLs for local remote multicasts.
2697      */
2698     if (gwy == 0)
2699       if ((qdst & dst_netmask) == (lcl_addr & dst_netmask)) tdst = query_cast;
2700       else tdst = qgrp;
2701     else tdst = gwy;
2702     if (tdst == 0 && qgrp == 0)
2703         errx(1, "mtrace: weak mtrace requires -g if destination is not local.\n");
2704
2705     if (IN_MULTICAST(ntohl(tdst))) {
2706       k_set_loop(1);    /* If I am running on a router, I need to hear this */
2707       if (tdst == query_cast) k_set_ttl(qttl ? qttl : 1);
2708       else k_set_ttl(qttl ? qttl : MULTICAST_TTL1);
2709     }
2710
2711     /*
2712      * Try a query at the requested number of hops or MAXHOPS if unspecified.
2713      */
2714     if (qno == 0) {
2715         hops = MAXHOPS;
2716         tries = 1;
2717         printf("Querying full reverse path... ");
2718         fflush(stdout);
2719     } else {
2720         hops = qno;
2721         tries = nqueries;
2722         if (fflag)
2723             printf("Querying full reverse path, starting at hop %d...", qno);
2724         else
2725             printf("Querying reverse path, maximum %d hops... ", qno);
2726         fflush(stdout); 
2727     }
2728     base.rtime = 0;
2729     base.len = 0;
2730     hopbyhop = FALSE;
2731
2732     recvlen = send_recv(tdst, IGMP_MTRACE, hops, tries, &base, mtrace_callback);
2733
2734     /*
2735      * If the initial query was successful, print it.  Otherwise, if
2736      * the query max hop count is the default of zero, loop starting
2737      * from one until there is no response for extrahops more hops.  The
2738      * extra hops allow getting past an mtrace-capable mrouter that can't
2739      * send multicast packets because all phyints are disabled.
2740      */
2741     if (recvlen) {
2742         printf("\n  0  ");
2743         print_host(qdst);
2744         printf("\n");
2745         print_trace(1, &base, names);
2746         r = base.resps + base.len - 1;
2747         if (r->tr_rflags == TR_OLD_ROUTER || r->tr_rflags == TR_NO_SPACE ||
2748                 (qno != 0 && r->tr_rmtaddr != 0 && !fflag)) {
2749             printf("%3d  ", -(base.len+1));
2750             what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2751                                    "doesn't support mtrace"
2752                                  : "is the next hop");
2753         } else {
2754             if (fflag) {
2755                 nexthop = hops = qno;
2756                 goto continuehop;
2757             }
2758             VAL_TO_MASK(smask, r->tr_smask);
2759             if ((r->tr_inaddr & smask) == (qsrc & smask)) {
2760                 printf("%3d  ", -(base.len+1));
2761                 print_host(qsrc);
2762                 printf("\n");
2763             }
2764         }
2765     } else if (qno == 0) {
2766         hopbyhop = TRUE;
2767         printf("switching to hop-by-hop:\n  0  ");
2768         print_host(qdst);
2769         printf("\n");
2770
2771         for (hops = 1, nexthop = 1; hops <= MAXHOPS; ++hops) {
2772             printf("%3d  ", -hops);
2773             fflush(stdout);
2774
2775             /*
2776              * After a successful first hop, try switching to the unicast
2777              * address of the last-hop router instead of multicasting the
2778              * trace query.  This should be safe for mrouted versions 3.3
2779              * and 3.5 because there is a long route timeout with metric
2780              * infinity before a route disappears.  Switching to unicast
2781              * reduces the amount of multicast traffic and avoids a bug
2782              * with duplicate suppression in mrouted 3.5.
2783              */
2784             if (hops == 2 && gwy == 0 && lastout != 0 &&
2785                 (recvlen = send_recv(lastout, IGMP_MTRACE, hops, 1, &base, mtrace_callback)))
2786               tdst = lastout;
2787             else recvlen = send_recv(tdst, IGMP_MTRACE, hops, nqueries, &base, mtrace_callback);
2788
2789             if (recvlen == 0) {
2790                 /*if (hops == 1) break;*/
2791                 if (hops == nexthop) {
2792                     if (hops == 1) {
2793                         printf("\n");
2794                     } else if (what_kind(&base, "didn't respond")) {
2795                         /* the ask_neighbors determined that the
2796                          * not-responding router is the first-hop. */
2797                         break;
2798                     }
2799                     if (extrahops == 0)
2800                         break;
2801                 } else if (hops < nexthop + extrahops) {
2802                     printf("\n");
2803                 } else {
2804                     printf("...giving up\n");
2805                     break;
2806                 }
2807                 continue;
2808             }
2809             if (base.len == hops &&
2810                 (hops == 1 || (base.resps+nexthop-2)->tr_outaddr == lastout)) {
2811                 if (hops == nexthop) {
2812                     print_trace(-hops, &base, names);
2813                 } else {
2814                     printf("\nResuming...\n");
2815                     print_trace(nexthop, &base, names);
2816                 }
2817             } else {
2818                 if (base.len < hops) {
2819                     /*
2820                      * A shorter trace than requested means a fatal error
2821                      * occurred along the path, or that the route changed
2822                      * to a shorter one.
2823                      *
2824                      * If the trace is longer than the last one we received,
2825                      * then we are resuming from a skipped router (but there
2826                      * is still probably a problem).
2827                      *
2828                      * If the trace is shorter than the last one we
2829                      * received, then the route must have changed (and
2830                      * there is still probably a problem).
2831                      */
2832                     if (nexthop <= base.len) {
2833                         printf("\nResuming...\n");
2834                         print_trace(nexthop, &base, names);
2835                     } else if (nexthop > base.len + 1) {
2836                         hops = base.len;
2837                         printf("\nRoute must have changed...\n");
2838                         print_trace(1, &base, names);
2839                     }
2840                 } else {
2841                     /*
2842                      * The last hop address is not the same as it was.
2843                      * If we didn't know the last hop then we just
2844                      * got the first response from a hop-by-hop trace;
2845                      * if we did know the last hop then
2846                      * the route probably changed underneath us.
2847                      */
2848                     hops = base.len;
2849                     if (lastout != 0)
2850                         printf("\nRoute must have changed...\n");
2851                     else
2852                         printf("\nResuming...\n");
2853                     print_trace(1, &base, names);
2854                 }
2855             }
2856 continuehop:
2857             r = base.resps + base.len - 1;
2858             lastout = r->tr_outaddr;
2859
2860             if (base.len < hops ||
2861                 r->tr_rmtaddr == 0 ||
2862                 (r->tr_rflags & 0x80)) {
2863                 VAL_TO_MASK(smask, r->tr_smask);
2864                 if (r->tr_rmtaddr) {
2865                     if (hops != nexthop) {
2866                         printf("\n%3d  ", -(base.len+1));
2867                     }
2868                     what_kind(&base, r->tr_rflags == TR_OLD_ROUTER ?
2869                                 "doesn't support mtrace" :
2870                                 "would be the next hop");
2871                     /* XXX could do segmented trace if TR_NO_SPACE */
2872                 } else if (r->tr_rflags == TR_NO_ERR &&
2873                            (r->tr_inaddr & smask) == (qsrc & smask)) {
2874                     printf("%3d  ", -(hops + 1));
2875                     print_host(qsrc);
2876                     printf("\n");
2877                 }
2878                 break;
2879             }
2880
2881             nexthop = hops + 1;
2882         }
2883     }
2884
2885     if (base.rtime == 0) {
2886         printf("Timed out receiving responses\n");
2887         if (IN_MULTICAST(ntohl(tdst)))
2888           if (tdst == query_cast)
2889             printf("Perhaps no local router has a route for source %s\n",
2890                    inet_fmt(qsrc, s1));
2891           else
2892             printf("Perhaps receiver %s is not a member of group %s,\n\
2893 or no router local to it has a route for source %s,\n\
2894 or multicast at ttl %d doesn't reach its last-hop router for that source\n",
2895                    inet_fmt(qdst, s2), inet_fmt(qgrp, s3), inet_fmt(qsrc, s1),
2896                    qttl ? qttl : MULTICAST_TTL1);
2897         exit(1);
2898     }
2899
2900     printf("Round trip time %d ms; ", t_diff(base.rtime, base.qtime));
2901     {
2902         struct tr_resp *n = base.resps + base.len - 1;
2903         u_int ttl = n->tr_fttl + 1;
2904
2905         rno = base.len - 1;
2906         while (--rno > 0) {
2907             --n;
2908             ttl = MaX(ttl, MaX(1, n->tr_fttl) + base.len - rno);
2909         }
2910         printf("total ttl of %d required.\n\n",ttl);
2911     }
2912
2913     /*
2914      * Use the saved response which was the longest one received,
2915      * and make additional probes after delay to measure loss.
2916      */
2917     raddr = base.qhdr.tr_raddr;
2918     rttl = TR_GETTTL(base.qhdr.tr_rttlqid);
2919     gettimeofday(&tv, 0);
2920     waittime = statint - (((tv.tv_sec + JAN_1970) & 0xFFFF) - (base.qtime >> 16));
2921     prev = &base;
2922     new = &incr[numstats&1];
2923
2924     /*
2925      * Zero out bug-avoidance counters
2926      */
2927     memset(bugs, 0, sizeof(bugs));
2928
2929     if (!printstats)
2930         printf("Monitoring path..");
2931
2932     while (numstats--) {
2933         if (waittime < 1) printf("\n");
2934         else {
2935             if (printstats && (lossthresh == 0 || printed)) {
2936                 printf("Waiting to accumulate statistics...");
2937             } else {
2938                 printf(".");
2939             }
2940             fflush(stdout);
2941             sleep((unsigned)waittime);
2942         }
2943         printed = 0;
2944         rno = hopbyhop ? base.len : qno ? qno : MAXHOPS;
2945         recvlen = send_recv(tdst, IGMP_MTRACE, rno, nqueries, new, mtrace_callback);
2946
2947         if (recvlen == 0) {
2948             printf("Timed out.\n");
2949             if (numstats) {
2950                 numstats++;
2951                 continue;
2952             } else
2953                 exit(1);
2954         }
2955
2956         if (base.len != new->len || path_changed(&base, new)) {
2957             printf("%s", base.len == new->len ? "Route changed" :
2958                                         "Trace length doesn't match");
2959             if (!printstats)
2960                 printf(" after %d seconds",
2961                    (int)((new->qtime - base.qtime) >> 16));
2962             printf(":\n");
2963 printandcontinue:
2964             print_trace(1, new, names);
2965             numstats++;
2966             bcopy(new, &base, sizeof(base));
2967             nexthop = hops = new->len;
2968             printf("Continuing with hop-by-hop...\n");
2969             goto continuehop;
2970         }
2971
2972         if (printstats) {
2973             if (new->igmp.igmp_group.s_addr != qgrp ||
2974                 new->qhdr.tr_src != qsrc || new->qhdr.tr_dst != qdst)
2975                 printf("\nWARNING: trace modified en route; statistics may be incorrect\n");
2976             fixup_stats(&base, prev, new, bugs);
2977             if ((lossthresh == 0) || check_thresh(lossthresh, &base, prev, new)) {
2978                 printf("Results after %d seconds",
2979                        (int)((new->qtime - base.qtime) >> 16));
2980                 if (lossthresh)
2981                     printf(" (this trace %d seconds)",
2982                            (int)((new->qtime - prev->qtime) >> 16));
2983                 if (verbose) {
2984                     time_t t = time(0);
2985                     struct tm *qr = localtime(&t);
2986
2987                     printf(" qid 0x%06x at %2d:%02d:%02d",
2988                                 TR_GETQID(base.qhdr.tr_rttlqid),
2989                                 qr->tm_hour, qr->tm_min, qr->tm_sec);
2990                 }
2991                 printf(":\n\n");
2992                 printed = 1;
2993                 if (print_stats(&base, prev, new, bugs, names)) {
2994                     printf("This should have been detected earlier, but ");
2995                     printf("Route changed:\n");
2996                     goto printandcontinue;
2997                 }
2998             }
2999         }
3000         prev = new;
3001         new = &incr[numstats&1];
3002         waittime = statint;
3003     }
3004
3005     /*
3006      * If the response was multicast back, leave the group
3007      */
3008     if (raddr) {
3009         if (IN_MULTICAST(ntohl(raddr))) k_leave(raddr, lcl_addr);
3010     } else k_leave(resp_cast, lcl_addr);
3011
3012     return (0);
3013 }
3014
3015 static void
3016 usage(void)
3017 {
3018         fprintf(stderr, "%s\n%s\n%s\n",
3019         "usage: mtrace [-MUOPTWVlnpvs] [-e extra_hops] [-f first_hop] [-i if_addr]",
3020         "              [-g gateway] [-m max_hops] [-q nqueries] [-r resp_dest]",
3021         "              [-S statint] [-t ttl] [-w wait] source [receiver] [group]");
3022         exit(1);
3023 }
3024
3025 void
3026 check_vif_state(void)
3027 {
3028     dolog(LOG_WARNING, errno, "sendto");
3029 }
3030
3031 /*
3032  * Log errors and other messages to stderr, according to the severity
3033  * of the message and the current debug level.  For errors of severity
3034  * LOG_ERR or worse, terminate the program.
3035  */
3036 void
3037 dolog(int severity, int syserr, char *format, ...)
3038 {
3039         va_list ap;
3040         char    fmt[100];
3041
3042         va_start(ap, format);
3043
3044     switch (debug) {
3045         case 0: if (severity > LOG_WARNING) return;
3046         case 1: if (severity > LOG_NOTICE) return;
3047         case 2: if (severity > LOG_INFO  ) return;
3048         default:
3049             fmt[0] = '\0';
3050             if (severity == LOG_WARNING) 
3051                 strcpy(fmt, "warning - ");
3052             strncat(fmt, format, sizeof(fmt)-strlen(fmt));
3053             fmt[sizeof(fmt)-1]='\0';
3054             vfprintf(stderr, fmt, ap);
3055             if (syserr == 0)
3056                 fprintf(stderr, "\n");
3057             else if (syserr < sys_nerr)
3058                 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
3059             else
3060                 fprintf(stderr, ": errno %d\n", syserr);
3061     }
3062     if (severity <= LOG_ERR) exit(1);
3063 }