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