hush: remove superfluous assignment
[oweals/busybox.git] / networking / traceroute.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Copyright (c) 1988, 1989, 1991, 1994, 1995, 1996, 1997, 1998, 1999, 2000
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * Busybox port by Vladimir Oleynik (C) 2005 <dzo@simtreas.ru>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that: (1) source code distributions
10  * retain the above copyright notice and this paragraph in its entirety, (2)
11  * distributions including binary code include the above copyright notice and
12  * this paragraph in its entirety in the documentation or other materials
13  * provided with the distribution, and (3) all advertising materials mentioning
14  * features or use of this software display the following acknowledgement:
15  * ``This product includes software developed by the University of California,
16  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
17  * the University nor the names of its contributors may be used to endorse
18  * or promote products derived from this software without specific prior
19  * written permission.
20  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
21  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
22  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
23  */
24
25 /*
26  * traceroute host  - trace the route ip packets follow going to "host".
27  *
28  * Attempt to trace the route an ip packet would follow to some
29  * internet host.  We find out intermediate hops by launching probe
30  * packets with a small ttl (time to live) then listening for an
31  * icmp "time exceeded" reply from a gateway.  We start our probes
32  * with a ttl of one and increase by one until we get an icmp "port
33  * unreachable" (which means we got to "host") or hit a max (which
34  * defaults to 30 hops & can be changed with the -m flag).  Three
35  * probes (change with -q flag) are sent at each ttl setting and a
36  * line is printed showing the ttl, address of the gateway and
37  * round trip time of each probe.  If the probe answers come from
38  * different gateways, the address of each responding system will
39  * be printed.  If there is no response within a 5 sec. timeout
40  * interval (changed with the -w flag), a "*" is printed for that
41  * probe.
42  *
43  * Probe packets are UDP format.  We don't want the destination
44  * host to process them so the destination port is set to an
45  * unlikely value (if some clod on the destination is using that
46  * value, it can be changed with the -p flag).
47  *
48  * A sample use might be:
49  *
50  *     [yak 71]% traceroute nis.nsf.net.
51  *     traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
52  *      1  helios.ee.lbl.gov (128.3.112.1)  19 ms  19 ms  0 ms
53  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
54  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
55  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  39 ms
56  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  39 ms  39 ms  39 ms
57  *      6  128.32.197.4 (128.32.197.4)  40 ms  59 ms  59 ms
58  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  59 ms
59  *      8  129.140.70.13 (129.140.70.13)  99 ms  99 ms  80 ms
60  *      9  129.140.71.6 (129.140.71.6)  139 ms  239 ms  319 ms
61  *     10  129.140.81.7 (129.140.81.7)  220 ms  199 ms  199 ms
62  *     11  nic.merit.edu (35.1.1.48)  239 ms  239 ms  239 ms
63  *
64  * Note that lines 2 & 3 are the same.  This is due to a buggy
65  * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
66  * packets with a zero ttl.
67  *
68  * A more interesting example is:
69  *
70  *     [yak 72]% traceroute allspice.lcs.mit.edu.
71  *     traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
72  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
73  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  19 ms  19 ms
74  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  19 ms
75  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  19 ms  39 ms  39 ms
76  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  20 ms  39 ms  39 ms
77  *      6  128.32.197.4 (128.32.197.4)  59 ms  119 ms  39 ms
78  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  39 ms
79  *      8  129.140.70.13 (129.140.70.13)  80 ms  79 ms  99 ms
80  *      9  129.140.71.6 (129.140.71.6)  139 ms  139 ms  159 ms
81  *     10  129.140.81.7 (129.140.81.7)  199 ms  180 ms  300 ms
82  *     11  129.140.72.17 (129.140.72.17)  300 ms  239 ms  239 ms
83  *     12  * * *
84  *     13  128.121.54.72 (128.121.54.72)  259 ms  499 ms  279 ms
85  *     14  * * *
86  *     15  * * *
87  *     16  * * *
88  *     17  * * *
89  *     18  ALLSPICE.LCS.MIT.EDU (18.26.0.115)  339 ms  279 ms  279 ms
90  *
91  * (I start to see why I'm having so much trouble with mail to
92  * MIT.)  Note that the gateways 12, 14, 15, 16 & 17 hops away
93  * either don't send ICMP "time exceeded" messages or send them
94  * with a ttl too small to reach us.  14 - 17 are running the
95  * MIT C Gateway code that doesn't send "time exceeded"s.  God
96  * only knows what's going on with 12.
97  *
98  * The silent gateway 12 in the above may be the result of a bug in
99  * the 4.[23]BSD network code (and its derivatives):  4.x (x <= 3)
100  * sends an unreachable message using whatever ttl remains in the
101  * original datagram.  Since, for gateways, the remaining ttl is
102  * zero, the icmp "time exceeded" is guaranteed to not make it back
103  * to us.  The behavior of this bug is slightly more interesting
104  * when it appears on the destination system:
105  *
106  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
107  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  39 ms
108  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  39 ms  19 ms
109  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  19 ms
110  *      5  ccn-nerif35.Berkeley.EDU (128.32.168.35)  39 ms  39 ms  39 ms
111  *      6  csgw.Berkeley.EDU (128.32.133.254)  39 ms  59 ms  39 ms
112  *      7  * * *
113  *      8  * * *
114  *      9  * * *
115  *     10  * * *
116  *     11  * * *
117  *     12  * * *
118  *     13  rip.Berkeley.EDU (128.32.131.22)  59 ms !  39 ms !  39 ms !
119  *
120  * Notice that there are 12 "gateways" (13 is the final
121  * destination) and exactly the last half of them are "missing".
122  * What's really happening is that rip (a Sun-3 running Sun OS3.5)
123  * is using the ttl from our arriving datagram as the ttl in its
124  * icmp reply.  So, the reply will time out on the return path
125  * (with no notice sent to anyone since icmp's aren't sent for
126  * icmp's) until we probe with a ttl that's at least twice the path
127  * length.  I.e., rip is really only 7 hops away.  A reply that
128  * returns with a ttl of 1 is a clue this problem exists.
129  * Traceroute prints a "!" after the time if the ttl is <= 1.
130  * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
131  * non-standard (HPUX) software, expect to see this problem
132  * frequently and/or take care picking the target host of your
133  * probes.
134  *
135  * Other possible annotations after the time are !H, !N, !P (got a host,
136  * network or protocol unreachable, respectively), !S or !F (source
137  * route failed or fragmentation needed -- neither of these should
138  * ever occur and the associated gateway is busted if you see one).  If
139  * almost all the probes result in some kind of unreachable, traceroute
140  * will give up and exit.
141  *
142  * Notes
143  * -----
144  * This program must be run by root or be setuid.  (I suggest that
145  * you *don't* make it setuid -- casual use could result in a lot
146  * of unnecessary traffic on our poor, congested nets.)
147  *
148  * This program requires a kernel mod that does not appear in any
149  * system available from Berkeley:  A raw ip socket using proto
150  * IPPROTO_RAW must interpret the data sent as an ip datagram (as
151  * opposed to data to be wrapped in a ip datagram).  See the README
152  * file that came with the source to this program for a description
153  * of the mods I made to /sys/netinet/raw_ip.c.  Your mileage may
154  * vary.  But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
155  * MODIFIED TO RUN THIS PROGRAM.
156  *
157  * The udp port usage may appear bizarre (well, ok, it is bizarre).
158  * The problem is that an icmp message only contains 8 bytes of
159  * data from the original datagram.  8 bytes is the size of a udp
160  * header so, if we want to associate replies with the original
161  * datagram, the necessary information must be encoded into the
162  * udp header (the ip id could be used but there's no way to
163  * interlock with the kernel's assignment of ip id's and, anyway,
164  * it would have taken a lot more kernel hacking to allow this
165  * code to set the ip id).  So, to allow two or more users to
166  * use traceroute simultaneously, we use this task's pid as the
167  * source port (the high bit is set to move the port number out
168  * of the "likely" range).  To keep track of which probe is being
169  * replied to (so times and/or hop counts don't get confused by a
170  * reply that was delayed in transit), we increment the destination
171  * port number before each probe.
172  *
173  * Don't use this as a coding example.  I was trying to find a
174  * routing problem and this code sort-of popped out after 48 hours
175  * without sleep.  I was amazed it ever compiled, much less ran.
176  *
177  * I stole the idea for this program from Steve Deering.  Since
178  * the first release, I've learned that had I attended the right
179  * IETF working group meetings, I also could have stolen it from Guy
180  * Almes or Matt Mathis.  I don't know (or care) who came up with
181  * the idea first.  I envy the originators' perspicacity and I'm
182  * glad they didn't keep the idea a secret.
183  *
184  * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
185  * enhancements to the original distribution.
186  *
187  * I've hacked up a round-trip-route version of this that works by
188  * sending a loose-source-routed udp datagram through the destination
189  * back to yourself.  Unfortunately, SO many gateways botch source
190  * routing, the thing is almost worthless.  Maybe one day...
191  *
192  *  -- Van Jacobson (van@ee.lbl.gov)
193  *     Tue Dec 20 03:50:13 PST 1988
194  */
195
196 #define TRACEROUTE_SO_DEBUG 0
197
198 /* TODO: undefs were uncommented - ??! we have config system for that! */
199 /* probably ok to remove altogether */
200 //#undef CONFIG_FEATURE_TRACEROUTE_VERBOSE
201 //#define CONFIG_FEATURE_TRACEROUTE_VERBOSE
202 //#undef CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE
203 //#define CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE
204 //#undef CONFIG_FEATURE_TRACEROUTE_USE_ICMP
205 //#define CONFIG_FEATURE_TRACEROUTE_USE_ICMP
206
207
208 #include <net/if.h>
209 #include <arpa/inet.h>
210 #include <netinet/in.h>
211 #include <netinet/udp.h>
212 #include <netinet/ip.h>
213 #include <netinet/ip_icmp.h>
214
215 #include "libbb.h"
216 #include "inet_common.h"
217
218 #ifndef IPPROTO_ICMP
219 # define IPPROTO_ICMP 1
220 #endif
221 #ifndef IPPROTO_IP
222 # define IPPROTO_IP 0
223 #endif
224
225 /* Keep in sync with getopt32 call! */
226 enum {
227         OPT_DONT_FRAGMNT = (1 << 0),    /* F */
228         OPT_USE_ICMP     = (1 << 1) * ENABLE_FEATURE_TRACEROUTE_USE_ICMP, /* I */
229         OPT_TTL_FLAG     = (1 << 2),    /* l */
230         OPT_ADDR_NUM     = (1 << 3),    /* n */
231         OPT_BYPASS_ROUTE = (1 << 4),    /* r */
232         OPT_DEBUG        = (1 << 5),    /* d */
233         OPT_VERBOSE      = (1 << 6) * ENABLE_FEATURE_TRACEROUTE_VERBOSE, /* v */
234         OPT_IP_CHKSUM    = (1 << 7),    /* x */
235         OPT_TOS          = (1 << 8),    /* t */
236         OPT_DEVICE       = (1 << 9),    /* i */
237         OPT_MAX_TTL      = (1 << 10),   /* m */
238         OPT_PORT         = (1 << 11),   /* p */
239         OPT_NPROBES      = (1 << 12),   /* q */
240         OPT_SOURCE       = (1 << 13),   /* s */
241         OPT_WAITTIME     = (1 << 14),   /* w */
242         OPT_PAUSE_MS     = (1 << 15),   /* z */
243         OPT_FIRST_TTL    = (1 << 16),   /* f */
244 };
245 #define verbose (option_mask32 & OPT_VERBOSE)
246
247 enum {
248         SIZEOF_ICMP_HDR = 8,
249         rcvsock = 3, /* receive (icmp) socket file descriptor */
250         sndsock = 4, /* send (udp/icmp) socket file descriptor */
251 };
252
253 /* Data section of the probe packet */
254 struct outdata_t {
255         unsigned char seq;             /* sequence number of this packet */
256         unsigned char ttl;             /* ttl packet left with */
257 // UNUSED. Retaining to have the same packet size.
258         struct timeval tv_UNUSED PACKED; /* time packet left */
259 };
260
261 struct globals {
262         struct ip *outip;
263         struct outdata_t *outdata;
264         len_and_sockaddr *dest_lsa;
265         int packlen;                    /* total length of packet */
266         int pmtu;                       /* Path MTU Discovery (RFC1191) */
267         uint16_t ident;
268         uint16_t port; // 32768 + 666;  /* start udp dest port # for probe packets */
269         int waittime; // 5;             /* time to wait for response (in seconds) */
270 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
271         int optlen;                     /* length of ip options */
272 #else
273 #define optlen 0
274 #endif
275         unsigned char recv_pkt[512];    /* last inbound (icmp) packet */
276 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
277         /* Maximum number of gateways (include room for one noop) */
278 #define NGATEWAYS ((int)((MAX_IPOPTLEN - IPOPT_MINOFF - 1) / sizeof(uint32_t)))
279         /* loose source route gateway list (including room for final destination) */
280         uint32_t gwlist[NGATEWAYS + 1];
281 #endif
282 };
283
284 #define G (*ptr_to_globals)
285 #define outip     (G.outip    )
286 #define outdata   (G.outdata  )
287 #define dest_lsa  (G.dest_lsa )
288 #define packlen   (G.packlen  )
289 #define pmtu      (G.pmtu     )
290 #define ident     (G.ident    )
291 #define port      (G.port     )
292 #define waittime  (G.waittime )
293 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
294 # define optlen   (G.optlen   )
295 #endif
296 #define recv_pkt  (G.recv_pkt )
297 #define gwlist    (G.gwlist   )
298 #define INIT_G() do { \
299         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
300         port = 32768 + 666; \
301         waittime = 5; \
302 } while (0)
303
304 #define outicmp ((struct icmp *)(outip + 1))
305 #define outudp  ((struct udphdr *)(outip + 1))
306
307
308 static int
309 wait_for_reply(struct sockaddr_in *fromp)
310 {
311         struct pollfd pfd[1];
312         int cc = 0;
313         socklen_t fromlen = sizeof(*fromp);
314
315         pfd[0].fd = rcvsock;
316         pfd[0].events = POLLIN;
317         if (safe_poll(pfd, 1, waittime * 1000) > 0)
318                 cc = recvfrom(rcvsock, recv_pkt, sizeof(recv_pkt), 0,
319                             (struct sockaddr *)fromp, &fromlen);
320         return cc;
321 }
322
323 /*
324  * Checksum routine for Internet Protocol family headers (C Version)
325  */
326 static uint16_t
327 in_cksum(uint16_t *addr, int len)
328 {
329         int nleft = len;
330         uint16_t *w = addr;
331         uint16_t answer;
332         int sum = 0;
333
334         /*
335          * Our algorithm is simple, using a 32 bit accumulator (sum),
336          * we add sequential 16 bit words to it, and at the end, fold
337          * back all the carry bits from the top 16 bits into the lower
338          * 16 bits.
339          */
340         while (nleft > 1) {
341                 sum += *w++;
342                 nleft -= 2;
343         }
344
345         /* mop up an odd byte, if necessary */
346         if (nleft == 1)
347                 sum += *(unsigned char *)w;
348
349         /* add back carry outs from top 16 bits to low 16 bits */
350         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
351         sum += (sum >> 16);                     /* add carry */
352         answer = ~sum;                          /* truncate to 16 bits */
353         return answer;
354 }
355
356 static void
357 send_probe(int seq, int ttl)
358 {
359         int len, res;
360         void *out;
361
362         /* Payload */
363         outdata->seq = seq;
364         outdata->ttl = ttl;
365 // UNUSED: was storing gettimeofday's result there, but never ever checked it
366         /*memcpy(&outdata->tv, tp, sizeof(outdata->tv));*/
367
368         if (option_mask32 & OPT_USE_ICMP) {
369                 outicmp->icmp_seq = htons(seq);
370
371                 /* Always calculate checksum for icmp packets */
372                 outicmp->icmp_cksum = 0;
373                 outicmp->icmp_cksum = in_cksum((uint16_t *)outicmp,
374                                         packlen - (sizeof(*outip) + optlen));
375                 if (outicmp->icmp_cksum == 0)
376                         outicmp->icmp_cksum = 0xffff;
377         }
378
379 //BUG! verbose is (x & OPT_VERBOSE), not a counter!
380 #if 0 //ENABLE_FEATURE_TRACEROUTE_VERBOSE
381         /* XXX undocumented debugging hack */
382         if (verbose > 1) {
383                 const uint16_t *sp;
384                 int nshorts, i;
385
386                 sp = (uint16_t *)outip;
387                 nshorts = (unsigned)packlen / sizeof(uint16_t);
388                 i = 0;
389                 printf("[ %d bytes", packlen);
390                 while (--nshorts >= 0) {
391                         if ((i++ % 8) == 0)
392                                 printf("\n\t");
393                         printf(" %04x", ntohs(*sp));
394                         sp++;
395                 }
396                 if (packlen & 1) {
397                         if ((i % 8) == 0)
398                                 printf("\n\t");
399                         printf(" %02x", *(unsigned char *)sp);
400                 }
401                 printf("]\n");
402         }
403 #endif
404
405 #if defined(IP_TTL)
406         if (setsockopt(sndsock, IPPROTO_IP, IP_TTL,
407                                 (char *)&ttl, sizeof(ttl)) < 0) {
408                 bb_perror_msg_and_die("setsockopt ttl %d", ttl);
409         }
410 #endif
411
412         len = packlen - sizeof(*outip);
413         if (option_mask32 & OPT_USE_ICMP)
414                 out = outicmp;
415         else {
416                 out = outdata;
417                 len -= sizeof(*outudp);
418                 set_nport(dest_lsa, htons(port + seq));
419         }
420         res = xsendto(sndsock, out, len,
421                         (struct sockaddr *)&dest_lsa->u.sa, dest_lsa->len);
422         if (res != len) {
423                 bb_info_msg("sent %d octets, ret=%d", len, res);
424         }
425 }
426
427 #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
428 /*
429  * Convert an ICMP "type" field to a printable string.
430  */
431 static inline const char *
432 pr_type(unsigned char t)
433 {
434         static const char *const ttab[] = {
435         "Echo Reply",   "ICMP 1",       "ICMP 2",       "Dest Unreachable",
436         "Source Quench", "Redirect",    "ICMP 6",       "ICMP 7",
437         "Echo",         "Router Advert", "Router Solicit", "Time Exceeded",
438         "Param Problem", "Timestamp",   "Timestamp Reply", "Info Request",
439         "Info Reply",   "Mask Request", "Mask Reply"
440         };
441
442         if (t >= ARRAY_SIZE(ttab))
443                 return "OUT-OF-RANGE";
444
445         return ttab[t];
446 }
447 #endif
448
449 #if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
450 #define packet_ok(cc, from, seq) \
451         packet_ok(cc, seq)
452 #endif
453 static int
454 packet_ok(int cc, const struct sockaddr_in *from, int seq)
455 {
456         const struct icmp *icp;
457         unsigned char type, code;
458         int hlen;
459         const struct ip *ip;
460
461         ip = (struct ip *) recv_pkt;
462         hlen = ip->ip_hl << 2;
463         if (cc < hlen + ICMP_MINLEN) {
464 #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
465                 if (verbose)
466                         printf("packet too short (%d bytes) from %s\n", cc,
467                                 inet_ntoa(from->sin_addr));
468 #endif
469                 return 0;
470         }
471         cc -= hlen;
472         icp = (struct icmp *)(recv_pkt + hlen);
473         type = icp->icmp_type;
474         code = icp->icmp_code;
475         /* Path MTU Discovery (RFC1191) */
476         pmtu = 0;
477         if (code == ICMP_UNREACH_NEEDFRAG)
478                 pmtu = ntohs(icp->icmp_nextmtu);
479
480         if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS)
481          || type == ICMP_UNREACH
482          || type == ICMP_ECHOREPLY
483         ) {
484                 const struct ip *hip;
485                 const struct udphdr *up;
486
487                 hip = &icp->icmp_ip;
488                 hlen = hip->ip_hl << 2;
489                 if (option_mask32 & OPT_USE_ICMP) {
490                         struct icmp *hicmp;
491
492                         /* XXX */
493                         if (type == ICMP_ECHOREPLY
494                          && icp->icmp_id == htons(ident)
495                          && icp->icmp_seq == htons(seq)
496                         ) {
497                                 return -2;
498                         }
499
500                         hicmp = (struct icmp *)((unsigned char *)hip + hlen);
501                         if (hlen + SIZEOF_ICMP_HDR <= cc
502                          && hip->ip_p == IPPROTO_ICMP
503                          && hicmp->icmp_id == htons(ident)
504                          && hicmp->icmp_seq == htons(seq)
505                         ) {
506                                 return (type == ICMP_TIMXCEED ? -1 : code + 1);
507                         }
508                 } else {
509                         up = (struct udphdr *)((char *)hip + hlen);
510                         if (hlen + 12 <= cc
511                          && hip->ip_p == IPPROTO_UDP
512 // Off: since we do not form the entire IP packet,
513 // but defer it to kernel, we can't set source port,
514 // and thus can't check it here in the reply
515                         /* && up->source == htons(ident) */
516                          && up->dest == htons(port + seq)
517                         ) {
518                                 return (type == ICMP_TIMXCEED ? -1 : code + 1);
519                         }
520                 }
521         }
522 #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
523         if (verbose) {
524                 int i;
525                 uint32_t *lp = (uint32_t *)&icp->icmp_ip;
526
527                 printf("\n%d bytes from %s to "
528                        "%s: icmp type %d (%s) code %d\n",
529                         cc, inet_ntoa(from->sin_addr),
530                         inet_ntoa(ip->ip_dst),
531                         type, pr_type(type), icp->icmp_code);
532                 for (i = 4; i < cc; i += sizeof(*lp))
533                         printf("%2d: x%8.8x\n", i, *lp++);
534         }
535 #endif
536         return 0;
537 }
538
539 /*
540  * Construct an Internet address representation.
541  * If the -n flag has been supplied, give
542  * numeric value, otherwise try for symbolic name.
543  */
544 static void
545 print_inetname(const struct sockaddr_in *from)
546 {
547         const char *ina;
548
549         ina = inet_ntoa(from->sin_addr);
550         if (option_mask32 & OPT_ADDR_NUM)
551                 printf("  %s", ina);
552         else {
553                 char *n = NULL;
554                 if (from->sin_addr.s_addr != INADDR_ANY)
555                         n = xmalloc_sockaddr2host_noport((struct sockaddr*)from);
556                 printf("  %s (%s)", (n ? n : ina), ina);
557                 free(n);
558         }
559 }
560
561 static void
562 print(int cc, const struct sockaddr_in *from)
563 {
564         print_inetname(from);
565         if (verbose) {
566                 const struct ip *ip;
567                 int hlen;
568
569                 ip = (struct ip *) recv_pkt;
570                 hlen = ip->ip_hl << 2;
571                 cc -= hlen;
572                 printf(" %d bytes to %s", cc, inet_ntoa(ip->ip_dst));
573         }
574 }
575
576 static void
577 print_delta_ms(unsigned t1p, unsigned t2p)
578 {
579         unsigned tt = t2p - t1p;
580         printf("  %u.%03u ms", tt / 1000, tt % 1000);
581 }
582
583 /*
584 Usage: [-dFIlnrvx] [-g gateway] [-i iface] [-f first_ttl]
585 [-m max_ttl] [ -p port] [-q nqueries] [-s src_addr] [-t tos]
586 [-w waittime] [-z pausemsecs] host [packetlen]"
587 */
588
589 int traceroute_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
590 int traceroute_main(int argc, char **argv)
591 {
592         int minpacket;
593         int ttl, i;
594         int seq = 0;
595         int tos = 0;
596         int max_ttl = 30;
597         int nprobes = 3;
598         int first_ttl = 1;
599         unsigned pausemsecs = 0;
600         unsigned op;
601         char *source;
602         char *device;
603         char *tos_str;
604         char *max_ttl_str;
605         char *port_str;
606         char *nprobes_str;
607         char *waittime_str;
608         char *pausemsecs_str;
609         char *first_ttl_str;
610 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
611         llist_t *source_route_list = NULL;
612         int lsrr = 0;
613 #endif
614
615         INIT_G();
616
617 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
618         opt_complementary = "x-x:g::";
619 #else
620         opt_complementary = "x-x";
621 #endif
622
623         op = getopt32(argv, "FIlnrdvxt:i:m:p:q:s:w:z:f:"
624 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
625                                         "g:"
626 #endif
627                 , &tos_str, &device, &max_ttl_str, &port_str, &nprobes_str
628                 , &source, &waittime_str, &pausemsecs_str, &first_ttl_str
629 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
630                 , &source_route_list
631 #endif
632         );
633
634 #if 0 /* IGNORED */
635         if (op & OPT_IP_CHKSUM)
636                 bb_error_msg("warning: ip checksums disabled");
637 #endif
638         if (op & OPT_TOS)
639                 tos = xatou_range(tos_str, 0, 255);
640         if (op & OPT_MAX_TTL)
641                 max_ttl = xatou_range(max_ttl_str, 1, 255);
642         if (op & OPT_PORT)
643                 port = xatou16(port_str);
644         if (op & OPT_NPROBES)
645                 nprobes = xatou_range(nprobes_str, 1, INT_MAX);
646         if (op & OPT_SOURCE) {
647                 /*
648                  * set the ip source address of the outbound
649                  * probe (e.g., on a multi-homed host).
650                  */
651                 if (getuid() != 0)
652                         bb_error_msg_and_die("you must be root to use -s");
653         }
654         if (op & OPT_WAITTIME)
655                 waittime = xatou_range(waittime_str, 1, 24 * 60 * 60);
656         if (op & OPT_PAUSE_MS)
657                 pausemsecs = xatou_range(pausemsecs_str, 0, 60 * 60 * 1000);
658         if (op & OPT_FIRST_TTL)
659                 first_ttl = xatou_range(first_ttl_str, 1, max_ttl);
660
661 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
662         if (source_route_list) {
663                 while (source_route_list) {
664                         len_and_sockaddr *lsa;
665
666                         if (lsrr >= NGATEWAYS)
667                                 bb_error_msg_and_die("no more than %d gateways", NGATEWAYS);
668                         lsa = xhost_and_af2sockaddr(llist_pop(&source_route_list), 0, AF_INET);
669                         gwlist[lsrr] = lsa->u.sin.sin_addr.s_addr;
670                         free(lsa);
671                         ++lsrr;
672                 }
673                 optlen = (lsrr + 1) * sizeof(gwlist[0]);
674         }
675 #endif
676
677         minpacket = sizeof(*outip) + SIZEOF_ICMP_HDR + sizeof(*outdata) + optlen;
678         if (!(op & OPT_USE_ICMP))
679                 minpacket += sizeof(*outudp) - SIZEOF_ICMP_HDR;
680         packlen = minpacket;
681
682         /* Process destination and optional packet size */
683         argv += optind;
684         argc -= optind;
685         switch (argc) {
686         case 2:
687                 packlen = xatoul_range(argv[1], minpacket, 32 * 1024);
688                 /* Fall through */
689         case 1:
690                 dest_lsa = xhost2sockaddr(argv[0], port);
691                 break;
692         default:
693                 bb_show_usage();
694         }
695
696         /* Ensure the socket fds won't be 0, 1 or 2 */
697         bb_sanitize_stdio();
698
699         xmove_fd(xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP), rcvsock);
700 #if TRACEROUTE_SO_DEBUG
701         if (op & OPT_DEBUG)
702                 setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
703                                 &const_int_1, sizeof(const_int_1));
704 #endif
705         if (op & OPT_BYPASS_ROUTE)
706                 setsockopt(rcvsock, SOL_SOCKET, SO_DONTROUTE,
707                                 &const_int_1, sizeof(const_int_1));
708
709         if (op & OPT_USE_ICMP)
710                 xmove_fd(xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP), sndsock);
711         else
712                 xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), sndsock);
713 #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
714 #if defined(IP_OPTIONS)
715         if (lsrr > 0) {
716                 unsigned char optlist[MAX_IPOPTLEN];
717
718                 /* final hop */
719                 gwlist[lsrr] = dest_lsa->u.sin.sin_addr.s_addr;
720                 ++lsrr;
721
722                 /* force 4 byte alignment */
723                 optlist[0] = IPOPT_NOP;
724                 /* loose source route option */
725                 optlist[1] = IPOPT_LSRR;
726                 i = lsrr * sizeof(gwlist[0]);
727                 optlist[2] = i + 3;
728                 /* pointer to LSRR addresses */
729                 optlist[3] = IPOPT_MINOFF;
730                 memcpy(optlist + 4, gwlist, i);
731
732                 if (setsockopt(sndsock, IPPROTO_IP, IP_OPTIONS,
733                                 (char *)optlist, i + sizeof(gwlist[0])) < 0) {
734                         bb_perror_msg_and_die("IP_OPTIONS");
735                 }
736         }
737 #endif /* IP_OPTIONS */
738 #endif /* CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE */
739 #ifdef SO_SNDBUF
740         if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, &packlen, sizeof(packlen)) < 0) {
741                 bb_perror_msg_and_die("SO_SNDBUF");
742         }
743 #endif
744 #ifdef IP_TOS
745         if ((op & OPT_TOS) && setsockopt(sndsock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) {
746                 bb_perror_msg_and_die("setsockopt tos %d", tos);
747         }
748 #endif
749 #ifdef IP_DONTFRAG
750         if (op & OPT_DONT_FRAGMNT)
751                 setsockopt(sndsock, IPPROTO_IP, IP_DONTFRAG,
752                                 &const_int_1, sizeof(const_int_1));
753 #endif
754 #if TRACEROUTE_SO_DEBUG
755         if (op & OPT_DEBUG)
756                 setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
757                                 &const_int_1, sizeof(const_int_1));
758 #endif
759         if (op & OPT_BYPASS_ROUTE)
760                 setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
761                                 &const_int_1, sizeof(const_int_1));
762
763         outip = xzalloc(packlen);
764
765         if (op & OPT_USE_ICMP) {
766                 ident = getpid() | 0x8000;
767                 outicmp->icmp_type = ICMP_ECHO;
768                 outicmp->icmp_id = htons(ident);
769                 outdata = (struct outdata_t *)((char *)outicmp + SIZEOF_ICMP_HDR);
770         } else {
771                 outdata = (struct outdata_t *)(outudp + 1);
772         }
773
774         if (op & OPT_DEVICE) /* hmm, do we need error check? */
775                 setsockopt_bindtodevice(sndsock, device);
776
777         if (op & OPT_SOURCE) {
778                 len_and_sockaddr *source_lsa = xdotted2sockaddr(source, 0);
779                 /* Ping does this (why?) */
780                 if (setsockopt(sndsock, IPPROTO_IP, IP_MULTICAST_IF,
781                                 &source_lsa->u.sa, source_lsa->len))
782                         bb_error_msg_and_die("can't set multicast source interface");
783 //TODO: we can query source port we bound to,
784 // and check it in replies... if we care enough
785                 xbind(sndsock, &source_lsa->u.sa, source_lsa->len);
786                 free(source_lsa);
787         }
788
789         /* Revert to non-privileged user after opening sockets */
790         xsetgid(getgid());
791         xsetuid(getuid());
792
793         printf("traceroute to %s (%s)", argv[0],
794                         xmalloc_sockaddr2dotted_noport(&dest_lsa->u.sa));
795         if (op & OPT_SOURCE)
796                 printf(" from %s", source);
797         printf(", %d hops max, %d byte packets\n", max_ttl, packlen);
798
799         for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
800 //TODO: make it protocol agnostic (get rid of sockaddr_in)
801                 struct sockaddr_in from;
802                 uint32_t lastaddr = 0;
803                 int probe;
804                 int unreachable = 0; /* counter */
805                 int gotlastaddr = 0; /* flags */
806                 int got_there = 0;
807                 int first = 1;
808
809                 printf("%2d", ttl);
810                 for (probe = 0; probe < nprobes; ++probe) {
811                         int cc;
812                         unsigned t1;
813                         unsigned t2;
814                         struct ip *ip;
815
816                         if (!first && pausemsecs > 0)
817                                 usleep(pausemsecs * 1000);
818                         fflush(stdout);
819
820                         t1 = monotonic_us();
821                         send_probe(++seq, ttl);
822                         first = 0;
823
824                         while ((cc = wait_for_reply(&from)) != 0) {
825                                 t2 = monotonic_us();
826                                 i = packet_ok(cc, &from, seq);
827                                 /* Skip short packet */
828                                 if (i == 0)
829                                         continue;
830                                 if (!gotlastaddr
831                                  || from.sin_addr.s_addr != lastaddr
832                                 ) {
833                                         print(cc, &from);
834                                         lastaddr = from.sin_addr.s_addr;
835                                         gotlastaddr = 1;
836                                 }
837                                 print_delta_ms(t1, t2);
838                                 ip = (struct ip *)recv_pkt;
839                                 if (op & OPT_TTL_FLAG)
840                                         printf(" (%d)", ip->ip_ttl);
841                                 if (i == -2) {
842                                         if (ip->ip_ttl <= 1)
843                                                 printf(" !");
844                                         got_there = 1;
845                                         break;
846                                 }
847                                 /* time exceeded in transit */
848                                 if (i == -1)
849                                         break;
850                                 i--;
851                                 switch (i) {
852                                 case ICMP_UNREACH_PORT:
853                                         if (ip->ip_ttl <= 1)
854                                                 printf(" !");
855                                         got_there = 1;
856                                         break;
857                                 case ICMP_UNREACH_NET:
858                                         printf(" !N");
859                                         ++unreachable;
860                                         break;
861                                 case ICMP_UNREACH_HOST:
862                                         printf(" !H");
863                                         ++unreachable;
864                                         break;
865                                 case ICMP_UNREACH_PROTOCOL:
866                                         printf(" !P");
867                                         got_there = 1;
868                                         break;
869                                 case ICMP_UNREACH_NEEDFRAG:
870                                         printf(" !F-%d", pmtu);
871                                         ++unreachable;
872                                         break;
873                                 case ICMP_UNREACH_SRCFAIL:
874                                         printf(" !S");
875                                         ++unreachable;
876                                         break;
877                                 case ICMP_UNREACH_FILTER_PROHIB:
878                                 case ICMP_UNREACH_NET_PROHIB:   /* misuse */
879                                         printf(" !A");
880                                         ++unreachable;
881                                         break;
882                                 case ICMP_UNREACH_HOST_PROHIB:
883                                         printf(" !C");
884                                         ++unreachable;
885                                         break;
886                                 case ICMP_UNREACH_HOST_PRECEDENCE:
887                                         printf(" !V");
888                                         ++unreachable;
889                                         break;
890                                 case ICMP_UNREACH_PRECEDENCE_CUTOFF:
891                                         printf(" !C");
892                                         ++unreachable;
893                                         break;
894                                 case ICMP_UNREACH_NET_UNKNOWN:
895                                 case ICMP_UNREACH_HOST_UNKNOWN:
896                                         printf(" !U");
897                                         ++unreachable;
898                                         break;
899                                 case ICMP_UNREACH_ISOLATED:
900                                         printf(" !I");
901                                         ++unreachable;
902                                         break;
903                                 case ICMP_UNREACH_TOSNET:
904                                 case ICMP_UNREACH_TOSHOST:
905                                         printf(" !T");
906                                         ++unreachable;
907                                         break;
908                                 default:
909                                         printf(" !<%d>", i);
910                                         ++unreachable;
911                                         break;
912                                 }
913                                 break;
914                         }
915                         if (cc == 0)
916                                 printf("  *");
917                 }
918                 bb_putchar('\n');
919                 if (got_there
920                  || (unreachable > 0 && unreachable >= nprobes - 1)
921                 ) {
922                         break;
923                 }
924         }
925         return 0;
926 }