Ditch the sysvinit stuff
[profile/ivi/iputils.git] / 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 #define MAX_HOSTNAMELEN NI_MAXHOST
270
271 #ifndef FD_SET
272 #define NFDBITS         (8*sizeof(fd_set))
273 #define FD_SETSIZE      NFDBITS
274 #define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
275 #define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
276 #define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
277 #define FD_ZERO(p)      memset((char *)(p), 0, sizeof(*(p)))
278 #endif
279
280 #define Fprintf (void)fprintf
281 #define Printf (void)printf
282
283 u_char  packet[512];            /* last inbound (icmp) packet */
284
285 int     wait_for_reply(int, struct sockaddr_in6 *, struct in6_addr *, int);
286 int     packet_ok(u_char *buf, int cc, struct sockaddr_in6 *from,
287                   struct in6_addr *to, int seq, struct timeval *);
288 void    send_probe(int seq, int ttl);
289 double  deltaT (struct timeval *, struct timeval *);
290 void    print(unsigned char *buf, int cc, struct sockaddr_in6 *from);
291 void    tvsub (struct timeval *, struct timeval *);
292 void    usage(void);
293
294 int icmp_sock;                  /* receive (icmp) socket file descriptor */
295 int sndsock;                    /* send (udp) socket file descriptor */
296 struct timezone tz;             /* leftover */
297
298 struct sockaddr_in6 whereto;    /* Who to try to reach */
299
300 struct sockaddr_in6 saddr;
301 struct sockaddr_in6 firsthop;
302 char *source = NULL;
303 char *device = NULL;
304 char *hostname;
305
306 int nprobes = 3;
307 int max_ttl = 30;
308 pid_t ident;
309 u_short port = 32768+666;       /* start udp dest port # for probe packets */
310 int options;                    /* socket options */
311 int verbose;
312 int waittime = 5;               /* time to wait for response (in seconds) */
313 int nflag;                      /* print addresses numerically */
314
315
316 struct pkt_format
317 {
318         __u32 ident;
319         __u32 seq;
320         struct timeval tv;
321 };
322
323 char *sendbuff;
324 int datalen = sizeof(struct pkt_format);
325
326
327
328 int main(int argc, char *argv[])
329 {
330         char pa[MAX_HOSTNAMELEN];
331         extern char *optarg;
332         extern int optind;
333         struct hostent *hp;
334         struct sockaddr_in6 from, *to;
335         int ch, i, on, probe, seq, tos, ttl;
336         int socket_errno;
337
338         icmp_sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
339         socket_errno = errno;
340
341         if (setuid(getuid())) {
342                 perror("traceroute6: setuid");
343                 exit(-1);
344         }
345
346         on = 1;
347         seq = tos = 0;
348         to = (struct sockaddr_in6 *)&whereto;
349         while ((ch = getopt(argc, argv, "dm:np:q:rs:t:w:vi:g:V")) != EOF) {
350                 switch(ch) {
351                 case 'd':
352                         options |= SO_DEBUG;
353                         break;
354                 case 'm':
355                         max_ttl = atoi(optarg);
356                         if (max_ttl <= 1) {
357                                 Fprintf(stderr,
358                                     "traceroute: max ttl must be >1.\n");
359                                 exit(1);
360                         }
361                         break;
362                 case 'n':
363                         nflag++;
364                         break;
365                 case 'p':
366                         port = atoi(optarg);
367                         if (port < 1) {
368                                 Fprintf(stderr,
369                                     "traceroute: port must be >0.\n");
370                                 exit(1);
371                         }
372                         break;
373                 case 'q':
374                         nprobes = atoi(optarg);
375                         if (nprobes < 1) {
376                                 Fprintf(stderr,
377                                     "traceroute: nprobes must be >0.\n");
378                                 exit(1);
379                         }
380                         break;
381                 case 'r':
382                         options |= SO_DONTROUTE;
383                         break;
384                 case 's':
385                         /*
386                          * set the ip source address of the outbound
387                          * probe (e.g., on a multi-homed host).
388                          */
389                         source = optarg;
390                         break;
391                 case 'i':
392                         device = optarg;
393                         break;
394                 case 'g':
395                         Fprintf(stderr, "Sorry, rthdr is not yet supported\n");
396                         break;
397                 case 'v':
398                         verbose++;
399                         break;
400                 case 'w':
401                         waittime = atoi(optarg);
402                         if (waittime <= 1) {
403                                 Fprintf(stderr,
404                                     "traceroute: wait must be >1 sec.\n");
405                                 exit(1);
406                         }
407                         break;
408                 case 'V':
409                         printf("traceroute6 utility, iputils-ss%s\n", SNAPSHOT);
410                         exit(0);
411                 default:
412                         usage();
413                 }
414         }
415         argc -= optind;
416         argv += optind;
417
418         if (argc < 1)
419                 usage();
420
421         setlinebuf (stdout);
422
423         (void) memset((char *)&whereto, 0, sizeof(whereto));
424
425         to->sin6_family = AF_INET6;
426         to->sin6_port = htons(port);
427
428         if (inet_pton(AF_INET6, *argv, &to->sin6_addr) > 0) {
429                 hostname = *argv;
430         } else {
431                 hp = gethostbyname2(*argv, AF_INET6);
432                 if (hp) {
433                         memmove((caddr_t)&to->sin6_addr, hp->h_addr, sizeof(to->sin6_addr));
434                         hostname = (char *)hp->h_name;
435                 } else {
436                         (void)fprintf(stderr,
437                             "traceroute: unknown host %s\n", *argv);
438                         exit(1);
439                 }
440         }
441         firsthop = *to;
442         if (*++argv) {
443                 datalen = atoi(*argv);
444                 /* Message for rpm maintainers: have _shame_. If you want
445                  * to fix something send the patch to me for sanity checking.
446                  * "datalen" patch is a shit. */
447                 if (datalen == 0)
448                         datalen = sizeof(struct pkt_format);
449                 else if (datalen < (int)sizeof(struct pkt_format) ||
450                          datalen >= MAXPACKET) {
451                         Fprintf(stderr,
452                             "traceroute: packet size must be %d <= s < %d.\n",
453                                 (int)sizeof(struct pkt_format), MAXPACKET);
454                         exit(1);
455                 }
456         }
457
458         ident = getpid();
459
460         sendbuff = malloc(datalen);
461         if (sendbuff == NULL) {
462                 fprintf(stderr, "malloc failed\n");
463                 exit(1);
464         }
465
466         if (icmp_sock < 0) {
467                 errno = socket_errno;
468                 perror("traceroute6: icmp socket");
469                 exit(1);
470         }
471
472 #ifdef IPV6_RECVPKTINFO
473         setsockopt(icmp_sock, SOL_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
474         setsockopt(icmp_sock, SOL_IPV6, IPV6_2292PKTINFO, &on, sizeof(on));
475 #else
476         setsockopt(icmp_sock, SOL_IPV6, IPV6_PKTINFO, &on, sizeof(on));
477 #endif
478
479         if (options & SO_DEBUG)
480                 setsockopt(icmp_sock, SOL_SOCKET, SO_DEBUG,
481                            (char *)&on, sizeof(on));
482         if (options & SO_DONTROUTE)
483                 setsockopt(icmp_sock, SOL_SOCKET, SO_DONTROUTE,
484                            (char *)&on, sizeof(on));
485
486 #ifdef __linux__
487         on = 2;
488         if (setsockopt(icmp_sock, SOL_RAW, IPV6_CHECKSUM, &on, sizeof(on)) < 0) {
489                 /* checksum should be enabled by default and setting this
490                  * option might fail anyway.
491                  */
492                 fprintf(stderr, "setsockopt(RAW_CHECKSUM) failed - try to continue.");
493         }
494 #endif
495
496         if ((sndsock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
497                 perror("traceroute: UDP socket");
498                 exit(5);
499         }
500 #ifdef SO_SNDBUF
501         if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
502                        sizeof(datalen)) < 0) {
503                 perror("traceroute: SO_SNDBUF");
504                 exit(6);
505         }
506 #endif /* SO_SNDBUF */
507
508         if (options & SO_DEBUG)
509                 (void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
510                                   (char *)&on, sizeof(on));
511         if (options & SO_DONTROUTE)
512                 (void) setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
513                                   (char *)&on, sizeof(on));
514
515         if (source == NULL) {
516                 socklen_t alen;
517                 int probe_fd = socket(AF_INET6, SOCK_DGRAM, 0);
518
519                 if (probe_fd < 0) {
520                         perror("socket");
521                         exit(1);
522                 }
523                 if (device) {
524                         if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1)
525                                 perror("WARNING: interface is ignored");
526                 }
527                 firsthop.sin6_port = htons(1025);
528                 if (connect(probe_fd, (struct sockaddr*)&firsthop, sizeof(firsthop)) == -1) {
529                         perror("connect");
530                         exit(1);
531                 }
532                 alen = sizeof(saddr);
533                 if (getsockname(probe_fd, (struct sockaddr*)&saddr, &alen) == -1) {
534                         perror("getsockname");
535                         exit(1);
536                 }
537                 saddr.sin6_port = 0;
538                 close(probe_fd);
539         } else {
540                 (void) memset((char *)&saddr, 0, sizeof(saddr));
541                 saddr.sin6_family = AF_INET6;
542                 if (inet_pton(AF_INET6, source, &saddr.sin6_addr) <= 0)
543                 {
544                         Printf("traceroute: unknown addr %s\n", source);
545                         exit(1);
546                 }
547         }
548
549         if (bind(sndsock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
550                 perror ("traceroute: bind sending socket");
551                 exit (1);
552         }
553         if (bind(icmp_sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
554                 perror ("traceroute: bind icmp6 socket");
555                 exit (1);
556         }
557
558         Fprintf(stderr, "traceroute to %s (%s)", hostname,
559                 inet_ntop(AF_INET6, &to->sin6_addr, pa, sizeof(pa)));
560
561         Fprintf(stderr, " from %s",
562                 inet_ntop(AF_INET6, &saddr.sin6_addr, pa, sizeof(pa)));
563         Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl, datalen);
564         (void) fflush(stderr);
565
566         for (ttl = 1; ttl <= max_ttl; ++ttl) {
567                 struct in6_addr lastaddr = {{{0,}}};
568                 int got_there = 0;
569                 int unreachable = 0;
570
571                 Printf("%2d ", ttl);
572                 for (probe = 0; probe < nprobes; ++probe) {
573                         int cc, reset_timer;
574                         struct timeval t1, t2;
575                         struct timezone tz;
576                         struct in6_addr to;
577
578                         gettimeofday(&t1, &tz);
579                         send_probe(++seq, ttl);
580                         reset_timer = 1;
581
582                         while ((cc = wait_for_reply(icmp_sock, &from, &to, reset_timer)) != 0) {
583                                 gettimeofday(&t2, &tz);
584                                 if ((i = packet_ok(packet, cc, &from, &to, seq, &t1))) {
585                                         reset_timer = 1;
586                                         if (memcmp(&from.sin6_addr, &lastaddr, sizeof(from.sin6_addr))) {
587                                                 print(packet, cc, &from);
588                                                 memcpy(&lastaddr,
589                                                        &from.sin6_addr,
590                                                        sizeof(lastaddr));
591                                         }
592                                         Printf("  %g ms", deltaT(&t1, &t2));
593                                         switch(i - 1) {
594                                         case ICMP6_DST_UNREACH_NOPORT:
595                                                 ++got_there;
596                                                 break;
597
598                                         case ICMP6_DST_UNREACH_NOROUTE:
599                                                 ++unreachable;
600                                                 Printf(" !N");
601                                                 break;
602                                         case ICMP6_DST_UNREACH_ADDR:
603                                                 ++unreachable;
604                                                 Printf(" !H");
605                                                 break;
606
607                                         case ICMP6_DST_UNREACH_ADMIN:
608                                                 ++unreachable;
609                                                 Printf(" !S");
610                                                 break;
611                                         }
612                                         break;
613                                 } else
614                                         reset_timer = 0;
615                         }
616                         if (cc <= 0)
617                                 Printf(" *");
618                         (void) fflush(stdout);
619                 }
620                 putchar('\n');
621                 if (got_there ||
622                     (unreachable > 0 && unreachable >= nprobes-1))
623                         exit(0);
624         }
625
626         return 0;
627 }
628
629 int
630 wait_for_reply(sock, from, to, reset_timer)
631         int sock;
632         struct sockaddr_in6 *from;
633         struct in6_addr *to;
634         int reset_timer;
635 {
636         fd_set fds;
637         static struct timeval wait;
638         int cc = 0;
639         char cbuf[512];
640
641         FD_ZERO(&fds);
642         FD_SET(sock, &fds);
643         if (reset_timer) {
644                 /*
645                  * traceroute could hang if someone else has a ping
646                  * running and our ICMP reply gets dropped but we don't
647                  * realize it because we keep waking up to handle those
648                  * other ICMP packets that keep coming in.  To fix this,
649                  * "reset_timer" will only be true if the last packet that
650                  * came in was for us or if this is the first time we're
651                  * waiting for a reply since sending out a probe.  Note
652                  * that this takes advantage of the select() feature on
653                  * Linux where the remaining timeout is written to the
654                  * struct timeval area.
655                  */
656                 wait.tv_sec = waittime;
657                 wait.tv_usec = 0;
658         }
659
660         if (select(sock+1, &fds, (fd_set *)0, (fd_set *)0, &wait) > 0) {
661                 struct iovec iov;
662                 struct msghdr msg;
663                 iov.iov_base = packet;
664                 iov.iov_len = sizeof(packet);
665                 msg.msg_name = (void *)from;
666                 msg.msg_namelen = sizeof(*from);
667                 msg.msg_iov = &iov;
668                 msg.msg_iovlen = 1;
669                 msg.msg_flags = 0;
670                 msg.msg_control = cbuf;
671                 msg.msg_controllen = sizeof(cbuf);
672
673                 cc = recvmsg(icmp_sock, &msg, 0);
674                 if (cc >= 0) {
675                         struct cmsghdr *cmsg;
676                         struct in6_pktinfo *ipi;
677
678                         for (cmsg = CMSG_FIRSTHDR(&msg);
679                              cmsg;
680                              cmsg = CMSG_NXTHDR(&msg, cmsg)) {
681                                 if (cmsg->cmsg_level != SOL_IPV6)
682                                         continue;
683                                 switch (cmsg->cmsg_type) {
684                                 case IPV6_PKTINFO:
685 #ifdef IPV6_2292PKTINFO
686                                 case IPV6_2292PKTINFO:
687 #endif
688                                         ipi = (struct in6_pktinfo *)CMSG_DATA(cmsg);
689                                         memcpy(to, ipi, sizeof(*to));
690                                 }
691                         }
692                 }
693         }
694
695         return(cc);
696 }
697
698
699 void send_probe(int seq, int ttl)
700 {
701         struct pkt_format *pkt = (struct pkt_format *) sendbuff;
702         int i;
703
704         pkt->ident = htonl(ident);
705         pkt->seq = htonl(seq);
706         gettimeofday(&pkt->tv, &tz);
707
708         i = setsockopt(sndsock, SOL_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
709         if (i < 0)
710         {
711                 perror("setsockopt");
712                 exit(1);
713         }
714
715         do {
716                 i = sendto(sndsock, sendbuff, datalen, 0,
717                            (struct sockaddr *)&whereto, sizeof(whereto));
718         } while (i<0 && errno == ECONNREFUSED);
719
720         if (i < 0 || i != datalen)  {
721                 if (i<0)
722                         perror("sendto");
723                 Printf("traceroute: wrote %s %d chars, ret=%d\n", hostname,
724                         datalen, i);
725                 (void) fflush(stdout);
726         }
727 }
728
729
730 double deltaT(struct timeval *t1p, struct timeval *t2p)
731 {
732         register double dt;
733
734         dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
735              (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
736         return (dt);
737 }
738
739
740 /*
741  * Convert an ICMP "type" field to a printable string.
742  */
743 char * pr_type(unsigned char t)
744 {
745         switch(t) {
746         /* Unknown */
747         case 0:
748                 return "Error";
749         case 1:
750                 /* ICMP6_DST_UNREACH: */
751                 return "Destination Unreachable";
752         case 2:
753                 /* ICMP6_PACKET_TOO_BIG: */
754                 return "Packet Too Big";
755         case 3:
756                 /* ICMP6_TIME_EXCEEDED */
757                 return "Time Exceeded in Transit";
758         case 4:
759                 /* ICMP6_PARAM_PROB */
760                 return "Parameter Problem";
761         case 128:
762                 /* ICMP6_ECHO_REQUEST */
763                 return "Echo Request";
764         case 129:
765                 /* ICMP6_ECHO_REPLY */
766                 return "Echo Reply";
767         case 130:
768                 /* ICMP6_MEMBERSHIP_QUERY */
769                 return "Membership Query";
770         case 131:
771                 /* ICMP6_MEMBERSHIP_REPORT */
772                 return "Membership Report";
773         case 132:
774                 /* ICMP6_MEMBERSHIP_REDUCTION */
775                 return "Membership Reduction";
776         case 133:
777                 /* ND_ROUTER_SOLICIT */
778                 return "Router Solicitation";
779         case 134:
780                 /* ND_ROUTER_ADVERT */
781                 return "Router Advertisement";
782         case 135:
783                 /* ND_NEIGHBOR_SOLICIT */
784                 return "Neighbor Solicitation";
785         case 136:
786                 /* ND_NEIGHBOR_ADVERT */
787                 return "Neighbor Advertisement";
788         case 137:
789                 /* ND_REDIRECT */
790                 return "Redirect";
791         }
792
793         return("OUT-OF-RANGE");
794 }
795
796
797 int packet_ok(u_char *buf, int cc, struct sockaddr_in6 *from,
798               struct in6_addr *to, int seq,
799               struct timeval *tv)
800 {
801         struct icmp6_hdr *icp;
802         u_char type, code;
803
804         icp = (struct icmp6_hdr *) buf;
805
806         type = icp->icmp6_type;
807         code = icp->icmp6_code;
808
809         if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT) ||
810             type == ICMP6_DST_UNREACH)
811         {
812                 struct ip6_hdr *hip;
813                 struct udphdr *up;
814                 int nexthdr;
815
816                 hip = (struct ip6_hdr *) (icp + 1);
817                 up = (struct udphdr *)(hip+1);
818                 nexthdr = hip->ip6_nxt;
819
820                 if (nexthdr == 44) {
821                         nexthdr = *(unsigned char*)up;
822                         up++;
823                 }
824                 if (nexthdr == IPPROTO_UDP)
825                 {
826                         struct pkt_format *pkt;
827
828                         pkt = (struct pkt_format *) (up + 1);
829
830                         if (ntohl(pkt->ident) == ident &&
831                             ntohl(pkt->seq) == seq)
832                         {
833                                 *tv = pkt->tv;
834                                 return (type == ICMP6_TIME_EXCEEDED ? -1 : code+1);
835                         }
836                 }
837
838         }
839
840         if (verbose) {
841                 unsigned char *p;
842                 char pa1[MAX_HOSTNAMELEN];
843                 char pa2[MAX_HOSTNAMELEN];
844                 int i;
845
846                 p = (unsigned char *) (icp + 1);
847
848                 Printf("\n%d bytes from %s to %s", cc,
849                        inet_ntop(AF_INET6, &from->sin6_addr, pa1, sizeof(pa1)),
850                        inet_ntop(AF_INET6, to, pa2, sizeof(pa2)));
851
852                 Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
853                        icp->icmp6_code);
854
855                 cc -= sizeof(struct icmp6_hdr);
856                 for (i = 0; i < cc ; i++) {
857                         if (i % 16 == 0)
858                                 Printf("%04x:", i);
859                         if (i % 4 == 0)
860                                 Printf(" ");
861                         Printf("%02x", 0xff & (unsigned)p[i]);
862                         if (i % 16 == 15 && i + 1 < cc)
863                                 Printf("\n");
864                 }
865                 Printf("\n");
866         }
867
868         return(0);
869 }
870
871
872 void print(unsigned char *buf, int cc, struct sockaddr_in6 *from)
873 {
874         char pa[MAX_HOSTNAMELEN];
875
876         if (nflag)
877                 Printf(" %s", inet_ntop(AF_INET6, &from->sin6_addr,
878                                         pa, sizeof(pa)));
879         else
880         {
881                 const char *hostname;
882                 struct hostent *hp;
883
884                 hostname = inet_ntop(AF_INET6, &from->sin6_addr, pa, sizeof(pa));
885
886                 if ((hp = gethostbyaddr((char *)&from->sin6_addr,
887                                         sizeof(from->sin6_addr), AF_INET6)))
888                         hostname = hp->h_name;
889
890                 Printf(" %s (%s)", hostname, pa);
891         }
892 }
893
894
895 /*
896  * Subtract 2 timeval structs:  out = out - in.
897  * Out is assumed to be >= in.
898  */
899 void
900 tvsub(out, in)
901         register struct timeval *out, *in;
902 {
903         if ((out->tv_usec -= in->tv_usec) < 0)   {
904                 out->tv_sec--;
905                 out->tv_usec += 1000000;
906         }
907         out->tv_sec -= in->tv_sec;
908 }
909
910 void usage(void)
911 {
912         fprintf(stderr,
913 "Usage: traceroute6 [-dnrvV] [-m max_ttl] [-p port#] [-q nqueries]\n\t\
914 [-s src_addr] [-t tos] [-w wait] host [data size]\n");
915         exit(1);
916 }