3
0

traceroute.c 37 KB

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