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