Home | History | Annotate | Line # | Download | only in traceroute6
traceroute6.c revision 1.18
      1 /*	$NetBSD: traceroute6.c,v 1.18 2002/02/19 02:29:58 itojun Exp $	*/
      2 /*	$KAME: traceroute6.c,v 1.39 2000/12/22 15:11:05 itojun Exp $	*/
      3 
      4 /*
      5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. Neither the name of the project nor the names of its contributors
     17  *    may be used to endorse or promote products derived from this software
     18  *    without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  * SUCH DAMAGE.
     31  */
     32 
     33 /*-
     34  * Copyright (c) 1990, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * This code is derived from software contributed to Berkeley by
     38  * Van Jacobson.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  * 3. All advertising materials mentioning features or use of this software
     49  *    must display the following acknowledgement:
     50  *	This product includes software developed by the University of
     51  *	California, Berkeley and its contributors.
     52  * 4. Neither the name of the University nor the names of its contributors
     53  *    may be used to endorse or promote products derived from this software
     54  *    without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     66  * SUCH DAMAGE.
     67  */
     68 
     69 #if 0
     70 #ifndef lint
     71 static char copyright[] =
     72 "@(#) Copyright (c) 1990, 1993\n\
     73 	The Regents of the University of California.  All rights reserved.\n";
     74 #endif /* not lint */
     75 
     76 #ifndef lint
     77 static char sccsid[] = "@(#)traceroute.c	8.1 (Berkeley) 6/6/93";
     78 #endif /* not lint */
     79 #else
     80 #include <sys/cdefs.h>
     81 #ifndef lint
     82 __RCSID("$NetBSD: traceroute6.c,v 1.18 2002/02/19 02:29:58 itojun Exp $");
     83 #endif
     84 #endif
     85 
     86 /*
     87  * traceroute host  - trace the route ip packets follow going to "host".
     88  *
     89  * Attempt to trace the route an ip packet would follow to some
     90  * internet host.  We find out intermediate hops by launching probe
     91  * packets with a small ttl (time to live) then listening for an
     92  * icmp "time exceeded" reply from a gateway.  We start our probes
     93  * with a ttl of one and increase by one until we get an icmp "port
     94  * unreachable" (which means we got to "host") or hit a max (which
     95  * defaults to 30 hops & can be changed with the -m flag).  Three
     96  * probes (change with -q flag) are sent at each ttl setting and a
     97  * line is printed showing the ttl, address of the gateway and
     98  * round trip time of each probe.  If the probe answers come from
     99  * different gateways, the address of each responding system will
    100  * be printed.  If there is no response within a 5 sec. timeout
    101  * interval (changed with the -w flag), a "*" is printed for that
    102  * probe.
    103  *
    104  * Probe packets are UDP format.  We don't want the destination
    105  * host to process them so the destination port is set to an
    106  * unlikely value (if some clod on the destination is using that
    107  * value, it can be changed with the -p flag).
    108  *
    109  * A sample use might be:
    110  *
    111  *     [yak 71]% traceroute nis.nsf.net.
    112  *     traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
    113  *      1  helios.ee.lbl.gov (128.3.112.1)  19 ms  19 ms  0 ms
    114  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
    115  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
    116  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  39 ms
    117  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  39 ms  39 ms  39 ms
    118  *      6  128.32.197.4 (128.32.197.4)  40 ms  59 ms  59 ms
    119  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  59 ms
    120  *      8  129.140.70.13 (129.140.70.13)  99 ms  99 ms  80 ms
    121  *      9  129.140.71.6 (129.140.71.6)  139 ms  239 ms  319 ms
    122  *     10  129.140.81.7 (129.140.81.7)  220 ms  199 ms  199 ms
    123  *     11  nic.merit.edu (35.1.1.48)  239 ms  239 ms  239 ms
    124  *
    125  * Note that lines 2 & 3 are the same.  This is due to a buggy
    126  * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
    127  * packets with a zero ttl.
    128  *
    129  * A more interesting example is:
    130  *
    131  *     [yak 72]% traceroute allspice.lcs.mit.edu.
    132  *     traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
    133  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
    134  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  19 ms  19 ms
    135  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  19 ms
    136  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  19 ms  39 ms  39 ms
    137  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  20 ms  39 ms  39 ms
    138  *      6  128.32.197.4 (128.32.197.4)  59 ms  119 ms  39 ms
    139  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  39 ms
    140  *      8  129.140.70.13 (129.140.70.13)  80 ms  79 ms  99 ms
    141  *      9  129.140.71.6 (129.140.71.6)  139 ms  139 ms  159 ms
    142  *     10  129.140.81.7 (129.140.81.7)  199 ms  180 ms  300 ms
    143  *     11  129.140.72.17 (129.140.72.17)  300 ms  239 ms  239 ms
    144  *     12  * * *
    145  *     13  128.121.54.72 (128.121.54.72)  259 ms  499 ms  279 ms
    146  *     14  * * *
    147  *     15  * * *
    148  *     16  * * *
    149  *     17  * * *
    150  *     18  ALLSPICE.LCS.MIT.EDU (18.26.0.115)  339 ms  279 ms  279 ms
    151  *
    152  * (I start to see why I'm having so much trouble with mail to
    153  * MIT.)  Note that the gateways 12, 14, 15, 16 & 17 hops away
    154  * either don't send ICMP "time exceeded" messages or send them
    155  * with a ttl too small to reach us.  14 - 17 are running the
    156  * MIT C Gateway code that doesn't send "time exceeded"s.  God
    157  * only knows what's going on with 12.
    158  *
    159  * The silent gateway 12 in the above may be the result of a bug in
    160  * the 4.[23]BSD network code (and its derivatives):  4.x (x <= 3)
    161  * sends an unreachable message using whatever ttl remains in the
    162  * original datagram.  Since, for gateways, the remaining ttl is
    163  * zero, the icmp "time exceeded" is guaranteed to not make it back
    164  * to us.  The behavior of this bug is slightly more interesting
    165  * when it appears on the destination system:
    166  *
    167  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
    168  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  39 ms
    169  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  39 ms  19 ms
    170  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  19 ms
    171  *      5  ccn-nerif35.Berkeley.EDU (128.32.168.35)  39 ms  39 ms  39 ms
    172  *      6  csgw.Berkeley.EDU (128.32.133.254)  39 ms  59 ms  39 ms
    173  *      7  * * *
    174  *      8  * * *
    175  *      9  * * *
    176  *     10  * * *
    177  *     11  * * *
    178  *     12  * * *
    179  *     13  rip.Berkeley.EDU (128.32.131.22)  59 ms !  39 ms !  39 ms !
    180  *
    181  * Notice that there are 12 "gateways" (13 is the final
    182  * destination) and exactly the last half of them are "missing".
    183  * What's really happening is that rip (a Sun-3 running Sun OS3.5)
    184  * is using the ttl from our arriving datagram as the ttl in its
    185  * icmp reply.  So, the reply will time out on the return path
    186  * (with no notice sent to anyone since icmp's aren't sent for
    187  * icmp's) until we probe with a ttl that's at least twice the path
    188  * length.  I.e., rip is really only 7 hops away.  A reply that
    189  * returns with a ttl of 1 is a clue this problem exists.
    190  * Traceroute prints a "!" after the time if the ttl is <= 1.
    191  * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
    192  * non-standard (HPUX) software, expect to see this problem
    193  * frequently and/or take care picking the target host of your
    194  * probes.
    195  *
    196  * Other possible annotations after the time are !H, !N, !P (got a host,
    197  * network or protocol unreachable, respectively), !S or !F (source
    198  * route failed or fragmentation needed -- neither of these should
    199  * ever occur and the associated gateway is busted if you see one).  If
    200  * almost all the probes result in some kind of unreachable, traceroute
    201  * will give up and exit.
    202  *
    203  * Notes
    204  * -----
    205  * This program must be run by root or be setuid.  (I suggest that
    206  * you *don't* make it setuid -- casual use could result in a lot
    207  * of unnecessary traffic on our poor, congested nets.)
    208  *
    209  * This program requires a kernel mod that does not appear in any
    210  * system available from Berkeley:  A raw ip socket using proto
    211  * IPPROTO_RAW must interpret the data sent as an ip datagram (as
    212  * opposed to data to be wrapped in a ip datagram).  See the README
    213  * file that came with the source to this program for a description
    214  * of the mods I made to /sys/netinet/raw_ip.c.  Your mileage may
    215  * vary.  But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
    216  * MODIFIED TO RUN THIS PROGRAM.
    217  *
    218  * The udp port usage may appear bizarre (well, ok, it is bizarre).
    219  * The problem is that an icmp message only contains 8 bytes of
    220  * data from the original datagram.  8 bytes is the size of a udp
    221  * header so, if we want to associate replies with the original
    222  * datagram, the necessary information must be encoded into the
    223  * udp header (the ip id could be used but there's no way to
    224  * interlock with the kernel's assignment of ip id's and, anyway,
    225  * it would have taken a lot more kernel hacking to allow this
    226  * code to set the ip id).  So, to allow two or more users to
    227  * use traceroute simultaneously, we use this task's pid as the
    228  * source port (the high bit is set to move the port number out
    229  * of the "likely" range).  To keep track of which probe is being
    230  * replied to (so times and/or hop counts don't get confused by a
    231  * reply that was delayed in transit), we increment the destination
    232  * port number before each probe.
    233  *
    234  * Don't use this as a coding example.  I was trying to find a
    235  * routing problem and this code sort-of popped out after 48 hours
    236  * without sleep.  I was amazed it ever compiled, much less ran.
    237  *
    238  * I stole the idea for this program from Steve Deering.  Since
    239  * the first release, I've learned that had I attended the right
    240  * IETF working group meetings, I also could have stolen it from Guy
    241  * Almes or Matt Mathis.  I don't know (or care) who came up with
    242  * the idea first.  I envy the originators' perspicacity and I'm
    243  * glad they didn't keep the idea a secret.
    244  *
    245  * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
    246  * enhancements to the original distribution.
    247  *
    248  * I've hacked up a round-trip-route version of this that works by
    249  * sending a loose-source-routed udp datagram through the destination
    250  * back to yourself.  Unfortunately, SO many gateways botch source
    251  * routing, the thing is almost worthless.  Maybe one day...
    252  *
    253  *  -- Van Jacobson (van (at) helios.ee.lbl.gov)
    254  *     Tue Dec 20 03:50:13 PST 1988
    255  */
    256 
    257 #include <sys/param.h>
    258 #include <sys/time.h>
    259 #include <sys/socket.h>
    260 #include <sys/uio.h>
    261 #include <sys/file.h>
    262 #include <sys/ioctl.h>
    263 
    264 #include <netinet/in.h>
    265 
    266 #include <arpa/inet.h>
    267 
    268 #include <netdb.h>
    269 #include <stdio.h>
    270 #include <err.h>
    271 #ifdef HAVE_POLL
    272 #include <poll.h>
    273 #endif
    274 #include <errno.h>
    275 #include <stdlib.h>
    276 #include <string.h>
    277 #include <unistd.h>
    278 
    279 #include <netinet/ip6.h>
    280 #include <netinet/icmp6.h>
    281 #include <netinet/udp.h>
    282 
    283 #ifdef IPSEC
    284 #include <net/route.h>
    285 #include <netinet6/ipsec.h>
    286 #endif
    287 
    288 #define DUMMY_PORT 10010
    289 
    290 #define	MAXPACKET	65535	/* max ip packet size */
    291 
    292 #ifndef FD_SET
    293 #define NFDBITS         (8*sizeof(fd_set))
    294 #define FD_SETSIZE      NFDBITS
    295 #define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
    296 #define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
    297 #define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
    298 #define FD_ZERO(p)      bzero((char *)(p), sizeof(*(p)))
    299 #endif
    300 
    301 #define Fprintf (void)fprintf
    302 #define Sprintf (void)sprintf
    303 #define Printf (void)printf
    304 
    305 #ifndef HAVE_GETIPNODEBYNAME
    306 #define getipnodebyname(x, y, z, u)	gethostbyname2((x), (y))
    307 #define freehostent(x)
    308 #endif
    309 
    310 /*
    311  * format of a (udp) probe packet.
    312  */
    313 struct opacket {
    314 	u_char seq;		/* sequence number of this packet */
    315 	u_char hops;		/* hop limit of the packet */
    316 	struct timeval tv;	/* time packet left */
    317 };
    318 
    319 u_char	packet[512];		/* last inbound (icmp) packet */
    320 struct opacket	*outpacket;	/* last output (udp) packet */
    321 
    322 int	main __P((int, char *[]));
    323 int	wait_for_reply __P((int, struct msghdr *));
    324 #ifdef IPSEC
    325 #ifdef IPSEC_POLICY_IPSEC
    326 int	setpolicy __P((int so, char *policy));
    327 #endif
    328 #endif
    329 void	send_probe __P((int, int));
    330 struct udphdr *get_udphdr __P((struct ip6_hdr *, u_char *));
    331 int	get_hoplim __P((struct msghdr *));
    332 double	deltaT __P((struct timeval *, struct timeval *));
    333 char	*pr_type __P((int));
    334 int	packet_ok __P((struct msghdr *, int, int));
    335 void	print __P((struct msghdr *, int));
    336 void	tvsub __P((struct timeval *, struct timeval *));
    337 const char *inetname __P((struct sockaddr *));
    338 void	usage __P((void));
    339 
    340 int rcvsock;			/* receive (icmp) socket file descriptor */
    341 int sndsock;			/* send (udp) socket file descriptor */
    342 struct timezone tz;		/* leftover */
    343 
    344 struct msghdr rcvmhdr;
    345 struct iovec rcviov[2];
    346 int rcvhlim;
    347 struct in6_pktinfo *rcvpktinfo;
    348 
    349 struct sockaddr_in6 Src, Dst, Rcv;
    350 int datalen;			/* How much data */
    351 /* XXX: 2064 = 127(max hops in type 0 rthdr) * sizeof(ip6_hdr) + 16(margin) */
    352 char rtbuf[2064];
    353 #ifdef USE_RFC2292BIS
    354 struct ip6_rthdr *rth;
    355 #endif
    356 struct cmsghdr *cmsg;
    357 
    358 char *source = 0;
    359 char *hostname;
    360 
    361 int nprobes = 3;
    362 int first_hop = 1;
    363 int max_hops = 30;
    364 u_short ident;
    365 u_short port = 32768+666;	/* start udp dest port # for probe packets */
    366 int options;			/* socket options */
    367 int verbose;
    368 int waittime = 5;		/* time to wait for response (in seconds) */
    369 int nflag;			/* print addresses numerically */
    370 int lflag;			/* print both numerical address & hostname */
    371 
    372 #ifdef KAME_SCOPEID
    373 const int niflag = NI_WITHSCOPEID;
    374 #else
    375 const int niflag = 0;
    376 #endif
    377 
    378 int
    379 main(argc, argv)
    380 	int argc;
    381 	char *argv[];
    382 {
    383 	struct hostent *hp;
    384 	int error;
    385 	struct addrinfo hints, *res;
    386 	int ch, i, on, probe, seq, hops, rcvcmsglen;
    387 	static u_char *rcvcmsgbuf;
    388 	char hbuf[NI_MAXHOST], src0[NI_MAXHOST];
    389 	char *ep;
    390 
    391 	/*
    392 	 * Receive ICMP
    393 	 */
    394 	if ((rcvsock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0) {
    395 		perror("socket(ICMPv6)");
    396 		exit(5);
    397 	}
    398 
    399 	/* revoke privs */
    400 	seteuid(getuid());
    401 	setuid(getuid());
    402 
    403 	/* set a minimum set of socket options */
    404 	on = 1;
    405 	/* specify to tell receiving interface */
    406 #ifdef IPV6_RECVPKTINFO
    407 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
    408 		       sizeof(on)) < 0)
    409 		err(1, "setsockopt(IPV6_RECVPKTINFO)");
    410 #else  /* old adv. API */
    411 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_PKTINFO, &on,
    412 		       sizeof(on)) < 0)
    413 		err(1, "setsockopt(IPV6_PKTINFO)");
    414 #endif
    415 
    416 	/* specify to tell value of hoplimit field of received IP6 hdr */
    417 #ifdef IPV6_RECVHOPLIMIT
    418 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
    419 		       sizeof(on)) < 0)
    420 		err(1, "setsockopt(IPV6_RECVHOPLIMIT)");
    421 #else  /* old adv. API */
    422 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_HOPLIMIT, &on,
    423 		       sizeof(on)) < 0)
    424 		err(1, "setsockopt(IPV6_HOPLIMIT)");
    425 #endif
    426 
    427 	seq = 0;
    428 
    429 	while ((ch = getopt(argc, argv, "df:g:lm:np:q:rs:w:v")) != -1)
    430 		switch(ch) {
    431 		case 'd':
    432 			options |= SO_DEBUG;
    433 			break;
    434 		case 'f':
    435 			ep = NULL;
    436 			first_hop = strtoul(optarg, &ep, 0);
    437 			if (!*argv || *ep) {
    438 				Fprintf(stderr,
    439 				    "traceroute6: invalid min hoplimit.\n");
    440 				exit(1);
    441 			}
    442 			if (first_hop > max_hops) {
    443 				Fprintf(stderr,
    444 				    "traceroute6: min hoplimit must be <= %d.\n", max_hops);
    445 				exit(1);
    446 			}
    447 			break;
    448 		case 'g':
    449 			hp = getipnodebyname(optarg, AF_INET6, 0, &h_errno);
    450 			if (hp == NULL) {
    451 				Fprintf(stderr,
    452 				    "traceroute6: unknown host %s\n", optarg);
    453 				exit(1);
    454 			}
    455 #ifdef USE_RFC2292BIS
    456 			if (rth == NULL) {
    457 				/*
    458 				 * XXX: We can't detect the number of
    459 				 * intermediate nodes yet.
    460 				 */
    461 				if ((rth = inet6_rth_init((void *)rtbuf,
    462 							 sizeof(rtbuf),
    463 							 IPV6_RTHDR_TYPE_0,
    464 							 0)) == NULL) {
    465 					Fprintf(stderr,
    466 						"inet6_rth_init failed.\n");
    467 					exit(1);
    468 				}
    469 			}
    470 			if (inet6_rth_add((void *)rth,
    471 					  (struct in6_addr *)hp->h_addr)) {
    472 				Fprintf(stderr,
    473 					"inet6_rth_add failed for %s\n",
    474 					optarg);
    475 				exit(1);
    476 			}
    477 #else  /* old advanced API */
    478 			if (cmsg == NULL)
    479 				cmsg = inet6_rthdr_init(rtbuf, IPV6_RTHDR_TYPE_0);
    480 			inet6_rthdr_add(cmsg, (struct in6_addr *)hp->h_addr, IPV6_RTHDR_LOOSE);
    481 #endif
    482 			freehostent(hp);
    483 			break;
    484 		case 'l':
    485 			lflag++;
    486 			break;
    487 		case 'm':
    488 			ep = NULL;
    489 			max_hops = strtoul(optarg, &ep, 0);
    490 			if (!*argv || *ep) {
    491 				Fprintf(stderr,
    492 				    "traceroute6: invalid max hoplimit.\n");
    493 				exit(1);
    494 			}
    495 			if (max_hops < first_hop) {
    496 				Fprintf(stderr,
    497 				    "traceroute6: max hoplimit must be >= %d.\n", first_hop);
    498 				exit(1);
    499 			}
    500 			break;
    501 		case 'n':
    502 			nflag++;
    503 			break;
    504 		case 'p':
    505 			ep = NULL;
    506 			port = strtoul(optarg, &ep, 0);
    507 			if (!*argv || *ep) {
    508 				Fprintf(stderr,
    509 				    "traceroute6: port.\n");
    510 				exit(1);
    511 			}
    512 			if (port < 1) {
    513 				Fprintf(stderr,
    514 				    "traceroute6: port must be >0.\n");
    515 				exit(1);
    516 			}
    517 			break;
    518 		case 'q':
    519 			ep = NULL;
    520 			nprobes = strtoul(optarg, &ep, 0);
    521 			if (!*argv || *ep) {
    522 				Fprintf(stderr,
    523 				    "traceroute6: invalid nprobes.\n");
    524 				exit(1);
    525 			}
    526 			if (nprobes < 1) {
    527 				Fprintf(stderr,
    528 				    "traceroute6: nprobes must be >0.\n");
    529 				exit(1);
    530 			}
    531 			break;
    532 		case 'r':
    533 			options |= SO_DONTROUTE;
    534 			break;
    535 		case 's':
    536 			/*
    537 			 * set the ip source address of the outbound
    538 			 * probe (e.g., on a multi-homed host).
    539 			 */
    540 			source = optarg;
    541 			break;
    542 		case 'v':
    543 			verbose++;
    544 			break;
    545 		case 'w':
    546 			ep = NULL;
    547 			waittime = strtoul(optarg, &ep, 0);
    548 			if (!*argv || *ep) {
    549 				Fprintf(stderr,
    550 				    "traceroute6: invalid wait time.\n");
    551 				exit(1);
    552 			}
    553 			if (waittime <= 1) {
    554 				Fprintf(stderr,
    555 				    "traceroute6: wait must be >1 sec.\n");
    556 				exit(1);
    557 			}
    558 			break;
    559 		default:
    560 			usage();
    561 		}
    562 	argc -= optind;
    563 	argv += optind;
    564 
    565 	if (argc < 1 || argc > 2)
    566 		usage();
    567 
    568 #if 1
    569 	setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
    570 #else
    571 	setlinebuf (stdout);
    572 #endif
    573 
    574 	memset(&hints, 0, sizeof(hints));
    575 	hints.ai_family = PF_INET6;
    576 	hints.ai_socktype = SOCK_RAW;
    577 	hints.ai_protocol = IPPROTO_ICMPV6;
    578 	hints.ai_flags = AI_CANONNAME;
    579 	error = getaddrinfo(*argv, NULL, &hints, &res);
    580 	if (error) {
    581 		(void)fprintf(stderr,
    582 			      "traceroute6: %s\n", gai_strerror(error));
    583 		exit(1);
    584 	}
    585 	if (res->ai_addrlen != sizeof(Dst)) {
    586 		(void)fprintf(stderr,
    587 			      "traceroute6: size of sockaddr mismatch\n");
    588 		exit(1);
    589 	}
    590 	memcpy(&Dst, res->ai_addr, res->ai_addrlen);
    591 	hostname = res->ai_canonname ? strdup(res->ai_canonname) : *argv;
    592 	if (!hostname) {
    593 		(void)fprintf(stderr, "traceroute6: not enhough core\n");
    594 		exit(1);
    595 	}
    596 
    597 	if (*++argv) {
    598 		ep = NULL;
    599 		datalen = strtoul(*argv, &ep, 0);
    600 		if (!*argv || *ep) {
    601 			Fprintf(stderr,
    602 			    "traceroute6: invalid packet length.\n");
    603 			exit(1);
    604 		}
    605 	}
    606 	if (datalen < 0 || datalen >= MAXPACKET - sizeof(struct opacket)) {
    607 		Fprintf(stderr,
    608 		    "traceroute6: packet size must be 0 <= s < %ld.\n",
    609 		    (long)(MAXPACKET - sizeof(struct opacket)));
    610 		exit(1);
    611 	}
    612 	datalen += sizeof(struct opacket);
    613 	outpacket = (struct opacket *)malloc((unsigned)datalen);
    614 	if (! outpacket) {
    615 		perror("malloc");
    616 		exit(1);
    617 	}
    618 	(void) bzero((char *)outpacket, datalen);
    619 
    620 	/* initialize msghdr for receiving packets */
    621 	rcviov[0].iov_base = (caddr_t)packet;
    622 	rcviov[0].iov_len = sizeof(packet);
    623 	rcvmhdr.msg_name = (caddr_t)&Rcv;
    624 	rcvmhdr.msg_namelen = sizeof(Rcv);
    625 	rcvmhdr.msg_iov = rcviov;
    626 	rcvmhdr.msg_iovlen = 1;
    627 	rcvcmsglen = CMSG_SPACE(sizeof(struct in6_pktinfo))
    628 		+ CMSG_SPACE(sizeof(int));
    629 	if ((rcvcmsgbuf = malloc(rcvcmsglen)) == NULL) {
    630 		Fprintf(stderr, "traceroute6: malloc failed\n");
    631 		exit(1);
    632 	}
    633 	rcvmhdr.msg_control = (caddr_t) rcvcmsgbuf;
    634 	rcvmhdr.msg_controllen = rcvcmsglen;
    635 
    636 	if (options & SO_DEBUG)
    637 		(void) setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
    638 				  (char *)&on, sizeof(on));
    639 	if (options & SO_DONTROUTE)
    640 		(void) setsockopt(rcvsock, SOL_SOCKET, SO_DONTROUTE,
    641 				  (char *)&on, sizeof(on));
    642 #ifdef IPSEC
    643 #ifdef IPSEC_POLICY_IPSEC
    644 	/*
    645 	 * do not raise error even if setsockopt fails, kernel may have ipsec
    646 	 * turned off.
    647 	 */
    648 	if (setpolicy(rcvsock, "in bypass") < 0)
    649 		errx(1, "%s", ipsec_strerror());
    650 	if (setpolicy(rcvsock, "out bypass") < 0)
    651 		errx(1, "%s", ipsec_strerror());
    652 #else
    653     {
    654 	int level = IPSEC_LEVEL_NONE;
    655 
    656 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, &level,
    657 		sizeof(level));
    658 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_ESP_NETWORK_LEVEL, &level,
    659 		sizeof(level));
    660 #ifdef IP_AUTH_TRANS_LEVEL
    661 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, &level,
    662 		sizeof(level));
    663 #else
    664 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_LEVEL, &level,
    665 		sizeof(level));
    666 #endif
    667 #ifdef IP_AUTH_NETWORK_LEVEL
    668 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_NETWORK_LEVEL, &level,
    669 		sizeof(level));
    670 #endif
    671     }
    672 #endif /*IPSEC_POLICY_IPSEC*/
    673 #endif /*IPSEC*/
    674 
    675 	/*
    676 	 * Send UDP
    677 	 */
    678 	if ((sndsock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
    679 		perror("socket(SOCK_DGRAM)");
    680 		exit(5);
    681 	}
    682 #ifdef SO_SNDBUF
    683 	if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
    684 		       sizeof(datalen)) < 0) {
    685 		perror("setsockopt(SO_SNDBUF)");
    686 		exit(6);
    687 	}
    688 #endif /* SO_SNDBUF */
    689 	if (options & SO_DEBUG)
    690 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
    691 				  (char *)&on, sizeof(on));
    692 	if (options & SO_DONTROUTE)
    693 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
    694 				  (char *)&on, sizeof(on));
    695 #ifdef USE_RFC2292BIS
    696 	if (rth) {/* XXX: there is no library to finalize the header... */
    697 		rth->ip6r_len = rth->ip6r_segleft * 2;
    698 		if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_RTHDR,
    699 			       (void *)rth, (rth->ip6r_len + 1) << 3)) {
    700 			Fprintf(stderr, "setsockopt(IPV6_RTHDR): %s\n",
    701 				strerror(errno));
    702 			exit(1);
    703 		}
    704 	}
    705 #else  /* old advanced API */
    706 	if (cmsg != NULL) {
    707 		inet6_rthdr_lasthop(cmsg, IPV6_RTHDR_LOOSE);
    708 		if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_PKTOPTIONS,
    709 			       rtbuf, cmsg->cmsg_len) < 0) {
    710 			Fprintf(stderr, "setsockopt(IPV6_PKTOPTIONS): %s\n",
    711 				strerror(errno));
    712 			exit(1);
    713 		}
    714 	}
    715 #endif /* USE_RFC2292BIS */
    716 #ifdef IPSEC
    717 #ifdef IPSEC_POLICY_IPSEC
    718 	/*
    719 	 * do not raise error even if setsockopt fails, kernel may have ipsec
    720 	 * turned off.
    721 	 */
    722 	if (setpolicy(sndsock, "in bypass") < 0)
    723 		errx(1, "%s", ipsec_strerror());
    724 	if (setpolicy(sndsock, "out bypass") < 0)
    725 		errx(1, "%s", ipsec_strerror());
    726 #else
    727     {
    728 	int level = IPSEC_LEVEL_BYPASS;
    729 
    730 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, &level,
    731 		sizeof(level));
    732 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_ESP_NETWORK_LEVEL, &level,
    733 		sizeof(level));
    734 #ifdef IP_AUTH_TRANS_LEVEL
    735 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, &level,
    736 		sizeof(level));
    737 #else
    738 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_LEVEL, &level,
    739 		sizeof(level));
    740 #endif
    741 #ifdef IP_AUTH_NETWORK_LEVEL
    742 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_NETWORK_LEVEL, &level,
    743 		sizeof(level));
    744 #endif
    745     }
    746 #endif /*IPSEC_POLICY_IPSEC*/
    747 #endif /*IPSEC*/
    748 
    749 	/*
    750 	 * Source selection
    751 	 */
    752 	bzero(&Src, sizeof(Src));
    753 	if (source) {
    754 		struct addrinfo hints, *res;
    755 		int error;
    756 
    757 		memset(&hints, 0, sizeof(hints));
    758 		hints.ai_family = AF_INET6;
    759 		hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
    760 		hints.ai_flags = AI_NUMERICHOST;
    761 		error = getaddrinfo(source, "0", &hints, &res);
    762 		if (error) {
    763 			Printf("traceroute6: %s: %s\n", source,
    764 			    gai_strerror(error));
    765 			exit(1);
    766 		}
    767 		if (res->ai_addrlen > sizeof(Src)) {
    768 			Printf("traceroute6: %s: %s\n", source,
    769 			    gai_strerror(error));
    770 			exit(1);
    771 		}
    772 		memcpy(&Src, res->ai_addr, res->ai_addrlen);
    773 		freeaddrinfo(res);
    774 	} else {
    775 		struct sockaddr_in6 Nxt;
    776 		int dummy, len;
    777 
    778 		Nxt = Dst;
    779 		Nxt.sin6_port = htons(DUMMY_PORT);
    780 		if (cmsg != NULL)
    781 			bcopy(inet6_rthdr_getaddr(cmsg, 1), &Nxt.sin6_addr,
    782 			      sizeof(Nxt.sin6_addr));
    783 		if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
    784 			perror("socket");
    785 			exit(1);
    786 		}
    787 		if (connect(dummy, (struct sockaddr *)&Nxt, Nxt.sin6_len) < 0) {
    788 			perror("connect");
    789 			exit(1);
    790 		}
    791 		len = sizeof(Src);
    792 		if (getsockname(dummy, (struct sockaddr *)&Src, &len) < 0) {
    793 			perror("getsockname");
    794 			exit(1);
    795 		}
    796 		if (getnameinfo((struct sockaddr *)&Src, Src.sin6_len,
    797 				src0, sizeof(src0), NULL, 0,
    798 				NI_NUMERICHOST | niflag)) {
    799 			Fprintf(stderr, "getnameinfo failed for source\n");
    800 			exit(1);
    801 		}
    802 		source = src0;
    803 		close(dummy);
    804 	}
    805 
    806 #if 1
    807 	ident = (getpid() & 0xffff) | 0x8000;
    808 #else
    809 	ident = 0;	/*let the kernel pick one*/
    810 #endif
    811 	Src.sin6_port = htons(ident);
    812 	if (bind(sndsock, (struct sockaddr *)&Src, Src.sin6_len) < 0) {
    813 		perror("bind");
    814 		exit(1);
    815 	}
    816 
    817 	if (ident == 0) {
    818 		int len;
    819 
    820 		len = sizeof(Src);
    821 		if (getsockname(sndsock, (struct sockaddr *)&Src, &i) < 0) {
    822 			perror("getsockname");
    823 			exit(1);
    824 		}
    825 		ident = ntohs(Src.sin6_port);
    826 	}
    827 
    828 	/*
    829 	 * Message to users
    830 	 */
    831 	if (getnameinfo((struct sockaddr *)&Dst, Dst.sin6_len, hbuf,
    832 			sizeof(hbuf), NULL, 0, NI_NUMERICHOST | niflag))
    833 		strlcpy(hbuf, "(invalid)", sizeof(hbuf));
    834 	Fprintf(stderr, "traceroute6");
    835 	Fprintf(stderr, " to %s (%s)", hostname, hbuf);
    836 	if (source)
    837 		Fprintf(stderr, " from %s", source);
    838 	Fprintf(stderr,
    839 		", %d hops max, %d byte packets\n",
    840 		max_hops, datalen);
    841 	(void) fflush(stderr);
    842 
    843 	if (first_hop > 1)
    844 		Printf("Skipping %d intermediate hops\n", first_hop - 1);
    845 
    846 	/*
    847 	 * Main loop
    848 	 */
    849 	for (hops = first_hop; hops <= max_hops; ++hops) {
    850 		struct in6_addr lastaddr;
    851 		int got_there = 0;
    852 		int unreachable = 0;
    853 
    854 		Printf("%2d ", hops);
    855 		bzero(&lastaddr, sizeof(lastaddr));
    856 		for (probe = 0; probe < nprobes; ++probe) {
    857 			int cc;
    858 			struct timeval t1, t2;
    859 			struct timezone tz;
    860 
    861 			(void) gettimeofday(&t1, &tz);
    862 			send_probe(++seq, hops);
    863 			while ((cc = wait_for_reply(rcvsock, &rcvmhdr))) {
    864 				(void) gettimeofday(&t2, &tz);
    865 				if ((i = packet_ok(&rcvmhdr, cc, seq))) {
    866 					if (! IN6_ARE_ADDR_EQUAL(&Rcv.sin6_addr,
    867 							    &lastaddr)) {
    868 						print(&rcvmhdr, cc);
    869 						lastaddr = Rcv.sin6_addr;
    870 					}
    871 					Printf("  %g ms", deltaT(&t1, &t2));
    872 					switch(i - 1) {
    873 					case ICMP6_DST_UNREACH_NOROUTE:
    874 						++unreachable;
    875 						Printf(" !N");
    876 						break;
    877 					case ICMP6_DST_UNREACH_ADMIN:
    878 						++unreachable;
    879 						Printf(" !P");
    880 						break;
    881 					case ICMP6_DST_UNREACH_NOTNEIGHBOR:
    882 						++unreachable;
    883 						Printf(" !S");
    884 						break;
    885 					case ICMP6_DST_UNREACH_ADDR:
    886 						++unreachable;
    887 						Printf(" !A");
    888 						break;
    889 					case ICMP6_DST_UNREACH_NOPORT:
    890 						if (rcvhlim >= 0 &&
    891 						    rcvhlim <= 1)
    892 							Printf(" !");
    893 						++got_there;
    894 						break;
    895 					}
    896 					break;
    897 				}
    898 			}
    899 			if (cc == 0)
    900 				Printf(" *");
    901 			(void) fflush(stdout);
    902 		}
    903 		putchar('\n');
    904 		if (got_there ||
    905 		    (unreachable > 0 && unreachable >= ((nprobes + 1) / 2))) {
    906 			exit(0);
    907 		}
    908 	}
    909 
    910 	exit(0);
    911 }
    912 
    913 int
    914 wait_for_reply(sock, mhdr)
    915 	int sock;
    916 	struct msghdr *mhdr;
    917 {
    918 #ifdef HAVE_POLL
    919 	struct pollfd pfd[1];
    920 	int cc = 0;
    921 
    922 	pfd[0].fd = sock;
    923 	pfd[0].events = POLLIN;
    924 	pfd[0].revents = 0;
    925 
    926 	if (poll(pfd, 1, waittime * 1000) > 0)
    927 		cc = recvmsg(rcvsock, mhdr, 0);
    928 
    929 	return(cc);
    930 #else
    931 	fd_set *fdsp;
    932 	struct timeval wait;
    933 	int cc = 0, fdsn;
    934 
    935 	fdsn = howmany(sock + 1, NFDBITS) * sizeof(fd_mask);
    936 	if ((fdsp = (fd_set *)malloc(fdsn)) == NULL)
    937 		err(1, "malloc");
    938 	memset(fdsp, 0, fdsn);
    939 	FD_SET(sock, fdsp);
    940 	wait.tv_sec = waittime; wait.tv_usec = 0;
    941 
    942 	if (select(sock+1, fdsp, (fd_set *)0, (fd_set *)0, &wait) > 0)
    943 		cc = recvmsg(rcvsock, mhdr, 0);
    944 
    945 	free(fdsp);
    946 	return(cc);
    947 #endif
    948 }
    949 
    950 #ifdef IPSEC
    951 #ifdef IPSEC_POLICY_IPSEC
    952 int
    953 setpolicy(so, policy)
    954 	int so;
    955 	char *policy;
    956 {
    957 	char *buf;
    958 
    959 	buf = ipsec_set_policy(policy, strlen(policy));
    960 	if (buf == NULL) {
    961 		warnx("%s", ipsec_strerror());
    962 		return -1;
    963 	}
    964 	(void)setsockopt(so, IPPROTO_IPV6, IPV6_IPSEC_POLICY,
    965 		buf, ipsec_get_policylen(buf));
    966 
    967 	free(buf);
    968 
    969 	return 0;
    970 }
    971 #endif
    972 #endif
    973 
    974 void
    975 send_probe(seq, hops)
    976 	int seq, hops;
    977 {
    978 	struct opacket *op = outpacket;
    979 	int i;
    980 
    981 	if(setsockopt(sndsock, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
    982 		      (char *)&hops, sizeof(hops)) < 0) {
    983 		perror("setsockopt IPV6_UNICAST_HOPS");
    984 	}
    985 
    986 	Dst.sin6_port = htons(port + seq);
    987 
    988 	op->seq = seq;
    989 	op->hops = hops;
    990 	(void) gettimeofday(&op->tv, &tz);
    991 
    992 	i = sendto(sndsock, (char *)outpacket, datalen , 0,
    993 		   (struct sockaddr *)&Dst, Dst.sin6_len);
    994 	if (i < 0 || i != datalen)  {
    995 		if (i<0)
    996 			perror("sendto");
    997 		Printf("traceroute6: wrote %s %d chars, ret=%d\n", hostname,
    998 		       datalen, i);
    999 		(void) fflush(stdout);
   1000 	}
   1001 }
   1002 
   1003 int
   1004 get_hoplim(mhdr)
   1005 	struct msghdr *mhdr;
   1006 {
   1007 	struct cmsghdr *cm;
   1008 
   1009 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
   1010 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
   1011 		if (cm->cmsg_level == IPPROTO_IPV6 &&
   1012 		    cm->cmsg_type == IPV6_HOPLIMIT &&
   1013 		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
   1014 			return(*(int *)CMSG_DATA(cm));
   1015 	}
   1016 
   1017 	return(-1);
   1018 }
   1019 
   1020 double
   1021 deltaT(t1p, t2p)
   1022 	struct timeval *t1p, *t2p;
   1023 {
   1024 	register double dt;
   1025 
   1026 	dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
   1027 	     (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
   1028 	return (dt);
   1029 }
   1030 
   1031 
   1032 /*
   1033  * Convert an ICMP "type" field to a printable string.
   1034  */
   1035 char *
   1036 pr_type(t0)
   1037 	int t0;
   1038 {
   1039 	u_char t = t0 & 0xff;
   1040 	char *cp;
   1041 
   1042 	switch (t) {
   1043 	case ICMP6_DST_UNREACH:
   1044 		cp = "Destination Unreachable";
   1045 		break;
   1046 	case ICMP6_PACKET_TOO_BIG:
   1047 		cp = "Pakcet Too Big";
   1048 		break;
   1049 	case ICMP6_TIME_EXCEEDED:
   1050 		cp = "Time Exceeded";
   1051 		break;
   1052 	case ICMP6_PARAM_PROB:
   1053 		cp = "Parameter Problem";
   1054 		break;
   1055 	case ICMP6_ECHO_REQUEST:
   1056 		cp = "Echo Request";
   1057 		break;
   1058 	case ICMP6_ECHO_REPLY:
   1059 		cp = "Echo Reply";
   1060 		break;
   1061 	case ICMP6_MEMBERSHIP_QUERY:
   1062 		cp = "Group Membership Query";
   1063 		break;
   1064 	case ICMP6_MEMBERSHIP_REPORT:
   1065 		cp = "Group Membership Report";
   1066 		break;
   1067 	case ICMP6_MEMBERSHIP_REDUCTION:
   1068 		cp = "Group Membership Reduction";
   1069 		break;
   1070 	case ND_ROUTER_SOLICIT:
   1071 		cp = "Router Solicitation";
   1072 		break;
   1073 	case ND_ROUTER_ADVERT:
   1074 		cp = "Router Advertisement";
   1075 		break;
   1076 	case ND_NEIGHBOR_SOLICIT:
   1077 		cp = "Neighbor Solicitation";
   1078 		break;
   1079 	case ND_NEIGHBOR_ADVERT:
   1080 		cp = "Neighbor Advertisement";
   1081 		break;
   1082 	case ND_REDIRECT:
   1083 		cp = "Redirect";
   1084 		break;
   1085 	default:
   1086 		cp = "Unknown";
   1087 		break;
   1088 	}
   1089 	return cp;
   1090 }
   1091 
   1092 
   1093 int
   1094 packet_ok(mhdr, cc, seq)
   1095 	struct msghdr *mhdr;
   1096 	int cc;
   1097 	int seq;
   1098 {
   1099 	register struct icmp6_hdr *icp;
   1100 	struct sockaddr_in6 *from = (struct sockaddr_in6 *)mhdr->msg_name;
   1101 	u_char type, code;
   1102 	char *buf = (char *)mhdr->msg_iov[0].iov_base;
   1103 	struct cmsghdr *cm;
   1104 	int *hlimp;
   1105 	char hbuf[NI_MAXHOST];
   1106 
   1107 #ifdef OLDRAWSOCKET
   1108 	int hlen;
   1109 	struct ip6_hdr *ip;
   1110 #endif
   1111 
   1112 #ifdef OLDRAWSOCKET
   1113 	ip = (struct ip6_hdr *) buf;
   1114 	hlen = sizeof(struct ip6_hdr);
   1115 	if (cc < hlen + sizeof(struct icmp6_hdr)) {
   1116 		if (verbose) {
   1117 			if (getnameinfo((struct sockaddr *)from, from->sin6_len,
   1118 			    hbuf, sizeof(hbuf), NULL, 0,
   1119 			    NI_NUMERICHOST | niflag) != 0)
   1120 				strlcpy(hbuf, "invalid", sizeof(hbuf));
   1121 			Printf("packet too short (%d bytes) from %s\n", cc,
   1122 			    hbuf);
   1123 		}
   1124 		return (0);
   1125 	}
   1126 	cc -= hlen;
   1127 	icp = (struct icmp6_hdr *)(buf + hlen);
   1128 #else
   1129 	if (cc < sizeof(struct icmp6_hdr)) {
   1130 		if (verbose) {
   1131 			if (getnameinfo((struct sockaddr *)from, from->sin6_len,
   1132 			    hbuf, sizeof(hbuf), NULL, 0,
   1133 			    NI_NUMERICHOST | niflag) != 0)
   1134 				strlcpy(hbuf, "invalid", sizeof(hbuf));
   1135 			Printf("data too short (%d bytes) from %s\n", cc, hbuf);
   1136 		}
   1137 		return(0);
   1138 	}
   1139 	icp = (struct icmp6_hdr *)buf;
   1140 #endif
   1141 	/* get optional information via advanced API */
   1142 	rcvpktinfo = NULL;
   1143 	hlimp = NULL;
   1144 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
   1145 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
   1146 		if (cm->cmsg_level == IPPROTO_IPV6 &&
   1147 		    cm->cmsg_type == IPV6_PKTINFO &&
   1148 		    cm->cmsg_len ==
   1149 		    CMSG_LEN(sizeof(struct in6_pktinfo)))
   1150 			rcvpktinfo = (struct in6_pktinfo *)(CMSG_DATA(cm));
   1151 
   1152 		if (cm->cmsg_level == IPPROTO_IPV6 &&
   1153 		    cm->cmsg_type == IPV6_HOPLIMIT &&
   1154 		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
   1155 			hlimp = (int *)CMSG_DATA(cm);
   1156 	}
   1157 	if (rcvpktinfo == NULL || hlimp == NULL) {
   1158 		warnx("failed to get received hop limit or packet info");
   1159 #if 0
   1160 		return(0);
   1161 #else
   1162 		rcvhlim = 0;	/*XXX*/
   1163 #endif
   1164 	}
   1165 	else
   1166 		rcvhlim = *hlimp;
   1167 
   1168 	type = icp->icmp6_type;
   1169 	code = icp->icmp6_code;
   1170 	if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT)
   1171 	 || type == ICMP6_DST_UNREACH) {
   1172 		struct ip6_hdr *hip;
   1173 		struct udphdr *up;
   1174 
   1175 		hip = (struct ip6_hdr *)(icp + 1);
   1176 		if ((up = get_udphdr(hip, (u_char *)(buf + cc))) == NULL) {
   1177 			if (verbose)
   1178 				warnx("failed to get upper layer header");
   1179 			return(0);
   1180 		}
   1181 		if (up->uh_sport == htons(ident) &&
   1182 		    up->uh_dport == htons(port+seq))
   1183 			return (type == ICMP6_TIME_EXCEEDED ? -1 : code + 1);
   1184 	}
   1185 	if (verbose) {
   1186 		int i;
   1187 		u_int8_t *p;
   1188 		char sbuf[NI_MAXHOST+1], dbuf[INET6_ADDRSTRLEN];
   1189 
   1190 		if (getnameinfo((struct sockaddr *)from, from->sin6_len,
   1191 		    sbuf, sizeof(sbuf), NULL, 0, NI_NUMERICHOST | niflag) != 0)
   1192 			strlcpy(sbuf, "invalid", sizeof(hbuf));
   1193 		Printf("\n%d bytes from %s to %s", cc, sbuf,
   1194 		    rcvpktinfo ? inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
   1195 					dbuf, sizeof(dbuf))
   1196 			       : "?");
   1197 		Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
   1198 		       icp->icmp6_code);
   1199 		p = (u_int8_t *)(icp + 1);
   1200 #define WIDTH	16
   1201 		for (i = 0; i < cc; i++) {
   1202 			if (i % WIDTH == 0)
   1203 				Printf("%04x:", i);
   1204 			if (i % 4 == 0)
   1205 				Printf(" ");
   1206 			Printf("%02x", p[i]);
   1207 			if (i % WIDTH == WIDTH - 1)
   1208 				Printf("\n");
   1209 		}
   1210 		if (cc % WIDTH != 0)
   1211 			Printf("\n");
   1212 	}
   1213 	return(0);
   1214 }
   1215 
   1216 /*
   1217  * Increment pointer until find the UDP header.
   1218  */
   1219 struct udphdr *
   1220 get_udphdr(ip6, lim)
   1221 	struct ip6_hdr *ip6;
   1222 	u_char *lim;
   1223 {
   1224 	u_char *cp = (u_char *)ip6, nh;
   1225 	int hlen;
   1226 
   1227 	if (cp + sizeof(*ip6) >= lim)
   1228 		return(NULL);
   1229 
   1230 	nh = ip6->ip6_nxt;
   1231 	cp += sizeof(struct ip6_hdr);
   1232 
   1233 	while(lim - cp >= 8) {
   1234 		switch(nh) {
   1235 		 case IPPROTO_ESP:
   1236 		 case IPPROTO_TCP:
   1237 		 case IPPROTO_ICMPV6:
   1238 			 return(NULL);
   1239 		 case IPPROTO_UDP:
   1240 			 return((struct udphdr *)cp);
   1241 		 case IPPROTO_FRAGMENT:
   1242 			 hlen = sizeof(struct ip6_frag);
   1243 			 nh = ((struct ip6_frag *)cp)->ip6f_nxt;
   1244 			 break;
   1245 		 case IPPROTO_AH:
   1246 			 hlen = (((struct ip6_ext *)cp)->ip6e_len + 2) << 2;
   1247 			 nh = ((struct ip6_ext *)cp)->ip6e_nxt;
   1248 			 break;
   1249 		  default:
   1250 			  hlen = (((struct ip6_ext *)cp)->ip6e_len + 1) << 3;
   1251 			  nh = ((struct ip6_ext *)cp)->ip6e_nxt;
   1252 			  break;
   1253 		}
   1254 
   1255 		cp += hlen;
   1256 	}
   1257 
   1258 	return(NULL);
   1259 }
   1260 
   1261 void
   1262 print(mhdr, cc)
   1263 	struct msghdr *mhdr;
   1264 	int cc;
   1265 {
   1266 	struct sockaddr_in6 *from = (struct sockaddr_in6 *)mhdr->msg_name;
   1267 	char hbuf[NI_MAXHOST];
   1268 
   1269 	if (getnameinfo((struct sockaddr *)from, from->sin6_len,
   1270 	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST | niflag) != 0)
   1271 		strlcpy(hbuf, "invalid", sizeof(hbuf));
   1272 	if (nflag)
   1273 		Printf(" %s", hbuf);
   1274 	else if (lflag)
   1275 		Printf(" %s (%s)", inetname((struct sockaddr *)from), hbuf);
   1276 	else
   1277 		Printf(" %s", inetname((struct sockaddr *)from));
   1278 
   1279 	if (verbose) {
   1280 #ifdef OLDRAWSOCKET
   1281 		Printf(" %d bytes to %s", cc,
   1282 		    rcvpktinfo ? inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
   1283 					hbuf, sizeof(hbuf))
   1284 			       : "?");
   1285 #else
   1286 		Printf(" %d bytes of data to %s", cc,
   1287 		    rcvpktinfo ?  inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
   1288 					hbuf, sizeof(hbuf))
   1289 			       : "?");
   1290 #endif
   1291 	}
   1292 }
   1293 
   1294 /*
   1295  * Subtract 2 timeval structs:  out = out - in.
   1296  * Out is assumed to be >= in.
   1297  */
   1298 void
   1299 tvsub(out, in)
   1300 	register struct timeval *out, *in;
   1301 {
   1302 	if ((out->tv_usec -= in->tv_usec) < 0)   {
   1303 		out->tv_sec--;
   1304 		out->tv_usec += 1000000;
   1305 	}
   1306 	out->tv_sec -= in->tv_sec;
   1307 }
   1308 
   1309 
   1310 /*
   1311  * Construct an Internet address representation.
   1312  * If the nflag has been supplied, give
   1313  * numeric value, otherwise try for symbolic name.
   1314  */
   1315 const char *
   1316 inetname(sa)
   1317 	struct sockaddr *sa;
   1318 {
   1319 	register char *cp;
   1320 	static char line[NI_MAXHOST];
   1321 	static char domain[MAXHOSTNAMELEN + 1];
   1322 	static int first = 1;
   1323 
   1324 	if (first && !nflag) {
   1325 		first = 0;
   1326 		if (gethostname(domain, sizeof(domain)) == 0 &&
   1327 		    (cp = index(domain, '.')))
   1328 			(void) strlcpy(domain, cp + 1, sizeof(domain));
   1329 		else
   1330 			domain[0] = 0;
   1331 	}
   1332 	cp = NULL;
   1333 	if (!nflag) {
   1334 		if (getnameinfo(sa, sa->sa_len, line, sizeof(line), NULL, 0,
   1335 		    NI_NAMEREQD) == 0) {
   1336 			if ((cp = index(line, '.')) &&
   1337 			    !strcmp(cp + 1, domain))
   1338 				*cp = 0;
   1339 			cp = line;
   1340 		}
   1341 	}
   1342 	if (cp)
   1343 		return cp;
   1344 
   1345 	if (getnameinfo(sa, sa->sa_len, line, sizeof(line), NULL, 0,
   1346 	    NI_NUMERICHOST | niflag) != 0)
   1347 		strlcpy(line, "invalid", sizeof(line));
   1348 	return line;
   1349 }
   1350 
   1351 void
   1352 usage()
   1353 {
   1354 	(void)fprintf(stderr,
   1355 "usage: traceroute6 [-dlnrv] [-f firsthop] [-g gateway] [-m hoplimit] [-p port]\n"
   1356 "       [-q probes] [-s src] [-w waittime] target [datalen]\n");
   1357 	exit(1);
   1358 }
   1359