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