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