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