OSDN Git Service

Fix no pic
[uclinux-h8/uClinux-dist.git] / user / iputils / traceroute6.c
1 /*
2  *      Modified for NRL 4.4BSD IPv6 release.
3  *      07/31/96 bgp
4  *
5  *      Search for "#ifdef NRL" to find the changes.
6  */
7
8 /*
9  *      Modified for Linux IPv6 by Pedro Roque <roque@di.fc.ul.pt>
10  *      31/07/1996
11  *
12  *      As ICMP error messages for IPv6 now include more than 8 bytes
13  *      UDP datagrams are now sent via an UDP socket instead of magic
14  *      RAW socket tricks.
15  *
16  *      Original copyright and comments left intact. They might not
17  *      match the code anymore.
18  */
19
20 /*-
21  * Copyright (c) 1990, 1993
22  *      The Regents of the University of California.  All rights reserved.
23  *
24  * This code is derived from software contributed to Berkeley by
25  * Van Jacobson.
26  *
27  * Redistribution and use in source and binary forms, with or without
28  * modification, are permitted provided that the following conditions
29  * are met:
30  * 1. Redistributions of source code must retain the above copyright
31  *    notice, this list of conditions and the following disclaimer.
32  * 2. Redistributions in binary form must reproduce the above copyright
33  *    notice, this list of conditions and the following disclaimer in the
34  *    documentation and/or other materials provided with the distribution.
35  * 3. All advertising materials mentioning features or use of this software
36  *    must display the following acknowledgement:
37  *      This product includes software developed by the University of
38  *      California, Berkeley and its contributors.
39  * 4. Neither the name of the University nor the names of its contributors
40  *    may be used to endorse or promote products derived from this software
41  *    without specific prior written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  */
55
56 #ifndef lint
57 char copyright[] =
58 "@(#) Copyright (c) 1990, 1993\n\
59         The Regents of the University of California.  All rights reserved.\n";
60 #endif /* not lint */
61
62 /*
63  * traceroute host  - trace the route ip packets follow going to "host".
64  *
65  * Attempt to trace the route an ip packet would follow to some
66  * internet host.  We find out intermediate hops by launching probe
67  * packets with a small ttl (time to live) then listening for an
68  * icmp "time exceeded" reply from a gateway.  We start our probes
69  * with a ttl of one and increase by one until we get an icmp "port
70  * unreachable" (which means we got to "host") or hit a max (which
71  * defaults to 30 hops & can be changed with the -m flag).  Three
72  * probes (change with -q flag) are sent at each ttl setting and a
73  * line is printed showing the ttl, address of the gateway and
74  * round trip time of each probe.  If the probe answers come from
75  * different gateways, the address of each responding system will
76  * be printed.  If there is no response within a 5 sec. timeout
77  * interval (changed with the -w flag), a "*" is printed for that
78  * probe.
79  *
80  * Probe packets are UDP format.  We don't want the destination
81  * host to process them so the destination port is set to an
82  * unlikely value (if some clod on the destination is using that
83  * value, it can be changed with the -p flag).
84  *
85  * A sample use might be:
86  *
87  *     [yak 71]% traceroute nis.nsf.net.
88  *     traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
89  *      1  helios.ee.lbl.gov (128.3.112.1)  19 ms  19 ms  0 ms
90  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
91  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
92  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  39 ms
93  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  39 ms  39 ms  39 ms
94  *      6  128.32.197.4 (128.32.197.4)  40 ms  59 ms  59 ms
95  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  59 ms
96  *      8  129.140.70.13 (129.140.70.13)  99 ms  99 ms  80 ms
97  *      9  129.140.71.6 (129.140.71.6)  139 ms  239 ms  319 ms
98  *     10  129.140.81.7 (129.140.81.7)  220 ms  199 ms  199 ms
99  *     11  nic.merit.edu (35.1.1.48)  239 ms  239 ms  239 ms
100  *
101  * Note that lines 2 & 3 are the same.  This is due to a buggy
102  * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
103  * packets with a zero ttl.
104  *
105  * A more interesting example is:
106  *
107  *     [yak 72]% traceroute allspice.lcs.mit.edu.
108  *     traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
109  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
110  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  19 ms  19 ms
111  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  19 ms
112  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  19 ms  39 ms  39 ms
113  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  20 ms  39 ms  39 ms
114  *      6  128.32.197.4 (128.32.197.4)  59 ms  119 ms  39 ms
115  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  39 ms
116  *      8  129.140.70.13 (129.140.70.13)  80 ms  79 ms  99 ms
117  *      9  129.140.71.6 (129.140.71.6)  139 ms  139 ms  159 ms
118  *     10  129.140.81.7 (129.140.81.7)  199 ms  180 ms  300 ms
119  *     11  129.140.72.17 (129.140.72.17)  300 ms  239 ms  239 ms
120  *     12  * * *
121  *     13  128.121.54.72 (128.121.54.72)  259 ms  499 ms  279 ms
122  *     14  * * *
123  *     15  * * *
124  *     16  * * *
125  *     17  * * *
126  *     18  ALLSPICE.LCS.MIT.EDU (18.26.0.115)  339 ms  279 ms  279 ms
127  *
128  * (I start to see why I'm having so much trouble with mail to
129  * MIT.)  Note that the gateways 12, 14, 15, 16 & 17 hops away
130  * either don't send ICMP "time exceeded" messages or send them
131  * with a ttl too small to reach us.  14 - 17 are running the
132  * MIT C Gateway code that doesn't send "time exceeded"s.  God
133  * only knows what's going on with 12.
134  *
135  * The silent gateway 12 in the above may be the result of a bug in
136  * the 4.[23]BSD network code (and its derivatives):  4.x (x <= 3)
137  * sends an unreachable message using whatever ttl remains in the
138  * original datagram.  Since, for gateways, the remaining ttl is
139  * zero, the icmp "time exceeded" is guaranteed to not make it back
140  * to us.  The behavior of this bug is slightly more interesting
141  * when it appears on the destination system:
142  *
143  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
144  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  39 ms
145  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  39 ms  19 ms
146  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  19 ms
147  *      5  ccn-nerif35.Berkeley.EDU (128.32.168.35)  39 ms  39 ms  39 ms
148  *      6  csgw.Berkeley.EDU (128.32.133.254)  39 ms  59 ms  39 ms
149  *      7  * * *
150  *      8  * * *
151  *      9  * * *
152  *     10  * * *
153  *     11  * * *
154  *     12  * * *
155  *     13  rip.Berkeley.EDU (128.32.131.22)  59 ms !  39 ms !  39 ms !
156  *
157  * Notice that there are 12 "gateways" (13 is the final
158  * destination) and exactly the last half of them are "missing".
159  * What's really happening is that rip (a Sun-3 running Sun OS3.5)
160  * is using the ttl from our arriving datagram as the ttl in its
161  * icmp reply.  So, the reply will time out on the return path
162  * (with no notice sent to anyone since icmp's aren't sent for
163  * icmp's) until we probe with a ttl that's at least twice the path
164  * length.  I.e., rip is really only 7 hops away.  A reply that
165  * returns with a ttl of 1 is a clue this problem exists.
166  * Traceroute prints a "!" after the time if the ttl is <= 1.
167  * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
168  * non-standard (HPUX) software, expect to see this problem
169  * frequently and/or take care picking the target host of your
170  * probes.
171  *
172  * Other possible annotations after the time are !H, !N, !P (got a host,
173  * network or protocol unreachable, respectively), !S or !F (source
174  * route failed or fragmentation needed -- neither of these should
175  * ever occur and the associated gateway is busted if you see one).  If
176  * almost all the probes result in some kind of unreachable, traceroute
177  * will give up and exit.
178  *
179  * Notes
180  * -----
181  * This program must be run by root or be setuid.  (I suggest that
182  * you *don't* make it setuid -- casual use could result in a lot
183  * of unnecessary traffic on our poor, congested nets.)
184  *
185  * This program requires a kernel mod that does not appear in any
186  * system available from Berkeley:  A raw ip socket using proto
187  * IPPROTO_RAW must interpret the data sent as an ip datagram (as
188  * opposed to data to be wrapped in a ip datagram).  See the README
189  * file that came with the source to this program for a description
190  * of the mods I made to /sys/netinet/raw_ip.c.  Your mileage may
191  * vary.  But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
192  * MODIFIED TO RUN THIS PROGRAM.
193  *
194  * The udp port usage may appear bizarre (well, ok, it is bizarre).
195  * The problem is that an icmp message only contains 8 bytes of
196  * data from the original datagram.  8 bytes is the size of a udp
197  * header so, if we want to associate replies with the original
198  * datagram, the necessary information must be encoded into the
199  * udp header (the ip id could be used but there's no way to
200  * interlock with the kernel's assignment of ip id's and, anyway,
201  * it would have taken a lot more kernel hacking to allow this
202  * code to set the ip id).  So, to allow two or more users to
203  * use traceroute simultaneously, we use this task's pid as the
204  * source port (the high bit is set to move the port number out
205  * of the "likely" range).  To keep track of which probe is being
206  * replied to (so times and/or hop counts don't get confused by a
207  * reply that was delayed in transit), we increment the destination
208  * port number before each probe.
209  *
210  * Don't use this as a coding example.  I was trying to find a
211  * routing problem and this code sort-of popped out after 48 hours
212  * without sleep.  I was amazed it ever compiled, much less ran.
213  *
214  * I stole the idea for this program from Steve Deering.  Since
215  * the first release, I've learned that had I attended the right
216  * IETF working group meetings, I also could have stolen it from Guy
217  * Almes or Matt Mathis.  I don't know (or care) who came up with
218  * the idea first.  I envy the originators' perspicacity and I'm
219  * glad they didn't keep the idea a secret.
220  *
221  * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
222  * enhancements to the original distribution.
223  *
224  * I've hacked up a round-trip-route version of this that works by
225  * sending a loose-source-routed udp datagram through the destination
226  * back to yourself.  Unfortunately, SO many gateways botch source
227  * routing, the thing is almost worthless.  Maybe one day...
228  *
229  *  -- Van Jacobson (van@helios.ee.lbl.gov)
230  *     Tue Dec 20 03:50:13 PST 1988
231  */
232
233 #include <sys/param.h>
234 #include <sys/time.h>
235 #include <sys/socket.h>
236 #include <sys/file.h>
237 #include <sys/ioctl.h>
238 #include <net/if.h>
239
240 #if __linux__
241 #include <endian.h>
242 #endif
243 #include <netinet/in_systm.h>
244 #include <netinet/in.h>
245 #include <netinet/ip.h>
246 #include <netinet/ip_icmp.h>
247 #include <netinet/udp.h>
248
249 #include <netinet/ip6.h>
250 #include <netinet/icmp6.h>
251 #include <linux/types.h>
252
253 #include <arpa/inet.h>
254
255 #include <netdb.h>
256 #include <stdio.h>
257 #include <errno.h>
258 #include <stdlib.h>
259 #include <string.h>
260 #include <unistd.h>
261
262 #include "SNAPSHOT.h"
263
264 #ifndef SOL_IPV6
265 #define SOL_IPV6 IPPROTO_IPV6
266 #endif
267  
268 #define MAXPACKET       65535
269 #ifndef MAXHOSTNAMELEN
270 #define MAXHOSTNAMELEN  64
271 #endif
272
273 #ifndef FD_SET
274 #define NFDBITS         (8*sizeof(fd_set))
275 #define FD_SETSIZE      NFDBITS
276 #define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
277 #define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
278 #define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
279 #define FD_ZERO(p)      bzero((char *)(p), sizeof(*(p)))
280 #endif
281
282 #define Fprintf (void)fprintf
283 #define Printf (void)printf
284
285 u_char  packet[512];            /* last inbound (icmp) packet */
286
287 int     wait_for_reply(int, struct sockaddr_in6 *, struct in6_addr *, int);
288 int     packet_ok(u_char *buf, int cc, struct sockaddr_in6 *from,
289                   struct in6_addr *to, int seq, struct timeval *);
290 void    send_probe(int seq, int ttl);
291 double  deltaT (struct timeval *, struct timeval *);
292 void    print(unsigned char *buf, int cc, struct sockaddr_in6 *from);
293 void    tvsub (struct timeval *, struct timeval *);
294 void    usage(void);
295
296 int icmp_sock;                  /* receive (icmp) socket file descriptor */
297 int sndsock;                    /* send (udp) socket file descriptor */
298 struct timezone tz;             /* leftover */
299
300 struct sockaddr_in6 whereto;    /* Who to try to reach */
301
302 struct sockaddr_in6 saddr;
303 struct sockaddr_in6 firsthop;
304 char *source = NULL;
305 char *device = NULL;
306 char *hostname;
307
308 int nprobes = 3;
309 int max_ttl = 30;
310 pid_t ident;
311 u_short port = 32768+666;       /* start udp dest port # for probe packets */
312 int options;                    /* socket options */
313 int verbose;
314 int waittime = 5;               /* time to wait for response (in seconds) */
315 int nflag;                      /* print addresses numerically */
316
317
318 struct pkt_format
319 {
320         __u32 ident;
321         __u32 seq;
322         struct timeval tv;
323 };
324
325 char *sendbuff;
326 int datalen = sizeof(struct pkt_format);
327
328
329
330 int main(int argc, char *argv[])
331 {
332         char pa[MAXHOSTNAMELEN];
333         extern char *optarg;
334         extern int optind;
335         struct hostent *hp;
336         struct sockaddr_in6 from, *to;
337         int ch, i, on, probe, seq, tos, ttl;
338         int socket_errno;
339
340         icmp_sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
341         socket_errno = errno;
342
343         if (setuid(getuid())) {
344                 perror("traceroute6: setuid");
345                 exit(-1);
346         }
347
348         on = 1;
349         seq = tos = 0;
350         to = (struct sockaddr_in6 *)&whereto;
351         while ((ch = getopt(argc, argv, "dm:np:q:rs:t:w:vi:g:V")) != EOF) {
352                 switch(ch) {
353                 case 'd':
354                         options |= SO_DEBUG;
355                         break;
356                 case 'm':
357                         max_ttl = atoi(optarg);
358                         if (max_ttl <= 1) {
359                                 Fprintf(stderr,
360                                     "traceroute: max ttl must be >1.\n");
361                                 exit(1);
362                         }
363                         break;
364                 case 'n':
365                         nflag++;
366                         break;
367                 case 'p':
368                         port = atoi(optarg);
369                         if (port < 1) {
370                                 Fprintf(stderr,
371                                     "traceroute: port must be >0.\n");
372                                 exit(1);
373                         }
374                         break;
375                 case 'q':
376                         nprobes = atoi(optarg);
377                         if (nprobes < 1) {
378                                 Fprintf(stderr,
379                                     "traceroute: nprobes must be >0.\n");
380                                 exit(1);
381                         }
382                         break;
383                 case 'r':
384                         options |= SO_DONTROUTE;
385                         break;
386                 case 's':
387                         /*
388                          * set the ip source address of the outbound
389                          * probe (e.g., on a multi-homed host).
390                          */
391                         source = optarg;
392                         break;
393                 case 'i':
394                         device = optarg;
395                         break;
396                 case 'g':
397                         Fprintf(stderr, "Sorry, rthdr is not yet supported\n");
398                         break;
399                 case 'v':
400                         verbose++;
401                         break;
402                 case 'w':
403                         waittime = atoi(optarg);
404                         if (waittime <= 1) {
405                                 Fprintf(stderr,
406                                     "traceroute: wait must be >1 sec.\n");
407                                 exit(1);
408                         }
409                         break;
410                 case 'V':
411                         printf("traceroute6 utility, iputils-ss%s\n", SNAPSHOT);
412                         exit(0);
413                 default:
414                         usage();
415                 }
416         }
417         argc -= optind;
418         argv += optind;
419
420         if (argc < 1)
421                 usage();
422
423         setlinebuf (stdout);
424
425         (void) bzero((char *)&whereto, sizeof(whereto));
426
427         to->sin6_family = AF_INET6;
428         to->sin6_port = htons(port);
429
430         if (inet_pton(AF_INET6, *argv, &to->sin6_addr) > 0) {
431                 hostname = *argv;
432         } else {
433                 hp = gethostbyname2(*argv, AF_INET6);
434                 if (hp) {
435                         memmove((caddr_t)&to->sin6_addr, hp->h_addr, sizeof(to->sin6_addr));
436                         hostname = (char *)hp->h_name;
437                 } else {
438                         (void)fprintf(stderr,
439                             "traceroute: unknown host %s\n", *argv);
440                         exit(1);
441                 }
442         }
443         firsthop = *to;
444         if (*++argv) {
445                 datalen = atoi(*argv);
446                 /* Message for rpm maintainers: have _shame_. If you want
447                  * to fix something send the patch to me for sanity checking.
448                  * "datalen" patch is a shit. */
449                 if (datalen == 0)
450                         datalen = sizeof(struct pkt_format);
451                 else if (datalen < (int)sizeof(struct pkt_format) ||
452                          datalen >= MAXPACKET) {
453                         Fprintf(stderr,
454                             "traceroute: packet size must be %d <= s < %d.\n",
455                                 (int)sizeof(struct pkt_format), MAXPACKET);
456                         exit(1);
457                 }
458         }
459
460         ident = getpid();
461
462         sendbuff = malloc(datalen);
463         if (sendbuff == NULL) {
464                 fprintf(stderr, "malloc failed\n");
465                 exit(1);
466         }
467
468         if (icmp_sock < 0) {
469                 errno = socket_errno;
470                 perror("traceroute6: icmp socket");
471                 exit(1);
472         }
473
474 #ifdef IPV6_RECVPKTINFO
475         setsockopt(icmp_sock, SOL_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
476         setsockopt(icmp_sock, SOL_IPV6, IPV6_2292PKTINFO, &on, sizeof(on));
477 #else
478         setsockopt(icmp_sock, SOL_IPV6, IPV6_PKTINFO, &on, sizeof(on));
479 #endif
480
481         if (options & SO_DEBUG)
482                 setsockopt(icmp_sock, SOL_SOCKET, SO_DEBUG,
483                            (char *)&on, sizeof(on));
484         if (options & SO_DONTROUTE)
485                 setsockopt(icmp_sock, SOL_SOCKET, SO_DONTROUTE,
486                            (char *)&on, sizeof(on));
487         on = 2;
488         if (setsockopt(icmp_sock, SOL_RAW, IPV6_CHECKSUM, &on, sizeof(on)) < 0) {
489                 perror("setsockopt(RAW_CHECKSUM)");
490                 exit(2);
491         }
492
493         if ((sndsock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
494                 perror("traceroute: UDP socket");
495                 exit(5);
496         }
497 #ifdef SO_SNDBUF
498         if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
499                        sizeof(datalen)) < 0) {
500                 perror("traceroute: SO_SNDBUF");
501                 exit(6);
502         }
503 #endif /* SO_SNDBUF */
504
505         if (options & SO_DEBUG)
506                 (void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
507                                   (char *)&on, sizeof(on));
508         if (options & SO_DONTROUTE)
509                 (void) setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
510                                   (char *)&on, sizeof(on));
511
512         if (source == NULL) {
513                 socklen_t alen;
514                 int probe_fd = socket(AF_INET6, SOCK_DGRAM, 0);
515
516                 if (probe_fd < 0) {
517                         perror("socket");
518                         exit(1);
519                 }
520                 if (device) {
521                         if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1)
522                                 perror("WARNING: interface is ignored");
523                 }
524                 firsthop.sin6_port = htons(1025);
525                 if (connect(probe_fd, (struct sockaddr*)&firsthop, sizeof(firsthop)) == -1) {
526                         perror("connect");
527                         exit(1);
528                 }
529                 alen = sizeof(saddr);
530                 if (getsockname(probe_fd, (struct sockaddr*)&saddr, &alen) == -1) {
531                         perror("getsockname");
532                         exit(1);
533                 }
534                 saddr.sin6_port = 0;
535                 close(probe_fd);
536         } else {
537                 (void) bzero((char *)&saddr, sizeof(saddr));
538                 saddr.sin6_family = AF_INET6;
539                 if (inet_pton(AF_INET6, source, &saddr.sin6_addr) <= 0)
540                 {
541                         Printf("traceroute: unknown addr %s\n", source);
542                         exit(1);
543                 }
544         }
545
546         if (bind(sndsock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
547                 perror ("traceroute: bind sending socket");
548                 exit (1);
549         }
550         if (bind(icmp_sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
551                 perror ("traceroute: bind icmp6 socket");
552                 exit (1);
553         }
554
555         Fprintf(stderr, "traceroute to %s (%s)", hostname,
556                 inet_ntop(AF_INET6, &to->sin6_addr, pa, sizeof(pa)));
557
558         Fprintf(stderr, " from %s",
559                 inet_ntop(AF_INET6, &saddr.sin6_addr, pa, sizeof(pa)));
560         Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl, datalen);
561         (void) fflush(stderr);
562
563         for (ttl = 1; ttl <= max_ttl; ++ttl) {
564                 struct in6_addr lastaddr = {{{0,}}};
565                 int got_there = 0;
566                 int unreachable = 0;
567
568                 Printf("%2d ", ttl);
569                 for (probe = 0; probe < nprobes; ++probe) {
570                         int cc, reset_timer;
571                         struct timeval t1, t2;
572                         struct timezone tz;
573                         struct in6_addr to;
574
575                         gettimeofday(&t1, &tz);
576                         send_probe(++seq, ttl);
577                         reset_timer = 1;
578
579                         while ((cc = wait_for_reply(icmp_sock, &from, &to, reset_timer)) != 0) {
580                                 gettimeofday(&t2, &tz);
581                                 if ((i = packet_ok(packet, cc, &from, &to, seq, &t1))) {
582                                         reset_timer = 1;
583                                         if (memcmp(&from.sin6_addr, &lastaddr, sizeof(from.sin6_addr))) {
584                                                 print(packet, cc, &from);
585                                                 memcpy(&lastaddr,
586                                                        &from.sin6_addr,
587                                                        sizeof(lastaddr));
588                                         }
589                                         Printf("  %g ms", deltaT(&t1, &t2));
590                                         switch(i - 1) {
591                                         case ICMP6_DST_UNREACH_NOPORT:
592                                                 ++got_there;
593                                                 break;
594
595                                         case ICMP6_DST_UNREACH_NOROUTE:
596                                                 ++unreachable;
597                                                 Printf(" !N");
598                                                 break;
599                                         case ICMP6_DST_UNREACH_ADDR:
600                                                 ++unreachable;
601                                                 Printf(" !H");
602                                                 break;
603
604                                         case ICMP6_DST_UNREACH_ADMIN:
605                                                 ++unreachable;
606                                                 Printf(" !S");
607                                                 break;
608                                         }
609                                         break;
610                                 } else
611                                         reset_timer = 0;
612                         }
613                         if (cc <= 0)
614                                 Printf(" *");
615                         (void) fflush(stdout);
616                 }
617                 putchar('\n');
618                 if (got_there ||
619                     (unreachable > 0 && unreachable >= nprobes-1))
620                         exit(0);
621         }
622
623         return 0;
624 }
625
626 int
627 wait_for_reply(sock, from, to, reset_timer)
628         int sock;
629         struct sockaddr_in6 *from;
630         struct in6_addr *to;
631         int reset_timer;
632 {
633         fd_set fds;
634         static struct timeval wait;
635         int cc = 0;
636         char cbuf[512];
637
638         FD_ZERO(&fds);
639         FD_SET(sock, &fds);
640         if (reset_timer) {
641                 /*
642                  * traceroute could hang if someone else has a ping
643                  * running and our ICMP reply gets dropped but we don't
644                  * realize it because we keep waking up to handle those
645                  * other ICMP packets that keep coming in.  To fix this,
646                  * "reset_timer" will only be true if the last packet that
647                  * came in was for us or if this is the first time we're
648                  * waiting for a reply since sending out a probe.  Note
649                  * that this takes advantage of the select() feature on
650                  * Linux where the remaining timeout is written to the
651                  * struct timeval area.
652                  */
653                 wait.tv_sec = waittime;
654                 wait.tv_usec = 0;
655         }
656
657         if (select(sock+1, &fds, (fd_set *)0, (fd_set *)0, &wait) > 0) {
658                 struct iovec iov;
659                 struct msghdr msg;
660                 iov.iov_base = packet;
661                 iov.iov_len = sizeof(packet);
662                 msg.msg_name = (void *)from;
663                 msg.msg_namelen = sizeof(*from);
664                 msg.msg_iov = &iov;
665                 msg.msg_iovlen = 1;
666                 msg.msg_flags = 0;
667                 msg.msg_control = cbuf;
668                 msg.msg_controllen = sizeof(cbuf);
669
670                 cc = recvmsg(icmp_sock, &msg, 0);
671                 if (cc >= 0) {
672                         struct cmsghdr *cmsg;
673                         struct in6_pktinfo *ipi;
674
675                         for (cmsg = CMSG_FIRSTHDR(&msg);
676                              cmsg;
677                              cmsg = CMSG_NXTHDR(&msg, cmsg)) {
678                                 if (cmsg->cmsg_level != SOL_IPV6)
679                                         continue;
680                                 switch (cmsg->cmsg_type) {
681                                 case IPV6_PKTINFO:
682 #ifdef IPV6_2292PKTINFO
683                                 case IPV6_2292PKTINFO:
684 #endif
685                                         ipi = (struct in6_pktinfo *)CMSG_DATA(cmsg);
686                                         memcpy(to, ipi, sizeof(*to));
687                                 }
688                         }
689                 }
690         }
691
692         return(cc);
693 }
694
695
696 void send_probe(int seq, int ttl)
697 {
698         struct pkt_format *pkt = (struct pkt_format *) sendbuff;
699         int i;
700
701         pkt->ident = htonl(ident);
702         pkt->seq = htonl(seq);
703         gettimeofday(&pkt->tv, &tz);
704
705         i = setsockopt(sndsock, SOL_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
706         if (i < 0)
707         {
708                 perror("setsockopt");
709                 exit(1);
710         }
711
712         do {
713                 i = sendto(sndsock, sendbuff, datalen, 0,
714                            (struct sockaddr *)&whereto, sizeof(whereto));
715         } while (i<0 && errno == ECONNREFUSED);
716
717         if (i < 0 || i != datalen)  {
718                 if (i<0)
719                         perror("sendto");
720                 Printf("traceroute: wrote %s %d chars, ret=%d\n", hostname,
721                         datalen, i);
722                 (void) fflush(stdout);
723         }
724 }
725
726
727 double deltaT(struct timeval *t1p, struct timeval *t2p)
728 {
729         register double dt;
730
731         dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
732              (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
733         return (dt);
734 }
735
736
737 /*
738  * Convert an ICMP "type" field to a printable string.
739  */
740 char * pr_type(unsigned char t)
741 {
742         switch(t) {
743         /* Unknown */
744         case 0:
745                 return "Error";
746         case 1:
747                 /* ICMP6_DST_UNREACH: */
748                 return "Destination Unreachable";
749         case 2:
750                 /* ICMP6_PACKET_TOO_BIG: */
751                 return "Packet Too Big";
752         case 3:
753                 /* ICMP6_TIME_EXCEEDED */
754                 return "Time Exceeded in Transit";
755         case 4:
756                 /* ICMP6_PARAM_PROB */
757                 return "Parameter Problem";
758         case 128:
759                 /* ICMP6_ECHO_REQUEST */
760                 return "Echo Request";
761         case 129:
762                 /* ICMP6_ECHO_REPLY */
763                 return "Echo Reply";
764         case 130:
765                 /* ICMP6_MEMBERSHIP_QUERY */
766                 return "Membership Query";
767         case 131:
768                 /* ICMP6_MEMBERSHIP_REPORT */
769                 return "Membership Report";
770         case 132:
771                 /* ICMP6_MEMBERSHIP_REDUCTION */
772                 return "Membership Reduction";
773         case 133:
774                 /* ND_ROUTER_SOLICIT */
775                 return "Router Solicitation";
776         case 134:
777                 /* ND_ROUTER_ADVERT */
778                 return "Router Advertisement";
779         case 135:
780                 /* ND_NEIGHBOR_SOLICIT */
781                 return "Neighbor Solicitation";
782         case 136:
783                 /* ND_NEIGHBOR_ADVERT */
784                 return "Neighbor Advertisement";
785         case 137:
786                 /* ND_REDIRECT */
787                 return "Redirect";
788         }
789
790         return("OUT-OF-RANGE");
791 }
792
793
794 int packet_ok(u_char *buf, int cc, struct sockaddr_in6 *from, 
795               struct in6_addr *to, int seq,
796               struct timeval *tv)
797 {
798         struct icmp6_hdr *icp;
799         u_char type, code;
800
801         icp = (struct icmp6_hdr *) buf;
802
803         type = icp->icmp6_type;
804         code = icp->icmp6_code;
805
806         if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT) ||
807             type == ICMP6_DST_UNREACH)
808         {
809                 struct ip6_hdr *hip;
810                 struct udphdr *up;
811                 int nexthdr;
812
813                 hip = (struct ip6_hdr *) (icp + 1);
814                 up = (struct udphdr *)(hip+1);
815                 nexthdr = hip->ip6_nxt;
816
817                 if (nexthdr == 44) {
818                         nexthdr = *(unsigned char*)up;
819                         up++;
820                 }
821                 if (nexthdr == IPPROTO_UDP)
822                 {
823                         struct pkt_format *pkt;
824                         
825                         pkt = (struct pkt_format *) (up + 1);
826
827                         if (ntohl(pkt->ident) == ident &&
828                             ntohl(pkt->seq) == seq)
829                         {
830                                 *tv = pkt->tv;
831                                 return (type == ICMP6_TIME_EXCEEDED ? -1 : code+1);
832                         }
833                 }
834
835         }
836
837         if (verbose) {
838                 unsigned char *p;
839                 char pa1[MAXHOSTNAMELEN];
840                 char pa2[MAXHOSTNAMELEN];
841                 int i;
842
843                 p = (unsigned char *) (icp + 1);
844
845                 Printf("\n%d bytes from %s to %s", cc,
846                        inet_ntop(AF_INET6, &from->sin6_addr, pa1, sizeof(pa1)),
847                        inet_ntop(AF_INET6, to, pa2, sizeof(pa2)));
848                 
849                 Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
850                        icp->icmp6_code);
851
852                 cc -= sizeof(struct icmp6_hdr);
853                 for (i = 0; i < cc ; i++) {
854                         if (i % 16 == 0)
855                                 Printf("%04x:", i);
856                         if (i % 4 == 0)
857                                 Printf(" ");
858                         Printf("%02x", 0xff & (unsigned)p[i]);
859                         if (i % 16 == 15 && i + 1 < cc)
860                                 Printf("\n");
861                 }
862                 Printf("\n");
863         }
864
865         return(0);
866 }
867
868
869 void print(unsigned char *buf, int cc, struct sockaddr_in6 *from)
870 {
871         char pa[MAXHOSTNAMELEN];
872
873         if (nflag)
874                 Printf(" %s", inet_ntop(AF_INET6, &from->sin6_addr,
875                                         pa, sizeof(pa)));
876         else
877         {
878                 const char *hostname;
879                 struct hostent *hp;
880                 
881                 hostname = inet_ntop(AF_INET6, &from->sin6_addr, pa, sizeof(pa));
882
883                 if ((hp = gethostbyaddr((char *)&from->sin6_addr,
884                                         sizeof(from->sin6_addr), AF_INET6)))
885                         hostname = hp->h_name;
886                 
887                 Printf(" %s (%s)", hostname, pa);
888         }
889 }
890
891
892 /*
893  * Subtract 2 timeval structs:  out = out - in.
894  * Out is assumed to be >= in.
895  */
896 void
897 tvsub(out, in)
898         register struct timeval *out, *in;
899 {
900         if ((out->tv_usec -= in->tv_usec) < 0)   {
901                 out->tv_sec--;
902                 out->tv_usec += 1000000;
903         }
904         out->tv_sec -= in->tv_sec;
905 }
906
907 void usage(void)
908 {
909         fprintf(stderr,
910 "Usage: traceroute6 [-dnrvV] [-m max_ttl] [-p port#] [-q nqueries]\n\t\
911 [-s src_addr] [-t tos] [-w wait] host [data size]\n");
912         exit(1);
913 }