3
0

traceroute.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Copyright (c) 1988, 1989, 1991, 1994, 1995, 1996, 1997, 1998, 1999, 2000
  4. * The Regents of the University of California. All rights reserved.
  5. *
  6. * Busybox port by Vladimir Oleynik (C) 2005 <dzo@simtreas.ru>
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that: (1) source code distributions
  10. * retain the above copyright notice and this paragraph in its entirety, (2)
  11. * distributions including binary code include the above copyright notice and
  12. * this paragraph in its entirety in the documentation or other materials
  13. * provided with the distribution, and (3) all advertising materials mentioning
  14. * features or use of this software display the following acknowledgement:
  15. * ''This product includes software developed by the University of California,
  16. * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
  17. * the University nor the names of its contributors may be used to endorse
  18. * or promote products derived from this software without specific prior
  19. * written permission.
  20. * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
  21. * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
  22. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  23. */
  24. /*
  25. * traceroute6
  26. *
  27. * Modified for NRL 4.4BSD IPv6 release.
  28. * 07/31/96 bgp
  29. *
  30. * Modified for Linux IPv6 by Pedro Roque <roque@di.fc.ul.pt>
  31. * 31/07/1996
  32. *
  33. * As ICMP error messages for IPv6 now include more than 8 bytes
  34. * UDP datagrams are now sent via an UDP socket instead of magic
  35. * RAW socket tricks.
  36. *
  37. * Converted to busybox applet by Leonid Lisovskiy <lly@sf.net>
  38. * 2009-11-16
  39. */
  40. /*
  41. * traceroute host - trace the route ip packets follow going to "host".
  42. *
  43. * Attempt to trace the route an ip packet would follow to some
  44. * internet host. We find out intermediate hops by launching probe
  45. * packets with a small ttl (time to live) then listening for an
  46. * icmp "time exceeded" reply from a gateway. We start our probes
  47. * with a ttl of one and increase by one until we get an icmp "port
  48. * unreachable" (which means we got to "host") or hit a max (which
  49. * defaults to 30 hops & can be changed with the -m flag). Three
  50. * probes (change with -q flag) are sent at each ttl setting and a
  51. * line is printed showing the ttl, address of the gateway and
  52. * round trip time of each probe. If the probe answers come from
  53. * different gateways, the address of each responding system will
  54. * be printed. If there is no response within a 5 sec. timeout
  55. * interval (changed with the -w flag), a "*" is printed for that
  56. * probe.
  57. *
  58. * Probe packets are UDP format. We don't want the destination
  59. * host to process them so the destination port is set to an
  60. * unlikely value (if some clod on the destination is using that
  61. * value, it can be changed with the -p flag).
  62. *
  63. * A sample use might be:
  64. *
  65. * [yak 71]% traceroute nis.nsf.net.
  66. * traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
  67. * 1 helios.ee.lbl.gov (128.3.112.1) 19 ms 19 ms 0 ms
  68. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
  69. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
  70. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 39 ms
  71. * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 39 ms 39 ms 39 ms
  72. * 6 128.32.197.4 (128.32.197.4) 40 ms 59 ms 59 ms
  73. * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 59 ms
  74. * 8 129.140.70.13 (129.140.70.13) 99 ms 99 ms 80 ms
  75. * 9 129.140.71.6 (129.140.71.6) 139 ms 239 ms 319 ms
  76. * 10 129.140.81.7 (129.140.81.7) 220 ms 199 ms 199 ms
  77. * 11 nic.merit.edu (35.1.1.48) 239 ms 239 ms 239 ms
  78. *
  79. * Note that lines 2 & 3 are the same. This is due to a buggy
  80. * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
  81. * packets with a zero ttl.
  82. *
  83. * A more interesting example is:
  84. *
  85. * [yak 72]% traceroute allspice.lcs.mit.edu.
  86. * traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
  87. * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
  88. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 19 ms 19 ms
  89. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 19 ms
  90. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 19 ms 39 ms 39 ms
  91. * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 20 ms 39 ms 39 ms
  92. * 6 128.32.197.4 (128.32.197.4) 59 ms 119 ms 39 ms
  93. * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 39 ms
  94. * 8 129.140.70.13 (129.140.70.13) 80 ms 79 ms 99 ms
  95. * 9 129.140.71.6 (129.140.71.6) 139 ms 139 ms 159 ms
  96. * 10 129.140.81.7 (129.140.81.7) 199 ms 180 ms 300 ms
  97. * 11 129.140.72.17 (129.140.72.17) 300 ms 239 ms 239 ms
  98. * 12 * * *
  99. * 13 128.121.54.72 (128.121.54.72) 259 ms 499 ms 279 ms
  100. * 14 * * *
  101. * 15 * * *
  102. * 16 * * *
  103. * 17 * * *
  104. * 18 ALLSPICE.LCS.MIT.EDU (18.26.0.115) 339 ms 279 ms 279 ms
  105. *
  106. * (I start to see why I'm having so much trouble with mail to
  107. * MIT.) Note that the gateways 12, 14, 15, 16 & 17 hops away
  108. * either don't send ICMP "time exceeded" messages or send them
  109. * with a ttl too small to reach us. 14 - 17 are running the
  110. * MIT C Gateway code that doesn't send "time exceeded"s. God
  111. * only knows what's going on with 12.
  112. *
  113. * The silent gateway 12 in the above may be the result of a bug in
  114. * the 4.[23]BSD network code (and its derivatives): 4.x (x <= 3)
  115. * sends an unreachable message using whatever ttl remains in the
  116. * original datagram. Since, for gateways, the remaining ttl is
  117. * zero, the icmp "time exceeded" is guaranteed to not make it back
  118. * to us. The behavior of this bug is slightly more interesting
  119. * when it appears on the destination system:
  120. *
  121. * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
  122. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 39 ms
  123. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 39 ms 19 ms
  124. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 19 ms
  125. * 5 ccn-nerif35.Berkeley.EDU (128.32.168.35) 39 ms 39 ms 39 ms
  126. * 6 csgw.Berkeley.EDU (128.32.133.254) 39 ms 59 ms 39 ms
  127. * 7 * * *
  128. * 8 * * *
  129. * 9 * * *
  130. * 10 * * *
  131. * 11 * * *
  132. * 12 * * *
  133. * 13 rip.Berkeley.EDU (128.32.131.22) 59 ms ! 39 ms ! 39 ms !
  134. *
  135. * Notice that there are 12 "gateways" (13 is the final
  136. * destination) and exactly the last half of them are "missing".
  137. * What's really happening is that rip (a Sun-3 running Sun OS3.5)
  138. * is using the ttl from our arriving datagram as the ttl in its
  139. * icmp reply. So, the reply will time out on the return path
  140. * (with no notice sent to anyone since icmp's aren't sent for
  141. * icmp's) until we probe with a ttl that's at least twice the path
  142. * length. I.e., rip is really only 7 hops away. A reply that
  143. * returns with a ttl of 1 is a clue this problem exists.
  144. * Traceroute prints a "!" after the time if the ttl is <= 1.
  145. * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
  146. * non-standard (HPUX) software, expect to see this problem
  147. * frequently and/or take care picking the target host of your
  148. * probes.
  149. *
  150. * Other possible annotations after the time are !H, !N, !P (got a host,
  151. * network or protocol unreachable, respectively), !S or !F (source
  152. * route failed or fragmentation needed -- neither of these should
  153. * ever occur and the associated gateway is busted if you see one). If
  154. * almost all the probes result in some kind of unreachable, traceroute
  155. * will give up and exit.
  156. *
  157. * Notes
  158. * -----
  159. * This program must be run by root or be setuid. (I suggest that
  160. * you *don't* make it setuid -- casual use could result in a lot
  161. * of unnecessary traffic on our poor, congested nets.)
  162. *
  163. * This program requires a kernel mod that does not appear in any
  164. * system available from Berkeley: A raw ip socket using proto
  165. * IPPROTO_RAW must interpret the data sent as an ip datagram (as
  166. * opposed to data to be wrapped in a ip datagram). See the README
  167. * file that came with the source to this program for a description
  168. * of the mods I made to /sys/netinet/raw_ip.c. Your mileage may
  169. * vary. But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
  170. * MODIFIED TO RUN THIS PROGRAM.
  171. *
  172. * The udp port usage may appear bizarre (well, ok, it is bizarre).
  173. * The problem is that an icmp message only contains 8 bytes of
  174. * data from the original datagram. 8 bytes is the size of a udp
  175. * header so, if we want to associate replies with the original
  176. * datagram, the necessary information must be encoded into the
  177. * udp header (the ip id could be used but there's no way to
  178. * interlock with the kernel's assignment of ip id's and, anyway,
  179. * it would have taken a lot more kernel hacking to allow this
  180. * code to set the ip id). So, to allow two or more users to
  181. * use traceroute simultaneously, we use this task's pid as the
  182. * source port (the high bit is set to move the port number out
  183. * of the "likely" range). To keep track of which probe is being
  184. * replied to (so times and/or hop counts don't get confused by a
  185. * reply that was delayed in transit), we increment the destination
  186. * port number before each probe.
  187. *
  188. * Don't use this as a coding example. I was trying to find a
  189. * routing problem and this code sort-of popped out after 48 hours
  190. * without sleep. I was amazed it ever compiled, much less ran.
  191. *
  192. * I stole the idea for this program from Steve Deering. Since
  193. * the first release, I've learned that had I attended the right
  194. * IETF working group meetings, I also could have stolen it from Guy
  195. * Almes or Matt Mathis. I don't know (or care) who came up with
  196. * the idea first. I envy the originators' perspicacity and I'm
  197. * glad they didn't keep the idea a secret.
  198. *
  199. * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
  200. * enhancements to the original distribution.
  201. *
  202. * I've hacked up a round-trip-route version of this that works by
  203. * sending a loose-source-routed udp datagram through the destination
  204. * back to yourself. Unfortunately, SO many gateways botch source
  205. * routing, the thing is almost worthless. Maybe one day...
  206. *
  207. * -- Van Jacobson (van@ee.lbl.gov)
  208. * Tue Dec 20 03:50:13 PST 1988
  209. */
  210. //config:config TRACEROUTE
  211. //config: bool "traceroute (11 kb)"
  212. //config: default y
  213. //config: help
  214. //config: Utility to trace the route of IP packets.
  215. //config:
  216. //config:config TRACEROUTE6
  217. //config: bool "traceroute6 (13 kb)"
  218. //config: default y
  219. //config: depends on FEATURE_IPV6
  220. //config: help
  221. //config: Utility to trace the route of IPv6 packets.
  222. //config:
  223. //config:config FEATURE_TRACEROUTE_VERBOSE
  224. //config: bool "Enable verbose output"
  225. //config: default y
  226. //config: depends on TRACEROUTE || TRACEROUTE6
  227. //config: help
  228. //config: Add some verbosity to traceroute. This includes among other things
  229. //config: hostnames and ICMP response types.
  230. //config:
  231. //config:config FEATURE_TRACEROUTE_USE_ICMP
  232. //config: bool "Enable -I option (use ICMP instead of UDP)"
  233. //config: default y
  234. //config: depends on TRACEROUTE || TRACEROUTE6
  235. /* Needs socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), therefore BB_SUID_MAYBE: */
  236. //applet:IF_TRACEROUTE(APPLET(traceroute, BB_DIR_USR_BIN, BB_SUID_MAYBE))
  237. //applet:IF_TRACEROUTE6(APPLET(traceroute6, BB_DIR_USR_BIN, BB_SUID_MAYBE))
  238. //kbuild:lib-$(CONFIG_TRACEROUTE) += traceroute.o
  239. //kbuild:lib-$(CONFIG_TRACEROUTE6) += traceroute.o
  240. //usage:#define traceroute_trivial_usage
  241. //usage: "[-"IF_TRACEROUTE6("46")IF_FEATURE_TRACEROUTE_USE_ICMP("I")"Flnrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT]\n"
  242. //usage: " [-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE]\n"
  243. //usage: " [-z PAUSE_MSEC] HOST [BYTES]"
  244. //usage:#define traceroute_full_usage "\n\n"
  245. //usage: "Trace the route to HOST\n"
  246. //usage: IF_TRACEROUTE6(
  247. //usage: "\n -4,-6 Force IP or IPv6 name resolution"
  248. //usage: )
  249. //usage: "\n -F Set don't fragment bit"
  250. //usage: IF_FEATURE_TRACEROUTE_USE_ICMP(
  251. //usage: "\n -I Use ICMP ECHO instead of UDP datagrams"
  252. //usage: )
  253. //usage: "\n -l Display TTL value of the returned packet"
  254. //Currently disabled (TRACEROUTE_SO_DEBUG==0)
  255. ////usage: "\n -d Set SO_DEBUG options to socket"
  256. //usage: "\n -n Print numeric addresses"
  257. //usage: "\n -r Bypass routing tables, send directly to HOST"
  258. //usage: IF_FEATURE_TRACEROUTE_VERBOSE(
  259. //usage: "\n -v Verbose"
  260. //usage: )
  261. //usage: "\n -f N First number of hops (default 1)"
  262. //usage: "\n -m N Max number of hops"
  263. //usage: "\n -q N Number of probes per hop (default 3)"
  264. //usage: "\n -p N Base UDP port number used in probes"
  265. //usage: "\n (default 33434)"
  266. //usage: "\n -s IP Source address"
  267. //usage: "\n -i IFACE Source interface"
  268. //usage: "\n -t N Type-of-service in probe packets (default 0)"
  269. //usage: "\n -w SEC Wait for a response (default 3)"
  270. //usage: "\n -z MSEC Wait before each send"
  271. //usage:
  272. //usage:#define traceroute6_trivial_usage
  273. //usage: "[-"IF_FEATURE_TRACEROUTE_USE_ICMP("I")"nrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT]\n"
  274. //usage: " [-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE]\n"
  275. //usage: " [-z PAUSE_MSEC] HOST [BYTES]"
  276. //usage:#define traceroute6_full_usage "\n\n"
  277. //usage: "Trace the route to HOST\n"
  278. ////NOP? "\n -F Set don't fragment bit"
  279. //usage: IF_FEATURE_TRACEROUTE_USE_ICMP(
  280. //usage: "\n -I Use ICMP ECHO instead of UDP datagrams"
  281. //usage: )
  282. ////NOP: "\n -l Display TTL value of the returned packet"
  283. //Currently disabled (TRACEROUTE_SO_DEBUG==0)
  284. ////usage: "\n -d Set SO_DEBUG options to socket"
  285. //usage: "\n -n Print numeric addresses"
  286. //usage: "\n -r Bypass routing tables, send directly to HOST"
  287. //usage: IF_FEATURE_TRACEROUTE_VERBOSE(
  288. //usage: "\n -v Verbose"
  289. //usage: )
  290. //usage: "\n -f N First number of hops (default 1)"
  291. //usage: "\n -m N Max number of hops"
  292. //usage: "\n -q N Number of probes per hop (default 3)"
  293. //usage: "\n -p N Base UDP port number used in probes"
  294. //usage: "\n (default 33434)"
  295. //usage: "\n -s IP Source address"
  296. //usage: "\n -i IFACE Source interface"
  297. //usage: "\n -t N Type-of-service in probe packets (default 0)"
  298. //usage: "\n -w SEC Wait for a response (default 3)"
  299. //usage: "\n -z MSEC Wait before each send"
  300. #define TRACEROUTE_SO_DEBUG 0
  301. #include <net/if.h>
  302. #include <arpa/inet.h>
  303. #include <netinet/in.h>
  304. #include <netinet/udp.h>
  305. #include <netinet/ip.h>
  306. #include <netinet/ip_icmp.h>
  307. #if ENABLE_FEATURE_IPV6
  308. # include <netinet/ip6.h>
  309. # include <netinet/icmp6.h>
  310. # ifndef SOL_IPV6
  311. # define SOL_IPV6 IPPROTO_IPV6
  312. # endif
  313. # if defined(IPV6_PKTINFO) && !defined(IPV6_RECVPKTINFO)
  314. # define IPV6_RECVPKTINFO IPV6_PKTINFO
  315. # endif
  316. #endif
  317. #include "libbb.h"
  318. #include "inet_common.h"
  319. #ifndef IPPROTO_ICMP
  320. # define IPPROTO_ICMP 1
  321. #endif
  322. #ifndef IPPROTO_IP
  323. # define IPPROTO_IP 0
  324. #endif
  325. /* Some operating systems, like GNU/Hurd, don't define SOL_RAW, but do have
  326. * IPPROTO_RAW. Since the IPPROTO definitions are also valid to use for
  327. * setsockopt (and take the same value as their corresponding SOL definitions,
  328. * if they exist), we can just fall back on IPPROTO_RAW. */
  329. #ifndef SOL_RAW
  330. # define SOL_RAW IPPROTO_RAW
  331. #endif
  332. #define OPT_STRING \
  333. "FIlnrdvt:i:m:p:q:s:w:z:f:" \
  334. "4" IF_TRACEROUTE6("6")
  335. enum {
  336. OPT_DONT_FRAGMNT = (1 << 0), /* F */
  337. OPT_USE_ICMP = (1 << 1) * ENABLE_FEATURE_TRACEROUTE_USE_ICMP, /* I */
  338. OPT_TTL_FLAG = (1 << 2), /* l */
  339. OPT_ADDR_NUM = (1 << 3), /* n */
  340. OPT_BYPASS_ROUTE = (1 << 4), /* r */
  341. OPT_DEBUG = (1 << 5), /* d */
  342. OPT_VERBOSE = (1 << 6) * ENABLE_FEATURE_TRACEROUTE_VERBOSE, /* v */
  343. OPT_TOS = (1 << 7), /* t */
  344. OPT_DEVICE = (1 << 8), /* i */
  345. OPT_MAX_TTL = (1 << 9), /* m */
  346. OPT_PORT = (1 << 10), /* p */
  347. OPT_NPROBES = (1 << 11), /* q */
  348. OPT_SOURCE = (1 << 12), /* s */
  349. OPT_WAITTIME = (1 << 13), /* w */
  350. OPT_PAUSE_MS = (1 << 14), /* z */
  351. OPT_FIRST_TTL = (1 << 15), /* f */
  352. OPT_IPV4 = (1 << 16), /* 4 */
  353. OPT_IPV6 = (1 << 17) * ENABLE_TRACEROUTE6, /* 6 */
  354. };
  355. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  356. # define verbose (option_mask32 & OPT_VERBOSE)
  357. #else
  358. # define verbose 0
  359. #endif
  360. enum {
  361. SIZEOF_ICMP_HDR = 8,
  362. rcvsock = 3, /* receive (icmp) socket file descriptor */
  363. sndsock = 4, /* send (udp/icmp) socket file descriptor */
  364. };
  365. /* Data section of the probe packet */
  366. struct outdata_t {
  367. unsigned char seq; /* sequence number of this packet */
  368. unsigned char ttl; /* ttl packet left with */
  369. // UNUSED. Retaining to have the same packet size.
  370. struct timeval tv_UNUSED PACKED; /* time packet left */
  371. };
  372. #if ENABLE_TRACEROUTE6
  373. struct outdata6_t {
  374. uint32_t ident6;
  375. uint32_t seq6;
  376. struct timeval tv_UNUSED PACKED; /* time packet left */
  377. };
  378. #endif
  379. struct globals {
  380. /* Pointer to entire malloced IP packet, "packlen" bytes long: */
  381. struct ip *outip;
  382. /* Pointer to ICMP or UDP payload (not header): */
  383. struct outdata_t *outdata;
  384. len_and_sockaddr *dest_lsa;
  385. len_and_sockaddr *from_lsa; /* response came from this address */
  386. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  387. struct sockaddr *to; /* response came to this (local) address */
  388. #endif
  389. uint32_t ident;
  390. uint16_t port; /* start udp dest port # for probe packets */
  391. #if ENABLE_TRACEROUTE6
  392. smallint ipv6;
  393. # define G_ipv6 G.ipv6
  394. #else
  395. # define G_ipv6 0
  396. #endif
  397. int packlen; /* total length of packet */
  398. int pmtu; /* Path MTU Discovery (RFC1191) */
  399. int waittime; /* time to wait for response (in seconds) */
  400. int first_ttl;
  401. int nprobes;
  402. int max_ttl;
  403. unsigned pausemsecs;
  404. unsigned char recv_pkt[512]; /* last inbound (icmp) packet */
  405. };
  406. #define G (*ptr_to_globals)
  407. #define outip (G.outip )
  408. #define outdata (G.outdata )
  409. #define dest_lsa (G.dest_lsa )
  410. #define packlen (G.packlen )
  411. #define pmtu (G.pmtu )
  412. #define ident (G.ident )
  413. #define port (G.port )
  414. #define waittime (G.waittime )
  415. #define recv_pkt (G.recv_pkt )
  416. #define INIT_G() do { \
  417. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  418. } while (0)
  419. #define outudp ((struct udphdr *)(outip + 1))
  420. #define outudp6 ((struct udphdr *)(((struct ip6_hdr*)outip) + 1))
  421. #define outicmp ((struct icmp *)(outip + 1))
  422. #define outicmp6 ((struct icmp *)(((struct ip6_hdr*)outip) + 1))
  423. /* NB: for icmp echo, IPv4 and IPv6 fields are the same size and offset:
  424. * struct icmp:
  425. * uint8_t icmp_type;
  426. * uint8_t icmp_code;
  427. * uint16_t icmp_cksum;
  428. * uint16_t icmp_id;
  429. * uint16_t icmp_seq;
  430. * struct icmp6_hdr:
  431. * uint8_t icmp6_type;
  432. * uint8_t icmp6_code;
  433. * uint16_t icmp6_cksum;
  434. * uint16_t icmp6_id;
  435. * uint16_t icmp6_seq;
  436. * therefore both outicmp and outicmp6 are pointers to *IPv4* icmp struct.
  437. * SIZEOF_ICMP_HDR == 8 is the same for both, as well.
  438. * However, values of these pointers are not the same (since IPv6 IP header is larger),
  439. * and icmp_type constants are not the same:
  440. * #define ICMP_ECHO 8
  441. * #define ICMP_ECHOREPLY 0
  442. * #define ICMP6_ECHO_REQUEST 128
  443. * #define ICMP6_ECHO_REPLY 129
  444. */
  445. static int
  446. wait_for_reply(unsigned *timestamp_us, int *left_ms)
  447. {
  448. struct pollfd pfd[1];
  449. int read_len = 0;
  450. pfd[0].fd = rcvsock;
  451. pfd[0].events = POLLIN;
  452. if (*left_ms >= 0 && safe_poll(pfd, 1, *left_ms) > 0) {
  453. unsigned t;
  454. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  455. read_len = recv_from_to(rcvsock,
  456. recv_pkt, sizeof(recv_pkt),
  457. /*flags:*/ MSG_DONTWAIT,
  458. &G.from_lsa->u.sa, G.to, G.from_lsa->len);
  459. #else
  460. read_len = recvfrom(rcvsock,
  461. recv_pkt, sizeof(recv_pkt),
  462. /*flags:*/ MSG_DONTWAIT,
  463. &G.from_lsa->u.sa, &G.from_lsa->len);
  464. #endif
  465. if (read_len < 0)
  466. bb_simple_perror_msg_and_die("recv");
  467. t = monotonic_us();
  468. *left_ms -= (t - *timestamp_us) / 1000;
  469. *timestamp_us = t;
  470. }
  471. return read_len;
  472. }
  473. static void
  474. send_probe(int seq, int ttl)
  475. {
  476. int len, res;
  477. void *out;
  478. struct icmp *icp;
  479. /* Payload */
  480. #if ENABLE_TRACEROUTE6
  481. if (G_ipv6) {
  482. struct outdata6_t *pkt = (void *) outdata;
  483. pkt->ident6 = ident;
  484. pkt->seq6 = htonl(seq);
  485. /*gettimeofday(&pkt->tv, &tz);*/
  486. icp = outicmp6;
  487. } else
  488. #endif
  489. {
  490. outdata->seq = seq;
  491. outdata->ttl = ttl;
  492. // UNUSED: was storing gettimeofday's result there, but never ever checked it
  493. /*memcpy(&outdata->tv, tp, sizeof(outdata->tv));*/
  494. icp = outicmp;
  495. }
  496. out = outdata;
  497. if (option_mask32 & OPT_USE_ICMP) {
  498. out = icp;
  499. /*icp->icmp_type = ICMP[6]_ECHO; - already set */
  500. /*icp->icmp_code = 0; - already set */
  501. /*icp->icmp_id = ident; - already set */
  502. icp->icmp_seq = htons(seq);
  503. /* Always calculate checksum for icmp packets */
  504. icp->icmp_cksum = 0;
  505. icp->icmp_cksum = inet_cksum(
  506. icp,
  507. ((char*)outip + packlen) - (char*)icp
  508. );
  509. if (icp->icmp_cksum == 0)
  510. icp->icmp_cksum = 0xffff;
  511. }
  512. //BUG! verbose is (x & OPT_VERBOSE), not a counter!
  513. #if 0 //ENABLE_FEATURE_TRACEROUTE_VERBOSE
  514. /* XXX undocumented debugging hack */
  515. if (verbose > 1) {
  516. const uint16_t *sp;
  517. int nshorts, i;
  518. sp = (uint16_t *)outip;
  519. nshorts = (unsigned)packlen / sizeof(uint16_t);
  520. i = 0;
  521. printf("[ %d bytes", packlen);
  522. while (--nshorts >= 0) {
  523. if ((i++ % 8) == 0)
  524. printf("\n\t");
  525. printf(" %04x", ntohs(*sp));
  526. sp++;
  527. }
  528. if (packlen & 1) {
  529. if ((i % 8) == 0)
  530. printf("\n\t");
  531. printf(" %02x", *(unsigned char *)sp);
  532. }
  533. printf("]\n");
  534. }
  535. #endif
  536. #if ENABLE_TRACEROUTE6
  537. if (G_ipv6) {
  538. res = setsockopt_int(sndsock, SOL_IPV6, IPV6_UNICAST_HOPS, ttl);
  539. if (res != 0)
  540. bb_perror_msg_and_die("setsockopt(%s) %d", "UNICAST_HOPS", ttl);
  541. } else
  542. #endif
  543. {
  544. #if defined IP_TTL
  545. res = setsockopt_int(sndsock, IPPROTO_IP, IP_TTL, ttl);
  546. if (res != 0)
  547. bb_perror_msg_and_die("setsockopt(%s) %d", "TTL", ttl);
  548. #endif
  549. }
  550. if (!(option_mask32 & OPT_USE_ICMP)) {
  551. set_nport(&dest_lsa->u.sa, htons(port + seq));
  552. }
  553. len = ((char*)outip + packlen) - (char*)out;
  554. res = xsendto(sndsock, out, len, &dest_lsa->u.sa, dest_lsa->len);
  555. if (res != len)
  556. bb_error_msg("sent %d octets, ret=%d", len, res);
  557. }
  558. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  559. /* Convert an ICMP "type" field to a printable string */
  560. static const char *
  561. pr_type(unsigned char t)
  562. {
  563. static const char *const ttab[] ALIGN_PTR = {
  564. "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
  565. "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
  566. "Echo", "Router Advert", "Router Solicit", "Time Exceeded",
  567. "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
  568. "Info Reply", "Mask Request", "Mask Reply"
  569. };
  570. # if ENABLE_TRACEROUTE6
  571. static const char *const ttab6[] ALIGN_PTR = {
  572. [0] = "Error", "Dest Unreachable", "Packet Too Big", "Time Exceeded",
  573. [4] = "Param Problem",
  574. [8] = "Echo Request", "Echo Reply", "Membership Query", "Membership Report",
  575. [12] = "Membership Reduction", "Router Solicit", "Router Advert", "Neighbor Solicit",
  576. [16] = "Neighbor Advert", "Redirect",
  577. };
  578. if (G_ipv6) {
  579. if (t < 5)
  580. return ttab6[t];
  581. if (t < 128 || t > ND_REDIRECT)
  582. return "OUT-OF-RANGE";
  583. return ttab6[(t & 63) + 8];
  584. }
  585. # endif
  586. if (t >= ARRAY_SIZE(ttab))
  587. return "OUT-OF-RANGE";
  588. return ttab[t];
  589. }
  590. static int
  591. hexdump_if_verbose(const struct icmp *icp, int len)
  592. {
  593. const unsigned char *p;
  594. int i;
  595. if (!verbose)
  596. return 0;
  597. printf("\n%d bytes from %s to %s: icmp type %u (%s) code %u\n",
  598. len,
  599. auto_string(xmalloc_sockaddr2dotted_noport(&G.from_lsa->u.sa)),
  600. auto_string(xmalloc_sockaddr2dotted_noport(G.to)),
  601. icp->icmp_type, pr_type(icp->icmp_type),
  602. icp->icmp_code
  603. );
  604. p = (const void *)icp;
  605. for (i = 0; i < len; i++) {
  606. if (!(i & 0xf))
  607. printf("\n%04x:" + (i==0), i);
  608. printf(" %02x", p[i]);
  609. }
  610. bb_putchar('\n');
  611. return 0;
  612. }
  613. #else
  614. # define hexdump_if_verbose(...) 0
  615. #endif
  616. static int
  617. packet4_ok(int read_len, int seq)
  618. {
  619. const struct icmp *icp;
  620. unsigned char type, code;
  621. int hlen;
  622. const struct ip *ip;
  623. /* NB: reads from (AF_INET, SOCK_RAW, IPPROTO_ICMP) socket
  624. * return the entire IP packet (IOW: they do not strip IP header).
  625. * This differs from (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6) sockets!?
  626. */
  627. ip = (struct ip *) recv_pkt;
  628. hlen = ip->ip_hl << 2;
  629. if (read_len < hlen + ICMP_MINLEN) {
  630. if (verbose)
  631. printf("packet too short (%d bytes) from %s\n", read_len,
  632. inet_ntoa(G.from_lsa->u.sin.sin_addr));
  633. return 0;
  634. }
  635. read_len -= hlen;
  636. icp = (struct icmp *)(recv_pkt + hlen);
  637. type = icp->icmp_type;
  638. code = icp->icmp_code;
  639. /* Path MTU Discovery (RFC1191) */
  640. pmtu = 0;
  641. if (code == ICMP_UNREACH_NEEDFRAG)
  642. pmtu = ntohs(icp->icmp_nextmtu);
  643. if ((option_mask32 & OPT_USE_ICMP)
  644. && type == ICMP_ECHOREPLY
  645. && icp->icmp_seq == htons(seq)
  646. ) {
  647. if (icp->icmp_id != ident)
  648. /* reply to another ping/traceroute from this box? */
  649. return 0; /* ignore, silently */
  650. /* In UDP mode, when we reach the machine, we (usually)
  651. * would get "port unreachable" - in ICMP we got "echo reply".
  652. * Simulate "port unreachable" for caller:
  653. */
  654. return ICMP_UNREACH_PORT+1;
  655. }
  656. if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS)
  657. || type == ICMP_UNREACH
  658. ) {
  659. const struct ip *hip;
  660. const struct udphdr *up;
  661. hip = &icp->icmp_ip;
  662. hlen = hip->ip_hl << 2;
  663. if (option_mask32 & OPT_USE_ICMP) {
  664. struct icmp *hicmp;
  665. hicmp = (struct icmp *)((unsigned char *)hip + hlen);
  666. if (hlen + SIZEOF_ICMP_HDR <= read_len
  667. && hip->ip_p == IPPROTO_ICMP
  668. && hicmp->icmp_id == ident
  669. && hicmp->icmp_seq == htons(seq)
  670. ) {
  671. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  672. }
  673. } else {
  674. up = (struct udphdr *)((char *)hip + hlen);
  675. if (hlen + 12 <= read_len
  676. && hip->ip_p == IPPROTO_UDP
  677. // Off: since we do not form the entire IP packet,
  678. // but defer it to kernel, we can't set source port,
  679. // and thus can't check it here in the reply
  680. /* && up->source == ident */
  681. && up->dest == htons(port + seq)
  682. ) {
  683. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  684. }
  685. }
  686. }
  687. /* testcase: traceroute -vI 127.0.0.1 (sees its own echo requests) */
  688. return hexdump_if_verbose(icp, read_len);
  689. }
  690. #if ENABLE_TRACEROUTE6
  691. static int
  692. packet6_ok(int read_len, int seq)
  693. {
  694. const struct icmp6_hdr *icp;
  695. unsigned char type, code;
  696. /* NB: reads from (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6) socket
  697. * return only ICMP packet (IOW: they strip IPv6 header).
  698. * This differs from (AF_INET, SOCK_RAW, IPPROTO_ICMP) sockets!?
  699. */
  700. if (read_len < ICMP_MINLEN) {
  701. if (verbose)
  702. printf("packet too short (%d bytes) from %s\n", read_len,
  703. auto_string(xmalloc_sockaddr2dotted_noport(&G.from_lsa->u.sa)));
  704. return 0;
  705. }
  706. icp = (struct icmp6_hdr *) recv_pkt;
  707. type = icp->icmp6_type;
  708. code = icp->icmp6_code;
  709. if ((option_mask32 & OPT_USE_ICMP)
  710. && type == ICMP6_ECHO_REPLY
  711. && icp->icmp6_seq == htons(seq)
  712. ) {
  713. if (icp->icmp6_id != ident)
  714. /* reply to another ping/traceroute from this box? */
  715. return 0; /* ignore, silently */
  716. /* In UDP mode, when we reach the machine, we (usually)
  717. * would get "port unreachable" - in ICMP we got "echo reply".
  718. * Simulate "port unreachable" for caller:
  719. */
  720. return (ICMP6_DST_UNREACH_NOPORT << 8) + 1;
  721. }
  722. if ((type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT)
  723. || type == ICMP6_DST_UNREACH
  724. ) {
  725. struct ip6_hdr *hip;
  726. struct udphdr *up;
  727. int nexthdr;
  728. hip = (struct ip6_hdr *)(icp + 1);
  729. up = (struct udphdr *) (hip + 1);
  730. nexthdr = hip->ip6_nxt;
  731. if (nexthdr == IPPROTO_FRAGMENT) {
  732. nexthdr = *(unsigned char*)up;
  733. up++;
  734. }
  735. if (nexthdr == IPPROTO_UDP) {
  736. struct outdata6_t *pkt;
  737. pkt = (struct outdata6_t *) (up + 1);
  738. if (pkt->ident6 == ident
  739. && ntohl(pkt->seq6) == seq
  740. ) {
  741. return (type == ICMP6_TIME_EXCEEDED ? -1 : (code<<8)+1);
  742. }
  743. }
  744. }
  745. /* cast is safe since the beginning of icmp4 and icmp6 layouts match */
  746. return hexdump_if_verbose((const struct icmp *)icp, read_len);
  747. }
  748. static int
  749. packet_ok(int read_len, int seq)
  750. {
  751. if (!G_ipv6)
  752. return packet4_ok(read_len, seq);
  753. return packet6_ok(read_len, seq);
  754. }
  755. #else /* !ENABLE_TRACEROUTE6 */
  756. # define packet_ok(read_len, seq) packet4_ok(read_len, seq)
  757. #endif
  758. static void
  759. #if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
  760. print(void)
  761. # define print(len) print()
  762. #else
  763. print(int read_len)
  764. #endif
  765. {
  766. char *ina = auto_string(xmalloc_sockaddr2dotted_noport(&G.from_lsa->u.sa));
  767. if (option_mask32 & OPT_ADDR_NUM) {
  768. printf(" %s", ina);
  769. } else {
  770. char *n = NULL;
  771. if (G_ipv6
  772. || G.from_lsa->u.sin.sin_addr.s_addr != INADDR_ANY
  773. ) {
  774. /* Reverse resolve if IPV6 or not 0.0.0.0 */
  775. n = auto_string(xmalloc_sockaddr2host_noport(&G.from_lsa->u.sa));
  776. }
  777. printf(" %s (%s)", (n ? n : ina), ina);
  778. }
  779. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  780. if (verbose) {
  781. # if ENABLE_TRACEROUTE6
  782. /* NB: reads from (AF_INET, SOCK_RAW, IPPROTO_ICMP) socket
  783. * return the entire IP packet (IOW: they do not strip IP header).
  784. * Reads from (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6) do strip IPv6
  785. * header and return only ICMP6 packet. Weird.
  786. */
  787. if (G_ipv6) {
  788. /* read_len -= sizeof(struct ip6_hdr); - WRONG! */
  789. } else
  790. # endif
  791. {
  792. struct ip *ip4packet = (struct ip*)recv_pkt;
  793. read_len -= ip4packet->ip_hl << 2;
  794. }
  795. printf(" %d bytes to %s", read_len,
  796. auto_string(xmalloc_sockaddr2dotted_noport(G.to))
  797. );
  798. }
  799. #endif
  800. }
  801. static void
  802. print_delta_ms(unsigned t1p, unsigned t2p)
  803. {
  804. unsigned tt = t2p - t1p;
  805. printf(" %u.%03u ms", tt / 1000, tt % 1000);
  806. }
  807. /* Keeping init code in a separate (not inlined!) function
  808. * for stack use reduction and better register allocation in main loop.
  809. */
  810. static NOINLINE void
  811. traceroute_init(int op, char **argv)
  812. {
  813. char *source;
  814. char *device;
  815. char *tos_str;
  816. char *max_ttl_str;
  817. char *port_str;
  818. char *nprobes_str;
  819. char *waittime_str;
  820. char *pausemsecs_str;
  821. char *first_ttl_str;
  822. char *dest_str;
  823. #if ENABLE_TRACEROUTE6
  824. sa_family_t af;
  825. #else
  826. enum { af = AF_INET };
  827. #endif
  828. /* Ensure the socket fds won't be 0, 1 or 2 */
  829. bb_sanitize_stdio();
  830. INIT_G();
  831. port = 33434;
  832. waittime = 5;
  833. G.first_ttl = 1;
  834. G.nprobes = 3;
  835. G.max_ttl = 30;
  836. op |= getopt32(argv, "^"
  837. OPT_STRING
  838. "\0" "-1" /* minimum 1 arg */
  839. , &tos_str, &device, &max_ttl_str, &port_str, &nprobes_str
  840. , &source, &waittime_str, &pausemsecs_str, &first_ttl_str
  841. );
  842. argv += optind;
  843. if (op & OPT_MAX_TTL)
  844. G.max_ttl = xatou_range(max_ttl_str, 1, 255);
  845. if (op & OPT_PORT)
  846. port = xatou16(port_str);
  847. if (op & OPT_NPROBES)
  848. G.nprobes = xatou_range(nprobes_str, 1, INT_MAX);
  849. if (op & OPT_WAITTIME)
  850. waittime = xatou_range(waittime_str, 1, 24 * 60 * 60);
  851. if (op & OPT_PAUSE_MS)
  852. G.pausemsecs = xatou_range(pausemsecs_str, 0, 60 * 60 * 1000);
  853. if (op & OPT_FIRST_TTL)
  854. G.first_ttl = xatou_range(first_ttl_str, 1, G.max_ttl);
  855. /* Process destination and optional packet size */
  856. packlen = sizeof(struct ip)
  857. + sizeof(struct udphdr)
  858. + sizeof(struct outdata_t);
  859. if (op & OPT_USE_ICMP) {
  860. packlen = sizeof(struct ip)
  861. + SIZEOF_ICMP_HDR
  862. + sizeof(struct outdata_t);
  863. port = 0; /* on ICMP6 sockets, sendto(ipv6.nonzero_port) throws EINVAL! */
  864. }
  865. #if ENABLE_TRACEROUTE6
  866. af = AF_UNSPEC;
  867. if (op & OPT_IPV4)
  868. af = AF_INET;
  869. if (op & OPT_IPV6)
  870. af = AF_INET6;
  871. dest_lsa = xhost_and_af2sockaddr(argv[0], port, af);
  872. af = dest_lsa->u.sa.sa_family;
  873. //TODO: make sure af == AF_INET[6]? (FEATURE_UNIX_LOCAL=y allows "local:/PATH" to be translated to AF_UNIX)
  874. if (af == AF_INET6) {
  875. G_ipv6 = 1;
  876. packlen = sizeof(struct ip6_hdr)
  877. + sizeof(struct udphdr)
  878. + sizeof(struct outdata6_t);
  879. if (op & OPT_USE_ICMP)
  880. packlen = sizeof(struct ip6_hdr)
  881. + SIZEOF_ICMP_HDR
  882. + sizeof(struct outdata6_t);
  883. }
  884. #else
  885. /* accept only IPv4 addresses */
  886. dest_lsa = xhost_and_af2sockaddr(argv[0], port, AF_INET);
  887. #endif
  888. G.from_lsa = xmemdup(dest_lsa, LSA_LEN_SIZE + dest_lsa->len);
  889. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  890. G.to = xzalloc(dest_lsa->len);
  891. #endif
  892. if (argv[1])
  893. packlen = xatoul_range(argv[1], packlen, 32 * 1024);
  894. if (af == AF_INET) {
  895. xmove_fd(xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP), rcvsock);
  896. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  897. /* want recvmsg to report target local address (for -v) */
  898. setsockopt_1(rcvsock, IPPROTO_IP, IP_PKTINFO);
  899. #endif
  900. }
  901. #if ENABLE_TRACEROUTE6
  902. else {
  903. xmove_fd(xsocket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6), rcvsock);
  904. # if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  905. /* want recvmsg to report target local address (for -v) */
  906. setsockopt_1(rcvsock, SOL_IPV6, IPV6_RECVPKTINFO);
  907. # endif
  908. }
  909. #endif
  910. #if TRACEROUTE_SO_DEBUG
  911. if (op & OPT_DEBUG)
  912. setsockopt_SOL_SOCKET_1(rcvsock, SO_DEBUG);
  913. #endif
  914. {
  915. int snd;
  916. if (af == AF_INET) {
  917. if (op & OPT_USE_ICMP)
  918. snd = xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  919. else
  920. snd = xsocket(AF_INET, SOCK_DGRAM, 0);
  921. }
  922. #if ENABLE_TRACEROUTE6
  923. else {
  924. if (setsockopt_int(rcvsock, SOL_RAW, IPV6_CHECKSUM, 2) != 0)
  925. bb_perror_msg_and_die("setsockopt(%s)", "IPV6_CHECKSUM");
  926. if (op & OPT_USE_ICMP)
  927. snd = xsocket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
  928. else
  929. snd = xsocket(AF_INET6, SOCK_DGRAM, 0);
  930. }
  931. #endif
  932. xmove_fd(snd, sndsock);
  933. }
  934. #ifdef SO_SNDBUF
  935. if (setsockopt_SOL_SOCKET_int(sndsock, SO_SNDBUF, packlen) != 0) {
  936. bb_perror_msg_and_die("setsockopt(%s)", "SO_SNDBUF");
  937. }
  938. #endif
  939. #ifdef IP_TOS
  940. if (op & OPT_TOS) {
  941. int tos = xatou_range(tos_str, 0, 255);
  942. if (setsockopt_int(sndsock, IPPROTO_IP, IP_TOS, tos) != 0)
  943. bb_perror_msg_and_die("setsockopt(%s,%d)", "TOS", tos);
  944. }
  945. #endif
  946. #ifdef IP_DONTFRAG
  947. if (op & OPT_DONT_FRAGMNT)
  948. setsockopt_1(sndsock, IPPROTO_IP, IP_DONTFRAG);
  949. #endif
  950. #if TRACEROUTE_SO_DEBUG
  951. if (op & OPT_DEBUG)
  952. setsockopt_SOL_SOCKET_1(sndsock, SO_DEBUG);
  953. #endif
  954. if (op & OPT_BYPASS_ROUTE)
  955. setsockopt_SOL_SOCKET_1(sndsock, SO_DONTROUTE);
  956. outip = xzalloc(packlen);
  957. ident = getpid();
  958. /* we can use native-endian ident, but other Unix ping/traceroute
  959. * utils use *big-endian pid*, and e.g. ping on our machine may be
  960. * *not* from busybox, idents may collide. Follow the convention:
  961. */
  962. ident = htons(ident);
  963. outdata = (void*)(outudp + 1);
  964. if (af == AF_INET) {
  965. if (op & OPT_USE_ICMP) {
  966. outicmp->icmp_type = ICMP_ECHO;
  967. /*outicmp->icmp_code = 0; - set by xzalloc */
  968. outicmp->icmp_id = ident;
  969. outdata = (void*)((char *)outicmp + SIZEOF_ICMP_HDR);
  970. }
  971. }
  972. #if ENABLE_TRACEROUTE6
  973. else {
  974. outdata = (void*)(outudp6 + 1);
  975. if (op & OPT_USE_ICMP) {
  976. outicmp6->icmp_type = ICMP6_ECHO_REQUEST;
  977. /*outicmp->icmp_code = 0; - set by xzalloc */
  978. outicmp6->icmp_id = ident;
  979. outdata = (void*)((char *)outicmp6 + SIZEOF_ICMP_HDR);
  980. }
  981. }
  982. #endif
  983. if (op & OPT_DEVICE) /* hmm, do we need error check? */
  984. setsockopt_bindtodevice(sndsock, device);
  985. if (op & OPT_SOURCE) {
  986. #if ENABLE_TRACEROUTE6
  987. // TODO: need xdotted_and_af2sockaddr?
  988. len_and_sockaddr *source_lsa = xhost_and_af2sockaddr(source, 0, af);
  989. #else
  990. len_and_sockaddr *source_lsa = xdotted2sockaddr(source, 0);
  991. #endif
  992. if (getuid() != 0)
  993. bb_simple_error_msg_and_die(bb_msg_you_must_be_root);
  994. /* Ping4 does this (why?) */
  995. if (af == AF_INET)
  996. if (setsockopt(sndsock, IPPROTO_IP, IP_MULTICAST_IF,
  997. &source_lsa->u.sa, source_lsa->len))
  998. bb_simple_error_msg_and_die("can't set multicast source interface");
  999. //TODO: we can query source port we bound to,
  1000. // and check it in replies... if we care enough
  1001. xbind(sndsock, &source_lsa->u.sa, source_lsa->len);
  1002. if (ENABLE_FEATURE_CLEAN_UP)
  1003. free(source_lsa);
  1004. } else {
  1005. len_and_sockaddr *source_lsa;
  1006. set_nport(&dest_lsa->u.sa, htons(port));
  1007. /* Connect makes kernel pick source IP (and port if UDP) */
  1008. xconnect(sndsock, &dest_lsa->u.sa, dest_lsa->len);
  1009. /* Read IP and port */
  1010. source_lsa = get_sock_lsa(sndsock);
  1011. if (source_lsa == NULL)
  1012. bb_simple_perror_msg_and_die("getsockname");
  1013. /* bind our recv ICMP socket to this IP (but not port, ICMP has no ports) */
  1014. //set_nport(&source_lsa->u.sa, 0); - paranoia, seems to work without this for both ipv4 and ipv6
  1015. xbind(rcvsock, &source_lsa->u.sa, source_lsa->len);
  1016. if (ENABLE_FEATURE_CLEAN_UP)
  1017. free(source_lsa);
  1018. }
  1019. /* Revert to non-privileged user after opening sockets */
  1020. xsetgid(getgid());
  1021. xsetuid(getuid());
  1022. dest_str = xmalloc_sockaddr2dotted_noport(&dest_lsa->u.sa);
  1023. printf("traceroute to %s (%s)", argv[0], dest_str);
  1024. if (ENABLE_FEATURE_CLEAN_UP)
  1025. free(dest_str);
  1026. if (op & OPT_SOURCE)
  1027. printf(" from %s", source);
  1028. printf(", %d hops max, %d byte packets\n", G.max_ttl, packlen);
  1029. }
  1030. static int
  1031. common_traceroute_main(int op, char **argv)
  1032. {
  1033. int ttl;
  1034. int seq;
  1035. struct sockaddr *lastaddr;
  1036. traceroute_init(op, argv);
  1037. lastaddr = xzalloc(dest_lsa->len);
  1038. seq = 0;
  1039. for (ttl = G.first_ttl; ttl <= G.max_ttl; ++ttl) {
  1040. int probe;
  1041. int unreachable = 0; /* counter */
  1042. int got_there = 0;
  1043. printf("%2d", ttl);
  1044. for (probe = 0; probe < G.nprobes; ++probe) {
  1045. unsigned t1;
  1046. unsigned t2;
  1047. int left_ms;
  1048. int read_len;
  1049. int icmp_code;
  1050. fflush_all();
  1051. if (probe != 0)
  1052. msleep(G.pausemsecs);
  1053. send_probe(++seq, ttl);
  1054. t2 = t1 = monotonic_us();
  1055. left_ms = waittime * 1000;
  1056. for (;;) {
  1057. /* NB: wait_for_reply() fills "G.from_lsa" and "G.to" with
  1058. * "where it came from" and "what local address it arrived to"
  1059. * addresses. Sets t2 = monotonic_us(), updates left_ms.
  1060. */
  1061. read_len = wait_for_reply(&t2, &left_ms);
  1062. if (read_len == 0) { /* there was no packet at all? */
  1063. printf(" *");
  1064. goto next_probe;
  1065. }
  1066. icmp_code = packet_ok(read_len, seq);
  1067. if (icmp_code != 0)
  1068. break; /* got a good response */
  1069. /* unrecognized type/code or too short, back to recv */
  1070. }
  1071. if (probe == 0
  1072. || (memcmp(lastaddr, &G.from_lsa->u.sa, G.from_lsa->len) != 0)
  1073. ) {
  1074. print(read_len);
  1075. memcpy(lastaddr, &G.from_lsa->u.sa, G.from_lsa->len);
  1076. }
  1077. print_delta_ms(t1, t2);
  1078. if (!G_ipv6) {
  1079. if (op & OPT_TTL_FLAG) {
  1080. struct ip *ip = (struct ip *)recv_pkt;
  1081. printf(" (%d)", ip->ip_ttl);
  1082. }
  1083. }
  1084. /* Got a "time exceeded in transit" icmp message? */
  1085. if (icmp_code == -1)
  1086. continue;
  1087. icmp_code--;
  1088. switch (icmp_code) {
  1089. #if ENABLE_TRACEROUTE6
  1090. case ICMP6_DST_UNREACH_NOPORT << 8:
  1091. got_there = 1;
  1092. break;
  1093. #endif
  1094. case ICMP_UNREACH_PORT: {
  1095. struct ip *ip = (struct ip *)recv_pkt;
  1096. if (ip->ip_ttl <= 1)
  1097. printf(" !");
  1098. got_there = 1;
  1099. break;
  1100. }
  1101. case ICMP_UNREACH_NET:
  1102. #if ENABLE_TRACEROUTE6 && (ICMP6_DST_UNREACH_NOROUTE != ICMP_UNREACH_NET)
  1103. case ICMP6_DST_UNREACH_NOROUTE << 8:
  1104. #endif
  1105. printf(" !N");
  1106. ++unreachable;
  1107. break;
  1108. case ICMP_UNREACH_HOST:
  1109. #if ENABLE_TRACEROUTE6
  1110. case ICMP6_DST_UNREACH_ADDR << 8:
  1111. #endif
  1112. printf(" !H");
  1113. ++unreachable;
  1114. break;
  1115. case ICMP_UNREACH_PROTOCOL:
  1116. printf(" !P");
  1117. got_there = 1;
  1118. break;
  1119. case ICMP_UNREACH_NEEDFRAG:
  1120. printf(" !F-%d", pmtu);
  1121. ++unreachable;
  1122. break;
  1123. case ICMP_UNREACH_SRCFAIL:
  1124. #if ENABLE_TRACEROUTE6
  1125. case ICMP6_DST_UNREACH_ADMIN << 8:
  1126. #endif
  1127. printf(" !S");
  1128. ++unreachable;
  1129. break;
  1130. case ICMP_UNREACH_FILTER_PROHIB:
  1131. case ICMP_UNREACH_NET_PROHIB: /* misuse */
  1132. printf(" !A");
  1133. ++unreachable;
  1134. break;
  1135. case ICMP_UNREACH_HOST_PROHIB:
  1136. printf(" !C");
  1137. ++unreachable;
  1138. break;
  1139. case ICMP_UNREACH_HOST_PRECEDENCE:
  1140. printf(" !V");
  1141. ++unreachable;
  1142. break;
  1143. case ICMP_UNREACH_PRECEDENCE_CUTOFF:
  1144. printf(" !C");
  1145. ++unreachable;
  1146. break;
  1147. case ICMP_UNREACH_NET_UNKNOWN:
  1148. case ICMP_UNREACH_HOST_UNKNOWN:
  1149. printf(" !U");
  1150. ++unreachable;
  1151. break;
  1152. case ICMP_UNREACH_ISOLATED:
  1153. printf(" !I");
  1154. ++unreachable;
  1155. break;
  1156. case ICMP_UNREACH_TOSNET:
  1157. case ICMP_UNREACH_TOSHOST:
  1158. printf(" !T");
  1159. ++unreachable;
  1160. break;
  1161. default:
  1162. printf(" !<%d>", icmp_code);
  1163. ++unreachable;
  1164. break;
  1165. }
  1166. next_probe: ;
  1167. } /* for (nprobes) */
  1168. bb_putchar('\n');
  1169. if (got_there
  1170. || (unreachable > 0 && unreachable >= G.nprobes - 1)
  1171. ) {
  1172. break;
  1173. }
  1174. }
  1175. if (ENABLE_FEATURE_CLEAN_UP) {
  1176. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  1177. free(G.to);
  1178. #endif
  1179. free(lastaddr);
  1180. free(G.from_lsa);
  1181. }
  1182. return 0;
  1183. }
  1184. #if ENABLE_TRACEROUTE
  1185. int traceroute_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1186. int traceroute_main(int argc UNUSED_PARAM, char **argv)
  1187. {
  1188. return common_traceroute_main(0, argv);
  1189. }
  1190. #endif
  1191. #if ENABLE_TRACEROUTE6
  1192. int traceroute6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1193. int traceroute6_main(int argc UNUSED_PARAM, char **argv)
  1194. {
  1195. return common_traceroute_main(OPT_IPV6, argv);
  1196. }
  1197. #endif