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