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