traceroute.c 28 KB

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