traceroute.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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. //config:config TRACEROUTE
  211. //config: bool "traceroute (11 kb)"
  212. //config: default y
  213. //config: help
  214. //config: Utility to trace the route of IP packets.
  215. //config:
  216. //config:config TRACEROUTE6
  217. //config: bool "traceroute6 (12 kb)"
  218. //config: default y
  219. //config: depends on FEATURE_IPV6
  220. //config: help
  221. //config: Utility to trace the route of IPv6 packets.
  222. //config:
  223. //config:config FEATURE_TRACEROUTE_VERBOSE
  224. //config: bool "Enable verbose output"
  225. //config: default y
  226. //config: depends on TRACEROUTE || TRACEROUTE6
  227. //config: help
  228. //config: Add some verbosity to traceroute. This includes among other things
  229. //config: hostnames and ICMP response types.
  230. //config:
  231. //config:config FEATURE_TRACEROUTE_USE_ICMP
  232. //config: bool "Enable -I option (use ICMP instead of UDP)"
  233. //config: default y
  234. //config: depends on TRACEROUTE || TRACEROUTE6
  235. /* Needs socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), therefore BB_SUID_MAYBE: */
  236. //applet:IF_TRACEROUTE(APPLET(traceroute, BB_DIR_USR_BIN, BB_SUID_MAYBE))
  237. //applet:IF_TRACEROUTE6(APPLET(traceroute6, BB_DIR_USR_BIN, BB_SUID_MAYBE))
  238. //kbuild:lib-$(CONFIG_TRACEROUTE) += traceroute.o
  239. //kbuild:lib-$(CONFIG_TRACEROUTE6) += traceroute.o
  240. //usage:#define traceroute_trivial_usage
  241. //usage: "[-"IF_TRACEROUTE6("46")IF_FEATURE_TRACEROUTE_USE_ICMP("I")"Flnrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT]\n"
  242. //usage: " [-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE]\n"
  243. //usage: " [-z PAUSE_MSEC] HOST [BYTES]"
  244. //usage:#define traceroute_full_usage "\n\n"
  245. //usage: "Trace the route to HOST\n"
  246. //usage: IF_TRACEROUTE6(
  247. //usage: "\n -4,-6 Force IP or IPv6 name resolution"
  248. //usage: )
  249. //usage: "\n -F Set don't fragment bit"
  250. //usage: IF_FEATURE_TRACEROUTE_USE_ICMP(
  251. //usage: "\n -I Use ICMP ECHO instead of UDP datagrams"
  252. //usage: )
  253. //usage: "\n -l Display TTL value of the returned packet"
  254. //Currently disabled (TRACEROUTE_SO_DEBUG==0)
  255. ////usage: "\n -d Set SO_DEBUG options to socket"
  256. //usage: "\n -n Print numeric addresses"
  257. //usage: "\n -r Bypass routing tables, send directly to HOST"
  258. //usage: IF_FEATURE_TRACEROUTE_VERBOSE(
  259. //usage: "\n -v Verbose"
  260. //usage: )
  261. //usage: "\n -f N First number of hops (default 1)"
  262. //usage: "\n -m N Max number of hops"
  263. //usage: "\n -q N Number of probes per hop (default 3)"
  264. //usage: "\n -p N Base UDP port number used in probes"
  265. //usage: "\n (default 33434)"
  266. //usage: "\n -s IP Source address"
  267. //usage: "\n -i IFACE Source interface"
  268. //usage: "\n -t N Type-of-service in probe packets (default 0)"
  269. //usage: "\n -w SEC Wait for a response (default 3)"
  270. //usage: "\n -z MSEC Wait before each send"
  271. //usage:
  272. //usage:#define traceroute6_trivial_usage
  273. //usage: "[-"IF_FEATURE_TRACEROUTE_USE_ICMP("I")"nrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT]\n"
  274. //usage: " [-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE]\n"
  275. //usage: " [-z PAUSE_MSEC] HOST [BYTES]"
  276. //usage:#define traceroute6_full_usage "\n\n"
  277. //usage: "Trace the route to HOST\n"
  278. ////NOP? "\n -F Set don't fragment bit"
  279. //usage: IF_FEATURE_TRACEROUTE_USE_ICMP(
  280. //usage: "\n -I Use ICMP ECHO instead of UDP datagrams"
  281. //usage: )
  282. ////NOP: "\n -l Display TTL value of the returned packet"
  283. //Currently disabled (TRACEROUTE_SO_DEBUG==0)
  284. ////usage: "\n -d Set SO_DEBUG options to socket"
  285. //usage: "\n -n Print numeric addresses"
  286. //usage: "\n -r Bypass routing tables, send directly to HOST"
  287. //usage: IF_FEATURE_TRACEROUTE_VERBOSE(
  288. //usage: "\n -v Verbose"
  289. //usage: )
  290. //usage: "\n -f N First number of hops (default 1)"
  291. //usage: "\n -m N Max number of hops"
  292. //usage: "\n -q N Number of probes per hop (default 3)"
  293. //usage: "\n -p N Base UDP port number used in probes"
  294. //usage: "\n (default 33434)"
  295. //usage: "\n -s IP Source address"
  296. //usage: "\n -i IFACE Source interface"
  297. //usage: "\n -t N Type-of-service in probe packets (default 0)"
  298. //usage: "\n -w SEC Wait for a response (default 3)"
  299. //usage: "\n -z MSEC Wait before each send"
  300. #define TRACEROUTE_SO_DEBUG 0
  301. #include <net/if.h>
  302. #include <arpa/inet.h>
  303. #include <netinet/in.h>
  304. #include <netinet/udp.h>
  305. #include <netinet/ip.h>
  306. #include <netinet/ip_icmp.h>
  307. #if ENABLE_FEATURE_IPV6
  308. # include <netinet/ip6.h>
  309. # include <netinet/icmp6.h>
  310. # ifndef SOL_IPV6
  311. # define SOL_IPV6 IPPROTO_IPV6
  312. # endif
  313. # if defined(IPV6_PKTINFO) && !defined(IPV6_RECVPKTINFO)
  314. # define IPV6_RECVPKTINFO IPV6_PKTINFO
  315. # endif
  316. #endif
  317. #include "libbb.h"
  318. #include "inet_common.h"
  319. #ifndef IPPROTO_ICMP
  320. # define IPPROTO_ICMP 1
  321. #endif
  322. #ifndef IPPROTO_IP
  323. # define IPPROTO_IP 0
  324. #endif
  325. /* Some operating systems, like GNU/Hurd, don't define SOL_RAW, but do have
  326. * IPPROTO_RAW. Since the IPPROTO definitions are also valid to use for
  327. * setsockopt (and take the same value as their corresponding SOL definitions,
  328. * if they exist), we can just fall back on IPPROTO_RAW. */
  329. #ifndef SOL_RAW
  330. # define SOL_RAW IPPROTO_RAW
  331. #endif
  332. #define OPT_STRING \
  333. "FIlnrdvt:i:m:p:q:s:w:z:f:" \
  334. "4" IF_TRACEROUTE6("6")
  335. enum {
  336. OPT_DONT_FRAGMNT = (1 << 0), /* F */
  337. OPT_USE_ICMP = (1 << 1) * ENABLE_FEATURE_TRACEROUTE_USE_ICMP, /* I */
  338. OPT_TTL_FLAG = (1 << 2), /* l */
  339. OPT_ADDR_NUM = (1 << 3), /* n */
  340. OPT_BYPASS_ROUTE = (1 << 4), /* r */
  341. OPT_DEBUG = (1 << 5), /* d */
  342. OPT_VERBOSE = (1 << 6) * ENABLE_FEATURE_TRACEROUTE_VERBOSE, /* v */
  343. OPT_TOS = (1 << 7), /* t */
  344. OPT_DEVICE = (1 << 8), /* i */
  345. OPT_MAX_TTL = (1 << 9), /* m */
  346. OPT_PORT = (1 << 10), /* p */
  347. OPT_NPROBES = (1 << 11), /* q */
  348. OPT_SOURCE = (1 << 12), /* s */
  349. OPT_WAITTIME = (1 << 13), /* w */
  350. OPT_PAUSE_MS = (1 << 14), /* z */
  351. OPT_FIRST_TTL = (1 << 15), /* f */
  352. OPT_IPV4 = (1 << 16), /* 4 */
  353. OPT_IPV6 = (1 << 17) * ENABLE_TRACEROUTE6, /* 6 */
  354. };
  355. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  356. # define verbose (option_mask32 & OPT_VERBOSE)
  357. #else
  358. # define verbose 0
  359. #endif
  360. enum {
  361. SIZEOF_ICMP_HDR = 8,
  362. rcvsock = 3, /* receive (icmp) socket file descriptor */
  363. sndsock = 4, /* send (udp/icmp) socket file descriptor */
  364. };
  365. /* Data section of the probe packet */
  366. struct outdata_t {
  367. unsigned char seq; /* sequence number of this packet */
  368. unsigned char ttl; /* ttl packet left with */
  369. // UNUSED. Retaining to have the same packet size.
  370. struct timeval tv_UNUSED PACKED; /* time packet left */
  371. };
  372. #if ENABLE_TRACEROUTE6
  373. struct outdata6_t {
  374. uint32_t ident6;
  375. uint32_t seq6;
  376. struct timeval tv_UNUSED PACKED; /* time packet left */
  377. };
  378. #endif
  379. struct globals {
  380. /* Pointer to entire malloced IP packet, "packlen" bytes long: */
  381. struct ip *outip;
  382. /* Pointer to ICMP or UDP payload (not header): */
  383. struct outdata_t *outdata;
  384. len_and_sockaddr *dest_lsa;
  385. len_and_sockaddr *from_lsa; /* response came from this address */
  386. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  387. struct sockaddr *to; /* response came to this (local) address */
  388. #endif
  389. uint32_t ident;
  390. uint16_t port; /* start udp dest port # for probe packets */
  391. #if ENABLE_TRACEROUTE6
  392. smallint ipv6;
  393. # define G_ipv6 G.ipv6
  394. #else
  395. # define G_ipv6 0
  396. #endif
  397. int packlen; /* total length of packet */
  398. int pmtu; /* Path MTU Discovery (RFC1191) */
  399. int waittime; /* time to wait for response (in seconds) */
  400. int first_ttl;
  401. int nprobes;
  402. int max_ttl;
  403. unsigned pausemsecs;
  404. unsigned char recv_pkt[512]; /* last inbound (icmp) packet */
  405. };
  406. #define G (*ptr_to_globals)
  407. #define outip (G.outip )
  408. #define outdata (G.outdata )
  409. #define dest_lsa (G.dest_lsa )
  410. #define packlen (G.packlen )
  411. #define pmtu (G.pmtu )
  412. #define ident (G.ident )
  413. #define port (G.port )
  414. #define waittime (G.waittime )
  415. #define recv_pkt (G.recv_pkt )
  416. #define INIT_G() do { \
  417. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  418. } while (0)
  419. #define outudp ((struct udphdr *)(outip + 1))
  420. #define outudp6 ((struct udphdr *)(((struct ip6_hdr*)outip) + 1))
  421. #define outicmp ((struct icmp *)(outip + 1))
  422. #define outicmp6 ((struct icmp *)(((struct ip6_hdr*)outip) + 1))
  423. /* NB: for icmp echo, IPv4 and IPv6 fields are the same size and offset:
  424. * struct icmp:
  425. * uint8_t icmp_type;
  426. * uint8_t icmp_code;
  427. * uint16_t icmp_cksum;
  428. * uint16_t icmp_id;
  429. * uint16_t icmp_seq;
  430. * struct icmp6_hdr:
  431. * uint8_t icmp6_type;
  432. * uint8_t icmp6_code;
  433. * uint16_t icmp6_cksum;
  434. * uint16_t icmp6_id;
  435. * uint16_t icmp6_seq;
  436. * therefore both outicmp and outicmp6 are pointers to *IPv4* icmp struct.
  437. * SIZEOF_ICMP_HDR == 8 is the same for both, as well.
  438. * However, values of these pointers are not the same (since IPv6 IP header is larger),
  439. * and icmp_type constants are not the same:
  440. * #define ICMP_ECHO 8
  441. * #define ICMP_ECHOREPLY 0
  442. * #define ICMP6_ECHO_REQUEST 128
  443. * #define ICMP6_ECHO_REPLY 129
  444. */
  445. static int
  446. wait_for_reply(unsigned *timestamp_us, int *left_ms)
  447. {
  448. struct pollfd pfd[1];
  449. int read_len = 0;
  450. pfd[0].fd = rcvsock;
  451. pfd[0].events = POLLIN;
  452. if (*left_ms >= 0 && safe_poll(pfd, 1, *left_ms) > 0) {
  453. unsigned t;
  454. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  455. read_len = recv_from_to(rcvsock,
  456. recv_pkt, sizeof(recv_pkt),
  457. /*flags:*/ MSG_DONTWAIT,
  458. &G.from_lsa->u.sa, G.to, G.from_lsa->len);
  459. #else
  460. read_len = recvfrom(rcvsock,
  461. recv_pkt, sizeof(recv_pkt),
  462. /*flags:*/ MSG_DONTWAIT,
  463. &G.from_lsa->u.sa, &G.from_lsa->len);
  464. #endif
  465. if (read_len < 0)
  466. bb_simple_perror_msg_and_die("recv");
  467. t = monotonic_us();
  468. *left_ms -= (t - *timestamp_us) / 1000;
  469. *timestamp_us = t;
  470. }
  471. return read_len;
  472. }
  473. static void
  474. send_probe(int seq, int ttl)
  475. {
  476. int len, res;
  477. void *out;
  478. struct icmp *icp;
  479. /* Payload */
  480. #if ENABLE_TRACEROUTE6
  481. if (G_ipv6) {
  482. struct outdata6_t *pkt = (void *) outdata;
  483. pkt->ident6 = ident;
  484. pkt->seq6 = htonl(seq);
  485. /*xgettimeofday(&pkt->tv);*/
  486. icp = outicmp6;
  487. } else
  488. #endif
  489. {
  490. outdata->seq = seq;
  491. outdata->ttl = ttl;
  492. // UNUSED: was storing gettimeofday's result there, but never ever checked it
  493. /*memcpy(&outdata->tv, tp, sizeof(outdata->tv));*/
  494. icp = outicmp;
  495. }
  496. out = outdata;
  497. if (option_mask32 & OPT_USE_ICMP) {
  498. out = icp;
  499. /*icp->icmp_type = ICMP[6]_ECHO; - already set */
  500. /*icp->icmp_code = 0; - already set */
  501. /*icp->icmp_id = ident; - already set */
  502. icp->icmp_seq = htons(seq);
  503. /* Always calculate checksum for icmp packets */
  504. icp->icmp_cksum = 0;
  505. icp->icmp_cksum = inet_cksum(
  506. icp,
  507. ((char*)outip + packlen) - (char*)icp
  508. );
  509. if (icp->icmp_cksum == 0)
  510. icp->icmp_cksum = 0xffff;
  511. }
  512. //BUG! verbose is (x & OPT_VERBOSE), not a counter!
  513. #if 0 //ENABLE_FEATURE_TRACEROUTE_VERBOSE
  514. /* XXX undocumented debugging hack */
  515. if (verbose > 1) {
  516. const uint16_t *sp;
  517. int nshorts, i;
  518. sp = (uint16_t *)outip;
  519. nshorts = (unsigned)packlen / sizeof(uint16_t);
  520. i = 0;
  521. printf("[ %d bytes", packlen);
  522. while (--nshorts >= 0) {
  523. if ((i++ % 8) == 0)
  524. printf("\n\t");
  525. printf(" %04x", ntohs(*sp));
  526. sp++;
  527. }
  528. if (packlen & 1) {
  529. if ((i % 8) == 0)
  530. printf("\n\t");
  531. printf(" %02x", *(unsigned char *)sp);
  532. }
  533. printf("]\n");
  534. }
  535. #endif
  536. #if ENABLE_TRACEROUTE6
  537. if (G_ipv6) {
  538. res = setsockopt_int(sndsock, SOL_IPV6, IPV6_UNICAST_HOPS, ttl);
  539. if (res != 0)
  540. bb_perror_msg_and_die("setsockopt(%s) %d", "UNICAST_HOPS", ttl);
  541. } else
  542. #endif
  543. {
  544. #if defined IP_TTL
  545. res = setsockopt_int(sndsock, IPPROTO_IP, IP_TTL, ttl);
  546. if (res != 0)
  547. bb_perror_msg_and_die("setsockopt(%s) %d", "TTL", ttl);
  548. #endif
  549. }
  550. if (!(option_mask32 & OPT_USE_ICMP)) {
  551. set_nport(&dest_lsa->u.sa, htons(port + seq));
  552. }
  553. len = ((char*)outip + packlen) - (char*)out;
  554. res = xsendto(sndsock, out, len, &dest_lsa->u.sa, dest_lsa->len);
  555. if (res != len)
  556. bb_error_msg("sent %d octets, ret=%d", len, res);
  557. }
  558. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  559. /* Convert an ICMP "type" field to a printable string */
  560. static const char *
  561. pr_type(unsigned char t)
  562. {
  563. static const char *const ttab[] ALIGN_PTR = {
  564. "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
  565. "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
  566. "Echo", "Router Advert", "Router Solicit", "Time Exceeded",
  567. "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
  568. "Info Reply", "Mask Request", "Mask Reply"
  569. };
  570. # if ENABLE_TRACEROUTE6
  571. static const char *const ttab6[] ALIGN_PTR = {
  572. [0] = "Error", "Dest Unreachable", "Packet Too Big", "Time Exceeded",
  573. [4] = "Param Problem",
  574. [8] = "Echo Request", "Echo Reply", "Membership Query", "Membership Report",
  575. [12] = "Membership Reduction", "Router Solicit", "Router Advert", "Neighbor Solicit",
  576. [16] = "Neighbor Advert", "Redirect",
  577. };
  578. if (G_ipv6) {
  579. if (t < 5)
  580. return ttab6[t];
  581. if (t < 128 || t > ND_REDIRECT)
  582. return "OUT-OF-RANGE";
  583. return ttab6[(t & 63) + 8];
  584. }
  585. # endif
  586. if (t >= ARRAY_SIZE(ttab))
  587. return "OUT-OF-RANGE";
  588. return ttab[t];
  589. }
  590. static int
  591. hexdump_if_verbose(const struct icmp *icp, int len)
  592. {
  593. const unsigned char *p;
  594. int i;
  595. if (!verbose)
  596. return 0;
  597. printf("\n%d bytes from %s to %s: icmp type %u (%s) code %u\n",
  598. len,
  599. auto_string(xmalloc_sockaddr2dotted_noport(&G.from_lsa->u.sa)),
  600. auto_string(xmalloc_sockaddr2dotted_noport(G.to)),
  601. icp->icmp_type, pr_type(icp->icmp_type),
  602. icp->icmp_code
  603. );
  604. p = (const void *)icp;
  605. for (i = 0; i < len; i++) {
  606. if (!(i & 0xf))
  607. printf("\n%04x:" + (i==0), i);
  608. printf(" %02x", p[i]);
  609. }
  610. bb_putchar('\n');
  611. return 0;
  612. }
  613. #else
  614. # define hexdump_if_verbose(...) 0
  615. #endif
  616. static int
  617. packet4_ok(int read_len, int seq)
  618. {
  619. const struct icmp *icp;
  620. unsigned char type, code;
  621. int hlen;
  622. const struct ip *ip;
  623. /* NB: reads from (AF_INET, SOCK_RAW, IPPROTO_ICMP) socket
  624. * return the entire IP packet (IOW: they do not strip IP header).
  625. * This differs from (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6) sockets!?
  626. */
  627. ip = (struct ip *) recv_pkt;
  628. hlen = ip->ip_hl << 2;
  629. if (read_len < hlen + ICMP_MINLEN) {
  630. if (verbose)
  631. printf("packet too short (%d bytes) from %s\n", read_len,
  632. inet_ntoa(G.from_lsa->u.sin.sin_addr));
  633. return 0;
  634. }
  635. read_len -= hlen;
  636. icp = (struct icmp *)(recv_pkt + hlen);
  637. type = icp->icmp_type;
  638. code = icp->icmp_code;
  639. /* Path MTU Discovery (RFC1191) */
  640. pmtu = 0;
  641. if (code == ICMP_UNREACH_NEEDFRAG)
  642. pmtu = ntohs(icp->icmp_nextmtu);
  643. if ((option_mask32 & OPT_USE_ICMP)
  644. && type == ICMP_ECHOREPLY
  645. && icp->icmp_seq == htons(seq)
  646. ) {
  647. if (icp->icmp_id != ident)
  648. /* reply to another ping/traceroute from this box? */
  649. return 0; /* ignore, silently */
  650. /* In UDP mode, when we reach the machine, we (usually)
  651. * would get "port unreachable" - in ICMP we got "echo reply".
  652. * Simulate "port unreachable" for caller:
  653. */
  654. return ICMP_UNREACH_PORT+1;
  655. }
  656. if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS)
  657. || type == ICMP_UNREACH
  658. ) {
  659. const struct ip *hip;
  660. const struct udphdr *up;
  661. hip = &icp->icmp_ip;
  662. hlen = hip->ip_hl << 2;
  663. if (option_mask32 & OPT_USE_ICMP) {
  664. struct icmp *hicmp;
  665. hicmp = (struct icmp *)((unsigned char *)hip + hlen);
  666. if (hlen + SIZEOF_ICMP_HDR <= read_len
  667. && hip->ip_p == IPPROTO_ICMP
  668. && hicmp->icmp_id == ident
  669. && hicmp->icmp_seq == htons(seq)
  670. ) {
  671. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  672. }
  673. } else {
  674. up = (struct udphdr *)((char *)hip + hlen);
  675. if (hlen + 12 <= read_len
  676. && hip->ip_p == IPPROTO_UDP
  677. #if !defined(__FreeBSD__)
  678. // Disabled source check: since we do not form the entire IP packet,
  679. // but defer it to kernel, we can't set source port,
  680. // and thus can't check it here in the reply
  681. /* && up->source == ident */
  682. && up->dest == htons(port + seq)
  683. #else
  684. /* && up->uh_sport == ident */
  685. && up->uh_dport == htons(port + seq)
  686. #endif
  687. ) {
  688. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  689. }
  690. }
  691. }
  692. /* testcase: traceroute -vI 127.0.0.1 (sees its own echo requests) */
  693. return hexdump_if_verbose(icp, read_len);
  694. }
  695. #if ENABLE_TRACEROUTE6
  696. static int
  697. packet6_ok(int read_len, int seq)
  698. {
  699. const struct icmp6_hdr *icp;
  700. unsigned char type, code;
  701. /* NB: reads from (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6) socket
  702. * return only ICMP packet (IOW: they strip IPv6 header).
  703. * This differs from (AF_INET, SOCK_RAW, IPPROTO_ICMP) sockets!?
  704. */
  705. if (read_len < ICMP_MINLEN) {
  706. if (verbose)
  707. printf("packet too short (%d bytes) from %s\n", read_len,
  708. auto_string(xmalloc_sockaddr2dotted_noport(&G.from_lsa->u.sa)));
  709. return 0;
  710. }
  711. icp = (struct icmp6_hdr *) recv_pkt;
  712. type = icp->icmp6_type;
  713. code = icp->icmp6_code;
  714. if ((option_mask32 & OPT_USE_ICMP)
  715. && type == ICMP6_ECHO_REPLY
  716. && icp->icmp6_seq == htons(seq)
  717. ) {
  718. if (icp->icmp6_id != ident)
  719. /* reply to another ping/traceroute from this box? */
  720. return 0; /* ignore, silently */
  721. /* In UDP mode, when we reach the machine, we (usually)
  722. * would get "port unreachable" - in ICMP we got "echo reply".
  723. * Simulate "port unreachable" for caller:
  724. */
  725. return (ICMP6_DST_UNREACH_NOPORT << 8) + 1;
  726. }
  727. if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT)
  728. || type == ICMP6_DST_UNREACH
  729. ) {
  730. struct ip6_hdr *hip;
  731. struct udphdr *up;
  732. int nexthdr;
  733. hip = (struct ip6_hdr *)(icp + 1);
  734. up = (struct udphdr *) (hip + 1);
  735. nexthdr = hip->ip6_nxt;
  736. if (nexthdr == IPPROTO_FRAGMENT) {
  737. nexthdr = *(unsigned char*)up;
  738. up++;
  739. }
  740. if (nexthdr == IPPROTO_UDP) {
  741. struct outdata6_t *pkt;
  742. pkt = (struct outdata6_t *) (up + 1);
  743. if (pkt->ident6 == ident
  744. && ntohl(pkt->seq6) == seq
  745. ) {
  746. return (type == ICMP6_TIME_EXCEEDED ? -1 : (code<<8)+1);
  747. }
  748. }
  749. }
  750. /* cast is safe since the beginning of icmp4 and icmp6 layouts match */
  751. return hexdump_if_verbose((const struct icmp *)icp, read_len);
  752. }
  753. static int
  754. packet_ok(int read_len, int seq)
  755. {
  756. if (!G_ipv6)
  757. return packet4_ok(read_len, seq);
  758. return packet6_ok(read_len, seq);
  759. }
  760. #else /* !ENABLE_TRACEROUTE6 */
  761. # define packet_ok(read_len, seq) packet4_ok(read_len, seq)
  762. #endif
  763. static void
  764. #if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
  765. print(void)
  766. # define print(len) print()
  767. #else
  768. print(int read_len)
  769. #endif
  770. {
  771. char *ina = auto_string(xmalloc_sockaddr2dotted_noport(&G.from_lsa->u.sa));
  772. if (option_mask32 & OPT_ADDR_NUM) {
  773. printf(" %s", ina);
  774. } else {
  775. char *n = NULL;
  776. if (G_ipv6
  777. || G.from_lsa->u.sin.sin_addr.s_addr != INADDR_ANY
  778. ) {
  779. /* Reverse resolve if IPV6 or not 0.0.0.0 */
  780. n = auto_string(xmalloc_sockaddr2host_noport(&G.from_lsa->u.sa));
  781. }
  782. printf(" %s (%s)", (n ? n : ina), ina);
  783. }
  784. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  785. if (verbose) {
  786. # if ENABLE_TRACEROUTE6
  787. /* NB: reads from (AF_INET, SOCK_RAW, IPPROTO_ICMP) socket
  788. * return the entire IP packet (IOW: they do not strip IP header).
  789. * Reads from (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6) do strip IPv6
  790. * header and return only ICMP6 packet. Weird.
  791. */
  792. if (G_ipv6) {
  793. /* read_len -= sizeof(struct ip6_hdr); - WRONG! */
  794. } else
  795. # endif
  796. {
  797. struct ip *ip4packet = (struct ip*)recv_pkt;
  798. read_len -= ip4packet->ip_hl << 2;
  799. }
  800. printf(" %d bytes to %s", read_len,
  801. auto_string(xmalloc_sockaddr2dotted_noport(G.to))
  802. );
  803. }
  804. #endif
  805. }
  806. static void
  807. print_delta_ms(unsigned t1p, unsigned t2p)
  808. {
  809. unsigned tt = t2p - t1p;
  810. printf(" %u.%03u ms", tt / 1000, tt % 1000);
  811. }
  812. /* Keeping init code in a separate (not inlined!) function
  813. * for stack use reduction and better register allocation in main loop.
  814. */
  815. static NOINLINE void
  816. traceroute_init(int op, char **argv)
  817. {
  818. char *source;
  819. char *device;
  820. char *tos_str;
  821. char *max_ttl_str;
  822. char *port_str;
  823. char *nprobes_str;
  824. char *waittime_str;
  825. char *pausemsecs_str;
  826. char *first_ttl_str;
  827. char *dest_str;
  828. #if ENABLE_TRACEROUTE6
  829. sa_family_t af;
  830. #else
  831. enum { af = AF_INET };
  832. #endif
  833. /* Ensure the socket fds won't be 0, 1 or 2 */
  834. bb_sanitize_stdio();
  835. INIT_G();
  836. port = 33434;
  837. waittime = 5;
  838. G.first_ttl = 1;
  839. G.nprobes = 3;
  840. G.max_ttl = 30;
  841. op |= getopt32(argv, "^"
  842. OPT_STRING
  843. "\0" "-1" /* minimum 1 arg */
  844. , &tos_str, &device, &max_ttl_str, &port_str, &nprobes_str
  845. , &source, &waittime_str, &pausemsecs_str, &first_ttl_str
  846. );
  847. argv += optind;
  848. if (op & OPT_MAX_TTL)
  849. G.max_ttl = xatou_range(max_ttl_str, 1, 255);
  850. if (op & OPT_PORT)
  851. port = xatou16(port_str);
  852. if (op & OPT_NPROBES)
  853. G.nprobes = xatou_range(nprobes_str, 1, INT_MAX);
  854. if (op & OPT_WAITTIME)
  855. waittime = xatou_range(waittime_str, 1, 24 * 60 * 60);
  856. if (op & OPT_PAUSE_MS)
  857. G.pausemsecs = xatou_range(pausemsecs_str, 0, 60 * 60 * 1000);
  858. if (op & OPT_FIRST_TTL)
  859. G.first_ttl = xatou_range(first_ttl_str, 1, G.max_ttl);
  860. /* Process destination and optional packet size */
  861. packlen = sizeof(struct ip)
  862. + sizeof(struct udphdr)
  863. + sizeof(struct outdata_t);
  864. if (op & OPT_USE_ICMP) {
  865. packlen = sizeof(struct ip)
  866. + SIZEOF_ICMP_HDR
  867. + sizeof(struct outdata_t);
  868. port = 0; /* on ICMP6 sockets, sendto(ipv6.nonzero_port) throws EINVAL! */
  869. }
  870. #if ENABLE_TRACEROUTE6
  871. af = AF_UNSPEC;
  872. if (op & OPT_IPV4)
  873. af = AF_INET;
  874. if (op & OPT_IPV6)
  875. af = AF_INET6;
  876. dest_lsa = xhost_and_af2sockaddr(argv[0], port, af);
  877. af = dest_lsa->u.sa.sa_family;
  878. //TODO: make sure af == AF_INET[6]? (FEATURE_UNIX_LOCAL=y allows "local:/PATH" to be translated to AF_UNIX)
  879. if (af == AF_INET6) {
  880. G_ipv6 = 1;
  881. packlen = sizeof(struct ip6_hdr)
  882. + sizeof(struct udphdr)
  883. + sizeof(struct outdata6_t);
  884. if (op & OPT_USE_ICMP)
  885. packlen = sizeof(struct ip6_hdr)
  886. + SIZEOF_ICMP_HDR
  887. + sizeof(struct outdata6_t);
  888. }
  889. #else
  890. /* accept only IPv4 addresses */
  891. dest_lsa = xhost_and_af2sockaddr(argv[0], port, AF_INET);
  892. #endif
  893. G.from_lsa = xmemdup(dest_lsa, LSA_LEN_SIZE + dest_lsa->len);
  894. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  895. G.to = xzalloc(dest_lsa->len);
  896. #endif
  897. if (argv[1])
  898. packlen = xatoul_range(argv[1], packlen, 32 * 1024);
  899. if (af == AF_INET) {
  900. xmove_fd(xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP), rcvsock);
  901. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  902. /* want recvmsg to report target local address (for -v) */
  903. setsockopt_1(rcvsock, IPPROTO_IP, IP_PKTINFO);
  904. #endif
  905. }
  906. #if ENABLE_TRACEROUTE6
  907. else {
  908. xmove_fd(xsocket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6), rcvsock);
  909. # if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  910. /* want recvmsg to report target local address (for -v) */
  911. setsockopt_1(rcvsock, SOL_IPV6, IPV6_RECVPKTINFO);
  912. # endif
  913. }
  914. #endif
  915. #if TRACEROUTE_SO_DEBUG
  916. if (op & OPT_DEBUG)
  917. setsockopt_SOL_SOCKET_1(rcvsock, SO_DEBUG);
  918. #endif
  919. {
  920. int snd;
  921. if (af == AF_INET) {
  922. if (op & OPT_USE_ICMP)
  923. snd = xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  924. else
  925. snd = xsocket(AF_INET, SOCK_DGRAM, 0);
  926. }
  927. #if ENABLE_TRACEROUTE6
  928. # if defined(__FreeBSD__)
  929. # define SOL_V6_OPTION SOL_IPV6
  930. # else
  931. # define SOL_V6_OPTION SOL_RAW
  932. # endif
  933. else {
  934. if (setsockopt_int(rcvsock, SOL_V6_OPTION, IPV6_CHECKSUM, 2) != 0)
  935. bb_perror_msg_and_die("setsockopt(%s)", "IPV6_CHECKSUM");
  936. if (op & OPT_USE_ICMP)
  937. snd = xsocket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
  938. else
  939. snd = xsocket(AF_INET6, SOCK_DGRAM, 0);
  940. }
  941. #endif
  942. xmove_fd(snd, sndsock);
  943. }
  944. #ifdef SO_SNDBUF
  945. if (setsockopt_SOL_SOCKET_int(sndsock, SO_SNDBUF, packlen) != 0) {
  946. bb_perror_msg_and_die("setsockopt(%s)", "SO_SNDBUF");
  947. }
  948. #endif
  949. #ifdef IP_TOS
  950. if (op & OPT_TOS) {
  951. int tos = xatou_range(tos_str, 0, 255);
  952. if (setsockopt_int(sndsock, IPPROTO_IP, IP_TOS, tos) != 0)
  953. bb_perror_msg_and_die("setsockopt(%s,%d)", "TOS", tos);
  954. }
  955. #endif
  956. #ifdef IP_DONTFRAG
  957. if (op & OPT_DONT_FRAGMNT)
  958. setsockopt_1(sndsock, IPPROTO_IP, IP_DONTFRAG);
  959. #endif
  960. #if TRACEROUTE_SO_DEBUG
  961. if (op & OPT_DEBUG)
  962. setsockopt_SOL_SOCKET_1(sndsock, SO_DEBUG);
  963. #endif
  964. if (op & OPT_BYPASS_ROUTE)
  965. setsockopt_SOL_SOCKET_1(sndsock, SO_DONTROUTE);
  966. outip = xzalloc(packlen);
  967. ident = getpid();
  968. /* we can use native-endian ident, but other Unix ping/traceroute
  969. * utils use *big-endian pid*, and e.g. ping on our machine may be
  970. * *not* from busybox, idents may collide. Follow the convention:
  971. */
  972. ident = htons(ident);
  973. outdata = (void*)(outudp + 1);
  974. if (af == AF_INET) {
  975. if (op & OPT_USE_ICMP) {
  976. outicmp->icmp_type = ICMP_ECHO;
  977. /*outicmp->icmp_code = 0; - set by xzalloc */
  978. outicmp->icmp_id = ident;
  979. outdata = (void*)((char *)outicmp + SIZEOF_ICMP_HDR);
  980. }
  981. }
  982. #if ENABLE_TRACEROUTE6
  983. else {
  984. outdata = (void*)(outudp6 + 1);
  985. if (op & OPT_USE_ICMP) {
  986. outicmp6->icmp_type = ICMP6_ECHO_REQUEST;
  987. /*outicmp->icmp_code = 0; - set by xzalloc */
  988. outicmp6->icmp_id = ident;
  989. outdata = (void*)((char *)outicmp6 + SIZEOF_ICMP_HDR);
  990. }
  991. }
  992. #endif
  993. if (op & OPT_DEVICE) /* hmm, do we need error check? */
  994. setsockopt_bindtodevice(sndsock, device);
  995. if (op & OPT_SOURCE) {
  996. #if ENABLE_TRACEROUTE6
  997. // TODO: need xdotted_and_af2sockaddr?
  998. len_and_sockaddr *source_lsa = xhost_and_af2sockaddr(source, 0, af);
  999. #else
  1000. len_and_sockaddr *source_lsa = xdotted2sockaddr(source, 0);
  1001. #endif
  1002. if (getuid() != 0)
  1003. bb_simple_error_msg_and_die(bb_msg_you_must_be_root);
  1004. /* Ping4 does this (why?) */
  1005. if (af == AF_INET)
  1006. if (setsockopt(sndsock, IPPROTO_IP, IP_MULTICAST_IF,
  1007. &source_lsa->u.sa, source_lsa->len))
  1008. bb_simple_error_msg_and_die("can't set multicast source interface");
  1009. //TODO: we can query source port we bound to,
  1010. // and check it in replies... if we care enough
  1011. xbind(sndsock, &source_lsa->u.sa, source_lsa->len);
  1012. if (ENABLE_FEATURE_CLEAN_UP)
  1013. free(source_lsa);
  1014. } else {
  1015. len_and_sockaddr *source_lsa;
  1016. set_nport(&dest_lsa->u.sa, htons(port));
  1017. /* Connect makes kernel pick source IP (and port if UDP) */
  1018. xconnect(sndsock, &dest_lsa->u.sa, dest_lsa->len);
  1019. /* Read IP and port */
  1020. source_lsa = get_sock_lsa(sndsock);
  1021. if (source_lsa == NULL)
  1022. bb_simple_perror_msg_and_die("getsockname");
  1023. /* bind our recv ICMP socket to this IP (but not port, ICMP has no ports) */
  1024. //set_nport(&source_lsa->u.sa, 0); - paranoia, seems to work without this for both ipv4 and ipv6
  1025. xbind(rcvsock, &source_lsa->u.sa, source_lsa->len);
  1026. if (ENABLE_FEATURE_CLEAN_UP)
  1027. free(source_lsa);
  1028. }
  1029. /* Revert to non-privileged user after opening sockets */
  1030. xsetgid(getgid());
  1031. xsetuid(getuid());
  1032. dest_str = xmalloc_sockaddr2dotted_noport(&dest_lsa->u.sa);
  1033. printf("traceroute to %s (%s)", argv[0], dest_str);
  1034. if (ENABLE_FEATURE_CLEAN_UP)
  1035. free(dest_str);
  1036. if (op & OPT_SOURCE)
  1037. printf(" from %s", source);
  1038. printf(", %d hops max, %d byte packets\n", G.max_ttl, packlen);
  1039. }
  1040. static int
  1041. common_traceroute_main(int op, char **argv)
  1042. {
  1043. int ttl;
  1044. int seq;
  1045. struct sockaddr *lastaddr;
  1046. traceroute_init(op, argv);
  1047. lastaddr = xzalloc(dest_lsa->len);
  1048. seq = 0;
  1049. for (ttl = G.first_ttl; ttl <= G.max_ttl; ++ttl) {
  1050. int probe;
  1051. int unreachable = 0; /* counter */
  1052. int got_there = 0;
  1053. printf("%2d", ttl);
  1054. for (probe = 0; probe < G.nprobes; ++probe) {
  1055. unsigned t1;
  1056. unsigned t2;
  1057. int left_ms;
  1058. int read_len;
  1059. int icmp_code;
  1060. fflush_all();
  1061. if (probe != 0)
  1062. msleep(G.pausemsecs);
  1063. send_probe(++seq, ttl);
  1064. t2 = t1 = monotonic_us();
  1065. left_ms = waittime * 1000;
  1066. for (;;) {
  1067. /* NB: wait_for_reply() fills "G.from_lsa" and "G.to" with
  1068. * "where it came from" and "what local address it arrived to"
  1069. * addresses. Sets t2 = monotonic_us(), updates left_ms.
  1070. */
  1071. read_len = wait_for_reply(&t2, &left_ms);
  1072. if (read_len == 0) { /* there was no packet at all? */
  1073. printf(" *");
  1074. goto next_probe;
  1075. }
  1076. icmp_code = packet_ok(read_len, seq);
  1077. if (icmp_code != 0)
  1078. break; /* got a good response */
  1079. /* unrecognized type/code or too short, back to recv */
  1080. }
  1081. if (probe == 0
  1082. || (memcmp(lastaddr, &G.from_lsa->u.sa, G.from_lsa->len) != 0)
  1083. ) {
  1084. print(read_len);
  1085. memcpy(lastaddr, &G.from_lsa->u.sa, G.from_lsa->len);
  1086. }
  1087. print_delta_ms(t1, t2);
  1088. if (!G_ipv6) {
  1089. if (op & OPT_TTL_FLAG) {
  1090. struct ip *ip = (struct ip *)recv_pkt;
  1091. printf(" (%d)", ip->ip_ttl);
  1092. }
  1093. }
  1094. /* Got a "time exceeded in transit" icmp message? */
  1095. if (icmp_code == -1)
  1096. continue;
  1097. icmp_code--;
  1098. switch (icmp_code) {
  1099. #if ENABLE_TRACEROUTE6
  1100. case ICMP6_DST_UNREACH_NOPORT << 8:
  1101. got_there = 1;
  1102. break;
  1103. #endif
  1104. case ICMP_UNREACH_PORT: {
  1105. struct ip *ip = (struct ip *)recv_pkt;
  1106. if (ip->ip_ttl <= 1)
  1107. printf(" !");
  1108. got_there = 1;
  1109. break;
  1110. }
  1111. case ICMP_UNREACH_NET:
  1112. #if ENABLE_TRACEROUTE6 && (ICMP6_DST_UNREACH_NOROUTE != ICMP_UNREACH_NET)
  1113. case ICMP6_DST_UNREACH_NOROUTE << 8:
  1114. #endif
  1115. printf(" !N");
  1116. ++unreachable;
  1117. break;
  1118. case ICMP_UNREACH_HOST:
  1119. #if ENABLE_TRACEROUTE6
  1120. case ICMP6_DST_UNREACH_ADDR << 8:
  1121. #endif
  1122. printf(" !H");
  1123. ++unreachable;
  1124. break;
  1125. case ICMP_UNREACH_PROTOCOL:
  1126. printf(" !P");
  1127. got_there = 1;
  1128. break;
  1129. case ICMP_UNREACH_NEEDFRAG:
  1130. printf(" !F-%d", pmtu);
  1131. ++unreachable;
  1132. break;
  1133. case ICMP_UNREACH_SRCFAIL:
  1134. #if ENABLE_TRACEROUTE6
  1135. case ICMP6_DST_UNREACH_ADMIN << 8:
  1136. #endif
  1137. printf(" !S");
  1138. ++unreachable;
  1139. break;
  1140. case ICMP_UNREACH_FILTER_PROHIB:
  1141. case ICMP_UNREACH_NET_PROHIB: /* misuse */
  1142. printf(" !A");
  1143. ++unreachable;
  1144. break;
  1145. case ICMP_UNREACH_HOST_PROHIB:
  1146. printf(" !C");
  1147. ++unreachable;
  1148. break;
  1149. case ICMP_UNREACH_HOST_PRECEDENCE:
  1150. printf(" !V");
  1151. ++unreachable;
  1152. break;
  1153. case ICMP_UNREACH_PRECEDENCE_CUTOFF:
  1154. printf(" !C");
  1155. ++unreachable;
  1156. break;
  1157. case ICMP_UNREACH_NET_UNKNOWN:
  1158. case ICMP_UNREACH_HOST_UNKNOWN:
  1159. printf(" !U");
  1160. ++unreachable;
  1161. break;
  1162. case ICMP_UNREACH_ISOLATED:
  1163. printf(" !I");
  1164. ++unreachable;
  1165. break;
  1166. case ICMP_UNREACH_TOSNET:
  1167. case ICMP_UNREACH_TOSHOST:
  1168. printf(" !T");
  1169. ++unreachable;
  1170. break;
  1171. default:
  1172. printf(" !<%d>", icmp_code);
  1173. ++unreachable;
  1174. break;
  1175. }
  1176. next_probe: ;
  1177. } /* for (nprobes) */
  1178. bb_putchar('\n');
  1179. if (got_there
  1180. || (unreachable > 0 && unreachable >= G.nprobes - 1)
  1181. ) {
  1182. break;
  1183. }
  1184. }
  1185. if (ENABLE_FEATURE_CLEAN_UP) {
  1186. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  1187. free(G.to);
  1188. #endif
  1189. free(lastaddr);
  1190. free(G.from_lsa);
  1191. }
  1192. return 0;
  1193. }
  1194. #if ENABLE_TRACEROUTE
  1195. int traceroute_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1196. int traceroute_main(int argc UNUSED_PARAM, char **argv)
  1197. {
  1198. return common_traceroute_main(0, argv);
  1199. }
  1200. #endif
  1201. #if ENABLE_TRACEROUTE6
  1202. int traceroute6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1203. int traceroute6_main(int argc UNUSED_PARAM, char **argv)
  1204. {
  1205. return common_traceroute_main(OPT_IPV6, argv);
  1206. }
  1207. #endif