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