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