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