traceroute.c 37 KB

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