1 /*	$KAME: traceroute6.c,v 1.42 2001/05/08 04:36:41 itojun Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * @(#) Copyright (c) 1990, 1993 The Regents of the University of California.  All rights reserved.
32  * @(#)traceroute.c	8.1 (Berkeley) 6/6/93
33  * $FreeBSD: src/usr.sbin/traceroute6/traceroute6.c,v 1.4.2.4 2001/07/03 11:02:18 ume Exp $
34  * $DragonFly: src/usr.sbin/traceroute6/traceroute6.c,v 1.3 2003/11/03 19:31:44 eirikn Exp $
35  */
36 
37 /*-
38  * Copyright (c) 1990, 1993
39  *	The Regents of the University of California.  All rights reserved.
40  *
41  * This code is derived from software contributed to Berkeley by
42  * Van Jacobson.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. All advertising materials mentioning features or use of this software
53  *    must display the following acknowledgement:
54  *	This product includes software developed by the University of
55  *	California, Berkeley and its contributors.
56  * 4. Neither the name of the University nor the names of its contributors
57  *    may be used to endorse or promote products derived from this software
58  *    without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70  * SUCH DAMAGE.
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 a 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 
251 #include <netinet/in.h>
252 
253 #include <arpa/inet.h>
254 
255 #include <netdb.h>
256 #include <stdio.h>
257 #include <err.h>
258 #ifdef HAVE_POLL
259 #include <poll.h>
260 #endif
261 #include <errno.h>
262 #include <stdlib.h>
263 #include <string.h>
264 #include <unistd.h>
265 
266 #include <netinet/ip6.h>
267 #include <netinet/icmp6.h>
268 #include <netinet/udp.h>
269 
270 #ifdef IPSEC
271 #include <net/route.h>
272 #include <netinet6/ipsec.h>
273 #endif
274 
275 #define DUMMY_PORT 10010
276 
277 #define	MAXPACKET	65535	/* max ip packet size */
278 #ifndef MAXHOSTNAMELEN
279 #define MAXHOSTNAMELEN	64
280 #endif
281 
282 #ifndef FD_SET
283 #define NFDBITS         (8*sizeof(fd_set))
284 #define FD_SETSIZE      NFDBITS
285 #define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
286 #define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
287 #define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
288 #define FD_ZERO(p)      bzero((char *)(p), sizeof(*(p)))
289 #endif
290 
291 #define Fprintf (void)fprintf
292 #define Sprintf (void)sprintf
293 #define Printf (void)printf
294 
295 #ifndef HAVE_GETIPNODEBYNAME
296 #define getipnodebyname(x, y, z, u)	gethostbyname2((x), (y))
297 #define freehostent(x)
298 #endif
299 
300 /*
301  * format of a (udp) probe packet.
302  */
303 struct opacket {
304 	u_char seq;		/* sequence number of this packet */
305 	u_char hops;		/* hop limit of the packet */
306 	struct timeval tv;	/* time packet left */
307 };
308 
309 u_char	packet[512];		/* last inbound (icmp) packet */
310 struct opacket	*outpacket;	/* last output (udp) packet */
311 
312 int	main(int, char *[]);
313 int	wait_for_reply(int, struct msghdr *);
314 #ifdef IPSEC
315 #ifdef IPSEC_POLICY_IPSEC
316 int	setpolicy(int so, char *policy);
317 #endif
318 #endif
319 void	send_probe(int, int);
320 struct udphdr *get_udphdr(struct ip6_hdr *, u_char *);
321 int	get_hoplim(struct msghdr *);
322 double	deltaT(struct timeval *, struct timeval *);
323 char	*pr_type(int);
324 int	packet_ok(struct msghdr *, int, int);
325 void	print(struct msghdr *, int);
326 void	tvsub(struct timeval *, struct timeval *);
327 const char *inetname(struct sockaddr *);
328 void	usage(void);
329 
330 int rcvsock;			/* receive (icmp) socket file descriptor */
331 int sndsock;			/* send (udp) socket file descriptor */
332 struct timezone tz;		/* leftover */
333 
334 struct msghdr rcvmhdr;
335 struct iovec rcviov[2];
336 int rcvhlim;
337 struct in6_pktinfo *rcvpktinfo;
338 
339 struct sockaddr_in6 Src, Dst, Rcv;
340 int datalen;			/* How much data */
341 /* XXX: 2064 = 127(max hops in type 0 rthdr) * sizeof(ip6_hdr) + 16(margin) */
342 char rtbuf[2064];
343 #ifdef USE_RFC2292BIS
344 struct ip6_rthdr *rth;
345 #endif
346 struct cmsghdr *cmsg;
347 
348 char *source = 0;
349 char *hostname;
350 
351 int nprobes = 3;
352 int first_hop = 1;
353 int max_hops = 30;
354 u_short ident;
355 u_short port = 32768+666;	/* start udp dest port # for probe packets */
356 int options;			/* socket options */
357 int verbose;
358 int waittime = 5;		/* time to wait for response (in seconds) */
359 int nflag;			/* print addresses numerically */
360 int lflag;			/* print both numerical address & hostname */
361 
362 #ifdef KAME_SCOPEID
363 const int niflag = NI_WITHSCOPEID;
364 #else
365 const int niflag = 0;
366 #endif
367 
368 int
369 main(argc, argv)
370 	int argc;
371 	char *argv[];
372 {
373 	struct hostent *hp;
374 	int error;
375 	struct addrinfo hints, *res;
376 	int ch, i, on, probe, seq, hops, rcvcmsglen;
377 	static u_char *rcvcmsgbuf;
378 	char hbuf[NI_MAXHOST], src0[NI_MAXHOST];
379 	char *ep;
380 
381 	/*
382 	 * Receive ICMP
383 	 */
384 	if ((rcvsock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0) {
385 		perror("socket(ICMPv6)");
386 		exit(5);
387 	}
388 
389 	/* revoke privs */
390 	seteuid(getuid());
391 	setuid(getuid());
392 
393 	/* set a minimum set of socket options */
394 	on = 1;
395 	/* specify to tell receiving interface */
396 #ifdef IPV6_RECVPKTINFO
397 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
398 		       sizeof(on)) < 0)
399 		err(1, "setsockopt(IPV6_RECVPKTINFO)");
400 #else  /* old adv. API */
401 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_PKTINFO, &on,
402 		       sizeof(on)) < 0)
403 		err(1, "setsockopt(IPV6_PKTINFO)");
404 #endif
405 
406 	/* specify to tell value of hoplimit field of received IP6 hdr */
407 #ifdef IPV6_RECVHOPLIMIT
408 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
409 		       sizeof(on)) < 0)
410 		err(1, "setsockopt(IPV6_RECVHOPLIMIT)");
411 #else  /* old adv. API */
412 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_HOPLIMIT, &on,
413 		       sizeof(on)) < 0)
414 		err(1, "setsockopt(IPV6_HOPLIMIT)");
415 #endif
416 
417 	seq = 0;
418 
419 	while ((ch = getopt(argc, argv, "df:g:lm:np:q:rs:w:v")) != -1)
420 		switch(ch) {
421 		case 'd':
422 			options |= SO_DEBUG;
423 			break;
424 		case 'f':
425 			ep = NULL;
426 			first_hop = strtoul(optarg, &ep, 0);
427 			if (!*argv || *ep) {
428 				Fprintf(stderr,
429 				    "traceroute6: invalid min hoplimit.\n");
430 				exit(1);
431 			}
432 			if (first_hop > max_hops) {
433 				Fprintf(stderr,
434 				    "traceroute6: min hoplimit must be <= %d.\n", max_hops);
435 				exit(1);
436 			}
437 			break;
438 		case 'g':
439 			hp = getipnodebyname(optarg, AF_INET6, 0, &h_errno);
440 			if (hp == NULL) {
441 				Fprintf(stderr,
442 				    "traceroute6: unknown host %s\n", optarg);
443 				exit(1);
444 			}
445 #ifdef USE_RFC2292BIS
446 			if (rth == NULL) {
447 				/*
448 				 * XXX: We can't detect the number of
449 				 * intermediate nodes yet.
450 				 */
451 				if ((rth = inet6_rth_init((void *)rtbuf,
452 							 sizeof(rtbuf),
453 							 IPV6_RTHDR_TYPE_0,
454 							 0)) == NULL) {
455 					Fprintf(stderr,
456 						"inet6_rth_init failed.\n");
457 					exit(1);
458 				}
459 			}
460 			if (inet6_rth_add((void *)rth,
461 					  (struct in6_addr *)hp->h_addr)) {
462 				Fprintf(stderr,
463 					"inet6_rth_add failed for %s\n",
464 					optarg);
465 				exit(1);
466 			}
467 #else  /* old advanced API */
468 			if (cmsg == NULL)
469 				cmsg = inet6_rthdr_init(rtbuf, IPV6_RTHDR_TYPE_0);
470 			inet6_rthdr_add(cmsg, (struct in6_addr *)hp->h_addr, IPV6_RTHDR_LOOSE);
471 #endif
472 			freehostent(hp);
473 			break;
474 		case 'l':
475 			lflag++;
476 			break;
477 		case 'm':
478 			ep = NULL;
479 			max_hops = strtoul(optarg, &ep, 0);
480 			if (!*argv || *ep) {
481 				Fprintf(stderr,
482 				    "traceroute6: invalid max hoplimit.\n");
483 				exit(1);
484 			}
485 			if (max_hops < first_hop) {
486 				Fprintf(stderr,
487 				    "traceroute6: max hoplimit must be >= %d.\n", first_hop);
488 				exit(1);
489 			}
490 			break;
491 		case 'n':
492 			nflag++;
493 			break;
494 		case 'p':
495 			ep = NULL;
496 			port = strtoul(optarg, &ep, 0);
497 			if (!*argv || *ep) {
498 				Fprintf(stderr,
499 				    "traceroute6: port.\n");
500 				exit(1);
501 			}
502 			if (port < 1) {
503 				Fprintf(stderr,
504 				    "traceroute6: port must be >0.\n");
505 				exit(1);
506 			}
507 			break;
508 		case 'q':
509 			ep = NULL;
510 			nprobes = strtoul(optarg, &ep, 0);
511 			if (!*argv || *ep) {
512 				Fprintf(stderr,
513 				    "traceroute6: invalid nprobes.\n");
514 				exit(1);
515 			}
516 			if (nprobes < 1) {
517 				Fprintf(stderr,
518 				    "traceroute6: nprobes must be >0.\n");
519 				exit(1);
520 			}
521 			break;
522 		case 'r':
523 			options |= SO_DONTROUTE;
524 			break;
525 		case 's':
526 			/*
527 			 * set the ip source address of the outbound
528 			 * probe (e.g., on a multi-homed host).
529 			 */
530 			source = optarg;
531 			break;
532 		case 'v':
533 			verbose++;
534 			break;
535 		case 'w':
536 			ep = NULL;
537 			waittime = strtoul(optarg, &ep, 0);
538 			if (!*argv || *ep) {
539 				Fprintf(stderr,
540 				    "traceroute6: invalid wait time.\n");
541 				exit(1);
542 			}
543 			if (waittime <= 1) {
544 				Fprintf(stderr,
545 				    "traceroute6: wait must be >1 sec.\n");
546 				exit(1);
547 			}
548 			break;
549 		default:
550 			usage();
551 		}
552 	argc -= optind;
553 	argv += optind;
554 
555 	if (argc < 1 || argc > 2)
556 		usage();
557 
558 #if 1
559 	setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
560 #else
561 	setlinebuf (stdout);
562 #endif
563 
564 	memset(&hints, 0, sizeof(hints));
565 	hints.ai_family = PF_INET6;
566 	hints.ai_socktype = SOCK_RAW;
567 	hints.ai_protocol = IPPROTO_ICMPV6;
568 	hints.ai_flags = AI_CANONNAME;
569 	error = getaddrinfo(*argv, NULL, &hints, &res);
570 	if (error) {
571 		(void)fprintf(stderr,
572 			      "traceroute6: %s\n", gai_strerror(error));
573 		exit(1);
574 	}
575 	if (res->ai_addrlen != sizeof(Dst)) {
576 		(void)fprintf(stderr,
577 			      "traceroute6: size of sockaddr mismatch\n");
578 		exit(1);
579 	}
580 	memcpy(&Dst, res->ai_addr, res->ai_addrlen);
581 	hostname = res->ai_canonname ? strdup(res->ai_canonname) : *argv;
582 	if (!hostname) {
583 		(void)fprintf(stderr, "traceroute6: not enough core\n");
584 		exit(1);
585 	}
586 
587 	if (*++argv) {
588 		ep = NULL;
589 		datalen = strtoul(*argv, &ep, 0);
590 		if (!*argv || *ep) {
591 			Fprintf(stderr,
592 			    "traceroute6: invalid packet length.\n");
593 			exit(1);
594 		}
595 	}
596 	if (datalen < 0 || datalen >= MAXPACKET - sizeof(struct opacket)) {
597 		Fprintf(stderr,
598 		    "traceroute6: packet size must be 0 <= s < %ld.\n",
599 		    (long)(MAXPACKET - sizeof(struct opacket)));
600 		exit(1);
601 	}
602 	datalen += sizeof(struct opacket);
603 	outpacket = (struct opacket *)malloc((unsigned)datalen);
604 	if (! outpacket) {
605 		perror("malloc");
606 		exit(1);
607 	}
608 	(void) bzero((char *)outpacket, datalen);
609 
610 	/* initialize msghdr for receiving packets */
611 	rcviov[0].iov_base = (caddr_t)packet;
612 	rcviov[0].iov_len = sizeof(packet);
613 	rcvmhdr.msg_name = (caddr_t)&Rcv;
614 	rcvmhdr.msg_namelen = sizeof(Rcv);
615 	rcvmhdr.msg_iov = rcviov;
616 	rcvmhdr.msg_iovlen = 1;
617 	rcvcmsglen = CMSG_SPACE(sizeof(struct in6_pktinfo))
618 		+ CMSG_SPACE(sizeof(int));
619 	if ((rcvcmsgbuf = malloc(rcvcmsglen)) == NULL) {
620 		Fprintf(stderr, "traceroute6: malloc failed\n");
621 		exit(1);
622 	}
623 	rcvmhdr.msg_control = (caddr_t) rcvcmsgbuf;
624 	rcvmhdr.msg_controllen = rcvcmsglen;
625 
626 	if (options & SO_DEBUG)
627 		(void) setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
628 				  (char *)&on, sizeof(on));
629 	if (options & SO_DONTROUTE)
630 		(void) setsockopt(rcvsock, SOL_SOCKET, SO_DONTROUTE,
631 				  (char *)&on, sizeof(on));
632 #ifdef IPSEC
633 #ifdef IPSEC_POLICY_IPSEC
634 	/*
635 	 * do not raise error even if setsockopt fails, kernel may have ipsec
636 	 * turned off.
637 	 */
638 	if (setpolicy(rcvsock, "in bypass") < 0)
639 		errx(1, "%s", ipsec_strerror());
640 	if (setpolicy(rcvsock, "out bypass") < 0)
641 		errx(1, "%s", ipsec_strerror());
642 #else
643     {
644 	int level = IPSEC_LEVEL_NONE;
645 
646 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, &level,
647 		sizeof(level));
648 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_ESP_NETWORK_LEVEL, &level,
649 		sizeof(level));
650 #ifdef IP_AUTH_TRANS_LEVEL
651 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, &level,
652 		sizeof(level));
653 #else
654 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_LEVEL, &level,
655 		sizeof(level));
656 #endif
657 #ifdef IP_AUTH_NETWORK_LEVEL
658 	(void)setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_NETWORK_LEVEL, &level,
659 		sizeof(level));
660 #endif
661     }
662 #endif /*IPSEC_POLICY_IPSEC*/
663 #endif /*IPSEC*/
664 
665 	/*
666 	 * Send UDP
667 	 */
668 	if ((sndsock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
669 		perror("socket(SOCK_DGRAM)");
670 		exit(5);
671 	}
672 #ifdef SO_SNDBUF
673 	if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
674 		       sizeof(datalen)) < 0) {
675 		perror("setsockopt(SO_SNDBUF)");
676 		exit(6);
677 	}
678 #endif /* SO_SNDBUF */
679 	if (options & SO_DEBUG)
680 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
681 				  (char *)&on, sizeof(on));
682 	if (options & SO_DONTROUTE)
683 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
684 				  (char *)&on, sizeof(on));
685 #ifdef USE_RFC2292BIS
686 	if (rth) {/* XXX: there is no library to finalize the header... */
687 		rth->ip6r_len = rth->ip6r_segleft * 2;
688 		if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_RTHDR,
689 			       (void *)rth, (rth->ip6r_len + 1) << 3)) {
690 			Fprintf(stderr, "setsockopt(IPV6_RTHDR): %s\n",
691 				strerror(errno));
692 			exit(1);
693 		}
694 	}
695 #else  /* old advanced API */
696 	if (cmsg != NULL) {
697 		inet6_rthdr_lasthop(cmsg, IPV6_RTHDR_LOOSE);
698 		if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_PKTOPTIONS,
699 			       rtbuf, cmsg->cmsg_len) < 0) {
700 			Fprintf(stderr, "setsockopt(IPV6_PKTOPTIONS): %s\n",
701 				strerror(errno));
702 			exit(1);
703 		}
704 	}
705 #endif /* USE_RFC2292BIS */
706 #ifdef IPSEC
707 #ifdef IPSEC_POLICY_IPSEC
708 	/*
709 	 * do not raise error even if setsockopt fails, kernel may have ipsec
710 	 * turned off.
711 	 */
712 	if (setpolicy(sndsock, "in bypass") < 0)
713 		errx(1, "%s", ipsec_strerror());
714 	if (setpolicy(sndsock, "out bypass") < 0)
715 		errx(1, "%s", ipsec_strerror());
716 #else
717     {
718 	int level = IPSEC_LEVEL_BYPASS;
719 
720 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, &level,
721 		sizeof(level));
722 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_ESP_NETWORK_LEVEL, &level,
723 		sizeof(level));
724 #ifdef IP_AUTH_TRANS_LEVEL
725 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, &level,
726 		sizeof(level));
727 #else
728 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_LEVEL, &level,
729 		sizeof(level));
730 #endif
731 #ifdef IP_AUTH_NETWORK_LEVEL
732 	(void)setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_NETWORK_LEVEL, &level,
733 		sizeof(level));
734 #endif
735     }
736 #endif /*IPSEC_POLICY_IPSEC*/
737 #endif /*IPSEC*/
738 
739 	/*
740 	 * Source selection
741 	 */
742 	bzero(&Src, sizeof(Src));
743 	if (source) {
744 		struct addrinfo hints, *res;
745 		int error;
746 
747 		memset(&hints, 0, sizeof(hints));
748 		hints.ai_family = AF_INET6;
749 		hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
750 		hints.ai_flags = AI_NUMERICHOST;
751 		error = getaddrinfo(source, "0", &hints, &res);
752 		if (error) {
753 			Printf("traceroute6: %s: %s\n", source,
754 			    gai_strerror(error));
755 			exit(1);
756 		}
757 		if (res->ai_addrlen > sizeof(Src)) {
758 			Printf("traceroute6: %s: %s\n", source,
759 			    gai_strerror(error));
760 			exit(1);
761 		}
762 		memcpy(&Src, res->ai_addr, res->ai_addrlen);
763 		freeaddrinfo(res);
764 	} else {
765 		struct sockaddr_in6 Nxt;
766 		int dummy, len;
767 
768 		Nxt = Dst;
769 		Nxt.sin6_port = htons(DUMMY_PORT);
770 		if (cmsg != NULL)
771 			bcopy(inet6_rthdr_getaddr(cmsg, 1), &Nxt.sin6_addr,
772 			      sizeof(Nxt.sin6_addr));
773 		if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
774 			perror("socket");
775 			exit(1);
776 		}
777 		if (connect(dummy, (struct sockaddr *)&Nxt, Nxt.sin6_len) < 0) {
778 			perror("connect");
779 			exit(1);
780 		}
781 		len = sizeof(Src);
782 		if (getsockname(dummy, (struct sockaddr *)&Src, &len) < 0) {
783 			perror("getsockname");
784 			exit(1);
785 		}
786 		if (getnameinfo((struct sockaddr *)&Src, Src.sin6_len,
787 				src0, sizeof(src0), NULL, 0,
788 				NI_NUMERICHOST | niflag)) {
789 			Fprintf(stderr, "getnameinfo failed for source\n");
790 			exit(1);
791 		}
792 		source = src0;
793 		close(dummy);
794 	}
795 
796 #if 1
797 	ident = (getpid() & 0xffff) | 0x8000;
798 #else
799 	ident = 0;	/*let the kernel pick one*/
800 #endif
801 	Src.sin6_port = htons(ident);
802 	if (bind(sndsock, (struct sockaddr *)&Src, Src.sin6_len) < 0) {
803 		perror("bind");
804 		exit(1);
805 	}
806 
807 	if (ident == 0) {
808 		int len;
809 
810 		len = sizeof(Src);
811 		if (getsockname(sndsock, (struct sockaddr *)&Src, &i) < 0) {
812 			perror("getsockname");
813 			exit(1);
814 		}
815 		ident = ntohs(Src.sin6_port);
816 	}
817 
818 	/*
819 	 * Message to users
820 	 */
821 	if (getnameinfo((struct sockaddr *)&Dst, Dst.sin6_len, hbuf,
822 			sizeof(hbuf), NULL, 0, NI_NUMERICHOST | niflag))
823 		strlcpy(hbuf, "(invalid)", sizeof(hbuf));
824 	Fprintf(stderr, "traceroute6");
825 	Fprintf(stderr, " to %s (%s)", hostname, hbuf);
826 	if (source)
827 		Fprintf(stderr, " from %s", source);
828 	Fprintf(stderr,
829 		", %d hops max, %d byte packets\n",
830 		max_hops, datalen);
831 	(void) fflush(stderr);
832 
833 	if (first_hop > 1)
834 		Printf("Skipping %d intermediate hops\n", first_hop - 1);
835 
836 	/*
837 	 * Main loop
838 	 */
839 	for (hops = first_hop; hops <= max_hops; ++hops) {
840 		struct in6_addr lastaddr;
841 		int got_there = 0;
842 		int unreachable = 0;
843 
844 		Printf("%2d ", hops);
845 		bzero(&lastaddr, sizeof(lastaddr));
846 		for (probe = 0; probe < nprobes; ++probe) {
847 			int cc;
848 			struct timeval t1, t2;
849 			struct timezone tz;
850 
851 			(void) gettimeofday(&t1, &tz);
852 			send_probe(++seq, hops);
853 			while ((cc = wait_for_reply(rcvsock, &rcvmhdr))) {
854 				(void) gettimeofday(&t2, &tz);
855 				if ((i = packet_ok(&rcvmhdr, cc, seq))) {
856 					if (! IN6_ARE_ADDR_EQUAL(&Rcv.sin6_addr,
857 							    &lastaddr)) {
858 						print(&rcvmhdr, cc);
859 						lastaddr = Rcv.sin6_addr;
860 					}
861 					Printf("  %g ms", deltaT(&t1, &t2));
862 					switch(i - 1) {
863 					case ICMP6_DST_UNREACH_NOROUTE:
864 						++unreachable;
865 						Printf(" !N");
866 						break;
867 					case ICMP6_DST_UNREACH_ADMIN:
868 						++unreachable;
869 						Printf(" !P");
870 						break;
871 					case ICMP6_DST_UNREACH_NOTNEIGHBOR:
872 						++unreachable;
873 						Printf(" !S");
874 						break;
875 					case ICMP6_DST_UNREACH_ADDR:
876 						++unreachable;
877 						Printf(" !A");
878 						break;
879 					case ICMP6_DST_UNREACH_NOPORT:
880 						if (rcvhlim >= 0 &&
881 						    rcvhlim <= 1)
882 							Printf(" !");
883 						++got_there;
884 						break;
885 					}
886 					break;
887 				}
888 			}
889 			if (cc == 0)
890 				Printf(" *");
891 			(void) fflush(stdout);
892 		}
893 		putchar('\n');
894 		if (got_there ||
895 		    (unreachable > 0 && unreachable >= ((nprobes + 1) / 2))) {
896 			exit(0);
897 		}
898 	}
899 
900 	exit(0);
901 }
902 
903 int
904 wait_for_reply(sock, mhdr)
905 	int sock;
906 	struct msghdr *mhdr;
907 {
908 #ifdef HAVE_POLL
909 	struct pollfd pfd[1];
910 	int cc = 0;
911 
912 	pfd[0].fd = sock;
913 	pfd[0].events = POLLIN;
914 	pfd[0].revents = 0;
915 
916 	if (poll(pfd, 1, waittime * 1000) > 0)
917 		cc = recvmsg(rcvsock, mhdr, 0);
918 
919 	return(cc);
920 #else
921 	fd_set *fdsp;
922 	struct timeval wait;
923 	int cc = 0, fdsn;
924 
925 	fdsn = howmany(sock + 1, NFDBITS) * sizeof(fd_mask);
926 	if ((fdsp = (fd_set *)malloc(fdsn)) == NULL)
927 		err(1, "malloc");
928 	memset(fdsp, 0, fdsn);
929 	FD_SET(sock, fdsp);
930 	wait.tv_sec = waittime; wait.tv_usec = 0;
931 
932 	if (select(sock+1, fdsp, (fd_set *)0, (fd_set *)0, &wait) > 0)
933 		cc = recvmsg(rcvsock, mhdr, 0);
934 
935 	free(fdsp);
936 	return(cc);
937 #endif
938 }
939 
940 #ifdef IPSEC
941 #ifdef IPSEC_POLICY_IPSEC
942 int
943 setpolicy(so, policy)
944 	int so;
945 	char *policy;
946 {
947 	char *buf;
948 
949 	buf = ipsec_set_policy(policy, strlen(policy));
950 	if (buf == NULL) {
951 		warnx("%s", ipsec_strerror());
952 		return -1;
953 	}
954 	(void)setsockopt(so, IPPROTO_IPV6, IPV6_IPSEC_POLICY,
955 		buf, ipsec_get_policylen(buf));
956 
957 	free(buf);
958 
959 	return 0;
960 }
961 #endif
962 #endif
963 
964 void
965 send_probe(seq, hops)
966 	int seq, hops;
967 {
968 	struct opacket *op = outpacket;
969 	int i;
970 
971 	if(setsockopt(sndsock, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
972 		      (char *)&hops, sizeof(hops)) < 0) {
973 		perror("setsockopt IPV6_UNICAST_HOPS");
974 	}
975 
976 	Dst.sin6_port = htons(port + seq);
977 
978 	op->seq = seq;
979 	op->hops = hops;
980 	(void) gettimeofday(&op->tv, &tz);
981 
982 	i = sendto(sndsock, (char *)outpacket, datalen , 0,
983 		   (struct sockaddr *)&Dst, Dst.sin6_len);
984 	if (i < 0 || i != datalen)  {
985 		if (i<0)
986 			perror("sendto");
987 		Printf("traceroute6: wrote %s %d chars, ret=%d\n", hostname,
988 		       datalen, i);
989 		(void) fflush(stdout);
990 	}
991 }
992 
993 int
994 get_hoplim(mhdr)
995 	struct msghdr *mhdr;
996 {
997 	struct cmsghdr *cm;
998 
999 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1000 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1001 		if (cm->cmsg_level == IPPROTO_IPV6 &&
1002 		    cm->cmsg_type == IPV6_HOPLIMIT &&
1003 		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
1004 			return(*(int *)CMSG_DATA(cm));
1005 	}
1006 
1007 	return(-1);
1008 }
1009 
1010 double
1011 deltaT(t1p, t2p)
1012 	struct timeval *t1p, *t2p;
1013 {
1014 	register double dt;
1015 
1016 	dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
1017 	     (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
1018 	return (dt);
1019 }
1020 
1021 
1022 /*
1023  * Convert an ICMP "type" field to a printable string.
1024  */
1025 char *
1026 pr_type(t0)
1027 	int t0;
1028 {
1029 	u_char t = t0 & 0xff;
1030 	char *cp;
1031 
1032 	switch (t) {
1033 	case ICMP6_DST_UNREACH:
1034 		cp = "Destination Unreachable";
1035 		break;
1036 	case ICMP6_PACKET_TOO_BIG:
1037 		cp = "Pakcet Too Big";
1038 		break;
1039 	case ICMP6_TIME_EXCEEDED:
1040 		cp = "Time Exceeded";
1041 		break;
1042 	case ICMP6_PARAM_PROB:
1043 		cp = "Parameter Problem";
1044 		break;
1045 	case ICMP6_ECHO_REQUEST:
1046 		cp = "Echo Request";
1047 		break;
1048 	case ICMP6_ECHO_REPLY:
1049 		cp = "Echo Reply";
1050 		break;
1051 	case ICMP6_MEMBERSHIP_QUERY:
1052 		cp = "Group Membership Query";
1053 		break;
1054 	case ICMP6_MEMBERSHIP_REPORT:
1055 		cp = "Group Membership Report";
1056 		break;
1057 	case ICMP6_MEMBERSHIP_REDUCTION:
1058 		cp = "Group Membership Reduction";
1059 		break;
1060 	case ND_ROUTER_SOLICIT:
1061 		cp = "Router Solicitation";
1062 		break;
1063 	case ND_ROUTER_ADVERT:
1064 		cp = "Router Advertisement";
1065 		break;
1066 	case ND_NEIGHBOR_SOLICIT:
1067 		cp = "Neighbor Solicitation";
1068 		break;
1069 	case ND_NEIGHBOR_ADVERT:
1070 		cp = "Neighbor Advertisement";
1071 		break;
1072 	case ND_REDIRECT:
1073 		cp = "Redirect";
1074 		break;
1075 	default:
1076 		cp = "Unknown";
1077 		break;
1078 	}
1079 	return cp;
1080 }
1081 
1082 
1083 int
1084 packet_ok(mhdr, cc, seq)
1085 	struct msghdr *mhdr;
1086 	int cc;
1087 	int seq;
1088 {
1089 	register struct icmp6_hdr *icp;
1090 	struct sockaddr_in6 *from = (struct sockaddr_in6 *)mhdr->msg_name;
1091 	u_char type, code;
1092 	char *buf = (char *)mhdr->msg_iov[0].iov_base;
1093 	struct cmsghdr *cm;
1094 	int *hlimp;
1095 	char hbuf[NI_MAXHOST];
1096 
1097 #ifdef OLDRAWSOCKET
1098 	int hlen;
1099 	struct ip6_hdr *ip;
1100 #endif
1101 
1102 #ifdef OLDRAWSOCKET
1103 	ip = (struct ip6_hdr *) buf;
1104 	hlen = sizeof(struct ip6_hdr);
1105 	if (cc < hlen + sizeof(struct icmp6_hdr)) {
1106 		if (verbose) {
1107 			if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1108 			    hbuf, sizeof(hbuf), NULL, 0,
1109 			    NI_NUMERICHOST | niflag) != 0)
1110 				strlcpy(hbuf, "invalid", sizeof(hbuf));
1111 			Printf("packet too short (%d bytes) from %s\n", cc,
1112 			    hbuf);
1113 		}
1114 		return (0);
1115 	}
1116 	cc -= hlen;
1117 	icp = (struct icmp6_hdr *)(buf + hlen);
1118 #else
1119 	if (cc < sizeof(struct icmp6_hdr)) {
1120 		if (verbose) {
1121 			if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1122 			    hbuf, sizeof(hbuf), NULL, 0,
1123 			    NI_NUMERICHOST | niflag) != 0)
1124 				strlcpy(hbuf, "invalid", sizeof(hbuf));
1125 			Printf("data too short (%d bytes) from %s\n", cc, hbuf);
1126 		}
1127 		return(0);
1128 	}
1129 	icp = (struct icmp6_hdr *)buf;
1130 #endif
1131 	/* get optional information via advanced API */
1132 	rcvpktinfo = NULL;
1133 	hlimp = NULL;
1134 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1135 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1136 		if (cm->cmsg_level == IPPROTO_IPV6 &&
1137 		    cm->cmsg_type == IPV6_PKTINFO &&
1138 		    cm->cmsg_len ==
1139 		    CMSG_LEN(sizeof(struct in6_pktinfo)))
1140 			rcvpktinfo = (struct in6_pktinfo *)(CMSG_DATA(cm));
1141 
1142 		if (cm->cmsg_level == IPPROTO_IPV6 &&
1143 		    cm->cmsg_type == IPV6_HOPLIMIT &&
1144 		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
1145 			hlimp = (int *)CMSG_DATA(cm);
1146 	}
1147 	if (rcvpktinfo == NULL || hlimp == NULL) {
1148 		warnx("failed to get received hop limit or packet info");
1149 #if 0
1150 		return(0);
1151 #else
1152 		rcvhlim = 0;	/*XXX*/
1153 #endif
1154 	}
1155 	else
1156 		rcvhlim = *hlimp;
1157 
1158 	type = icp->icmp6_type;
1159 	code = icp->icmp6_code;
1160 	if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT)
1161 	 || type == ICMP6_DST_UNREACH) {
1162 		struct ip6_hdr *hip;
1163 		struct udphdr *up;
1164 
1165 		hip = (struct ip6_hdr *)(icp + 1);
1166 		if ((up = get_udphdr(hip, (u_char *)(buf + cc))) == NULL) {
1167 			if (verbose)
1168 				warnx("failed to get upper layer header");
1169 			return(0);
1170 		}
1171 		if (up->uh_sport == htons(ident) &&
1172 		    up->uh_dport == htons(port+seq))
1173 			return (type == ICMP6_TIME_EXCEEDED ? -1 : code + 1);
1174 	}
1175 	if (verbose) {
1176 		int i;
1177 		u_int8_t *p;
1178 		char sbuf[NI_MAXHOST+1], dbuf[INET6_ADDRSTRLEN];
1179 
1180 		if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1181 		    sbuf, sizeof(sbuf), NULL, 0, NI_NUMERICHOST | niflag) != 0)
1182 			strlcpy(sbuf, "invalid", sizeof(hbuf));
1183 		Printf("\n%d bytes from %s to %s", cc, sbuf,
1184 		    rcvpktinfo ? inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
1185 					dbuf, sizeof(dbuf))
1186 			       : "?");
1187 		Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
1188 		       icp->icmp6_code);
1189 		p = (u_int8_t *)(icp + 1);
1190 #define WIDTH	16
1191 		for (i = 0; i < cc; i++) {
1192 			if (i % WIDTH == 0)
1193 				Printf("%04x:", i);
1194 			if (i % 4 == 0)
1195 				Printf(" ");
1196 			Printf("%02x", p[i]);
1197 			if (i % WIDTH == WIDTH - 1)
1198 				Printf("\n");
1199 		}
1200 		if (cc % WIDTH != 0)
1201 			Printf("\n");
1202 	}
1203 	return(0);
1204 }
1205 
1206 /*
1207  * Increment pointer until find the UDP header.
1208  */
1209 struct udphdr *
1210 get_udphdr(ip6, lim)
1211 	struct ip6_hdr *ip6;
1212 	u_char *lim;
1213 {
1214 	u_char *cp = (u_char *)ip6, nh;
1215 	int hlen;
1216 
1217 	if (cp + sizeof(*ip6) >= lim)
1218 		return(NULL);
1219 
1220 	nh = ip6->ip6_nxt;
1221 	cp += sizeof(struct ip6_hdr);
1222 
1223 	while(lim - cp >= 8) {
1224 		switch(nh) {
1225 		 case IPPROTO_ESP:
1226 		 case IPPROTO_TCP:
1227 		 case IPPROTO_ICMPV6:
1228 			 return(NULL);
1229 		 case IPPROTO_UDP:
1230 			 return((struct udphdr *)cp);
1231 		 case IPPROTO_FRAGMENT:
1232 			 hlen = sizeof(struct ip6_frag);
1233 			 nh = ((struct ip6_frag *)cp)->ip6f_nxt;
1234 			 break;
1235 		 case IPPROTO_AH:
1236 			 hlen = (((struct ip6_ext *)cp)->ip6e_len + 2) << 2;
1237 			 nh = ((struct ip6_ext *)cp)->ip6e_nxt;
1238 			 break;
1239 		  default:
1240 			  hlen = (((struct ip6_ext *)cp)->ip6e_len + 1) << 3;
1241 			  nh = ((struct ip6_ext *)cp)->ip6e_nxt;
1242 			  break;
1243 		}
1244 
1245 		cp += hlen;
1246 	}
1247 
1248 	return(NULL);
1249 }
1250 
1251 void
1252 print(mhdr, cc)
1253 	struct msghdr *mhdr;
1254 	int cc;
1255 {
1256 	struct sockaddr_in6 *from = (struct sockaddr_in6 *)mhdr->msg_name;
1257 	char hbuf[NI_MAXHOST];
1258 
1259 	if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1260 	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST | niflag) != 0)
1261 		strlcpy(hbuf, "invalid", sizeof(hbuf));
1262 	if (nflag)
1263 		Printf(" %s", hbuf);
1264 	else if (lflag)
1265 		Printf(" %s (%s)", inetname((struct sockaddr *)from), hbuf);
1266 	else
1267 		Printf(" %s", inetname((struct sockaddr *)from));
1268 
1269 	if (verbose) {
1270 #ifdef OLDRAWSOCKET
1271 		Printf(" %d bytes to %s", cc,
1272 		    rcvpktinfo ? inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
1273 					hbuf, sizeof(hbuf))
1274 			       : "?");
1275 #else
1276 		Printf(" %d bytes of data to %s", cc,
1277 		    rcvpktinfo ?  inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
1278 					hbuf, sizeof(hbuf))
1279 			       : "?");
1280 #endif
1281 	}
1282 }
1283 
1284 /*
1285  * Subtract 2 timeval structs:  out = out - in.
1286  * Out is assumed to be >= in.
1287  */
1288 void
1289 tvsub(out, in)
1290 	register struct timeval *out, *in;
1291 {
1292 	if ((out->tv_usec -= in->tv_usec) < 0)   {
1293 		out->tv_sec--;
1294 		out->tv_usec += 1000000;
1295 	}
1296 	out->tv_sec -= in->tv_sec;
1297 }
1298 
1299 
1300 /*
1301  * Construct an Internet address representation.
1302  * If the nflag has been supplied, give
1303  * numeric value, otherwise try for symbolic name.
1304  */
1305 const char *
1306 inetname(sa)
1307 	struct sockaddr *sa;
1308 {
1309 	register char *cp;
1310 	static char line[NI_MAXHOST];
1311 	static char domain[MAXHOSTNAMELEN + 1];
1312 	static int first = 1;
1313 
1314 	if (first && !nflag) {
1315 		first = 0;
1316 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
1317 		    (cp = index(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 = index(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 | niflag) != 0)
1337 		strlcpy(line, "invalid", sizeof(line));
1338 	return line;
1339 }
1340 
1341 void
1342 usage()
1343 {
1344 	(void)fprintf(stderr,
1345 "usage: traceroute6 [-dlnrv] [-f firsthop] [-g gateway] [-m hoplimit] [-p port]\n"
1346 "       [-q probes] [-s src] [-w waittime] target [datalen]\n");
1347 	exit(1);
1348 }
1349