3
0

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")"FIlnrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT]\n"
  212. //usage: " [-t TOS] [-w WAIT_SEC]"
  213. //usage: IF_FEATURE_TRACEROUTE_SOURCE_ROUTE(" [-g GATEWAY]")" [-s SRC_IP] [-i IFACE]\n"
  214. //usage: " [-z PAUSE_MSEC] HOST [BYTES]"
  215. //usage:#define traceroute_full_usage "\n\n"
  216. //usage: "Trace the route to HOST\n"
  217. //usage: IF_TRACEROUTE6(
  218. //usage: "\n -4,-6 Force IP or IPv6 name resolution"
  219. //usage: )
  220. //usage: "\n -F Set don't fragment bit"
  221. //usage: IF_FEATURE_TRACEROUTE_USE_ICMP(
  222. //usage: "\n -I Use ICMP ECHO instead of UDP datagrams"
  223. //usage: )
  224. //usage: "\n -l Display TTL value of the returned packet"
  225. //Currently disabled (TRACEROUTE_SO_DEBUG==0)
  226. ////usage: "\n -d Set SO_DEBUG options to socket"
  227. //usage: "\n -n Print numeric addresses"
  228. //usage: "\n -r Bypass routing tables, send directly to HOST"
  229. //usage: IF_FEATURE_TRACEROUTE_VERBOSE(
  230. //usage: "\n -v Verbose"
  231. //usage: )
  232. //usage: "\n -f N First number of hops (default 1)"
  233. //usage: "\n -m N Max number of hops"
  234. //usage: "\n -q N Number of probes per hop (default 3)"
  235. //usage: "\n -p N Base UDP port number used in probes"
  236. //usage: "\n (default 33434)"
  237. //usage: "\n -s IP Source address"
  238. //usage: "\n -i IFACE Source interface"
  239. //usage: "\n -t N Type-of-service in probe packets (default 0)"
  240. //usage: "\n -w SEC Time to wait for a response (default 3)"
  241. //usage: "\n -g IP Loose source route gateway (8 max)"
  242. //usage:
  243. //usage:#define traceroute6_trivial_usage
  244. //usage: "[-nrv] [-m MAXTTL] [-q PROBES] [-p PORT]\n"
  245. //usage: " [-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE]\n"
  246. //usage: " HOST [BYTES]"
  247. //usage:#define traceroute6_full_usage "\n\n"
  248. //usage: "Trace the route to HOST\n"
  249. //Currently disabled (TRACEROUTE_SO_DEBUG==0)
  250. ////usage: "\n -d Set SO_DEBUG options to socket"
  251. //usage: "\n -n Print numeric addresses"
  252. //usage: "\n -r Bypass routing tables, send directly to HOST"
  253. //usage: IF_FEATURE_TRACEROUTE_VERBOSE(
  254. //usage: "\n -v Verbose"
  255. //usage: )
  256. //usage: "\n -m N Max number of hops"
  257. //usage: "\n -q N Number of probes per hop (default 3)"
  258. //usage: "\n -p N Base UDP port number used in probes"
  259. //usage: "\n (default 33434)"
  260. //usage: "\n -s IP Source address"
  261. //usage: "\n -i IFACE Source interface"
  262. //usage: "\n -t N Type-of-service in probe packets (default 0)"
  263. //usage: "\n -w SEC Time wait for a response (default 3)"
  264. #define TRACEROUTE_SO_DEBUG 0
  265. #include <net/if.h>
  266. #include <arpa/inet.h>
  267. #include <netinet/in.h>
  268. #include <netinet/udp.h>
  269. #include <netinet/ip.h>
  270. #include <netinet/ip_icmp.h>
  271. #if ENABLE_FEATURE_IPV6
  272. # include <netinet/ip6.h>
  273. # include <netinet/icmp6.h>
  274. # ifndef SOL_IPV6
  275. # define SOL_IPV6 IPPROTO_IPV6
  276. # endif
  277. #endif
  278. #include "libbb.h"
  279. #include "inet_common.h"
  280. #ifndef IPPROTO_ICMP
  281. # define IPPROTO_ICMP 1
  282. #endif
  283. #ifndef IPPROTO_IP
  284. # define IPPROTO_IP 0
  285. #endif
  286. #define OPT_STRING \
  287. "FIlnrdvxt:i:m:p:q:s:w:z:f:" \
  288. IF_FEATURE_TRACEROUTE_SOURCE_ROUTE("g:") \
  289. "4" IF_TRACEROUTE6("6")
  290. enum {
  291. OPT_DONT_FRAGMNT = (1 << 0), /* F */
  292. OPT_USE_ICMP = (1 << 1) * ENABLE_FEATURE_TRACEROUTE_USE_ICMP, /* I */
  293. OPT_TTL_FLAG = (1 << 2), /* l */
  294. OPT_ADDR_NUM = (1 << 3), /* n */
  295. OPT_BYPASS_ROUTE = (1 << 4), /* r */
  296. OPT_DEBUG = (1 << 5), /* d */
  297. OPT_VERBOSE = (1 << 6) * ENABLE_FEATURE_TRACEROUTE_VERBOSE, /* v */
  298. OPT_IP_CHKSUM = (1 << 7), /* x */
  299. OPT_TOS = (1 << 8), /* t */
  300. OPT_DEVICE = (1 << 9), /* i */
  301. OPT_MAX_TTL = (1 << 10), /* m */
  302. OPT_PORT = (1 << 11), /* p */
  303. OPT_NPROBES = (1 << 12), /* q */
  304. OPT_SOURCE = (1 << 13), /* s */
  305. OPT_WAITTIME = (1 << 14), /* w */
  306. OPT_PAUSE_MS = (1 << 15), /* z */
  307. OPT_FIRST_TTL = (1 << 16), /* f */
  308. OPT_SOURCE_ROUTE = (1 << 17) * ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE, /* g */
  309. OPT_IPV4 = (1 << (17+ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE)), /* 4 */
  310. OPT_IPV6 = (1 << (18+ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE)) * ENABLE_TRACEROUTE6, /* 6 */
  311. };
  312. #define verbose (option_mask32 & OPT_VERBOSE)
  313. enum {
  314. SIZEOF_ICMP_HDR = 8,
  315. rcvsock = 3, /* receive (icmp) socket file descriptor */
  316. sndsock = 4, /* send (udp/icmp) socket file descriptor */
  317. };
  318. /* Data section of the probe packet */
  319. struct outdata_t {
  320. unsigned char seq; /* sequence number of this packet */
  321. unsigned char ttl; /* ttl packet left with */
  322. // UNUSED. Retaining to have the same packet size.
  323. struct timeval tv_UNUSED PACKED; /* time packet left */
  324. };
  325. #if ENABLE_TRACEROUTE6
  326. struct outdata6_t {
  327. uint32_t ident6;
  328. uint32_t seq6;
  329. struct timeval tv_UNUSED PACKED; /* time packet left */
  330. };
  331. #endif
  332. struct globals {
  333. struct ip *outip;
  334. struct outdata_t *outdata;
  335. len_and_sockaddr *dest_lsa;
  336. int packlen; /* total length of packet */
  337. int pmtu; /* Path MTU Discovery (RFC1191) */
  338. uint32_t ident;
  339. uint16_t port; // 32768 + 666; /* start udp dest port # for probe packets */
  340. int waittime; // 5; /* time to wait for response (in seconds) */
  341. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  342. int optlen; /* length of ip options */
  343. #else
  344. #define optlen 0
  345. #endif
  346. unsigned char recv_pkt[512]; /* last inbound (icmp) packet */
  347. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  348. /* Maximum number of gateways (include room for one noop) */
  349. #define NGATEWAYS ((int)((MAX_IPOPTLEN - IPOPT_MINOFF - 1) / sizeof(uint32_t)))
  350. /* loose source route gateway list (including room for final destination) */
  351. uint32_t gwlist[NGATEWAYS + 1];
  352. #endif
  353. };
  354. #define G (*ptr_to_globals)
  355. #define outip (G.outip )
  356. #define outdata (G.outdata )
  357. #define dest_lsa (G.dest_lsa )
  358. #define packlen (G.packlen )
  359. #define pmtu (G.pmtu )
  360. #define ident (G.ident )
  361. #define port (G.port )
  362. #define waittime (G.waittime )
  363. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  364. # define optlen (G.optlen )
  365. #endif
  366. #define recv_pkt (G.recv_pkt )
  367. #define gwlist (G.gwlist )
  368. #define INIT_G() do { \
  369. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  370. port = 32768 + 666; \
  371. waittime = 5; \
  372. } while (0)
  373. #define outicmp ((struct icmp *)(outip + 1))
  374. #define outudp ((struct udphdr *)(outip + 1))
  375. static int
  376. wait_for_reply(len_and_sockaddr *from_lsa, struct sockaddr *to, unsigned *timestamp_us, int *left_ms)
  377. {
  378. struct pollfd pfd[1];
  379. int read_len = 0;
  380. pfd[0].fd = rcvsock;
  381. pfd[0].events = POLLIN;
  382. if (*left_ms >= 0 && safe_poll(pfd, 1, *left_ms) > 0) {
  383. unsigned t;
  384. read_len = recv_from_to(rcvsock,
  385. recv_pkt, sizeof(recv_pkt),
  386. /*flags:*/ MSG_DONTWAIT,
  387. &from_lsa->u.sa, to, from_lsa->len);
  388. t = monotonic_us();
  389. *left_ms -= (t - *timestamp_us) / 1000;
  390. *timestamp_us = t;
  391. }
  392. return read_len;
  393. }
  394. static void
  395. send_probe(int seq, int ttl)
  396. {
  397. int len, res;
  398. void *out;
  399. /* Payload */
  400. #if ENABLE_TRACEROUTE6
  401. if (dest_lsa->u.sa.sa_family == AF_INET6) {
  402. struct outdata6_t *pkt = (struct outdata6_t *) outip;
  403. pkt->ident6 = htonl(ident);
  404. pkt->seq6 = htonl(seq);
  405. /*gettimeofday(&pkt->tv, &tz);*/
  406. } else
  407. #endif
  408. {
  409. outdata->seq = seq;
  410. outdata->ttl = ttl;
  411. // UNUSED: was storing gettimeofday's result there, but never ever checked it
  412. /*memcpy(&outdata->tv, tp, sizeof(outdata->tv));*/
  413. if (option_mask32 & OPT_USE_ICMP) {
  414. outicmp->icmp_seq = htons(seq);
  415. /* Always calculate checksum for icmp packets */
  416. outicmp->icmp_cksum = 0;
  417. outicmp->icmp_cksum = inet_cksum((uint16_t *)outicmp,
  418. packlen - (sizeof(*outip) + optlen));
  419. if (outicmp->icmp_cksum == 0)
  420. outicmp->icmp_cksum = 0xffff;
  421. }
  422. }
  423. //BUG! verbose is (x & OPT_VERBOSE), not a counter!
  424. #if 0 //ENABLE_FEATURE_TRACEROUTE_VERBOSE
  425. /* XXX undocumented debugging hack */
  426. if (verbose > 1) {
  427. const uint16_t *sp;
  428. int nshorts, i;
  429. sp = (uint16_t *)outip;
  430. nshorts = (unsigned)packlen / sizeof(uint16_t);
  431. i = 0;
  432. printf("[ %d bytes", packlen);
  433. while (--nshorts >= 0) {
  434. if ((i++ % 8) == 0)
  435. printf("\n\t");
  436. printf(" %04x", ntohs(*sp));
  437. sp++;
  438. }
  439. if (packlen & 1) {
  440. if ((i % 8) == 0)
  441. printf("\n\t");
  442. printf(" %02x", *(unsigned char *)sp);
  443. }
  444. printf("]\n");
  445. }
  446. #endif
  447. #if ENABLE_TRACEROUTE6
  448. if (dest_lsa->u.sa.sa_family == AF_INET6) {
  449. res = setsockopt_int(sndsock, SOL_IPV6, IPV6_UNICAST_HOPS, ttl);
  450. if (res != 0)
  451. bb_perror_msg_and_die("setsockopt(%s) %d", "UNICAST_HOPS", ttl);
  452. out = outip;
  453. len = packlen;
  454. } else
  455. #endif
  456. {
  457. #if defined IP_TTL
  458. res = setsockopt_int(sndsock, IPPROTO_IP, IP_TTL, ttl);
  459. if (res != 0)
  460. bb_perror_msg_and_die("setsockopt(%s) %d", "TTL", ttl);
  461. #endif
  462. out = outicmp;
  463. len = packlen - sizeof(*outip);
  464. if (!(option_mask32 & OPT_USE_ICMP)) {
  465. out = outdata;
  466. len -= sizeof(*outudp);
  467. set_nport(&dest_lsa->u.sa, htons(port + seq));
  468. }
  469. }
  470. res = xsendto(sndsock, out, len, &dest_lsa->u.sa, dest_lsa->len);
  471. if (res != len)
  472. bb_error_msg("sent %d octets, ret=%d", len, res);
  473. }
  474. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  475. /*
  476. * Convert an ICMP "type" field to a printable string.
  477. */
  478. static const char *
  479. pr_type(unsigned char t)
  480. {
  481. static const char *const ttab[] = {
  482. "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
  483. "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
  484. "Echo", "Router Advert", "Router Solicit", "Time Exceeded",
  485. "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
  486. "Info Reply", "Mask Request", "Mask Reply"
  487. };
  488. # if ENABLE_TRACEROUTE6
  489. static const char *const ttab6[] = {
  490. [0] "Error", "Dest Unreachable", "Packet Too Big", "Time Exceeded",
  491. [4] "Param Problem",
  492. [8] "Echo Request", "Echo Reply", "Membership Query", "Membership Report",
  493. [12] "Membership Reduction", "Router Solicit", "Router Advert", "Neighbor Solicit",
  494. [16] "Neighbor Advert", "Redirect",
  495. };
  496. if (dest_lsa->u.sa.sa_family == AF_INET6) {
  497. if (t < 5)
  498. return ttab6[t];
  499. if (t < 128 || t > ND_REDIRECT)
  500. return "OUT-OF-RANGE";
  501. return ttab6[(t & 63) + 8];
  502. }
  503. # endif
  504. if (t >= ARRAY_SIZE(ttab))
  505. return "OUT-OF-RANGE";
  506. return ttab[t];
  507. }
  508. #endif
  509. #if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
  510. #define packet4_ok(read_len, from, seq) \
  511. packet4_ok(read_len, seq)
  512. #endif
  513. static int
  514. packet4_ok(int read_len, const struct sockaddr_in *from, int seq)
  515. {
  516. const struct icmp *icp;
  517. unsigned char type, code;
  518. int hlen;
  519. const struct ip *ip;
  520. ip = (struct ip *) recv_pkt;
  521. hlen = ip->ip_hl << 2;
  522. if (read_len < hlen + ICMP_MINLEN) {
  523. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  524. if (verbose)
  525. printf("packet too short (%d bytes) from %s\n", read_len,
  526. inet_ntoa(from->sin_addr));
  527. #endif
  528. return 0;
  529. }
  530. read_len -= hlen;
  531. icp = (struct icmp *)(recv_pkt + hlen);
  532. type = icp->icmp_type;
  533. code = icp->icmp_code;
  534. /* Path MTU Discovery (RFC1191) */
  535. pmtu = 0;
  536. if (code == ICMP_UNREACH_NEEDFRAG)
  537. pmtu = ntohs(icp->icmp_nextmtu);
  538. if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS)
  539. || type == ICMP_UNREACH
  540. || type == ICMP_ECHOREPLY
  541. ) {
  542. const struct ip *hip;
  543. const struct udphdr *up;
  544. hip = &icp->icmp_ip;
  545. hlen = hip->ip_hl << 2;
  546. if (option_mask32 & OPT_USE_ICMP) {
  547. struct icmp *hicmp;
  548. /* XXX */
  549. if (type == ICMP_ECHOREPLY
  550. && icp->icmp_id == htons(ident)
  551. && icp->icmp_seq == htons(seq)
  552. ) {
  553. return ICMP_UNREACH_PORT+1;
  554. }
  555. hicmp = (struct icmp *)((unsigned char *)hip + hlen);
  556. if (hlen + SIZEOF_ICMP_HDR <= read_len
  557. && hip->ip_p == IPPROTO_ICMP
  558. && hicmp->icmp_id == htons(ident)
  559. && hicmp->icmp_seq == htons(seq)
  560. ) {
  561. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  562. }
  563. } else {
  564. up = (struct udphdr *)((char *)hip + hlen);
  565. if (hlen + 12 <= read_len
  566. && hip->ip_p == IPPROTO_UDP
  567. // Off: since we do not form the entire IP packet,
  568. // but defer it to kernel, we can't set source port,
  569. // and thus can't check it here in the reply
  570. /* && up->source == htons(ident) */
  571. && up->dest == htons(port + seq)
  572. ) {
  573. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  574. }
  575. }
  576. }
  577. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  578. if (verbose) {
  579. int i;
  580. uint32_t *lp = (uint32_t *)&icp->icmp_ip;
  581. printf("\n%d bytes from %s to "
  582. "%s: icmp type %d (%s) code %d\n",
  583. read_len, inet_ntoa(from->sin_addr),
  584. inet_ntoa(ip->ip_dst),
  585. type, pr_type(type), icp->icmp_code);
  586. for (i = 4; i < read_len; i += sizeof(*lp))
  587. printf("%2d: x%8.8x\n", i, *lp++);
  588. }
  589. #endif
  590. return 0;
  591. }
  592. #if ENABLE_TRACEROUTE6
  593. # if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
  594. #define packet_ok(read_len, from_lsa, to, seq) \
  595. packet_ok(read_len, from_lsa, seq)
  596. # endif
  597. static int
  598. packet_ok(int read_len, len_and_sockaddr *from_lsa,
  599. struct sockaddr *to,
  600. int seq)
  601. {
  602. const struct icmp6_hdr *icp;
  603. unsigned char type, code;
  604. if (from_lsa->u.sa.sa_family == AF_INET)
  605. return packet4_ok(read_len, &from_lsa->u.sin, seq);
  606. icp = (struct icmp6_hdr *) recv_pkt;
  607. type = icp->icmp6_type;
  608. code = icp->icmp6_code;
  609. if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT)
  610. || type == ICMP6_DST_UNREACH
  611. ) {
  612. struct ip6_hdr *hip;
  613. struct udphdr *up;
  614. int nexthdr;
  615. hip = (struct ip6_hdr *)(icp + 1);
  616. up = (struct udphdr *) (hip + 1);
  617. nexthdr = hip->ip6_nxt;
  618. if (nexthdr == IPPROTO_FRAGMENT) {
  619. nexthdr = *(unsigned char*)up;
  620. up++;
  621. }
  622. if (nexthdr == IPPROTO_UDP) {
  623. struct outdata6_t *pkt;
  624. pkt = (struct outdata6_t *) (up + 1);
  625. if (ntohl(pkt->ident6) == ident
  626. && ntohl(pkt->seq6) == seq
  627. ) {
  628. return (type == ICMP6_TIME_EXCEEDED ? -1 : (code<<8)+1);
  629. }
  630. }
  631. }
  632. # if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  633. if (verbose) {
  634. unsigned char *p;
  635. char pa1[MAXHOSTNAMELEN];
  636. char pa2[MAXHOSTNAMELEN];
  637. int i;
  638. p = (unsigned char *) (icp + 1);
  639. printf("\n%d bytes from %s to "
  640. "%s: icmp type %d (%s) code %d\n",
  641. read_len,
  642. inet_ntop(AF_INET6, &from_lsa->u.sin6.sin6_addr, pa1, sizeof(pa1)),
  643. inet_ntop(AF_INET6, &((struct sockaddr_in6*)to)->sin6_addr, pa2, sizeof(pa2)),
  644. type, pr_type(type), icp->icmp6_code);
  645. read_len -= sizeof(struct icmp6_hdr);
  646. for (i = 0; i < read_len; i++) {
  647. if (i % 16 == 0)
  648. printf("%04x:", i);
  649. if (i % 4 == 0)
  650. bb_putchar(' ');
  651. printf("%02x", p[i]);
  652. if ((i % 16 == 15) && (i + 1 < read_len))
  653. bb_putchar('\n');
  654. }
  655. bb_putchar('\n');
  656. }
  657. # endif
  658. return 0;
  659. }
  660. #else /* !ENABLE_TRACEROUTE6 */
  661. static ALWAYS_INLINE int
  662. packet_ok(int read_len,
  663. len_and_sockaddr *from_lsa IF_NOT_FEATURE_TRACEROUTE_VERBOSE(UNUSED_PARAM),
  664. struct sockaddr *to UNUSED_PARAM,
  665. int seq)
  666. {
  667. return packet4_ok(read_len, &from_lsa->u.sin, seq);
  668. }
  669. #endif
  670. /*
  671. * Construct an Internet address representation.
  672. * If the -n flag has been supplied, give
  673. * numeric value, otherwise try for symbolic name.
  674. */
  675. static void
  676. print_inetname(const struct sockaddr *from)
  677. {
  678. char *ina = xmalloc_sockaddr2dotted_noport(from);
  679. if (option_mask32 & OPT_ADDR_NUM) {
  680. printf(" %s", ina);
  681. } else {
  682. char *n = NULL;
  683. if (from->sa_family != AF_INET
  684. || ((struct sockaddr_in*)from)->sin_addr.s_addr != INADDR_ANY
  685. ) {
  686. /* Try to reverse resolve if it is not 0.0.0.0 */
  687. n = xmalloc_sockaddr2host_noport((struct sockaddr*)from);
  688. }
  689. printf(" %s (%s)", (n ? n : ina), ina);
  690. free(n);
  691. }
  692. free(ina);
  693. }
  694. static void
  695. print(int read_len, const struct sockaddr *from, const struct sockaddr *to)
  696. {
  697. print_inetname(from);
  698. if (verbose) {
  699. char *ina = xmalloc_sockaddr2dotted_noport(to);
  700. #if ENABLE_TRACEROUTE6
  701. if (to->sa_family == AF_INET6) {
  702. read_len -= sizeof(struct ip6_hdr);
  703. } else
  704. #endif
  705. {
  706. struct ip *ip4packet = (struct ip*)recv_pkt;
  707. read_len -= ip4packet->ip_hl << 2;
  708. }
  709. printf(" %d bytes to %s", read_len, ina);
  710. free(ina);
  711. }
  712. }
  713. static void
  714. print_delta_ms(unsigned t1p, unsigned t2p)
  715. {
  716. unsigned tt = t2p - t1p;
  717. printf(" %u.%03u ms", tt / 1000, tt % 1000);
  718. }
  719. /*
  720. * Usage: [-dFIlnrvx] [-g gateway] [-i iface] [-f first_ttl]
  721. * [-m max_ttl] [ -p port] [-q nqueries] [-s src_addr] [-t tos]
  722. * [-w waittime] [-z pausemsecs] host [packetlen]"
  723. */
  724. static int
  725. common_traceroute_main(int op, char **argv)
  726. {
  727. int minpacket;
  728. #ifdef IP_TOS
  729. int tos = 0;
  730. #endif
  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. char *dest_str;
  745. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  746. llist_t *source_route_list = NULL;
  747. int lsrr = 0;
  748. #endif
  749. #if ENABLE_TRACEROUTE6
  750. sa_family_t af;
  751. #else
  752. enum { af = AF_INET };
  753. #endif
  754. int ttl;
  755. int seq;
  756. len_and_sockaddr *from_lsa;
  757. struct sockaddr *lastaddr;
  758. struct sockaddr *to;
  759. INIT_G();
  760. /* minimum 1 arg */
  761. opt_complementary = "-1:x-x" IF_FEATURE_TRACEROUTE_SOURCE_ROUTE(":g::");
  762. op |= getopt32(argv, OPT_STRING
  763. , &tos_str, &device, &max_ttl_str, &port_str, &nprobes_str
  764. , &source, &waittime_str, &pausemsecs_str, &first_ttl_str
  765. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  766. , &source_route_list
  767. #endif
  768. );
  769. argv += optind;
  770. #if 0 /* IGNORED */
  771. if (op & OPT_IP_CHKSUM)
  772. bb_error_msg("warning: ip checksums disabled");
  773. #endif
  774. #ifdef IP_TOS
  775. if (op & OPT_TOS)
  776. tos = xatou_range(tos_str, 0, 255);
  777. #endif
  778. if (op & OPT_MAX_TTL)
  779. max_ttl = xatou_range(max_ttl_str, 1, 255);
  780. if (op & OPT_PORT)
  781. port = xatou16(port_str);
  782. if (op & OPT_NPROBES)
  783. nprobes = xatou_range(nprobes_str, 1, INT_MAX);
  784. if (op & OPT_SOURCE) {
  785. /*
  786. * set the ip source address of the outbound
  787. * probe (e.g., on a multi-homed host).
  788. */
  789. if (getuid() != 0)
  790. bb_error_msg_and_die(bb_msg_you_must_be_root);
  791. }
  792. if (op & OPT_WAITTIME)
  793. waittime = xatou_range(waittime_str, 1, 24 * 60 * 60);
  794. if (op & OPT_PAUSE_MS)
  795. pausemsecs = xatou_range(pausemsecs_str, 0, 60 * 60 * 1000);
  796. if (op & OPT_FIRST_TTL)
  797. first_ttl = xatou_range(first_ttl_str, 1, max_ttl);
  798. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  799. if (source_route_list) {
  800. while (source_route_list) {
  801. len_and_sockaddr *lsa;
  802. if (lsrr >= NGATEWAYS)
  803. bb_error_msg_and_die("no more than %d gateways", NGATEWAYS);
  804. lsa = xhost_and_af2sockaddr(llist_pop(&source_route_list), 0, AF_INET);
  805. gwlist[lsrr] = lsa->u.sin.sin_addr.s_addr;
  806. free(lsa);
  807. ++lsrr;
  808. }
  809. optlen = (lsrr + 1) * sizeof(gwlist[0]);
  810. }
  811. #endif
  812. /* Process destination and optional packet size */
  813. minpacket = sizeof(*outip) + SIZEOF_ICMP_HDR + sizeof(*outdata) + optlen;
  814. if (!(op & OPT_USE_ICMP))
  815. minpacket += sizeof(*outudp) - SIZEOF_ICMP_HDR;
  816. #if ENABLE_TRACEROUTE6
  817. af = AF_UNSPEC;
  818. if (op & OPT_IPV4)
  819. af = AF_INET;
  820. if (op & OPT_IPV6)
  821. af = AF_INET6;
  822. dest_lsa = xhost_and_af2sockaddr(argv[0], port, af);
  823. af = dest_lsa->u.sa.sa_family;
  824. if (af == AF_INET6)
  825. minpacket = sizeof(struct outdata6_t);
  826. #else
  827. dest_lsa = xhost2sockaddr(argv[0], port);
  828. #endif
  829. packlen = minpacket;
  830. if (argv[1])
  831. packlen = xatoul_range(argv[1], minpacket, 32 * 1024);
  832. /* Ensure the socket fds won't be 0, 1 or 2 */
  833. bb_sanitize_stdio();
  834. #if ENABLE_TRACEROUTE6
  835. if (af == AF_INET6) {
  836. xmove_fd(xsocket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6), rcvsock);
  837. # ifdef IPV6_RECVPKTINFO
  838. setsockopt_1(rcvsock, SOL_IPV6, IPV6_RECVPKTINFO);
  839. setsockopt_1(rcvsock, SOL_IPV6, IPV6_2292PKTINFO);
  840. # else
  841. setsockopt_1(rcvsock, SOL_IPV6, IPV6_PKTINFO);
  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_SOL_SOCKET_1(rcvsock, SO_DEBUG);
  851. #endif
  852. if (op & OPT_BYPASS_ROUTE)
  853. setsockopt_SOL_SOCKET_1(rcvsock, SO_DONTROUTE);
  854. #if ENABLE_TRACEROUTE6
  855. if (af == AF_INET6) {
  856. if (setsockopt_int(rcvsock, SOL_RAW, IPV6_CHECKSUM, 2) != 0)
  857. bb_perror_msg_and_die("setsockopt(%s)", "IPV6_CHECKSUM");
  858. xmove_fd(xsocket(af, SOCK_DGRAM, 0), sndsock);
  859. } else
  860. #endif
  861. {
  862. if (op & OPT_USE_ICMP)
  863. xmove_fd(xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP), sndsock);
  864. else
  865. xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), sndsock);
  866. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE && defined IP_OPTIONS
  867. if (lsrr > 0) {
  868. unsigned char optlist[MAX_IPOPTLEN];
  869. unsigned size;
  870. /* final hop */
  871. gwlist[lsrr] = dest_lsa->u.sin.sin_addr.s_addr;
  872. ++lsrr;
  873. /* force 4 byte alignment */
  874. optlist[0] = IPOPT_NOP;
  875. /* loose source route option */
  876. optlist[1] = IPOPT_LSRR;
  877. size = lsrr * sizeof(gwlist[0]);
  878. optlist[2] = size + 3;
  879. /* pointer to LSRR addresses */
  880. optlist[3] = IPOPT_MINOFF;
  881. memcpy(optlist + 4, gwlist, size);
  882. if (setsockopt(sndsock, IPPROTO_IP, IP_OPTIONS,
  883. (char *)optlist, size + sizeof(gwlist[0])) < 0) {
  884. bb_perror_msg_and_die("IP_OPTIONS");
  885. }
  886. }
  887. #endif
  888. }
  889. #ifdef SO_SNDBUF
  890. if (setsockopt_SOL_SOCKET_int(sndsock, SO_SNDBUF, packlen) != 0) {
  891. bb_perror_msg_and_die("setsockopt(%s)", "SO_SNDBUF");
  892. }
  893. #endif
  894. #ifdef IP_TOS
  895. if ((op & OPT_TOS) && setsockopt_int(sndsock, IPPROTO_IP, IP_TOS, tos) != 0) {
  896. bb_perror_msg_and_die("setsockopt(%s) %d", "TOS", tos);
  897. }
  898. #endif
  899. #ifdef IP_DONTFRAG
  900. if (op & OPT_DONT_FRAGMNT)
  901. setsockopt_1(sndsock, IPPROTO_IP, IP_DONTFRAG);
  902. #endif
  903. #if TRACEROUTE_SO_DEBUG
  904. if (op & OPT_DEBUG)
  905. setsockopt_SOL_SOCKET_1(sndsock, SO_DEBUG);
  906. #endif
  907. if (op & OPT_BYPASS_ROUTE)
  908. setsockopt_SOL_SOCKET_1(sndsock, SO_DONTROUTE);
  909. outip = xzalloc(packlen);
  910. ident = getpid();
  911. if (af == AF_INET) {
  912. if (op & OPT_USE_ICMP) {
  913. ident |= 0x8000;
  914. outicmp->icmp_type = ICMP_ECHO;
  915. outicmp->icmp_id = htons(ident);
  916. outdata = (struct outdata_t *)((char *)outicmp + SIZEOF_ICMP_HDR);
  917. } else {
  918. outdata = (struct outdata_t *)(outudp + 1);
  919. }
  920. }
  921. if (op & OPT_DEVICE) /* hmm, do we need error check? */
  922. setsockopt_bindtodevice(sndsock, device);
  923. if (op & OPT_SOURCE) {
  924. #if ENABLE_TRACEROUTE6
  925. // TODO: need xdotted_and_af2sockaddr?
  926. len_and_sockaddr *source_lsa = xhost_and_af2sockaddr(source, 0, af);
  927. #else
  928. len_and_sockaddr *source_lsa = xdotted2sockaddr(source, 0);
  929. #endif
  930. /* Ping4 does this (why?) */
  931. if (af == AF_INET)
  932. if (setsockopt(sndsock, IPPROTO_IP, IP_MULTICAST_IF,
  933. &source_lsa->u.sa, source_lsa->len))
  934. bb_error_msg_and_die("can't set multicast source interface");
  935. //TODO: we can query source port we bound to,
  936. // and check it in replies... if we care enough
  937. xbind(sndsock, &source_lsa->u.sa, source_lsa->len);
  938. free(source_lsa);
  939. }
  940. #if ENABLE_TRACEROUTE6
  941. else if (af == AF_INET6) {
  942. //TODO: why we don't do it for IPv4?
  943. len_and_sockaddr *source_lsa;
  944. int probe_fd = xsocket(af, SOCK_DGRAM, 0);
  945. if (op & OPT_DEVICE)
  946. setsockopt_bindtodevice(probe_fd, device);
  947. set_nport(&dest_lsa->u.sa, htons(1025));
  948. /* dummy connect. makes kernel pick source IP (and port) */
  949. xconnect(probe_fd, &dest_lsa->u.sa, dest_lsa->len);
  950. set_nport(&dest_lsa->u.sa, htons(port));
  951. /* read IP and port */
  952. source_lsa = get_sock_lsa(probe_fd);
  953. if (source_lsa == NULL)
  954. bb_error_msg_and_die("can't get probe addr");
  955. close(probe_fd);
  956. /* bind our sockets to this IP (but not port) */
  957. set_nport(&source_lsa->u.sa, 0);
  958. xbind(sndsock, &source_lsa->u.sa, source_lsa->len);
  959. xbind(rcvsock, &source_lsa->u.sa, source_lsa->len);
  960. free(source_lsa);
  961. }
  962. #endif
  963. /* Revert to non-privileged user after opening sockets */
  964. xsetgid(getgid());
  965. xsetuid(getuid());
  966. dest_str = xmalloc_sockaddr2dotted_noport(&dest_lsa->u.sa);
  967. printf("traceroute to %s (%s)", argv[0], dest_str);
  968. if (ENABLE_FEATURE_CLEAN_UP) {
  969. free(dest_str);
  970. }
  971. if (op & OPT_SOURCE)
  972. printf(" from %s", source);
  973. printf(", %d hops max, %d byte packets\n", max_ttl, packlen);
  974. from_lsa = xmemdup(dest_lsa, LSA_LEN_SIZE + dest_lsa->len);
  975. lastaddr = xzalloc(dest_lsa->len);
  976. to = xzalloc(dest_lsa->len);
  977. seq = 0;
  978. for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
  979. int probe;
  980. int unreachable = 0; /* counter */
  981. int gotlastaddr = 0; /* flags */
  982. int got_there = 0;
  983. printf("%2d", ttl);
  984. for (probe = 0; probe < nprobes; ++probe) {
  985. int read_len;
  986. unsigned t1;
  987. unsigned t2;
  988. int left_ms;
  989. struct ip *ip;
  990. fflush_all();
  991. if (probe != 0 && pausemsecs > 0)
  992. usleep(pausemsecs * 1000);
  993. send_probe(++seq, ttl);
  994. t2 = t1 = monotonic_us();
  995. left_ms = waittime * 1000;
  996. while ((read_len = wait_for_reply(from_lsa, to, &t2, &left_ms)) != 0) {
  997. int icmp_code;
  998. /* Recv'ed a packet, or read error */
  999. /* t2 = monotonic_us() - set by wait_for_reply */
  1000. if (read_len < 0)
  1001. continue;
  1002. icmp_code = packet_ok(read_len, from_lsa, to, seq);
  1003. /* Skip short packet */
  1004. if (icmp_code == 0)
  1005. continue;
  1006. if (!gotlastaddr
  1007. || (memcmp(lastaddr, &from_lsa->u.sa, from_lsa->len) != 0)
  1008. ) {
  1009. print(read_len, &from_lsa->u.sa, to);
  1010. memcpy(lastaddr, &from_lsa->u.sa, from_lsa->len);
  1011. gotlastaddr = 1;
  1012. }
  1013. print_delta_ms(t1, t2);
  1014. ip = (struct ip *)recv_pkt;
  1015. if (from_lsa->u.sa.sa_family == AF_INET)
  1016. if (op & OPT_TTL_FLAG)
  1017. printf(" (%d)", ip->ip_ttl);
  1018. /* time exceeded in transit */
  1019. if (icmp_code == -1)
  1020. break;
  1021. icmp_code--;
  1022. switch (icmp_code) {
  1023. #if ENABLE_TRACEROUTE6
  1024. case ICMP6_DST_UNREACH_NOPORT << 8:
  1025. got_there = 1;
  1026. break;
  1027. #endif
  1028. case ICMP_UNREACH_PORT:
  1029. if (ip->ip_ttl <= 1)
  1030. printf(" !");
  1031. got_there = 1;
  1032. break;
  1033. case ICMP_UNREACH_NET:
  1034. #if ENABLE_TRACEROUTE6 && (ICMP6_DST_UNREACH_NOROUTE != ICMP_UNREACH_NET)
  1035. case ICMP6_DST_UNREACH_NOROUTE << 8:
  1036. #endif
  1037. printf(" !N");
  1038. ++unreachable;
  1039. break;
  1040. case ICMP_UNREACH_HOST:
  1041. #if ENABLE_TRACEROUTE6
  1042. case ICMP6_DST_UNREACH_ADDR << 8:
  1043. #endif
  1044. printf(" !H");
  1045. ++unreachable;
  1046. break;
  1047. case ICMP_UNREACH_PROTOCOL:
  1048. printf(" !P");
  1049. got_there = 1;
  1050. break;
  1051. case ICMP_UNREACH_NEEDFRAG:
  1052. printf(" !F-%d", pmtu);
  1053. ++unreachable;
  1054. break;
  1055. case ICMP_UNREACH_SRCFAIL:
  1056. #if ENABLE_TRACEROUTE6
  1057. case ICMP6_DST_UNREACH_ADMIN << 8:
  1058. #endif
  1059. printf(" !S");
  1060. ++unreachable;
  1061. break;
  1062. case ICMP_UNREACH_FILTER_PROHIB:
  1063. case ICMP_UNREACH_NET_PROHIB: /* misuse */
  1064. printf(" !A");
  1065. ++unreachable;
  1066. break;
  1067. case ICMP_UNREACH_HOST_PROHIB:
  1068. printf(" !C");
  1069. ++unreachable;
  1070. break;
  1071. case ICMP_UNREACH_HOST_PRECEDENCE:
  1072. printf(" !V");
  1073. ++unreachable;
  1074. break;
  1075. case ICMP_UNREACH_PRECEDENCE_CUTOFF:
  1076. printf(" !C");
  1077. ++unreachable;
  1078. break;
  1079. case ICMP_UNREACH_NET_UNKNOWN:
  1080. case ICMP_UNREACH_HOST_UNKNOWN:
  1081. printf(" !U");
  1082. ++unreachable;
  1083. break;
  1084. case ICMP_UNREACH_ISOLATED:
  1085. printf(" !I");
  1086. ++unreachable;
  1087. break;
  1088. case ICMP_UNREACH_TOSNET:
  1089. case ICMP_UNREACH_TOSHOST:
  1090. printf(" !T");
  1091. ++unreachable;
  1092. break;
  1093. default:
  1094. printf(" !<%d>", icmp_code);
  1095. ++unreachable;
  1096. break;
  1097. }
  1098. break;
  1099. } /* while (wait and read a packet) */
  1100. /* there was no packet at all? */
  1101. if (read_len == 0)
  1102. printf(" *");
  1103. } /* for (nprobes) */
  1104. bb_putchar('\n');
  1105. if (got_there
  1106. || (unreachable > 0 && unreachable >= nprobes - 1)
  1107. ) {
  1108. break;
  1109. }
  1110. }
  1111. if (ENABLE_FEATURE_CLEAN_UP) {
  1112. free(to);
  1113. free(lastaddr);
  1114. free(from_lsa);
  1115. }
  1116. return 0;
  1117. }
  1118. int traceroute_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1119. int traceroute_main(int argc UNUSED_PARAM, char **argv)
  1120. {
  1121. return common_traceroute_main(0, argv);
  1122. }
  1123. #if ENABLE_TRACEROUTE6
  1124. int traceroute6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1125. int traceroute6_main(int argc UNUSED_PARAM, char **argv)
  1126. {
  1127. return common_traceroute_main(OPT_IPV6, argv);
  1128. }
  1129. #endif