traceroute.c 36 KB

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