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