traceroute.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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. * traceroute6
  26. *
  27. * Modified for NRL 4.4BSD IPv6 release.
  28. * 07/31/96 bgp
  29. *
  30. * Modified for Linux IPv6 by Pedro Roque <roque@di.fc.ul.pt>
  31. * 31/07/1996
  32. *
  33. * As ICMP error messages for IPv6 now include more than 8 bytes
  34. * UDP datagrams are now sent via an UDP socket instead of magic
  35. * RAW socket tricks.
  36. *
  37. * Converted to busybox applet by Leonid Lisovskiy <lly@sf.net>
  38. * 2009-11-16
  39. */
  40. /*
  41. * traceroute host - trace the route ip packets follow going to "host".
  42. *
  43. * Attempt to trace the route an ip packet would follow to some
  44. * internet host. We find out intermediate hops by launching probe
  45. * packets with a small ttl (time to live) then listening for an
  46. * icmp "time exceeded" reply from a gateway. We start our probes
  47. * with a ttl of one and increase by one until we get an icmp "port
  48. * unreachable" (which means we got to "host") or hit a max (which
  49. * defaults to 30 hops & can be changed with the -m flag). Three
  50. * probes (change with -q flag) are sent at each ttl setting and a
  51. * line is printed showing the ttl, address of the gateway and
  52. * round trip time of each probe. If the probe answers come from
  53. * different gateways, the address of each responding system will
  54. * be printed. If there is no response within a 5 sec. timeout
  55. * interval (changed with the -w flag), a "*" is printed for that
  56. * probe.
  57. *
  58. * Probe packets are UDP format. We don't want the destination
  59. * host to process them so the destination port is set to an
  60. * unlikely value (if some clod on the destination is using that
  61. * value, it can be changed with the -p flag).
  62. *
  63. * A sample use might be:
  64. *
  65. * [yak 71]% traceroute nis.nsf.net.
  66. * traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
  67. * 1 helios.ee.lbl.gov (128.3.112.1) 19 ms 19 ms 0 ms
  68. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
  69. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
  70. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 39 ms
  71. * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 39 ms 39 ms 39 ms
  72. * 6 128.32.197.4 (128.32.197.4) 40 ms 59 ms 59 ms
  73. * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 59 ms
  74. * 8 129.140.70.13 (129.140.70.13) 99 ms 99 ms 80 ms
  75. * 9 129.140.71.6 (129.140.71.6) 139 ms 239 ms 319 ms
  76. * 10 129.140.81.7 (129.140.81.7) 220 ms 199 ms 199 ms
  77. * 11 nic.merit.edu (35.1.1.48) 239 ms 239 ms 239 ms
  78. *
  79. * Note that lines 2 & 3 are the same. This is due to a buggy
  80. * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
  81. * packets with a zero ttl.
  82. *
  83. * A more interesting example is:
  84. *
  85. * [yak 72]% traceroute allspice.lcs.mit.edu.
  86. * traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
  87. * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
  88. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 19 ms 19 ms
  89. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 19 ms
  90. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 19 ms 39 ms 39 ms
  91. * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 20 ms 39 ms 39 ms
  92. * 6 128.32.197.4 (128.32.197.4) 59 ms 119 ms 39 ms
  93. * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 39 ms
  94. * 8 129.140.70.13 (129.140.70.13) 80 ms 79 ms 99 ms
  95. * 9 129.140.71.6 (129.140.71.6) 139 ms 139 ms 159 ms
  96. * 10 129.140.81.7 (129.140.81.7) 199 ms 180 ms 300 ms
  97. * 11 129.140.72.17 (129.140.72.17) 300 ms 239 ms 239 ms
  98. * 12 * * *
  99. * 13 128.121.54.72 (128.121.54.72) 259 ms 499 ms 279 ms
  100. * 14 * * *
  101. * 15 * * *
  102. * 16 * * *
  103. * 17 * * *
  104. * 18 ALLSPICE.LCS.MIT.EDU (18.26.0.115) 339 ms 279 ms 279 ms
  105. *
  106. * (I start to see why I'm having so much trouble with mail to
  107. * MIT.) Note that the gateways 12, 14, 15, 16 & 17 hops away
  108. * either don't send ICMP "time exceeded" messages or send them
  109. * with a ttl too small to reach us. 14 - 17 are running the
  110. * MIT C Gateway code that doesn't send "time exceeded"s. God
  111. * only knows what's going on with 12.
  112. *
  113. * The silent gateway 12 in the above may be the result of a bug in
  114. * the 4.[23]BSD network code (and its derivatives): 4.x (x <= 3)
  115. * sends an unreachable message using whatever ttl remains in the
  116. * original datagram. Since, for gateways, the remaining ttl is
  117. * zero, the icmp "time exceeded" is guaranteed to not make it back
  118. * to us. The behavior of this bug is slightly more interesting
  119. * when it appears on the destination system:
  120. *
  121. * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
  122. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 39 ms
  123. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 39 ms 19 ms
  124. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 19 ms
  125. * 5 ccn-nerif35.Berkeley.EDU (128.32.168.35) 39 ms 39 ms 39 ms
  126. * 6 csgw.Berkeley.EDU (128.32.133.254) 39 ms 59 ms 39 ms
  127. * 7 * * *
  128. * 8 * * *
  129. * 9 * * *
  130. * 10 * * *
  131. * 11 * * *
  132. * 12 * * *
  133. * 13 rip.Berkeley.EDU (128.32.131.22) 59 ms ! 39 ms ! 39 ms !
  134. *
  135. * Notice that there are 12 "gateways" (13 is the final
  136. * destination) and exactly the last half of them are "missing".
  137. * What's really happening is that rip (a Sun-3 running Sun OS3.5)
  138. * is using the ttl from our arriving datagram as the ttl in its
  139. * icmp reply. So, the reply will time out on the return path
  140. * (with no notice sent to anyone since icmp's aren't sent for
  141. * icmp's) until we probe with a ttl that's at least twice the path
  142. * length. I.e., rip is really only 7 hops away. A reply that
  143. * returns with a ttl of 1 is a clue this problem exists.
  144. * Traceroute prints a "!" after the time if the ttl is <= 1.
  145. * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
  146. * non-standard (HPUX) software, expect to see this problem
  147. * frequently and/or take care picking the target host of your
  148. * probes.
  149. *
  150. * Other possible annotations after the time are !H, !N, !P (got a host,
  151. * network or protocol unreachable, respectively), !S or !F (source
  152. * route failed or fragmentation needed -- neither of these should
  153. * ever occur and the associated gateway is busted if you see one). If
  154. * almost all the probes result in some kind of unreachable, traceroute
  155. * will give up and exit.
  156. *
  157. * Notes
  158. * -----
  159. * This program must be run by root or be setuid. (I suggest that
  160. * you *don't* make it setuid -- casual use could result in a lot
  161. * of unnecessary traffic on our poor, congested nets.)
  162. *
  163. * This program requires a kernel mod that does not appear in any
  164. * system available from Berkeley: A raw ip socket using proto
  165. * IPPROTO_RAW must interpret the data sent as an ip datagram (as
  166. * opposed to data to be wrapped in a ip datagram). See the README
  167. * file that came with the source to this program for a description
  168. * of the mods I made to /sys/netinet/raw_ip.c. Your mileage may
  169. * vary. But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
  170. * MODIFIED TO RUN THIS PROGRAM.
  171. *
  172. * The udp port usage may appear bizarre (well, ok, it is bizarre).
  173. * The problem is that an icmp message only contains 8 bytes of
  174. * data from the original datagram. 8 bytes is the size of a udp
  175. * header so, if we want to associate replies with the original
  176. * datagram, the necessary information must be encoded into the
  177. * udp header (the ip id could be used but there's no way to
  178. * interlock with the kernel's assignment of ip id's and, anyway,
  179. * it would have taken a lot more kernel hacking to allow this
  180. * code to set the ip id). So, to allow two or more users to
  181. * use traceroute simultaneously, we use this task's pid as the
  182. * source port (the high bit is set to move the port number out
  183. * of the "likely" range). To keep track of which probe is being
  184. * replied to (so times and/or hop counts don't get confused by a
  185. * reply that was delayed in transit), we increment the destination
  186. * port number before each probe.
  187. *
  188. * Don't use this as a coding example. I was trying to find a
  189. * routing problem and this code sort-of popped out after 48 hours
  190. * without sleep. I was amazed it ever compiled, much less ran.
  191. *
  192. * I stole the idea for this program from Steve Deering. Since
  193. * the first release, I've learned that had I attended the right
  194. * IETF working group meetings, I also could have stolen it from Guy
  195. * Almes or Matt Mathis. I don't know (or care) who came up with
  196. * the idea first. I envy the originators' perspicacity and I'm
  197. * glad they didn't keep the idea a secret.
  198. *
  199. * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
  200. * enhancements to the original distribution.
  201. *
  202. * I've hacked up a round-trip-route version of this that works by
  203. * sending a loose-source-routed udp datagram through the destination
  204. * back to yourself. Unfortunately, SO many gateways botch source
  205. * routing, the thing is almost worthless. Maybe one day...
  206. *
  207. * -- Van Jacobson (van@ee.lbl.gov)
  208. * Tue Dec 20 03:50:13 PST 1988
  209. */
  210. //usage:#define traceroute_trivial_usage
  211. //usage: "[-"IF_TRACEROUTE6("46")"FIldnrv] [-f 1ST_TTL] [-m MAXTTL] [-p PORT] [-q PROBES]\n"
  212. //usage: " [-s SRC_IP] [-t TOS] [-w WAIT_SEC] [-g GATEWAY] [-i IFACE]\n"
  213. //usage: " [-z PAUSE_MSEC] HOST [BYTES]"
  214. //usage:#define traceroute_full_usage "\n\n"
  215. //usage: "Trace the route to HOST\n"
  216. //usage: IF_TRACEROUTE6(
  217. //usage: "\n -4,-6 Force IP or IPv6 name resolution"
  218. //usage: )
  219. //usage: "\n -F Set the don't fragment bit"
  220. //usage: "\n -I Use ICMP ECHO instead of UDP datagrams"
  221. //usage: "\n -l Display the TTL value of the returned packet"
  222. //usage: "\n -d Set SO_DEBUG options to socket"
  223. //usage: "\n -n Print numeric addresses"
  224. //usage: "\n -r Bypass routing tables, send directly to HOST"
  225. //usage: "\n -v Verbose"
  226. //usage: "\n -m Max time-to-live (max number of hops)"
  227. //usage: "\n -p Base UDP port number used in probes"
  228. //usage: "\n (default 33434)"
  229. //usage: "\n -q Number of probes per TTL (default 3)"
  230. //usage: "\n -s IP address to use as the source address"
  231. //usage: "\n -t Type-of-service in probe packets (default 0)"
  232. //usage: "\n -w Time in seconds to wait for a response (default 3)"
  233. //usage: "\n -g Loose source route gateway (8 max)"
  234. //usage:
  235. //usage:#define traceroute6_trivial_usage
  236. //usage: "[-dnrv] [-m MAXTTL] [-p PORT] [-q PROBES]\n"
  237. //usage: " [-s SRC_IP] [-t TOS] [-w WAIT_SEC] [-i IFACE]\n"
  238. //usage: " HOST [BYTES]"
  239. //usage:#define traceroute6_full_usage "\n\n"
  240. //usage: "Trace the route to HOST\n"
  241. //usage: "\n -d Set SO_DEBUG options to socket"
  242. //usage: "\n -n Print numeric addresses"
  243. //usage: "\n -r Bypass routing tables, send directly to HOST"
  244. //usage: "\n -v Verbose"
  245. //usage: "\n -m Max time-to-live (max number of hops)"
  246. //usage: "\n -p Base UDP port number used in probes"
  247. //usage: "\n (default is 33434)"
  248. //usage: "\n -q Number of probes per TTL (default 3)"
  249. //usage: "\n -s IP address to use as the source address"
  250. //usage: "\n -t Type-of-service in probe packets (default 0)"
  251. //usage: "\n -w Time in seconds to wait for a response (default 3)"
  252. #define TRACEROUTE_SO_DEBUG 0
  253. /* TODO: undefs were uncommented - ??! we have config system for that! */
  254. /* probably ok to remove altogether */
  255. //#undef CONFIG_FEATURE_TRACEROUTE_VERBOSE
  256. //#define CONFIG_FEATURE_TRACEROUTE_VERBOSE
  257. //#undef CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE
  258. //#define CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE
  259. //#undef CONFIG_FEATURE_TRACEROUTE_USE_ICMP
  260. //#define CONFIG_FEATURE_TRACEROUTE_USE_ICMP
  261. #include <net/if.h>
  262. #include <arpa/inet.h>
  263. #include <netinet/in.h>
  264. #include <netinet/udp.h>
  265. #include <netinet/ip.h>
  266. #include <netinet/ip_icmp.h>
  267. #if ENABLE_FEATURE_IPV6
  268. # include <netinet/ip6.h>
  269. # include <netinet/icmp6.h>
  270. # ifndef SOL_IPV6
  271. # define SOL_IPV6 IPPROTO_IPV6
  272. # endif
  273. #endif
  274. #include "libbb.h"
  275. #include "inet_common.h"
  276. #ifndef IPPROTO_ICMP
  277. # define IPPROTO_ICMP 1
  278. #endif
  279. #ifndef IPPROTO_IP
  280. # define IPPROTO_IP 0
  281. #endif
  282. #define OPT_STRING "FIlnrdvxt:i:m:p:q:s:w:z:f:" \
  283. IF_FEATURE_TRACEROUTE_SOURCE_ROUTE("g:") \
  284. "4" IF_TRACEROUTE6("6")
  285. enum {
  286. OPT_DONT_FRAGMNT = (1 << 0), /* F */
  287. OPT_USE_ICMP = (1 << 1) * ENABLE_FEATURE_TRACEROUTE_USE_ICMP, /* I */
  288. OPT_TTL_FLAG = (1 << 2), /* l */
  289. OPT_ADDR_NUM = (1 << 3), /* n */
  290. OPT_BYPASS_ROUTE = (1 << 4), /* r */
  291. OPT_DEBUG = (1 << 5), /* d */
  292. OPT_VERBOSE = (1 << 6) * ENABLE_FEATURE_TRACEROUTE_VERBOSE, /* v */
  293. OPT_IP_CHKSUM = (1 << 7), /* x */
  294. OPT_TOS = (1 << 8), /* t */
  295. OPT_DEVICE = (1 << 9), /* i */
  296. OPT_MAX_TTL = (1 << 10), /* m */
  297. OPT_PORT = (1 << 11), /* p */
  298. OPT_NPROBES = (1 << 12), /* q */
  299. OPT_SOURCE = (1 << 13), /* s */
  300. OPT_WAITTIME = (1 << 14), /* w */
  301. OPT_PAUSE_MS = (1 << 15), /* z */
  302. OPT_FIRST_TTL = (1 << 16), /* f */
  303. OPT_SOURCE_ROUTE = (1 << 17) * ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE, /* g */
  304. OPT_IPV4 = (1 << (17+ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE)), /* 4 */
  305. OPT_IPV6 = (1 << (18+ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE)) * ENABLE_TRACEROUTE6, /* 6 */
  306. };
  307. #define verbose (option_mask32 & OPT_VERBOSE)
  308. enum {
  309. SIZEOF_ICMP_HDR = 8,
  310. rcvsock = 3, /* receive (icmp) socket file descriptor */
  311. sndsock = 4, /* send (udp/icmp) socket file descriptor */
  312. };
  313. /* Data section of the probe packet */
  314. struct outdata_t {
  315. unsigned char seq; /* sequence number of this packet */
  316. unsigned char ttl; /* ttl packet left with */
  317. // UNUSED. Retaining to have the same packet size.
  318. struct timeval tv_UNUSED PACKED; /* time packet left */
  319. };
  320. #if ENABLE_TRACEROUTE6
  321. struct outdata6_t {
  322. uint32_t ident6;
  323. uint32_t seq6;
  324. struct timeval tv_UNUSED PACKED; /* time packet left */
  325. };
  326. #endif
  327. struct globals {
  328. struct ip *outip;
  329. struct outdata_t *outdata;
  330. len_and_sockaddr *dest_lsa;
  331. int packlen; /* total length of packet */
  332. int pmtu; /* Path MTU Discovery (RFC1191) */
  333. uint32_t ident;
  334. uint16_t port; // 32768 + 666; /* start udp dest port # for probe packets */
  335. int waittime; // 5; /* time to wait for response (in seconds) */
  336. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  337. int optlen; /* length of ip options */
  338. #else
  339. #define optlen 0
  340. #endif
  341. unsigned char recv_pkt[512]; /* last inbound (icmp) packet */
  342. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  343. /* Maximum number of gateways (include room for one noop) */
  344. #define NGATEWAYS ((int)((MAX_IPOPTLEN - IPOPT_MINOFF - 1) / sizeof(uint32_t)))
  345. /* loose source route gateway list (including room for final destination) */
  346. uint32_t gwlist[NGATEWAYS + 1];
  347. #endif
  348. };
  349. #define G (*ptr_to_globals)
  350. #define outip (G.outip )
  351. #define outdata (G.outdata )
  352. #define dest_lsa (G.dest_lsa )
  353. #define packlen (G.packlen )
  354. #define pmtu (G.pmtu )
  355. #define ident (G.ident )
  356. #define port (G.port )
  357. #define waittime (G.waittime )
  358. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  359. # define optlen (G.optlen )
  360. #endif
  361. #define recv_pkt (G.recv_pkt )
  362. #define gwlist (G.gwlist )
  363. #define INIT_G() do { \
  364. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  365. port = 32768 + 666; \
  366. waittime = 5; \
  367. } while (0)
  368. #define outicmp ((struct icmp *)(outip + 1))
  369. #define outudp ((struct udphdr *)(outip + 1))
  370. /* libbb candidate? tftp uses this idiom too */
  371. static len_and_sockaddr* dup_sockaddr(const len_and_sockaddr *lsa)
  372. {
  373. len_and_sockaddr *new_lsa = xzalloc(LSA_LEN_SIZE + lsa->len);
  374. memcpy(new_lsa, lsa, LSA_LEN_SIZE + lsa->len);
  375. return new_lsa;
  376. }
  377. static int
  378. wait_for_reply(len_and_sockaddr *from_lsa, struct sockaddr *to, unsigned *timestamp_us, int *left_ms)
  379. {
  380. struct pollfd pfd[1];
  381. int read_len = 0;
  382. pfd[0].fd = rcvsock;
  383. pfd[0].events = POLLIN;
  384. if (*left_ms >= 0 && safe_poll(pfd, 1, *left_ms) > 0) {
  385. unsigned t;
  386. read_len = recv_from_to(rcvsock,
  387. recv_pkt, sizeof(recv_pkt),
  388. /*flags:*/ MSG_DONTWAIT,
  389. &from_lsa->u.sa, to, from_lsa->len);
  390. t = monotonic_us();
  391. *left_ms -= (t - *timestamp_us) / 1000;
  392. *timestamp_us = t;
  393. }
  394. return read_len;
  395. }
  396. static void
  397. send_probe(int seq, int ttl)
  398. {
  399. int len, res;
  400. void *out;
  401. /* Payload */
  402. #if ENABLE_TRACEROUTE6
  403. if (dest_lsa->u.sa.sa_family == AF_INET6) {
  404. struct outdata6_t *pkt = (struct outdata6_t *) outip;
  405. pkt->ident6 = htonl(ident);
  406. pkt->seq6 = htonl(seq);
  407. /*gettimeofday(&pkt->tv, &tz);*/
  408. } else
  409. #endif
  410. {
  411. outdata->seq = seq;
  412. outdata->ttl = ttl;
  413. // UNUSED: was storing gettimeofday's result there, but never ever checked it
  414. /*memcpy(&outdata->tv, tp, sizeof(outdata->tv));*/
  415. if (option_mask32 & OPT_USE_ICMP) {
  416. outicmp->icmp_seq = htons(seq);
  417. /* Always calculate checksum for icmp packets */
  418. outicmp->icmp_cksum = 0;
  419. outicmp->icmp_cksum = inet_cksum((uint16_t *)outicmp,
  420. packlen - (sizeof(*outip) + optlen));
  421. if (outicmp->icmp_cksum == 0)
  422. outicmp->icmp_cksum = 0xffff;
  423. }
  424. }
  425. //BUG! verbose is (x & OPT_VERBOSE), not a counter!
  426. #if 0 //ENABLE_FEATURE_TRACEROUTE_VERBOSE
  427. /* XXX undocumented debugging hack */
  428. if (verbose > 1) {
  429. const uint16_t *sp;
  430. int nshorts, i;
  431. sp = (uint16_t *)outip;
  432. nshorts = (unsigned)packlen / sizeof(uint16_t);
  433. i = 0;
  434. printf("[ %d bytes", packlen);
  435. while (--nshorts >= 0) {
  436. if ((i++ % 8) == 0)
  437. printf("\n\t");
  438. printf(" %04x", ntohs(*sp));
  439. sp++;
  440. }
  441. if (packlen & 1) {
  442. if ((i % 8) == 0)
  443. printf("\n\t");
  444. printf(" %02x", *(unsigned char *)sp);
  445. }
  446. printf("]\n");
  447. }
  448. #endif
  449. #if ENABLE_TRACEROUTE6
  450. if (dest_lsa->u.sa.sa_family == AF_INET6) {
  451. res = setsockopt(sndsock, SOL_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
  452. if (res < 0)
  453. bb_perror_msg_and_die("setsockopt UNICAST_HOPS %d", ttl);
  454. out = outip;
  455. len = packlen;
  456. } else
  457. #endif
  458. {
  459. #if defined IP_TTL
  460. res = setsockopt(sndsock, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
  461. if (res < 0)
  462. bb_perror_msg_and_die("setsockopt ttl %d", ttl);
  463. #endif
  464. out = outicmp;
  465. len = packlen - sizeof(*outip);
  466. if (!(option_mask32 & OPT_USE_ICMP)) {
  467. out = outdata;
  468. len -= sizeof(*outudp);
  469. set_nport(&dest_lsa->u.sa, htons(port + seq));
  470. }
  471. }
  472. res = xsendto(sndsock, out, len, &dest_lsa->u.sa, dest_lsa->len);
  473. if (res != len)
  474. bb_info_msg("sent %d octets, ret=%d", len, res);
  475. }
  476. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  477. /*
  478. * Convert an ICMP "type" field to a printable string.
  479. */
  480. static const char *
  481. pr_type(unsigned char t)
  482. {
  483. static const char *const ttab[] = {
  484. "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
  485. "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
  486. "Echo", "Router Advert", "Router Solicit", "Time Exceeded",
  487. "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
  488. "Info Reply", "Mask Request", "Mask Reply"
  489. };
  490. # if ENABLE_TRACEROUTE6
  491. static const char *const ttab6[] = {
  492. [0] "Error", "Dest Unreachable", "Packet Too Big", "Time Exceeded",
  493. [4] "Param Problem",
  494. [8] "Echo Request", "Echo Reply", "Membership Query", "Membership Report",
  495. [12] "Membership Reduction", "Router Solicit", "Router Advert", "Neighbor Solicit",
  496. [16] "Neighbor Advert", "Redirect",
  497. };
  498. if (dest_lsa->u.sa.sa_family == AF_INET6) {
  499. if (t < 5)
  500. return ttab6[t];
  501. if (t < 128 || t > ND_REDIRECT)
  502. return "OUT-OF-RANGE";
  503. return ttab6[(t & 63) + 8];
  504. }
  505. # endif
  506. if (t >= ARRAY_SIZE(ttab))
  507. return "OUT-OF-RANGE";
  508. return ttab[t];
  509. }
  510. #endif
  511. #if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
  512. #define packet4_ok(read_len, from, seq) \
  513. packet4_ok(read_len, seq)
  514. #endif
  515. static int
  516. packet4_ok(int read_len, const struct sockaddr_in *from, int seq)
  517. {
  518. const struct icmp *icp;
  519. unsigned char type, code;
  520. int hlen;
  521. const struct ip *ip;
  522. ip = (struct ip *) recv_pkt;
  523. hlen = ip->ip_hl << 2;
  524. if (read_len < hlen + ICMP_MINLEN) {
  525. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  526. if (verbose)
  527. printf("packet too short (%d bytes) from %s\n", read_len,
  528. inet_ntoa(from->sin_addr));
  529. #endif
  530. return 0;
  531. }
  532. read_len -= hlen;
  533. icp = (struct icmp *)(recv_pkt + hlen);
  534. type = icp->icmp_type;
  535. code = icp->icmp_code;
  536. /* Path MTU Discovery (RFC1191) */
  537. pmtu = 0;
  538. if (code == ICMP_UNREACH_NEEDFRAG)
  539. pmtu = ntohs(icp->icmp_nextmtu);
  540. if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS)
  541. || type == ICMP_UNREACH
  542. || type == ICMP_ECHOREPLY
  543. ) {
  544. const struct ip *hip;
  545. const struct udphdr *up;
  546. hip = &icp->icmp_ip;
  547. hlen = hip->ip_hl << 2;
  548. if (option_mask32 & OPT_USE_ICMP) {
  549. struct icmp *hicmp;
  550. /* XXX */
  551. if (type == ICMP_ECHOREPLY
  552. && icp->icmp_id == htons(ident)
  553. && icp->icmp_seq == htons(seq)
  554. ) {
  555. return ICMP_UNREACH_PORT+1;
  556. }
  557. hicmp = (struct icmp *)((unsigned char *)hip + hlen);
  558. if (hlen + SIZEOF_ICMP_HDR <= read_len
  559. && hip->ip_p == IPPROTO_ICMP
  560. && hicmp->icmp_id == htons(ident)
  561. && hicmp->icmp_seq == htons(seq)
  562. ) {
  563. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  564. }
  565. } else {
  566. up = (struct udphdr *)((char *)hip + hlen);
  567. if (hlen + 12 <= read_len
  568. && hip->ip_p == IPPROTO_UDP
  569. // Off: since we do not form the entire IP packet,
  570. // but defer it to kernel, we can't set source port,
  571. // and thus can't check it here in the reply
  572. /* && up->source == htons(ident) */
  573. && up->dest == htons(port + seq)
  574. ) {
  575. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  576. }
  577. }
  578. }
  579. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  580. if (verbose) {
  581. int i;
  582. uint32_t *lp = (uint32_t *)&icp->icmp_ip;
  583. printf("\n%d bytes from %s to "
  584. "%s: icmp type %d (%s) code %d\n",
  585. read_len, inet_ntoa(from->sin_addr),
  586. inet_ntoa(ip->ip_dst),
  587. type, pr_type(type), icp->icmp_code);
  588. for (i = 4; i < read_len; i += sizeof(*lp))
  589. printf("%2d: x%8.8x\n", i, *lp++);
  590. }
  591. #endif
  592. return 0;
  593. }
  594. #if ENABLE_TRACEROUTE6
  595. # if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
  596. #define packet_ok(read_len, from_lsa, to, seq) \
  597. packet_ok(read_len, from_lsa, seq)
  598. # endif
  599. static int
  600. packet_ok(int read_len, len_and_sockaddr *from_lsa,
  601. struct sockaddr *to,
  602. int seq)
  603. {
  604. const struct icmp6_hdr *icp;
  605. unsigned char type, code;
  606. if (from_lsa->u.sa.sa_family == AF_INET)
  607. return packet4_ok(read_len, &from_lsa->u.sin, seq);
  608. icp = (struct icmp6_hdr *) recv_pkt;
  609. type = icp->icmp6_type;
  610. code = icp->icmp6_code;
  611. if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT)
  612. || type == ICMP6_DST_UNREACH
  613. ) {
  614. struct ip6_hdr *hip;
  615. struct udphdr *up;
  616. int nexthdr;
  617. hip = (struct ip6_hdr *)(icp + 1);
  618. up = (struct udphdr *) (hip + 1);
  619. nexthdr = hip->ip6_nxt;
  620. if (nexthdr == IPPROTO_FRAGMENT) {
  621. nexthdr = *(unsigned char*)up;
  622. up++;
  623. }
  624. if (nexthdr == IPPROTO_UDP) {
  625. struct outdata6_t *pkt;
  626. pkt = (struct outdata6_t *) (up + 1);
  627. if (ntohl(pkt->ident6) == ident
  628. && ntohl(pkt->seq6) == seq
  629. ) {
  630. return (type == ICMP6_TIME_EXCEEDED ? -1 : (code<<8)+1);
  631. }
  632. }
  633. }
  634. # if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  635. if (verbose) {
  636. unsigned char *p;
  637. char pa1[MAXHOSTNAMELEN];
  638. char pa2[MAXHOSTNAMELEN];
  639. int i;
  640. p = (unsigned char *) (icp + 1);
  641. printf("\n%d bytes from %s to "
  642. "%s: icmp type %d (%s) code %d\n",
  643. read_len,
  644. inet_ntop(AF_INET6, &from_lsa->u.sin6.sin6_addr, pa1, sizeof(pa1)),
  645. inet_ntop(AF_INET6, &((struct sockaddr_in6*)to)->sin6_addr, pa2, sizeof(pa2)),
  646. type, pr_type(type), icp->icmp6_code);
  647. read_len -= sizeof(struct icmp6_hdr);
  648. for (i = 0; i < read_len; i++) {
  649. if (i % 16 == 0)
  650. printf("%04x:", i);
  651. if (i % 4 == 0)
  652. bb_putchar(' ');
  653. printf("%02x", p[i]);
  654. if ((i % 16 == 15) && (i + 1 < read_len))
  655. bb_putchar('\n');
  656. }
  657. bb_putchar('\n');
  658. }
  659. # endif
  660. return 0;
  661. }
  662. #else /* !ENABLE_TRACEROUTE6 */
  663. static ALWAYS_INLINE int
  664. packet_ok(int read_len,
  665. len_and_sockaddr *from_lsa IF_NOT_FEATURE_TRACEROUTE_VERBOSE(UNUSED_PARAM),
  666. struct sockaddr *to UNUSED_PARAM,
  667. int seq)
  668. {
  669. return packet4_ok(read_len, &from_lsa->u.sin, seq);
  670. }
  671. #endif
  672. /*
  673. * Construct an Internet address representation.
  674. * If the -n flag has been supplied, give
  675. * numeric value, otherwise try for symbolic name.
  676. */
  677. static void
  678. print_inetname(const struct sockaddr *from)
  679. {
  680. char *ina = xmalloc_sockaddr2dotted_noport(from);
  681. if (option_mask32 & OPT_ADDR_NUM) {
  682. printf(" %s", ina);
  683. } else {
  684. char *n = NULL;
  685. if (from->sa_family != AF_INET
  686. || ((struct sockaddr_in*)from)->sin_addr.s_addr != INADDR_ANY
  687. ) {
  688. /* Try to reverse resolve if it is not 0.0.0.0 */
  689. n = xmalloc_sockaddr2host_noport((struct sockaddr*)from);
  690. }
  691. printf(" %s (%s)", (n ? n : ina), ina);
  692. free(n);
  693. }
  694. free(ina);
  695. }
  696. static void
  697. print(int read_len, const struct sockaddr *from, const struct sockaddr *to)
  698. {
  699. print_inetname(from);
  700. if (verbose) {
  701. char *ina = xmalloc_sockaddr2dotted_noport(to);
  702. #if ENABLE_TRACEROUTE6
  703. if (to->sa_family == AF_INET6) {
  704. read_len -= sizeof(struct ip6_hdr);
  705. } else
  706. #endif
  707. {
  708. struct ip *ip4packet = (struct ip*)recv_pkt;
  709. read_len -= ip4packet->ip_hl << 2;
  710. }
  711. printf(" %d bytes to %s", read_len, ina);
  712. free(ina);
  713. }
  714. }
  715. static void
  716. print_delta_ms(unsigned t1p, unsigned t2p)
  717. {
  718. unsigned tt = t2p - t1p;
  719. printf(" %u.%03u ms", tt / 1000, tt % 1000);
  720. }
  721. /*
  722. * Usage: [-dFIlnrvx] [-g gateway] [-i iface] [-f first_ttl]
  723. * [-m max_ttl] [ -p port] [-q nqueries] [-s src_addr] [-t tos]
  724. * [-w waittime] [-z pausemsecs] host [packetlen]"
  725. */
  726. static int
  727. common_traceroute_main(int op, char **argv)
  728. {
  729. int minpacket;
  730. int tos = 0;
  731. int max_ttl = 30;
  732. int nprobes = 3;
  733. int first_ttl = 1;
  734. unsigned pausemsecs = 0;
  735. char *source;
  736. char *device;
  737. char *tos_str;
  738. char *max_ttl_str;
  739. char *port_str;
  740. char *nprobes_str;
  741. char *waittime_str;
  742. char *pausemsecs_str;
  743. char *first_ttl_str;
  744. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  745. llist_t *source_route_list = NULL;
  746. int lsrr = 0;
  747. #endif
  748. #if ENABLE_TRACEROUTE6
  749. sa_family_t af;
  750. #else
  751. enum { af = AF_INET };
  752. #endif
  753. int ttl;
  754. int seq;
  755. len_and_sockaddr *from_lsa;
  756. struct sockaddr *lastaddr;
  757. struct sockaddr *to;
  758. INIT_G();
  759. /* minimum 1 arg */
  760. opt_complementary = "-1:x-x" IF_FEATURE_TRACEROUTE_SOURCE_ROUTE(":g::");
  761. op |= getopt32(argv, OPT_STRING
  762. , &tos_str, &device, &max_ttl_str, &port_str, &nprobes_str
  763. , &source, &waittime_str, &pausemsecs_str, &first_ttl_str
  764. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  765. , &source_route_list
  766. #endif
  767. );
  768. argv += optind;
  769. #if 0 /* IGNORED */
  770. if (op & OPT_IP_CHKSUM)
  771. bb_error_msg("warning: ip checksums disabled");
  772. #endif
  773. if (op & OPT_TOS)
  774. tos = xatou_range(tos_str, 0, 255);
  775. if (op & OPT_MAX_TTL)
  776. max_ttl = xatou_range(max_ttl_str, 1, 255);
  777. if (op & OPT_PORT)
  778. port = xatou16(port_str);
  779. if (op & OPT_NPROBES)
  780. nprobes = xatou_range(nprobes_str, 1, INT_MAX);
  781. if (op & OPT_SOURCE) {
  782. /*
  783. * set the ip source address of the outbound
  784. * probe (e.g., on a multi-homed host).
  785. */
  786. if (getuid() != 0)
  787. bb_error_msg_and_die(bb_msg_you_must_be_root);
  788. }
  789. if (op & OPT_WAITTIME)
  790. waittime = xatou_range(waittime_str, 1, 24 * 60 * 60);
  791. if (op & OPT_PAUSE_MS)
  792. pausemsecs = xatou_range(pausemsecs_str, 0, 60 * 60 * 1000);
  793. if (op & OPT_FIRST_TTL)
  794. first_ttl = xatou_range(first_ttl_str, 1, max_ttl);
  795. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  796. if (source_route_list) {
  797. while (source_route_list) {
  798. len_and_sockaddr *lsa;
  799. if (lsrr >= NGATEWAYS)
  800. bb_error_msg_and_die("no more than %d gateways", NGATEWAYS);
  801. lsa = xhost_and_af2sockaddr(llist_pop(&source_route_list), 0, AF_INET);
  802. gwlist[lsrr] = lsa->u.sin.sin_addr.s_addr;
  803. free(lsa);
  804. ++lsrr;
  805. }
  806. optlen = (lsrr + 1) * sizeof(gwlist[0]);
  807. }
  808. #endif
  809. /* Process destination and optional packet size */
  810. minpacket = sizeof(*outip) + SIZEOF_ICMP_HDR + sizeof(*outdata) + optlen;
  811. if (!(op & OPT_USE_ICMP))
  812. minpacket += sizeof(*outudp) - SIZEOF_ICMP_HDR;
  813. #if ENABLE_TRACEROUTE6
  814. af = AF_UNSPEC;
  815. if (op & OPT_IPV4)
  816. af = AF_INET;
  817. if (op & OPT_IPV6)
  818. af = AF_INET6;
  819. dest_lsa = xhost_and_af2sockaddr(argv[0], port, af);
  820. af = dest_lsa->u.sa.sa_family;
  821. if (af == AF_INET6)
  822. minpacket = sizeof(struct outdata6_t);
  823. #else
  824. dest_lsa = xhost2sockaddr(argv[0], port);
  825. #endif
  826. packlen = minpacket;
  827. if (argv[1])
  828. packlen = xatoul_range(argv[1], minpacket, 32 * 1024);
  829. /* Ensure the socket fds won't be 0, 1 or 2 */
  830. bb_sanitize_stdio();
  831. #if ENABLE_TRACEROUTE6
  832. if (af == AF_INET6) {
  833. xmove_fd(xsocket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6), rcvsock);
  834. # ifdef IPV6_RECVPKTINFO
  835. setsockopt(rcvsock, SOL_IPV6, IPV6_RECVPKTINFO,
  836. &const_int_1, sizeof(const_int_1));
  837. setsockopt(rcvsock, SOL_IPV6, IPV6_2292PKTINFO,
  838. &const_int_1, sizeof(const_int_1));
  839. # else
  840. setsockopt(rcvsock, SOL_IPV6, IPV6_PKTINFO,
  841. &const_int_1, sizeof(const_int_1));
  842. # endif
  843. } else
  844. #endif
  845. {
  846. xmove_fd(xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP), rcvsock);
  847. }
  848. #if TRACEROUTE_SO_DEBUG
  849. if (op & OPT_DEBUG)
  850. setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
  851. &const_int_1, sizeof(const_int_1));
  852. #endif
  853. if (op & OPT_BYPASS_ROUTE)
  854. setsockopt(rcvsock, SOL_SOCKET, SO_DONTROUTE,
  855. &const_int_1, sizeof(const_int_1));
  856. #if ENABLE_TRACEROUTE6
  857. if (af == AF_INET6) {
  858. static const int two = 2;
  859. if (setsockopt(rcvsock, SOL_RAW, IPV6_CHECKSUM, &two, sizeof(two)) < 0)
  860. bb_perror_msg_and_die("setsockopt RAW_CHECKSUM");
  861. xmove_fd(xsocket(af, SOCK_DGRAM, 0), sndsock);
  862. } else
  863. #endif
  864. {
  865. if (op & OPT_USE_ICMP)
  866. xmove_fd(xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP), sndsock);
  867. else
  868. xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), sndsock);
  869. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE && defined IP_OPTIONS
  870. if (lsrr > 0) {
  871. unsigned char optlist[MAX_IPOPTLEN];
  872. unsigned size;
  873. /* final hop */
  874. gwlist[lsrr] = dest_lsa->u.sin.sin_addr.s_addr;
  875. ++lsrr;
  876. /* force 4 byte alignment */
  877. optlist[0] = IPOPT_NOP;
  878. /* loose source route option */
  879. optlist[1] = IPOPT_LSRR;
  880. size = lsrr * sizeof(gwlist[0]);
  881. optlist[2] = size + 3;
  882. /* pointer to LSRR addresses */
  883. optlist[3] = IPOPT_MINOFF;
  884. memcpy(optlist + 4, gwlist, size);
  885. if (setsockopt(sndsock, IPPROTO_IP, IP_OPTIONS,
  886. (char *)optlist, size + sizeof(gwlist[0])) < 0) {
  887. bb_perror_msg_and_die("IP_OPTIONS");
  888. }
  889. }
  890. #endif
  891. }
  892. #ifdef SO_SNDBUF
  893. if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, &packlen, sizeof(packlen)) < 0) {
  894. bb_perror_msg_and_die("SO_SNDBUF");
  895. }
  896. #endif
  897. #ifdef IP_TOS
  898. if ((op & OPT_TOS) && setsockopt(sndsock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) {
  899. bb_perror_msg_and_die("setsockopt tos %d", tos);
  900. }
  901. #endif
  902. #ifdef IP_DONTFRAG
  903. if (op & OPT_DONT_FRAGMNT)
  904. setsockopt(sndsock, IPPROTO_IP, IP_DONTFRAG,
  905. &const_int_1, sizeof(const_int_1));
  906. #endif
  907. #if TRACEROUTE_SO_DEBUG
  908. if (op & OPT_DEBUG)
  909. setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
  910. &const_int_1, sizeof(const_int_1));
  911. #endif
  912. if (op & OPT_BYPASS_ROUTE)
  913. setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
  914. &const_int_1, sizeof(const_int_1));
  915. outip = xzalloc(packlen);
  916. ident = getpid();
  917. if (af == AF_INET) {
  918. if (op & OPT_USE_ICMP) {
  919. ident |= 0x8000;
  920. outicmp->icmp_type = ICMP_ECHO;
  921. outicmp->icmp_id = htons(ident);
  922. outdata = (struct outdata_t *)((char *)outicmp + SIZEOF_ICMP_HDR);
  923. } else {
  924. outdata = (struct outdata_t *)(outudp + 1);
  925. }
  926. }
  927. if (op & OPT_DEVICE) /* hmm, do we need error check? */
  928. setsockopt_bindtodevice(sndsock, device);
  929. if (op & OPT_SOURCE) {
  930. #if ENABLE_TRACEROUTE6
  931. // TODO: need xdotted_and_af2sockaddr?
  932. len_and_sockaddr *source_lsa = xhost_and_af2sockaddr(source, 0, af);
  933. #else
  934. len_and_sockaddr *source_lsa = xdotted2sockaddr(source, 0);
  935. #endif
  936. /* Ping4 does this (why?) */
  937. if (af == AF_INET)
  938. if (setsockopt(sndsock, IPPROTO_IP, IP_MULTICAST_IF,
  939. &source_lsa->u.sa, source_lsa->len))
  940. bb_error_msg_and_die("can't set multicast source interface");
  941. //TODO: we can query source port we bound to,
  942. // and check it in replies... if we care enough
  943. xbind(sndsock, &source_lsa->u.sa, source_lsa->len);
  944. free(source_lsa);
  945. }
  946. #if ENABLE_TRACEROUTE6
  947. else if (af == AF_INET6) {
  948. //TODO: why we don't do it for IPv4?
  949. len_and_sockaddr *source_lsa;
  950. int probe_fd = xsocket(af, SOCK_DGRAM, 0);
  951. if (op & OPT_DEVICE)
  952. setsockopt_bindtodevice(probe_fd, device);
  953. set_nport(&dest_lsa->u.sa, htons(1025));
  954. /* dummy connect. makes kernel pick source IP (and port) */
  955. xconnect(probe_fd, &dest_lsa->u.sa, dest_lsa->len);
  956. set_nport(&dest_lsa->u.sa, htons(port));
  957. /* read IP and port */
  958. source_lsa = get_sock_lsa(probe_fd);
  959. if (source_lsa == NULL)
  960. bb_error_msg_and_die("can't get probe addr");
  961. close(probe_fd);
  962. /* bind our sockets to this IP (but not port) */
  963. set_nport(&source_lsa->u.sa, 0);
  964. xbind(sndsock, &source_lsa->u.sa, source_lsa->len);
  965. xbind(rcvsock, &source_lsa->u.sa, source_lsa->len);
  966. free(source_lsa);
  967. }
  968. #endif
  969. /* Revert to non-privileged user after opening sockets */
  970. xsetgid(getgid());
  971. xsetuid(getuid());
  972. printf("traceroute to %s (%s)", argv[0],
  973. xmalloc_sockaddr2dotted_noport(&dest_lsa->u.sa));
  974. if (op & OPT_SOURCE)
  975. printf(" from %s", source);
  976. printf(", %d hops max, %d byte packets\n", max_ttl, packlen);
  977. from_lsa = dup_sockaddr(dest_lsa);
  978. lastaddr = xzalloc(dest_lsa->len);
  979. to = xzalloc(dest_lsa->len);
  980. seq = 0;
  981. for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
  982. int probe;
  983. int unreachable = 0; /* counter */
  984. int gotlastaddr = 0; /* flags */
  985. int got_there = 0;
  986. printf("%2d", ttl);
  987. for (probe = 0; probe < nprobes; ++probe) {
  988. int read_len;
  989. unsigned t1;
  990. unsigned t2;
  991. int left_ms;
  992. struct ip *ip;
  993. fflush_all();
  994. if (probe != 0 && pausemsecs > 0)
  995. usleep(pausemsecs * 1000);
  996. send_probe(++seq, ttl);
  997. t2 = t1 = monotonic_us();
  998. left_ms = waittime * 1000;
  999. while ((read_len = wait_for_reply(from_lsa, to, &t2, &left_ms)) != 0) {
  1000. int icmp_code;
  1001. /* Recv'ed a packet, or read error */
  1002. /* t2 = monotonic_us() - set by wait_for_reply */
  1003. if (read_len < 0)
  1004. continue;
  1005. icmp_code = packet_ok(read_len, from_lsa, to, seq);
  1006. /* Skip short packet */
  1007. if (icmp_code == 0)
  1008. continue;
  1009. if (!gotlastaddr
  1010. || (memcmp(lastaddr, &from_lsa->u.sa, from_lsa->len) != 0)
  1011. ) {
  1012. print(read_len, &from_lsa->u.sa, to);
  1013. memcpy(lastaddr, &from_lsa->u.sa, from_lsa->len);
  1014. gotlastaddr = 1;
  1015. }
  1016. print_delta_ms(t1, t2);
  1017. ip = (struct ip *)recv_pkt;
  1018. if (from_lsa->u.sa.sa_family == AF_INET)
  1019. if (op & OPT_TTL_FLAG)
  1020. printf(" (%d)", ip->ip_ttl);
  1021. /* time exceeded in transit */
  1022. if (icmp_code == -1)
  1023. break;
  1024. icmp_code--;
  1025. switch (icmp_code) {
  1026. #if ENABLE_TRACEROUTE6
  1027. case ICMP6_DST_UNREACH_NOPORT << 8:
  1028. got_there = 1;
  1029. break;
  1030. #endif
  1031. case ICMP_UNREACH_PORT:
  1032. if (ip->ip_ttl <= 1)
  1033. printf(" !");
  1034. got_there = 1;
  1035. break;
  1036. case ICMP_UNREACH_NET:
  1037. #if ENABLE_TRACEROUTE6 && (ICMP6_DST_UNREACH_NOROUTE != ICMP_UNREACH_NET)
  1038. case ICMP6_DST_UNREACH_NOROUTE << 8:
  1039. #endif
  1040. printf(" !N");
  1041. ++unreachable;
  1042. break;
  1043. case ICMP_UNREACH_HOST:
  1044. #if ENABLE_TRACEROUTE6
  1045. case ICMP6_DST_UNREACH_ADDR << 8:
  1046. #endif
  1047. printf(" !H");
  1048. ++unreachable;
  1049. break;
  1050. case ICMP_UNREACH_PROTOCOL:
  1051. printf(" !P");
  1052. got_there = 1;
  1053. break;
  1054. case ICMP_UNREACH_NEEDFRAG:
  1055. printf(" !F-%d", pmtu);
  1056. ++unreachable;
  1057. break;
  1058. case ICMP_UNREACH_SRCFAIL:
  1059. #if ENABLE_TRACEROUTE6
  1060. case ICMP6_DST_UNREACH_ADMIN << 8:
  1061. #endif
  1062. printf(" !S");
  1063. ++unreachable;
  1064. break;
  1065. case ICMP_UNREACH_FILTER_PROHIB:
  1066. case ICMP_UNREACH_NET_PROHIB: /* misuse */
  1067. printf(" !A");
  1068. ++unreachable;
  1069. break;
  1070. case ICMP_UNREACH_HOST_PROHIB:
  1071. printf(" !C");
  1072. ++unreachable;
  1073. break;
  1074. case ICMP_UNREACH_HOST_PRECEDENCE:
  1075. printf(" !V");
  1076. ++unreachable;
  1077. break;
  1078. case ICMP_UNREACH_PRECEDENCE_CUTOFF:
  1079. printf(" !C");
  1080. ++unreachable;
  1081. break;
  1082. case ICMP_UNREACH_NET_UNKNOWN:
  1083. case ICMP_UNREACH_HOST_UNKNOWN:
  1084. printf(" !U");
  1085. ++unreachable;
  1086. break;
  1087. case ICMP_UNREACH_ISOLATED:
  1088. printf(" !I");
  1089. ++unreachable;
  1090. break;
  1091. case ICMP_UNREACH_TOSNET:
  1092. case ICMP_UNREACH_TOSHOST:
  1093. printf(" !T");
  1094. ++unreachable;
  1095. break;
  1096. default:
  1097. printf(" !<%d>", icmp_code);
  1098. ++unreachable;
  1099. break;
  1100. }
  1101. break;
  1102. } /* while (wait and read a packet) */
  1103. /* there was no packet at all? */
  1104. if (read_len == 0)
  1105. printf(" *");
  1106. } /* for (nprobes) */
  1107. bb_putchar('\n');
  1108. if (got_there
  1109. || (unreachable > 0 && unreachable >= nprobes - 1)
  1110. ) {
  1111. break;
  1112. }
  1113. }
  1114. return 0;
  1115. }
  1116. int traceroute_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1117. int traceroute_main(int argc UNUSED_PARAM, char **argv)
  1118. {
  1119. return common_traceroute_main(0, argv);
  1120. }
  1121. #if ENABLE_TRACEROUTE6
  1122. int traceroute6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1123. int traceroute6_main(int argc UNUSED_PARAM, char **argv)
  1124. {
  1125. return common_traceroute_main(OPT_IPV6, argv);
  1126. }
  1127. #endif