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