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.7 2007/10/25 08:12:42 hasso 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 fprintf
292 #define Sprintf sprintf
293 #define Printf 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(int argc, char **argv)
370 {
371 	struct hostent *hp;
372 	int error;
373 	struct addrinfo hints, *res;
374 	int ch, i, on, probe, seq, hops, rcvcmsglen;
375 	static u_char *rcvcmsgbuf;
376 	char hbuf[NI_MAXHOST], src0[NI_MAXHOST];
377 	char *ep;
378 
379 	/*
380 	 * Receive ICMP
381 	 */
382 	if ((rcvsock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0) {
383 		perror("socket(ICMPv6)");
384 		exit(5);
385 	}
386 
387 	/* revoke privs */
388 	seteuid(getuid());
389 	setuid(getuid());
390 
391 	/* set a minimum set of socket options */
392 	on = 1;
393 	/* specify to tell receiving interface */
394 #ifdef IPV6_RECVPKTINFO
395 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
396 		       sizeof(on)) < 0)
397 		err(1, "setsockopt(IPV6_RECVPKTINFO)");
398 #else  /* old adv. API */
399 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_PKTINFO, &on,
400 		       sizeof(on)) < 0)
401 		err(1, "setsockopt(IPV6_PKTINFO)");
402 #endif
403 
404 	/* specify to tell value of hoplimit field of received IP6 hdr */
405 #ifdef IPV6_RECVHOPLIMIT
406 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
407 		       sizeof(on)) < 0)
408 		err(1, "setsockopt(IPV6_RECVHOPLIMIT)");
409 #else  /* old adv. API */
410 	if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_HOPLIMIT, &on,
411 		       sizeof(on)) < 0)
412 		err(1, "setsockopt(IPV6_HOPLIMIT)");
413 #endif
414 
415 	seq = 0;
416 
417 	while ((ch = getopt(argc, argv, "df:g:lm:np:q:rs:w:v")) != -1)
418 		switch(ch) {
419 		case 'd':
420 			options |= SO_DEBUG;
421 			break;
422 		case 'f':
423 			ep = NULL;
424 			first_hop = strtoul(optarg, &ep, 0);
425 			if (!*argv || *ep) {
426 				Fprintf(stderr,
427 				    "traceroute6: invalid min hoplimit.\n");
428 				exit(1);
429 			}
430 			if (first_hop > max_hops) {
431 				Fprintf(stderr,
432 				    "traceroute6: min hoplimit must be <= %d.\n", max_hops);
433 				exit(1);
434 			}
435 			break;
436 		case 'g':
437 			hp = getipnodebyname(optarg, AF_INET6, 0, &h_errno);
438 			if (hp == NULL) {
439 				Fprintf(stderr,
440 				    "traceroute6: unknown host %s\n", optarg);
441 				exit(1);
442 			}
443 #ifdef USE_RFC2292BIS
444 			if (rth == NULL) {
445 				/*
446 				 * XXX: We can't detect the number of
447 				 * intermediate nodes yet.
448 				 */
449 				if ((rth = inet6_rth_init((void *)rtbuf,
450 							 sizeof(rtbuf),
451 							 IPV6_RTHDR_TYPE_0,
452 							 0)) == NULL) {
453 					Fprintf(stderr,
454 						"inet6_rth_init failed.\n");
455 					exit(1);
456 				}
457 			}
458 			if (inet6_rth_add((void *)rth,
459 					  (struct in6_addr *)hp->h_addr)) {
460 				Fprintf(stderr,
461 					"inet6_rth_add failed for %s\n",
462 					optarg);
463 				exit(1);
464 			}
465 #else  /* old advanced API */
466 			if (cmsg == NULL)
467 				cmsg = inet6_rthdr_init(rtbuf, IPV6_RTHDR_TYPE_0);
468 			inet6_rthdr_add(cmsg, (struct in6_addr *)hp->h_addr, IPV6_RTHDR_LOOSE);
469 #endif
470 			freehostent(hp);
471 			break;
472 		case 'l':
473 			lflag++;
474 			break;
475 		case 'm':
476 			ep = NULL;
477 			max_hops = strtoul(optarg, &ep, 0);
478 			if (!*argv || *ep) {
479 				Fprintf(stderr,
480 				    "traceroute6: invalid max hoplimit.\n");
481 				exit(1);
482 			}
483 			if (max_hops < first_hop) {
484 				Fprintf(stderr,
485 				    "traceroute6: max hoplimit must be >= %d.\n", first_hop);
486 				exit(1);
487 			}
488 			break;
489 		case 'n':
490 			nflag++;
491 			break;
492 		case 'p':
493 			ep = NULL;
494 			port = strtoul(optarg, &ep, 0);
495 			if (!*argv || *ep) {
496 				Fprintf(stderr,
497 				    "traceroute6: port.\n");
498 				exit(1);
499 			}
500 			if (port < 1) {
501 				Fprintf(stderr,
502 				    "traceroute6: port must be >0.\n");
503 				exit(1);
504 			}
505 			break;
506 		case 'q':
507 			ep = NULL;
508 			nprobes = strtoul(optarg, &ep, 0);
509 			if (!*argv || *ep) {
510 				Fprintf(stderr,
511 				    "traceroute6: invalid nprobes.\n");
512 				exit(1);
513 			}
514 			if (nprobes < 1) {
515 				Fprintf(stderr,
516 				    "traceroute6: nprobes must be >0.\n");
517 				exit(1);
518 			}
519 			break;
520 		case 'r':
521 			options |= SO_DONTROUTE;
522 			break;
523 		case 's':
524 			/*
525 			 * set the ip source address of the outbound
526 			 * probe (e.g., on a multi-homed host).
527 			 */
528 			source = optarg;
529 			break;
530 		case 'v':
531 			verbose++;
532 			break;
533 		case 'w':
534 			ep = NULL;
535 			waittime = strtoul(optarg, &ep, 0);
536 			if (!*argv || *ep) {
537 				Fprintf(stderr,
538 				    "traceroute6: invalid wait time.\n");
539 				exit(1);
540 			}
541 			if (waittime <= 1) {
542 				Fprintf(stderr,
543 				    "traceroute6: wait must be >1 sec.\n");
544 				exit(1);
545 			}
546 			break;
547 		default:
548 			usage();
549 		}
550 	argc -= optind;
551 	argv += optind;
552 
553 	if (argc < 1 || argc > 2)
554 		usage();
555 
556 #if 1
557 	setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
558 #else
559 	setlinebuf (stdout);
560 #endif
561 
562 	memset(&hints, 0, sizeof(hints));
563 	hints.ai_family = PF_INET6;
564 	hints.ai_socktype = SOCK_RAW;
565 	hints.ai_protocol = IPPROTO_ICMPV6;
566 	hints.ai_flags = AI_CANONNAME;
567 	error = getaddrinfo(*argv, NULL, &hints, &res);
568 	if (error) {
569 		fprintf(stderr, "traceroute6: %s\n", gai_strerror(error));
570 		exit(1);
571 	}
572 	if (res->ai_addrlen != sizeof(Dst)) {
573 		fprintf(stderr, "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 
583 	if (*++argv) {
584 		ep = NULL;
585 		datalen = strtoul(*argv, &ep, 0);
586 		if (!*argv || *ep) {
587 			Fprintf(stderr,
588 			    "traceroute6: invalid packet length.\n");
589 			exit(1);
590 		}
591 	}
592 	if (datalen < 0 || datalen >= MAXPACKET - sizeof(struct opacket)) {
593 		Fprintf(stderr,
594 		    "traceroute6: packet size must be 0 <= s < %ld.\n",
595 		    (long)(MAXPACKET - sizeof(struct opacket)));
596 		exit(1);
597 	}
598 	datalen += sizeof(struct opacket);
599 	outpacket = (struct opacket *)malloc((unsigned)datalen);
600 	if (! outpacket) {
601 		perror("malloc");
602 		exit(1);
603 	}
604 	bzero((char *)outpacket, datalen);
605 
606 	/* initialize msghdr for receiving packets */
607 	rcviov[0].iov_base = (caddr_t)packet;
608 	rcviov[0].iov_len = sizeof(packet);
609 	rcvmhdr.msg_name = (caddr_t)&Rcv;
610 	rcvmhdr.msg_namelen = sizeof(Rcv);
611 	rcvmhdr.msg_iov = rcviov;
612 	rcvmhdr.msg_iovlen = 1;
613 	rcvcmsglen = CMSG_SPACE(sizeof(struct in6_pktinfo))
614 		+ CMSG_SPACE(sizeof(int));
615 	if ((rcvcmsgbuf = malloc(rcvcmsglen)) == NULL) {
616 		Fprintf(stderr, "traceroute6: malloc failed\n");
617 		exit(1);
618 	}
619 	rcvmhdr.msg_control = (caddr_t) rcvcmsgbuf;
620 	rcvmhdr.msg_controllen = rcvcmsglen;
621 
622 	if (options & SO_DEBUG)
623 		setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
624 			   (char *)&on, sizeof(on));
625 	if (options & SO_DONTROUTE)
626 		setsockopt(rcvsock, SOL_SOCKET, SO_DONTROUTE,
627 			   (char *)&on, sizeof(on));
628 #ifdef IPSEC
629 #ifdef IPSEC_POLICY_IPSEC
630 	/*
631 	 * do not raise error even if setsockopt fails, kernel may have ipsec
632 	 * turned off.
633 	 */
634 	if (setpolicy(rcvsock, "in bypass") < 0)
635 		errx(1, "%s", ipsec_strerror());
636 	if (setpolicy(rcvsock, "out bypass") < 0)
637 		errx(1, "%s", ipsec_strerror());
638 #else
639     {
640 	int level = IPSEC_LEVEL_NONE;
641 
642 	setsockopt(rcvsock, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, &level,
643 		   sizeof(level));
644 	setsockopt(rcvsock, IPPROTO_IPV6, IPV6_ESP_NETWORK_LEVEL, &level,
645 		   sizeof(level));
646 #ifdef IP_AUTH_TRANS_LEVEL
647 	setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, &level,
648 		sizeof(level));
649 #else
650 	setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_LEVEL, &level,
651 		   sizeof(level));
652 #endif
653 #ifdef IP_AUTH_NETWORK_LEVEL
654 	setsockopt(rcvsock, IPPROTO_IPV6, IPV6_AUTH_NETWORK_LEVEL, &level,
655 		   sizeof(level));
656 #endif
657     }
658 #endif /*IPSEC_POLICY_IPSEC*/
659 #endif /*IPSEC*/
660 
661 	/*
662 	 * Send UDP
663 	 */
664 	if ((sndsock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
665 		perror("socket(SOCK_DGRAM)");
666 		exit(5);
667 	}
668 #ifdef SO_SNDBUF
669 	if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
670 		       sizeof(datalen)) < 0) {
671 		perror("setsockopt(SO_SNDBUF)");
672 		exit(6);
673 	}
674 #endif /* SO_SNDBUF */
675 	if (options & SO_DEBUG)
676 		setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
677 			   (char *)&on, sizeof(on));
678 	if (options & SO_DONTROUTE)
679 		setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
680 			   (char *)&on, sizeof(on));
681 #ifdef USE_RFC2292BIS
682 	if (rth) {/* XXX: there is no library to finalize the header... */
683 		rth->ip6r_len = rth->ip6r_segleft * 2;
684 		if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_RTHDR,
685 			       (void *)rth, (rth->ip6r_len + 1) << 3)) {
686 			Fprintf(stderr, "setsockopt(IPV6_RTHDR): %s\n",
687 				strerror(errno));
688 			exit(1);
689 		}
690 	}
691 #else  /* old advanced API */
692 	if (cmsg != NULL) {
693 		inet6_rthdr_lasthop(cmsg, IPV6_RTHDR_LOOSE);
694 		if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_PKTOPTIONS,
695 			       rtbuf, cmsg->cmsg_len) < 0) {
696 			Fprintf(stderr, "setsockopt(IPV6_PKTOPTIONS): %s\n",
697 				strerror(errno));
698 			exit(1);
699 		}
700 	}
701 #endif /* USE_RFC2292BIS */
702 #ifdef IPSEC
703 #ifdef IPSEC_POLICY_IPSEC
704 	/*
705 	 * do not raise error even if setsockopt fails, kernel may have ipsec
706 	 * turned off.
707 	 */
708 	if (setpolicy(sndsock, "in bypass") < 0)
709 		errx(1, "%s", ipsec_strerror());
710 	if (setpolicy(sndsock, "out bypass") < 0)
711 		errx(1, "%s", ipsec_strerror());
712 #else
713     {
714 	int level = IPSEC_LEVEL_BYPASS;
715 
716 	setsockopt(sndsock, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, &level,
717 		   sizeof(level));
718 	setsockopt(sndsock, IPPROTO_IPV6, IPV6_ESP_NETWORK_LEVEL, &level,
719 		   sizeof(level));
720 #ifdef IP_AUTH_TRANS_LEVEL
721 	setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, &level,
722 		   sizeof(level));
723 #else
724 	setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_LEVEL, &level,
725 		   sizeof(level));
726 #endif
727 #ifdef IP_AUTH_NETWORK_LEVEL
728 	setsockopt(sndsock, IPPROTO_IPV6, IPV6_AUTH_NETWORK_LEVEL, &level,
729 		   sizeof(level));
730 #endif
731     }
732 #endif /*IPSEC_POLICY_IPSEC*/
733 #endif /*IPSEC*/
734 
735 	/*
736 	 * Source selection
737 	 */
738 	bzero(&Src, sizeof(Src));
739 	if (source) {
740 		struct addrinfo hints, *res;
741 		int error;
742 
743 		memset(&hints, 0, sizeof(hints));
744 		hints.ai_family = AF_INET6;
745 		hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
746 		hints.ai_flags = AI_NUMERICHOST;
747 		error = getaddrinfo(source, "0", &hints, &res);
748 		if (error) {
749 			Printf("traceroute6: %s: %s\n", source,
750 			    gai_strerror(error));
751 			exit(1);
752 		}
753 		if (res->ai_addrlen > sizeof(Src)) {
754 			Printf("traceroute6: %s: %s\n", source,
755 			    gai_strerror(error));
756 			exit(1);
757 		}
758 		memcpy(&Src, res->ai_addr, res->ai_addrlen);
759 		freeaddrinfo(res);
760 	} else {
761 		struct sockaddr_in6 Nxt;
762 		int dummy, len;
763 
764 		Nxt = Dst;
765 		Nxt.sin6_port = htons(DUMMY_PORT);
766 		if (cmsg != NULL)
767 			bcopy(inet6_rthdr_getaddr(cmsg, 1), &Nxt.sin6_addr,
768 			      sizeof(Nxt.sin6_addr));
769 		if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
770 			perror("socket");
771 			exit(1);
772 		}
773 		if (connect(dummy, (struct sockaddr *)&Nxt, Nxt.sin6_len) < 0) {
774 			perror("connect");
775 			exit(1);
776 		}
777 		len = sizeof(Src);
778 		if (getsockname(dummy, (struct sockaddr *)&Src, &len) < 0) {
779 			perror("getsockname");
780 			exit(1);
781 		}
782 		if (getnameinfo((struct sockaddr *)&Src, Src.sin6_len,
783 				src0, sizeof(src0), NULL, 0,
784 				NI_NUMERICHOST | niflag)) {
785 			Fprintf(stderr, "getnameinfo failed for source\n");
786 			exit(1);
787 		}
788 		source = src0;
789 		close(dummy);
790 	}
791 
792 #if 1
793 	ident = (getpid() & 0xffff) | 0x8000;
794 #else
795 	ident = 0;	/*let the kernel pick one*/
796 #endif
797 	Src.sin6_port = htons(ident);
798 	if (bind(sndsock, (struct sockaddr *)&Src, Src.sin6_len) < 0) {
799 		perror("bind");
800 		exit(1);
801 	}
802 
803 	if (ident == 0) {
804 		int len;
805 
806 		len = sizeof(Src);
807 		if (getsockname(sndsock, (struct sockaddr *)&Src, &i) < 0) {
808 			perror("getsockname");
809 			exit(1);
810 		}
811 		ident = ntohs(Src.sin6_port);
812 	}
813 
814 	/*
815 	 * Message to users
816 	 */
817 	if (getnameinfo((struct sockaddr *)&Dst, Dst.sin6_len, hbuf,
818 			sizeof(hbuf), NULL, 0, NI_NUMERICHOST | niflag))
819 		strlcpy(hbuf, "(invalid)", sizeof(hbuf));
820 	Fprintf(stderr, "traceroute6");
821 	Fprintf(stderr, " to %s (%s)", hostname, hbuf);
822 	if (source)
823 		Fprintf(stderr, " from %s", source);
824 	Fprintf(stderr,
825 		", %d hops max, %d byte packets\n",
826 		max_hops, datalen);
827 	fflush(stderr);
828 
829 	if (first_hop > 1)
830 		Printf("Skipping %d intermediate hops\n", first_hop - 1);
831 
832 	/*
833 	 * Main loop
834 	 */
835 	for (hops = first_hop; hops <= max_hops; ++hops) {
836 		struct in6_addr lastaddr;
837 		int got_there = 0;
838 		int unreachable = 0;
839 		int gotlastaddr = 0;
840 
841 		Printf("%2d ", hops);
842 		bzero(&lastaddr, sizeof(lastaddr));
843 		for (probe = 0; probe < nprobes; ++probe) {
844 			int cc;
845 			struct timeval t1, t2;
846 			struct timezone tz;
847 
848 			gettimeofday(&t1, &tz);
849 			send_probe(++seq, hops);
850 			while ((cc = wait_for_reply(rcvsock, &rcvmhdr))) {
851 				gettimeofday(&t2, &tz);
852 				if ((i = packet_ok(&rcvmhdr, cc, seq))) {
853 					if (!gotlastaddr ||
854 					    !IN6_ARE_ADDR_EQUAL(&Rcv.sin6_addr,
855 							    &lastaddr)) {
856 						if (gotlastaddr)
857 							printf("\n   ");
858 						print(&rcvmhdr, cc);
859 						lastaddr = Rcv.sin6_addr;
860 						++gotlastaddr;
861 					}
862 					Printf("  %g ms", deltaT(&t1, &t2));
863 					switch(i - 1) {
864 					case ICMP6_DST_UNREACH_NOROUTE:
865 						++unreachable;
866 						Printf(" !N");
867 						break;
868 					case ICMP6_DST_UNREACH_ADMIN:
869 						++unreachable;
870 						Printf(" !P");
871 						break;
872 					case ICMP6_DST_UNREACH_NOTNEIGHBOR:
873 						++unreachable;
874 						Printf(" !S");
875 						break;
876 					case ICMP6_DST_UNREACH_ADDR:
877 						++unreachable;
878 						Printf(" !A");
879 						break;
880 					case ICMP6_DST_UNREACH_NOPORT:
881 						if (rcvhlim >= 0 &&
882 						    rcvhlim <= 1)
883 							Printf(" !");
884 						++got_there;
885 						break;
886 					}
887 					break;
888 				}
889 			}
890 			if (cc == 0)
891 				Printf(" *");
892 			fflush(stdout);
893 		}
894 		putchar('\n');
895 		if (got_there ||
896 		    (unreachable > 0 && unreachable >= ((nprobes + 1) / 2))) {
897 			exit(0);
898 		}
899 	}
900 
901 	exit(0);
902 }
903 
904 int
905 wait_for_reply(int sock, struct msghdr *mhdr)
906 {
907 #ifdef HAVE_POLL
908 	struct pollfd pfd[1];
909 	int cc = 0;
910 
911 	pfd[0].fd = sock;
912 	pfd[0].events = POLLIN;
913 	pfd[0].revents = 0;
914 
915 	if (poll(pfd, 1, waittime * 1000) > 0)
916 		cc = recvmsg(rcvsock, mhdr, 0);
917 
918 	return(cc);
919 #else
920 	fd_set *fdsp;
921 	struct timeval wait;
922 	int cc = 0, fdsn;
923 
924 	fdsn = howmany(sock + 1, NFDBITS) * sizeof(fd_mask);
925 	if ((fdsp = (fd_set *)malloc(fdsn)) == NULL)
926 		err(1, "malloc");
927 	memset(fdsp, 0, fdsn);
928 	FD_SET(sock, fdsp);
929 	wait.tv_sec = waittime; wait.tv_usec = 0;
930 
931 	if (select(sock+1, fdsp, (fd_set *)0, (fd_set *)0, &wait) > 0)
932 		cc = recvmsg(rcvsock, mhdr, 0);
933 
934 	free(fdsp);
935 	return(cc);
936 #endif
937 }
938 
939 #ifdef IPSEC
940 #ifdef IPSEC_POLICY_IPSEC
941 int
942 setpolicy(int so, char *policy)
943 {
944 	char *buf;
945 
946 	buf = ipsec_set_policy(policy, strlen(policy));
947 	if (buf == NULL) {
948 		warnx("%s", ipsec_strerror());
949 		return -1;
950 	}
951 	setsockopt(so, IPPROTO_IPV6, IPV6_IPSEC_POLICY,
952 		   buf, ipsec_get_policylen(buf));
953 
954 	free(buf);
955 
956 	return 0;
957 }
958 #endif
959 #endif
960 
961 void
962 send_probe(int seq, int hops)
963 {
964 	struct opacket *op = outpacket;
965 	int i;
966 
967 	if(setsockopt(sndsock, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
968 		      (char *)&hops, sizeof(hops)) < 0) {
969 		perror("setsockopt IPV6_UNICAST_HOPS");
970 	}
971 
972 	Dst.sin6_port = htons(port + seq);
973 
974 	op->seq = seq;
975 	op->hops = hops;
976 	gettimeofday(&op->tv, &tz);
977 
978 	i = sendto(sndsock, (char *)outpacket, datalen , 0,
979 		   (struct sockaddr *)&Dst, Dst.sin6_len);
980 	if (i < 0 || i != datalen)  {
981 		if (i<0)
982 			perror("sendto");
983 		Printf("traceroute6: wrote %s %d chars, ret=%d\n", hostname,
984 		       datalen, i);
985 		fflush(stdout);
986 	}
987 }
988 
989 int
990 get_hoplim(struct msghdr *mhdr)
991 {
992 	struct cmsghdr *cm;
993 
994 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
995 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
996 		if (cm->cmsg_level == IPPROTO_IPV6 &&
997 		    cm->cmsg_type == IPV6_HOPLIMIT &&
998 		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
999 			return(*(int *)CMSG_DATA(cm));
1000 	}
1001 
1002 	return(-1);
1003 }
1004 
1005 double
1006 deltaT(struct timeval *t1p, struct timeval *t2p)
1007 {
1008 	double dt;
1009 
1010 	dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
1011 	     (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
1012 	return (dt);
1013 }
1014 
1015 
1016 /*
1017  * Convert an ICMP "type" field to a printable string.
1018  */
1019 char *
1020 pr_type(int t0)
1021 {
1022 	u_char t = t0 & 0xff;
1023 	char *cp;
1024 
1025 	switch (t) {
1026 	case ICMP6_DST_UNREACH:
1027 		cp = "Destination Unreachable";
1028 		break;
1029 	case ICMP6_PACKET_TOO_BIG:
1030 		cp = "Pakcet Too Big";
1031 		break;
1032 	case ICMP6_TIME_EXCEEDED:
1033 		cp = "Time Exceeded";
1034 		break;
1035 	case ICMP6_PARAM_PROB:
1036 		cp = "Parameter Problem";
1037 		break;
1038 	case ICMP6_ECHO_REQUEST:
1039 		cp = "Echo Request";
1040 		break;
1041 	case ICMP6_ECHO_REPLY:
1042 		cp = "Echo Reply";
1043 		break;
1044 	case ICMP6_MEMBERSHIP_QUERY:
1045 		cp = "Group Membership Query";
1046 		break;
1047 	case ICMP6_MEMBERSHIP_REPORT:
1048 		cp = "Group Membership Report";
1049 		break;
1050 	case ICMP6_MEMBERSHIP_REDUCTION:
1051 		cp = "Group Membership Reduction";
1052 		break;
1053 	case ND_ROUTER_SOLICIT:
1054 		cp = "Router Solicitation";
1055 		break;
1056 	case ND_ROUTER_ADVERT:
1057 		cp = "Router Advertisement";
1058 		break;
1059 	case ND_NEIGHBOR_SOLICIT:
1060 		cp = "Neighbor Solicitation";
1061 		break;
1062 	case ND_NEIGHBOR_ADVERT:
1063 		cp = "Neighbor Advertisement";
1064 		break;
1065 	case ND_REDIRECT:
1066 		cp = "Redirect";
1067 		break;
1068 	default:
1069 		cp = "Unknown";
1070 		break;
1071 	}
1072 	return cp;
1073 }
1074 
1075 
1076 int
1077 packet_ok(struct msghdr *mhdr, int cc, int seq)
1078 {
1079 	struct icmp6_hdr *icp;
1080 	struct sockaddr_in6 *from = (struct sockaddr_in6 *)mhdr->msg_name;
1081 	u_char type, code;
1082 	char *buf = (char *)mhdr->msg_iov[0].iov_base;
1083 	struct cmsghdr *cm;
1084 	int *hlimp;
1085 	char hbuf[NI_MAXHOST];
1086 
1087 #ifdef OLDRAWSOCKET
1088 	int hlen;
1089 	struct ip6_hdr *ip;
1090 #endif
1091 
1092 #ifdef OLDRAWSOCKET
1093 	ip = (struct ip6_hdr *) buf;
1094 	hlen = sizeof(struct ip6_hdr);
1095 	if (cc < hlen + sizeof(struct icmp6_hdr)) {
1096 		if (verbose) {
1097 			if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1098 			    hbuf, sizeof(hbuf), NULL, 0,
1099 			    NI_NUMERICHOST | niflag) != 0)
1100 				strlcpy(hbuf, "invalid", sizeof(hbuf));
1101 			Printf("packet too short (%d bytes) from %s\n", cc,
1102 			    hbuf);
1103 		}
1104 		return (0);
1105 	}
1106 	cc -= hlen;
1107 	icp = (struct icmp6_hdr *)(buf + hlen);
1108 #else
1109 	if (cc < sizeof(struct icmp6_hdr)) {
1110 		if (verbose) {
1111 			if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1112 			    hbuf, sizeof(hbuf), NULL, 0,
1113 			    NI_NUMERICHOST | niflag) != 0)
1114 				strlcpy(hbuf, "invalid", sizeof(hbuf));
1115 			Printf("data too short (%d bytes) from %s\n", cc, hbuf);
1116 		}
1117 		return(0);
1118 	}
1119 	icp = (struct icmp6_hdr *)buf;
1120 #endif
1121 	/* get optional information via advanced API */
1122 	rcvpktinfo = NULL;
1123 	hlimp = NULL;
1124 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1125 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1126 		if (cm->cmsg_level == IPPROTO_IPV6 &&
1127 		    cm->cmsg_type == IPV6_PKTINFO &&
1128 		    cm->cmsg_len ==
1129 		    CMSG_LEN(sizeof(struct in6_pktinfo)))
1130 			rcvpktinfo = (struct in6_pktinfo *)(CMSG_DATA(cm));
1131 
1132 		if (cm->cmsg_level == IPPROTO_IPV6 &&
1133 		    cm->cmsg_type == IPV6_HOPLIMIT &&
1134 		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
1135 			hlimp = (int *)CMSG_DATA(cm);
1136 	}
1137 	if (rcvpktinfo == NULL || hlimp == NULL) {
1138 		warnx("failed to get received hop limit or packet info");
1139 #if 0
1140 		return(0);
1141 #else
1142 		rcvhlim = 0;	/*XXX*/
1143 #endif
1144 	}
1145 	else
1146 		rcvhlim = *hlimp;
1147 
1148 	type = icp->icmp6_type;
1149 	code = icp->icmp6_code;
1150 	if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT)
1151 	 || type == ICMP6_DST_UNREACH) {
1152 		struct ip6_hdr *hip;
1153 		struct udphdr *up;
1154 
1155 		hip = (struct ip6_hdr *)(icp + 1);
1156 		if ((up = get_udphdr(hip, (u_char *)(buf + cc))) == NULL) {
1157 			if (verbose)
1158 				warnx("failed to get upper layer header");
1159 			return(0);
1160 		}
1161 		if (up->uh_sport == htons(ident) &&
1162 		    up->uh_dport == htons(port+seq))
1163 			return (type == ICMP6_TIME_EXCEEDED ? -1 : code + 1);
1164 	}
1165 	if (verbose) {
1166 		int i;
1167 		u_int8_t *p;
1168 		char sbuf[NI_MAXHOST+1], dbuf[INET6_ADDRSTRLEN];
1169 
1170 		if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1171 		    sbuf, sizeof(sbuf), NULL, 0, NI_NUMERICHOST | niflag) != 0)
1172 			strlcpy(sbuf, "invalid", sizeof(hbuf));
1173 		Printf("\n%d bytes from %s to %s", cc, sbuf,
1174 		    rcvpktinfo ? inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
1175 					dbuf, sizeof(dbuf))
1176 			       : "?");
1177 		Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
1178 		       icp->icmp6_code);
1179 		p = (u_int8_t *)(icp + 1);
1180 #define WIDTH	16
1181 		for (i = 0; i < cc; i++) {
1182 			if (i % WIDTH == 0)
1183 				Printf("%04x:", i);
1184 			if (i % 4 == 0)
1185 				Printf(" ");
1186 			Printf("%02x", p[i]);
1187 			if (i % WIDTH == WIDTH - 1)
1188 				Printf("\n");
1189 		}
1190 		if (cc % WIDTH != 0)
1191 			Printf("\n");
1192 	}
1193 	return(0);
1194 }
1195 
1196 /*
1197  * Increment pointer until find the UDP header.
1198  */
1199 struct udphdr *
1200 get_udphdr(struct ip6_hdr *ip6, u_char *lim)
1201 {
1202 	u_char *cp = (u_char *)ip6, nh;
1203 	int hlen;
1204 
1205 	if (cp + sizeof(*ip6) >= lim)
1206 		return(NULL);
1207 
1208 	nh = ip6->ip6_nxt;
1209 	cp += sizeof(struct ip6_hdr);
1210 
1211 	while(lim - cp >= 8) {
1212 		switch(nh) {
1213 		 case IPPROTO_ESP:
1214 		 case IPPROTO_TCP:
1215 		 case IPPROTO_ICMPV6:
1216 			 return(NULL);
1217 		 case IPPROTO_UDP:
1218 			 return((struct udphdr *)cp);
1219 		 case IPPROTO_FRAGMENT:
1220 			 hlen = sizeof(struct ip6_frag);
1221 			 nh = ((struct ip6_frag *)cp)->ip6f_nxt;
1222 			 break;
1223 		 case IPPROTO_AH:
1224 			 hlen = (((struct ip6_ext *)cp)->ip6e_len + 2) << 2;
1225 			 nh = ((struct ip6_ext *)cp)->ip6e_nxt;
1226 			 break;
1227 		  default:
1228 			  hlen = (((struct ip6_ext *)cp)->ip6e_len + 1) << 3;
1229 			  nh = ((struct ip6_ext *)cp)->ip6e_nxt;
1230 			  break;
1231 		}
1232 
1233 		cp += hlen;
1234 	}
1235 
1236 	return(NULL);
1237 }
1238 
1239 void
1240 print(struct msghdr *mhdr, int cc)
1241 {
1242 	struct sockaddr_in6 *from = (struct sockaddr_in6 *)mhdr->msg_name;
1243 	char hbuf[NI_MAXHOST];
1244 
1245 	if (getnameinfo((struct sockaddr *)from, from->sin6_len,
1246 	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST | niflag) != 0)
1247 		strlcpy(hbuf, "invalid", sizeof(hbuf));
1248 	if (nflag)
1249 		Printf(" %s", hbuf);
1250 	else if (lflag)
1251 		Printf(" %s (%s)", inetname((struct sockaddr *)from), hbuf);
1252 	else
1253 		Printf(" %s", inetname((struct sockaddr *)from));
1254 
1255 	if (verbose) {
1256 #ifdef OLDRAWSOCKET
1257 		Printf(" %d bytes to %s", cc,
1258 		    rcvpktinfo ? inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
1259 					hbuf, sizeof(hbuf))
1260 			       : "?");
1261 #else
1262 		Printf(" %d bytes of data to %s", cc,
1263 		    rcvpktinfo ?  inet_ntop(AF_INET6, &rcvpktinfo->ipi6_addr,
1264 					hbuf, sizeof(hbuf))
1265 			       : "?");
1266 #endif
1267 	}
1268 }
1269 
1270 /*
1271  * Subtract 2 timeval structs:  out = out - in.
1272  * Out is assumed to be >= in.
1273  */
1274 void
1275 tvsub(struct timeval *out, struct timeval *in)
1276 {
1277 	if ((out->tv_usec -= in->tv_usec) < 0)   {
1278 		out->tv_sec--;
1279 		out->tv_usec += 1000000;
1280 	}
1281 	out->tv_sec -= in->tv_sec;
1282 }
1283 
1284 
1285 /*
1286  * Construct an Internet address representation.
1287  * If the nflag has been supplied, give
1288  * numeric value, otherwise try for symbolic name.
1289  */
1290 const char *
1291 inetname(struct sockaddr *sa)
1292 {
1293 	char *cp;
1294 	static char line[NI_MAXHOST];
1295 	static char domain[MAXHOSTNAMELEN + 1];
1296 	static int first = 1;
1297 
1298 	if (first && !nflag) {
1299 		first = 0;
1300 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
1301 		    (cp = strchr(domain, '.')))
1302 			strlcpy(domain, cp + 1, sizeof(domain));
1303 		else
1304 			domain[0] = 0;
1305 	}
1306 	cp = NULL;
1307 	if (!nflag) {
1308 		if (getnameinfo(sa, sa->sa_len, line, sizeof(line), NULL, 0,
1309 		    NI_NAMEREQD) == 0) {
1310 			if ((cp = strchr(line, '.')) &&
1311 			    !strcmp(cp + 1, domain))
1312 				*cp = 0;
1313 			cp = line;
1314 		}
1315 	}
1316 	if (cp)
1317 		return cp;
1318 
1319 	if (getnameinfo(sa, sa->sa_len, line, sizeof(line), NULL, 0,
1320 	    NI_NUMERICHOST | niflag) != 0)
1321 		strlcpy(line, "invalid", sizeof(line));
1322 	return line;
1323 }
1324 
1325 void
1326 usage(void)
1327 {
1328 	fprintf(stderr,
1329 "usage: traceroute6 [-dlnrv] [-f firsthop] [-g gateway] [-m hoplimit] [-p port]\n"
1330 "       [-q probes] [-s src] [-w waittime] target [datalen]\n");
1331 	exit(1);
1332 }
1333