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