3
0

traceroute.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. * traceroute host - trace the route ip packets follow going to "host".
  26. *
  27. * Attempt to trace the route an ip packet would follow to some
  28. * internet host. We find out intermediate hops by launching probe
  29. * packets with a small ttl (time to live) then listening for an
  30. * icmp "time exceeded" reply from a gateway. We start our probes
  31. * with a ttl of one and increase by one until we get an icmp "port
  32. * unreachable" (which means we got to "host") or hit a max (which
  33. * defaults to 30 hops & can be changed with the -m flag). Three
  34. * probes (change with -q flag) are sent at each ttl setting and a
  35. * line is printed showing the ttl, address of the gateway and
  36. * round trip time of each probe. If the probe answers come from
  37. * different gateways, the address of each responding system will
  38. * be printed. If there is no response within a 5 sec. timeout
  39. * interval (changed with the -w flag), a "*" is printed for that
  40. * probe.
  41. *
  42. * Probe packets are UDP format. We don't want the destination
  43. * host to process them so the destination port is set to an
  44. * unlikely value (if some clod on the destination is using that
  45. * value, it can be changed with the -p flag).
  46. *
  47. * A sample use might be:
  48. *
  49. * [yak 71]% traceroute nis.nsf.net.
  50. * traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
  51. * 1 helios.ee.lbl.gov (128.3.112.1) 19 ms 19 ms 0 ms
  52. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
  53. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
  54. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 39 ms
  55. * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 39 ms 39 ms 39 ms
  56. * 6 128.32.197.4 (128.32.197.4) 40 ms 59 ms 59 ms
  57. * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 59 ms
  58. * 8 129.140.70.13 (129.140.70.13) 99 ms 99 ms 80 ms
  59. * 9 129.140.71.6 (129.140.71.6) 139 ms 239 ms 319 ms
  60. * 10 129.140.81.7 (129.140.81.7) 220 ms 199 ms 199 ms
  61. * 11 nic.merit.edu (35.1.1.48) 239 ms 239 ms 239 ms
  62. *
  63. * Note that lines 2 & 3 are the same. This is due to a buggy
  64. * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
  65. * packets with a zero ttl.
  66. *
  67. * A more interesting example is:
  68. *
  69. * [yak 72]% traceroute allspice.lcs.mit.edu.
  70. * traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
  71. * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
  72. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 19 ms 19 ms
  73. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 19 ms
  74. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 19 ms 39 ms 39 ms
  75. * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 20 ms 39 ms 39 ms
  76. * 6 128.32.197.4 (128.32.197.4) 59 ms 119 ms 39 ms
  77. * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 39 ms
  78. * 8 129.140.70.13 (129.140.70.13) 80 ms 79 ms 99 ms
  79. * 9 129.140.71.6 (129.140.71.6) 139 ms 139 ms 159 ms
  80. * 10 129.140.81.7 (129.140.81.7) 199 ms 180 ms 300 ms
  81. * 11 129.140.72.17 (129.140.72.17) 300 ms 239 ms 239 ms
  82. * 12 * * *
  83. * 13 128.121.54.72 (128.121.54.72) 259 ms 499 ms 279 ms
  84. * 14 * * *
  85. * 15 * * *
  86. * 16 * * *
  87. * 17 * * *
  88. * 18 ALLSPICE.LCS.MIT.EDU (18.26.0.115) 339 ms 279 ms 279 ms
  89. *
  90. * (I start to see why I'm having so much trouble with mail to
  91. * MIT.) Note that the gateways 12, 14, 15, 16 & 17 hops away
  92. * either don't send ICMP "time exceeded" messages or send them
  93. * with a ttl too small to reach us. 14 - 17 are running the
  94. * MIT C Gateway code that doesn't send "time exceeded"s. God
  95. * only knows what's going on with 12.
  96. *
  97. * The silent gateway 12 in the above may be the result of a bug in
  98. * the 4.[23]BSD network code (and its derivatives): 4.x (x <= 3)
  99. * sends an unreachable message using whatever ttl remains in the
  100. * original datagram. Since, for gateways, the remaining ttl is
  101. * zero, the icmp "time exceeded" is guaranteed to not make it back
  102. * to us. The behavior of this bug is slightly more interesting
  103. * when it appears on the destination system:
  104. *
  105. * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
  106. * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 39 ms
  107. * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 39 ms 19 ms
  108. * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 19 ms
  109. * 5 ccn-nerif35.Berkeley.EDU (128.32.168.35) 39 ms 39 ms 39 ms
  110. * 6 csgw.Berkeley.EDU (128.32.133.254) 39 ms 59 ms 39 ms
  111. * 7 * * *
  112. * 8 * * *
  113. * 9 * * *
  114. * 10 * * *
  115. * 11 * * *
  116. * 12 * * *
  117. * 13 rip.Berkeley.EDU (128.32.131.22) 59 ms ! 39 ms ! 39 ms !
  118. *
  119. * Notice that there are 12 "gateways" (13 is the final
  120. * destination) and exactly the last half of them are "missing".
  121. * What's really happening is that rip (a Sun-3 running Sun OS3.5)
  122. * is using the ttl from our arriving datagram as the ttl in its
  123. * icmp reply. So, the reply will time out on the return path
  124. * (with no notice sent to anyone since icmp's aren't sent for
  125. * icmp's) until we probe with a ttl that's at least twice the path
  126. * length. I.e., rip is really only 7 hops away. A reply that
  127. * returns with a ttl of 1 is a clue this problem exists.
  128. * Traceroute prints a "!" after the time if the ttl is <= 1.
  129. * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
  130. * non-standard (HPUX) software, expect to see this problem
  131. * frequently and/or take care picking the target host of your
  132. * probes.
  133. *
  134. * Other possible annotations after the time are !H, !N, !P (got a host,
  135. * network or protocol unreachable, respectively), !S or !F (source
  136. * route failed or fragmentation needed -- neither of these should
  137. * ever occur and the associated gateway is busted if you see one). If
  138. * almost all the probes result in some kind of unreachable, traceroute
  139. * will give up and exit.
  140. *
  141. * Notes
  142. * -----
  143. * This program must be run by root or be setuid. (I suggest that
  144. * you *don't* make it setuid -- casual use could result in a lot
  145. * of unnecessary traffic on our poor, congested nets.)
  146. *
  147. * This program requires a kernel mod that does not appear in any
  148. * system available from Berkeley: A raw ip socket using proto
  149. * IPPROTO_RAW must interpret the data sent as an ip datagram (as
  150. * opposed to data to be wrapped in a ip datagram). See the README
  151. * file that came with the source to this program for a description
  152. * of the mods I made to /sys/netinet/raw_ip.c. Your mileage may
  153. * vary. But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
  154. * MODIFIED TO RUN THIS PROGRAM.
  155. *
  156. * The udp port usage may appear bizarre (well, ok, it is bizarre).
  157. * The problem is that an icmp message only contains 8 bytes of
  158. * data from the original datagram. 8 bytes is the size of a udp
  159. * header so, if we want to associate replies with the original
  160. * datagram, the necessary information must be encoded into the
  161. * udp header (the ip id could be used but there's no way to
  162. * interlock with the kernel's assignment of ip id's and, anyway,
  163. * it would have taken a lot more kernel hacking to allow this
  164. * code to set the ip id). So, to allow two or more users to
  165. * use traceroute simultaneously, we use this task's pid as the
  166. * source port (the high bit is set to move the port number out
  167. * of the "likely" range). To keep track of which probe is being
  168. * replied to (so times and/or hop counts don't get confused by a
  169. * reply that was delayed in transit), we increment the destination
  170. * port number before each probe.
  171. *
  172. * Don't use this as a coding example. I was trying to find a
  173. * routing problem and this code sort-of popped out after 48 hours
  174. * without sleep. I was amazed it ever compiled, much less ran.
  175. *
  176. * I stole the idea for this program from Steve Deering. Since
  177. * the first release, I've learned that had I attended the right
  178. * IETF working group meetings, I also could have stolen it from Guy
  179. * Almes or Matt Mathis. I don't know (or care) who came up with
  180. * the idea first. I envy the originators' perspicacity and I'm
  181. * glad they didn't keep the idea a secret.
  182. *
  183. * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
  184. * enhancements to the original distribution.
  185. *
  186. * I've hacked up a round-trip-route version of this that works by
  187. * sending a loose-source-routed udp datagram through the destination
  188. * back to yourself. Unfortunately, SO many gateways botch source
  189. * routing, the thing is almost worthless. Maybe one day...
  190. *
  191. * -- Van Jacobson (van@ee.lbl.gov)
  192. * Tue Dec 20 03:50:13 PST 1988
  193. */
  194. #define TRACEROUTE_SO_DEBUG 0
  195. /* TODO: undefs were uncommented - ??! we have config system for that! */
  196. /* probably ok to remove altogether */
  197. //#undef CONFIG_FEATURE_TRACEROUTE_VERBOSE
  198. //#define CONFIG_FEATURE_TRACEROUTE_VERBOSE
  199. //#undef CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE
  200. //#define CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE
  201. //#undef CONFIG_FEATURE_TRACEROUTE_USE_ICMP
  202. //#define CONFIG_FEATURE_TRACEROUTE_USE_ICMP
  203. #include <net/if.h>
  204. #include <arpa/inet.h>
  205. #include <netinet/in.h>
  206. #include <netinet/udp.h>
  207. #include <netinet/ip.h>
  208. #include <netinet/ip_icmp.h>
  209. #include "libbb.h"
  210. #include "inet_common.h"
  211. /*
  212. * Definitions for internet protocol version 4.
  213. * Per RFC 791, September 1981.
  214. */
  215. #define IPVERSION 4
  216. #ifndef IPPROTO_ICMP
  217. /* Grrrr.... */
  218. #define IPPROTO_ICMP 1
  219. #endif
  220. #ifndef IPPROTO_IP
  221. #define IPPROTO_IP 0
  222. #endif
  223. /*
  224. * Overlay for ip header used by other protocols (tcp, udp).
  225. */
  226. struct ipovly {
  227. unsigned char ih_x1[9]; /* (unused) */
  228. unsigned char ih_pr; /* protocol */
  229. short ih_len; /* protocol length */
  230. struct in_addr ih_src; /* source internet address */
  231. struct in_addr ih_dst; /* destination internet address */
  232. };
  233. /*
  234. * UDP kernel structures and variables.
  235. */
  236. struct udpiphdr {
  237. struct ipovly ui_i; /* overlaid ip structure */
  238. struct udphdr ui_u; /* udp header */
  239. };
  240. #define ui_next ui_i.ih_next
  241. #define ui_prev ui_i.ih_prev
  242. #define ui_x1 ui_i.ih_x1
  243. #define ui_pr ui_i.ih_pr
  244. #define ui_len ui_i.ih_len
  245. #define ui_src ui_i.ih_src
  246. #define ui_dst ui_i.ih_dst
  247. #define ui_sport ui_u.uh_sport
  248. #define ui_dport ui_u.uh_dport
  249. #define ui_ulen ui_u.uh_ulen
  250. #define ui_sum ui_u.uh_sum
  251. /* Host name and address list */
  252. struct hostinfo {
  253. char *name;
  254. int n;
  255. uint32_t *addrs;
  256. };
  257. /* Data section of the probe packet */
  258. typedef struct outdata {
  259. unsigned char seq; /* sequence number of this packet */
  260. unsigned char ttl; /* ttl packet left with */
  261. // UNUSED. Retaining to have the same packet size.
  262. struct timeval tv_UNUSED PACKED; /* time packet left */
  263. } outdata_t;
  264. struct IFADDRLIST {
  265. uint32_t addr;
  266. char device[sizeof(struct ifreq)];
  267. };
  268. /* Keep in sync with getopt32 call! */
  269. #define OPT_DONT_FRAGMNT (1<<0) /* F */
  270. #define OPT_USE_ICMP (1<<1) /* I */
  271. #define OPT_TTL_FLAG (1<<2) /* l */
  272. #define OPT_ADDR_NUM (1<<3) /* n */
  273. #define OPT_BYPASS_ROUTE (1<<4) /* r */
  274. #define OPT_DEBUG (1<<5) /* d */
  275. #define OPT_VERBOSE (1<<6) /* v */
  276. #define OPT_IP_CHKSUM (1<<7) /* x */
  277. #define OPT_TOS (1<<8) /* t */
  278. #define OPT_DEVICE (1<<9) /* i */
  279. #define OPT_MAX_TTL (1<<10) /* m */
  280. #define OPT_PORT (1<<11) /* p */
  281. #define OPT_NPROBES (1<<12) /* q */
  282. #define OPT_SOURCE (1<<13) /* s */
  283. #define OPT_WAITTIME (1<<14) /* w */
  284. #define OPT_PAUSE_MS (1<<15) /* z */
  285. #define OPT_FIRST_TTL (1<<16) /* f */
  286. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  287. /* use icmp echo instead of udp packets */
  288. #define useicmp (option_mask32 & OPT_USE_ICMP)
  289. #endif
  290. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  291. #define verbose (option_mask32 & OPT_VERBOSE)
  292. #endif
  293. #define nflag (option_mask32 & OPT_ADDR_NUM)
  294. struct globals {
  295. struct ip *outip; /* last output (udp) packet */
  296. struct udphdr *outudp; /* last output (udp) packet */
  297. struct outdata *outdata; /* last output (udp) packet */
  298. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  299. struct icmp *outicmp; /* last output (icmp) packet */
  300. #endif
  301. int rcvsock; /* receive (icmp) socket file descriptor */
  302. int sndsock; /* send (udp/icmp) socket file descriptor */
  303. int packlen; /* total length of packet */
  304. int minpacket; /* min ip packet size */
  305. int maxpacket; // 32 * 1024; /* max ip packet size */
  306. int pmtu; /* Path MTU Discovery (RFC1191) */
  307. char *hostname;
  308. uint16_t ident;
  309. uint16_t port; // 32768 + 666; /* start udp dest port # for probe packets */
  310. int waittime; // 5; /* time to wait for response (in seconds) */
  311. int doipcksum; // 1; /* calculate ip checksums by default */
  312. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  313. int optlen; /* length of ip options */
  314. #else
  315. #define optlen 0
  316. #endif
  317. struct sockaddr_storage whereto; /* Who to try to reach */
  318. struct sockaddr_storage wherefrom; /* Who we are */
  319. /* last inbound (icmp) packet */
  320. unsigned char packet[512];
  321. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  322. /* Maximum number of gateways (include room for one noop) */
  323. #define NGATEWAYS ((int)((MAX_IPOPTLEN - IPOPT_MINOFF - 1) / sizeof(uint32_t)))
  324. /* loose source route gateway list (including room for final destination) */
  325. uint32_t gwlist[NGATEWAYS + 1];
  326. #endif
  327. };
  328. #define G (*ptr_to_globals)
  329. #define outip (G.outip )
  330. #define outudp (G.outudp )
  331. #define outdata (G.outdata )
  332. #define outicmp (G.outicmp )
  333. #define rcvsock (G.rcvsock )
  334. #define sndsock (G.sndsock )
  335. #define packlen (G.packlen )
  336. #define minpacket (G.minpacket)
  337. #define maxpacket (G.maxpacket)
  338. #define pmtu (G.pmtu )
  339. #define hostname (G.hostname )
  340. #define ident (G.ident )
  341. #define port (G.port )
  342. #define waittime (G.waittime )
  343. #define doipcksum (G.doipcksum)
  344. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  345. #define optlen (G.optlen )
  346. #endif
  347. #define packet (G.packet )
  348. #define whereto (G.whereto )
  349. #define wherefrom (G.wherefrom)
  350. #define gwlist (G.gwlist )
  351. #define INIT_G() do { \
  352. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  353. maxpacket = 32 * 1024; \
  354. port = 32768 + 666; \
  355. waittime = 5; \
  356. doipcksum = 1; \
  357. } while (0)
  358. /*
  359. * Return the interface list
  360. */
  361. static int
  362. ifaddrlist(struct IFADDRLIST **ipaddrp)
  363. {
  364. enum { IFREQ_BUFSIZE = (32 * 1024) / sizeof(struct ifreq) };
  365. int fd, nipaddr;
  366. #ifdef HAVE_SOCKADDR_SA_LEN
  367. int n;
  368. #endif
  369. struct ifreq *ifrp, *ifend, *ifnext;
  370. struct sockaddr_in *addr_sin;
  371. struct IFADDRLIST *al;
  372. struct ifconf ifc;
  373. struct ifreq ifr;
  374. /* Was on stack, but 32k is a bit too much: */
  375. struct ifreq *ibuf = xmalloc(IFREQ_BUFSIZE * sizeof(ibuf[0]));
  376. struct IFADDRLIST *st_ifaddrlist;
  377. fd = xsocket(AF_INET, SOCK_DGRAM, 0);
  378. ifc.ifc_len = IFREQ_BUFSIZE * sizeof(ibuf[0]);
  379. ifc.ifc_buf = (caddr_t)ibuf;
  380. if (ioctl(fd, SIOCGIFCONF, (char *)&ifc) < 0
  381. || ifc.ifc_len < (int)sizeof(struct ifreq)
  382. ) {
  383. if (errno == EINVAL)
  384. bb_error_msg_and_die(
  385. "SIOCGIFCONF: ifreq struct too small (%u bytes)",
  386. (unsigned)(IFREQ_BUFSIZE * sizeof(ibuf[0])));
  387. bb_perror_msg_and_die("SIOCGIFCONF");
  388. }
  389. ifrp = ibuf;
  390. ifend = (struct ifreq *)((char *)ibuf + ifc.ifc_len);
  391. nipaddr = 1 + (ifc.ifc_len / sizeof(struct ifreq));
  392. st_ifaddrlist = xzalloc(nipaddr * sizeof(struct IFADDRLIST));
  393. al = st_ifaddrlist;
  394. nipaddr = 0;
  395. for (; ifrp < ifend; ifrp = ifnext) {
  396. #ifdef HAVE_SOCKADDR_SA_LEN
  397. n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
  398. if (n < sizeof(*ifrp))
  399. ifnext = ifrp + 1;
  400. else
  401. ifnext = (struct ifreq *)((char *)ifrp + n);
  402. if (ifrp->ifr_addr.sa_family != AF_INET)
  403. continue;
  404. #else
  405. ifnext = ifrp + 1;
  406. #endif
  407. /*
  408. * Need a template to preserve address info that is
  409. * used below to locate the next entry. (Otherwise,
  410. * SIOCGIFFLAGS stomps over it because the requests
  411. * are returned in a union.)
  412. */
  413. strncpy(ifr.ifr_name, ifrp->ifr_name, sizeof(ifr.ifr_name));
  414. if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
  415. if (errno == ENXIO)
  416. continue;
  417. bb_perror_msg_and_die("SIOCGIFFLAGS: %.*s",
  418. (int)sizeof(ifr.ifr_name), ifr.ifr_name);
  419. }
  420. /* Must be up */
  421. if ((ifr.ifr_flags & IFF_UP) == 0)
  422. continue;
  423. safe_strncpy(al->device, ifr.ifr_name, sizeof(ifr.ifr_name) + 1);
  424. #ifdef sun
  425. /* Ignore sun virtual interfaces */
  426. if (strchr(al->device, ':') != NULL)
  427. continue;
  428. #endif
  429. ioctl_or_perror_and_die(fd, SIOCGIFADDR, (char *)&ifr,
  430. "SIOCGIFADDR: %s", al->device);
  431. addr_sin = (struct sockaddr_in *)&ifr.ifr_addr;
  432. al->addr = addr_sin->sin_addr.s_addr;
  433. ++al;
  434. ++nipaddr;
  435. }
  436. if (nipaddr == 0)
  437. bb_error_msg_and_die("can't find any network interfaces");
  438. free(ibuf);
  439. close(fd);
  440. *ipaddrp = st_ifaddrlist;
  441. return nipaddr;
  442. }
  443. static void
  444. setsin(struct sockaddr_in *addr_sin, uint32_t addr)
  445. {
  446. memset(addr_sin, 0, sizeof(*addr_sin));
  447. #ifdef HAVE_SOCKADDR_SA_LEN
  448. addr_sin->sin_len = sizeof(*addr_sin);
  449. #endif
  450. addr_sin->sin_family = AF_INET;
  451. addr_sin->sin_addr.s_addr = addr;
  452. }
  453. /*
  454. * Return the source address for the given destination address
  455. */
  456. static void
  457. findsaddr(const struct sockaddr_in *to, struct sockaddr_in *from)
  458. {
  459. int i, n;
  460. FILE *f;
  461. uint32_t mask;
  462. uint32_t dest, tmask;
  463. struct IFADDRLIST *al;
  464. char buf[256], tdevice[256], device[256];
  465. f = xfopen_for_read("/proc/net/route");
  466. /* Find the appropriate interface */
  467. n = 0;
  468. mask = 0;
  469. device[0] = '\0';
  470. while (fgets(buf, sizeof(buf), f) != NULL) {
  471. ++n;
  472. if (n == 1 && strncmp(buf, "Iface", 5) == 0)
  473. continue;
  474. i = sscanf(buf, "%255s %x %*s %*s %*s %*s %*s %x",
  475. tdevice, &dest, &tmask);
  476. if (i != 3)
  477. bb_error_msg_and_die("junk in buffer");
  478. if ((to->sin_addr.s_addr & tmask) == dest
  479. && (tmask > mask || mask == 0)
  480. ) {
  481. mask = tmask;
  482. strcpy(device, tdevice);
  483. }
  484. }
  485. fclose(f);
  486. if (device[0] == '\0')
  487. bb_error_msg_and_die("can't find interface");
  488. /* Get the interface address list */
  489. n = ifaddrlist(&al);
  490. /* Find our appropriate source address */
  491. for (i = n; i > 0; --i, ++al)
  492. if (strcmp(device, al->device) == 0)
  493. break;
  494. if (i <= 0)
  495. bb_error_msg_and_die("can't find interface %s", device);
  496. setsin(from, al->addr);
  497. }
  498. /*
  499. "Usage: %s [-dFIlnrvx] [-g gateway] [-i iface] [-f first_ttl]\n"
  500. "\t[-m max_ttl] [ -p port] [-q nqueries] [-s src_addr] [-t tos]\n"
  501. "\t[-w waittime] [-z pausemsecs] host [packetlen]"
  502. */
  503. static int
  504. wait_for_reply(int sock, struct sockaddr_in *fromp)
  505. {
  506. struct pollfd pfd[1];
  507. int cc = 0;
  508. socklen_t fromlen = sizeof(*fromp);
  509. pfd[0].fd = sock;
  510. pfd[0].events = POLLIN;
  511. if (safe_poll(pfd, 1, waittime * 1000) > 0)
  512. cc = recvfrom(sock, packet, sizeof(packet), 0,
  513. (struct sockaddr *)fromp, &fromlen);
  514. return cc;
  515. }
  516. /*
  517. * Checksum routine for Internet Protocol family headers (C Version)
  518. */
  519. static uint16_t
  520. in_cksum(uint16_t *addr, int len)
  521. {
  522. int nleft = len;
  523. uint16_t *w = addr;
  524. uint16_t answer;
  525. int sum = 0;
  526. /*
  527. * Our algorithm is simple, using a 32 bit accumulator (sum),
  528. * we add sequential 16 bit words to it, and at the end, fold
  529. * back all the carry bits from the top 16 bits into the lower
  530. * 16 bits.
  531. */
  532. while (nleft > 1) {
  533. sum += *w++;
  534. nleft -= 2;
  535. }
  536. /* mop up an odd byte, if necessary */
  537. if (nleft == 1)
  538. sum += *(unsigned char *)w;
  539. /*
  540. * add back carry outs from top 16 bits to low 16 bits
  541. */
  542. sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
  543. sum += (sum >> 16); /* add carry */
  544. answer = ~sum; /* truncate to 16 bits */
  545. return answer;
  546. }
  547. static void
  548. send_probe(int seq, int ttl)
  549. {
  550. int cc;
  551. struct udpiphdr *ui, *oui;
  552. struct ip tip;
  553. outip->ip_ttl = ttl;
  554. outip->ip_id = htons(ident + seq);
  555. /*
  556. * In most cases, the kernel will recalculate the ip checksum.
  557. * But we must do it anyway so that the udp checksum comes out
  558. * right.
  559. */
  560. if (doipcksum) {
  561. outip->ip_sum =
  562. in_cksum((uint16_t *)outip, sizeof(*outip) + optlen);
  563. if (outip->ip_sum == 0)
  564. outip->ip_sum = 0xffff;
  565. }
  566. /* Payload */
  567. outdata->seq = seq;
  568. outdata->ttl = ttl;
  569. // UNUSED: was storing gettimeofday's result there, but never ever checked it
  570. /*memcpy(&outdata->tv, tp, sizeof(outdata->tv));*/
  571. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  572. if (useicmp)
  573. outicmp->icmp_seq = htons(seq);
  574. else
  575. #endif
  576. outudp->dest = htons(port + seq);
  577. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  578. if (useicmp) {
  579. /* Always calculate checksum for icmp packets */
  580. outicmp->icmp_cksum = 0;
  581. outicmp->icmp_cksum = in_cksum((uint16_t *)outicmp,
  582. packlen - (sizeof(*outip) + optlen));
  583. if (outicmp->icmp_cksum == 0)
  584. outicmp->icmp_cksum = 0xffff;
  585. } else
  586. #endif
  587. if (doipcksum) {
  588. /* Checksum (we must save and restore ip header) */
  589. tip = *outip;
  590. ui = (struct udpiphdr *)outip;
  591. oui = (struct udpiphdr *)&tip;
  592. /* Easier to zero and put back things that are ok */
  593. memset((char *)ui, 0, sizeof(ui->ui_i));
  594. ui->ui_src = oui->ui_src;
  595. ui->ui_dst = oui->ui_dst;
  596. ui->ui_pr = oui->ui_pr;
  597. ui->ui_len = outudp->len;
  598. outudp->check = 0;
  599. outudp->check = in_cksum((uint16_t *)ui, packlen);
  600. if (outudp->check == 0)
  601. outudp->check = 0xffff;
  602. *outip = tip;
  603. }
  604. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  605. /* XXX undocumented debugging hack */
  606. if (verbose > 1) {
  607. const uint16_t *sp;
  608. int nshorts, i;
  609. sp = (uint16_t *)outip;
  610. nshorts = (unsigned)packlen / sizeof(uint16_t);
  611. i = 0;
  612. printf("[ %d bytes", packlen);
  613. while (--nshorts >= 0) {
  614. if ((i++ % 8) == 0)
  615. printf("\n\t");
  616. printf(" %04x", ntohs(*sp));
  617. sp++;
  618. }
  619. if (packlen & 1) {
  620. if ((i % 8) == 0)
  621. printf("\n\t");
  622. printf(" %02x", *(unsigned char *)sp);
  623. }
  624. printf("]\n");
  625. }
  626. #endif
  627. #if !defined(IP_HDRINCL) && defined(IP_TTL)
  628. if (setsockopt(sndsock, IPPROTO_IP, IP_TTL,
  629. (char *)&ttl, sizeof(ttl)) < 0) {
  630. bb_perror_msg_and_die("setsockopt ttl %d", ttl);
  631. }
  632. #endif
  633. cc = xsendto(sndsock, (char *)outip,
  634. packlen, (struct sockaddr *)&whereto, sizeof(whereto));
  635. if (cc != packlen) {
  636. bb_info_msg("wrote %s %d chars, ret=%d", hostname, packlen, cc);
  637. }
  638. }
  639. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  640. /*
  641. * Convert an ICMP "type" field to a printable string.
  642. */
  643. static inline const char *
  644. pr_type(unsigned char t)
  645. {
  646. static const char *const ttab[] = {
  647. "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
  648. "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
  649. "Echo", "Router Advert", "Router Solicit", "Time Exceeded",
  650. "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
  651. "Info Reply", "Mask Request", "Mask Reply"
  652. };
  653. if (t > 18)
  654. return "OUT-OF-RANGE";
  655. return ttab[t];
  656. }
  657. #endif
  658. #if !ENABLE_FEATURE_TRACEROUTE_VERBOSE
  659. #define packet_ok(buf, cc, from, seq) \
  660. packet_ok(buf, cc, seq)
  661. #endif
  662. static int
  663. packet_ok(unsigned char *buf, int cc, struct sockaddr_in *from, int seq)
  664. {
  665. struct icmp *icp;
  666. unsigned char type, code;
  667. int hlen;
  668. struct ip *ip;
  669. ip = (struct ip *) buf;
  670. hlen = ip->ip_hl << 2;
  671. if (cc < hlen + ICMP_MINLEN) {
  672. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  673. if (verbose)
  674. printf("packet too short (%d bytes) from %s\n", cc,
  675. inet_ntoa(from->sin_addr));
  676. #endif
  677. return 0;
  678. }
  679. cc -= hlen;
  680. icp = (struct icmp *)(buf + hlen);
  681. type = icp->icmp_type;
  682. code = icp->icmp_code;
  683. /* Path MTU Discovery (RFC1191) */
  684. if (code != ICMP_UNREACH_NEEDFRAG)
  685. pmtu = 0;
  686. else {
  687. pmtu = ntohs(icp->icmp_nextmtu);
  688. }
  689. if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS) ||
  690. type == ICMP_UNREACH || type == ICMP_ECHOREPLY) {
  691. struct ip *hip;
  692. struct udphdr *up;
  693. hip = &icp->icmp_ip;
  694. hlen = hip->ip_hl << 2;
  695. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  696. if (useicmp) {
  697. struct icmp *hicmp;
  698. /* XXX */
  699. if (type == ICMP_ECHOREPLY &&
  700. icp->icmp_id == htons(ident) &&
  701. icp->icmp_seq == htons(seq))
  702. return -2;
  703. hicmp = (struct icmp *)((unsigned char *)hip + hlen);
  704. /* XXX 8 is a magic number */
  705. if (hlen + 8 <= cc &&
  706. hip->ip_p == IPPROTO_ICMP &&
  707. hicmp->icmp_id == htons(ident) &&
  708. hicmp->icmp_seq == htons(seq))
  709. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  710. } else
  711. #endif
  712. {
  713. up = (struct udphdr *)((unsigned char *)hip + hlen);
  714. /* XXX 8 is a magic number */
  715. if (hlen + 12 <= cc &&
  716. hip->ip_p == IPPROTO_UDP &&
  717. up->source == htons(ident) &&
  718. up->dest == htons(port + seq))
  719. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  720. }
  721. }
  722. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  723. if (verbose) {
  724. int i;
  725. uint32_t *lp = (uint32_t *)&icp->icmp_ip;
  726. printf("\n%d bytes from %s to "
  727. "%s: icmp type %d (%s) code %d\n",
  728. cc, inet_ntoa(from->sin_addr),
  729. inet_ntoa(ip->ip_dst), type, pr_type(type), icp->icmp_code);
  730. for (i = 4; i < cc; i += sizeof(*lp))
  731. printf("%2d: x%8.8x\n", i, *lp++);
  732. }
  733. #endif
  734. return 0;
  735. }
  736. /*
  737. * Construct an Internet address representation.
  738. * If the nflag has been supplied, give
  739. * numeric value, otherwise try for symbolic name.
  740. */
  741. static void
  742. print_inetname(struct sockaddr_in *from)
  743. {
  744. const char *ina;
  745. ina = inet_ntoa(from->sin_addr);
  746. if (nflag)
  747. printf(" %s", ina);
  748. else {
  749. char *n = NULL;
  750. if (from->sin_addr.s_addr != INADDR_ANY)
  751. n = xmalloc_sockaddr2host_noport((struct sockaddr*)from);
  752. printf(" %s (%s)", (n ? n : ina), ina);
  753. free(n);
  754. }
  755. }
  756. static void
  757. print(unsigned char *buf, int cc, struct sockaddr_in *from)
  758. {
  759. struct ip *ip;
  760. int hlen;
  761. ip = (struct ip *) buf;
  762. hlen = ip->ip_hl << 2;
  763. cc -= hlen;
  764. print_inetname(from);
  765. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  766. if (verbose)
  767. printf(" %d bytes to %s", cc, inet_ntoa(ip->ip_dst));
  768. #endif
  769. }
  770. static struct hostinfo *
  771. gethostinfo(const char *host)
  772. {
  773. int n;
  774. struct hostent *hp;
  775. struct hostinfo *hi;
  776. char **p;
  777. uint32_t addr, *ap;
  778. hi = xzalloc(sizeof(*hi));
  779. addr = inet_addr(host);
  780. if (addr != 0xffffffff) {
  781. hi->name = xstrdup(host);
  782. hi->n = 1;
  783. hi->addrs = xzalloc(sizeof(hi->addrs[0]));
  784. hi->addrs[0] = addr;
  785. return hi;
  786. }
  787. hp = xgethostbyname(host);
  788. if (hp->h_addrtype != AF_INET || hp->h_length != 4)
  789. bb_perror_msg_and_die("bad host %s", host);
  790. hi->name = xstrdup(hp->h_name);
  791. for (n = 0, p = hp->h_addr_list; *p != NULL; ++n, ++p)
  792. continue;
  793. hi->n = n;
  794. hi->addrs = xzalloc(n * sizeof(hi->addrs[0]));
  795. for (ap = hi->addrs, p = hp->h_addr_list; *p != NULL; ++ap, ++p)
  796. memcpy(ap, *p, sizeof(*ap));
  797. return hi;
  798. }
  799. static void
  800. freehostinfo(struct hostinfo *hi)
  801. {
  802. free(hi->name);
  803. free(hi->addrs);
  804. free(hi);
  805. }
  806. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  807. static void
  808. getaddr(uint32_t *ap, const char *host)
  809. {
  810. struct hostinfo *hi;
  811. hi = gethostinfo(host);
  812. *ap = hi->addrs[0];
  813. freehostinfo(hi);
  814. }
  815. #endif
  816. static void
  817. print_delta_ms(unsigned t1p, unsigned t2p)
  818. {
  819. unsigned tt = t2p - t1p;
  820. printf(" %u.%03u ms", tt/1000, tt%1000);
  821. }
  822. int traceroute_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  823. int traceroute_main(int argc, char **argv)
  824. {
  825. int code, n;
  826. unsigned char *outp;
  827. uint32_t *ap;
  828. struct sockaddr_in *from;
  829. struct sockaddr_in *to;
  830. struct hostinfo *hi;
  831. int ttl, probe, i;
  832. int seq = 0;
  833. int tos = 0;
  834. char *tos_str;
  835. char *source;
  836. unsigned op;
  837. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  838. int lsrr = 0;
  839. #endif
  840. uint16_t off = 0;
  841. struct IFADDRLIST *al;
  842. char *device;
  843. int max_ttl = 30;
  844. char *max_ttl_str;
  845. char *port_str;
  846. int nprobes = 3;
  847. char *nprobes_str;
  848. char *waittime_str;
  849. unsigned pausemsecs = 0;
  850. char *pausemsecs_str;
  851. int first_ttl = 1;
  852. char *first_ttl_str;
  853. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  854. llist_t *source_route_list = NULL;
  855. #endif
  856. INIT_G();
  857. from = (struct sockaddr_in *)&wherefrom;
  858. to = (struct sockaddr_in *)&whereto;
  859. //opterr = 0;
  860. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  861. opt_complementary = "x-x:g::";
  862. #else
  863. opt_complementary = "x-x";
  864. #endif
  865. op = getopt32(argv, "FIlnrdvxt:i:m:p:q:s:w:z:f:"
  866. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  867. "g:"
  868. #endif
  869. , &tos_str, &device, &max_ttl_str, &port_str, &nprobes_str
  870. , &source, &waittime_str, &pausemsecs_str, &first_ttl_str
  871. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  872. , &source_route_list
  873. #endif
  874. );
  875. if (op & OPT_DONT_FRAGMNT)
  876. off = IP_DF;
  877. if (op & OPT_IP_CHKSUM) {
  878. doipcksum = 0;
  879. bb_error_msg("warning: ip checksums disabled");
  880. }
  881. if (op & OPT_TOS)
  882. tos = xatou_range(tos_str, 0, 255);
  883. if (op & OPT_MAX_TTL)
  884. max_ttl = xatou_range(max_ttl_str, 1, 255);
  885. if (op & OPT_PORT)
  886. port = xatou16(port_str);
  887. if (op & OPT_NPROBES)
  888. nprobes = xatou_range(nprobes_str, 1, INT_MAX);
  889. if (op & OPT_SOURCE) {
  890. /*
  891. * set the ip source address of the outbound
  892. * probe (e.g., on a multi-homed host).
  893. */
  894. if (getuid())
  895. bb_error_msg_and_die("-s %s: permission denied", source);
  896. }
  897. if (op & OPT_WAITTIME)
  898. waittime = xatou_range(waittime_str, 2, 24 * 60 * 60);
  899. if (op & OPT_PAUSE_MS)
  900. pausemsecs = xatou_range(pausemsecs_str, 0, 60 * 60 * 1000);
  901. if (op & OPT_FIRST_TTL)
  902. first_ttl = xatou_range(first_ttl_str, 1, 255);
  903. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  904. if (source_route_list) {
  905. while (source_route_list) {
  906. if (lsrr >= NGATEWAYS)
  907. bb_error_msg_and_die("no more than %d gateways", NGATEWAYS);
  908. getaddr(gwlist + lsrr, llist_pop(&source_route_list));
  909. ++lsrr;
  910. }
  911. optlen = (lsrr + 1) * sizeof(gwlist[0]);
  912. }
  913. #endif
  914. if (first_ttl > max_ttl) {
  915. bb_error_msg_and_die(
  916. "first ttl (%d) may not be greater than max ttl (%d)",
  917. first_ttl, max_ttl);
  918. }
  919. minpacket = sizeof(*outip) + sizeof(*outdata) + optlen;
  920. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  921. if (useicmp)
  922. minpacket += 8; /* XXX magic number */
  923. else
  924. #endif
  925. minpacket += sizeof(*outudp);
  926. packlen = minpacket; /* minimum sized packet */
  927. /* Process destination and optional packet size */
  928. switch (argc - optind) {
  929. case 2:
  930. packlen = xatoul_range(argv[optind + 1], minpacket, maxpacket);
  931. /* Fall through */
  932. case 1:
  933. hostname = argv[optind];
  934. hi = gethostinfo(hostname);
  935. setsin(to, hi->addrs[0]);
  936. if (hi->n > 1)
  937. bb_error_msg("warning: %s has multiple addresses; using %s",
  938. hostname, inet_ntoa(to->sin_addr));
  939. hostname = hi->name;
  940. hi->name = NULL;
  941. freehostinfo(hi);
  942. break;
  943. default:
  944. bb_show_usage();
  945. }
  946. /* Ensure the socket fds won't be 0, 1 or 2 */
  947. bb_sanitize_stdio();
  948. rcvsock = xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  949. #if TRACEROUTE_SO_DEBUG
  950. if (op & OPT_DEBUG)
  951. setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
  952. &const_int_1, sizeof(const_int_1));
  953. #endif
  954. if (op & OPT_BYPASS_ROUTE)
  955. setsockopt(rcvsock, SOL_SOCKET, SO_DONTROUTE,
  956. &const_int_1, sizeof(const_int_1));
  957. sndsock = xsocket(AF_INET, SOCK_RAW, IPPROTO_RAW);
  958. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  959. #if defined(IP_OPTIONS)
  960. if (lsrr > 0) {
  961. unsigned char optlist[MAX_IPOPTLEN];
  962. /* final hop */
  963. gwlist[lsrr] = to->sin_addr.s_addr;
  964. ++lsrr;
  965. /* force 4 byte alignment */
  966. optlist[0] = IPOPT_NOP;
  967. /* loose source route option */
  968. optlist[1] = IPOPT_LSRR;
  969. i = lsrr * sizeof(gwlist[0]);
  970. optlist[2] = i + 3;
  971. /* Pointer to LSRR addresses */
  972. optlist[3] = IPOPT_MINOFF;
  973. memcpy(optlist + 4, gwlist, i);
  974. if ((setsockopt(sndsock, IPPROTO_IP, IP_OPTIONS,
  975. (char *)optlist, i + sizeof(gwlist[0]))) < 0) {
  976. bb_perror_msg_and_die("IP_OPTIONS");
  977. }
  978. }
  979. #endif /* IP_OPTIONS */
  980. #endif /* CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE */
  981. #ifdef SO_SNDBUF
  982. if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, &packlen, sizeof(packlen)) < 0) {
  983. bb_perror_msg_and_die("SO_SNDBUF");
  984. }
  985. #endif
  986. #ifdef IP_HDRINCL
  987. if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL, &const_int_1, sizeof(const_int_1)) < 0
  988. && errno != ENOPROTOOPT
  989. ) {
  990. bb_perror_msg_and_die("IP_HDRINCL");
  991. }
  992. #else
  993. #ifdef IP_TOS
  994. if (tos_str && setsockopt(sndsock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) {
  995. bb_perror_msg_and_die("setsockopt tos %d", tos);
  996. }
  997. #endif
  998. #endif
  999. #if TRACEROUTE_SO_DEBUG
  1000. if (op & OPT_DEBUG)
  1001. setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
  1002. &const_int_1, sizeof(const_int_1));
  1003. #endif
  1004. if (op & OPT_BYPASS_ROUTE)
  1005. setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
  1006. &const_int_1, sizeof(const_int_1));
  1007. /* Revert to non-privileged user after opening sockets */
  1008. xsetgid(getgid());
  1009. xsetuid(getuid());
  1010. outip = xzalloc(packlen);
  1011. outip->ip_v = IPVERSION;
  1012. if (tos_str)
  1013. outip->ip_tos = tos;
  1014. outip->ip_len = htons(packlen);
  1015. outip->ip_off = htons(off);
  1016. outp = (unsigned char *)(outip + 1);
  1017. outip->ip_dst = to->sin_addr;
  1018. outip->ip_hl = (outp - (unsigned char *)outip) >> 2;
  1019. ident = (getpid() & 0xffff) | 0x8000;
  1020. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  1021. if (useicmp) {
  1022. outip->ip_p = IPPROTO_ICMP;
  1023. outicmp = (struct icmp *)outp;
  1024. outicmp->icmp_type = ICMP_ECHO;
  1025. outicmp->icmp_id = htons(ident);
  1026. outdata = (outdata_t *)(outp + 8); /* XXX magic number */
  1027. } else
  1028. #endif
  1029. {
  1030. outip->ip_p = IPPROTO_UDP;
  1031. outudp = (struct udphdr *)outp;
  1032. outudp->source = htons(ident);
  1033. outudp->len = htons((uint16_t)(packlen - (sizeof(*outip) + optlen)));
  1034. outdata = (outdata_t *)(outudp + 1);
  1035. }
  1036. /* Get the interface address list */
  1037. n = ifaddrlist(&al);
  1038. /* Look for a specific device */
  1039. if (op & OPT_DEVICE) {
  1040. for (i = n; i > 0; --i, ++al)
  1041. if (strcmp(device, al->device) == 0)
  1042. goto found_dev;
  1043. bb_error_msg_and_die("can't find interface %s", device);
  1044. }
  1045. found_dev:
  1046. /* Determine our source address */
  1047. if (!(op & OPT_SOURCE)) {
  1048. /*
  1049. * If a device was specified, use the interface address.
  1050. * Otherwise, try to determine our source address.
  1051. */
  1052. if (op & OPT_DEVICE)
  1053. setsin(from, al->addr);
  1054. findsaddr(to, from);
  1055. } else {
  1056. hi = gethostinfo(source);
  1057. source = hi->name;
  1058. hi->name = NULL;
  1059. /*
  1060. * If the device was specified make sure it
  1061. * corresponds to the source address specified.
  1062. * Otherwise, use the first address (and warn if
  1063. * there are more than one).
  1064. */
  1065. if (op & OPT_DEVICE) {
  1066. for (i = hi->n, ap = hi->addrs; i > 0; --i, ++ap)
  1067. if (*ap == al->addr)
  1068. goto found_dev2;
  1069. bb_error_msg_and_die("%s is not on interface %s",
  1070. source, device);
  1071. found_dev2:
  1072. setsin(from, *ap);
  1073. } else {
  1074. setsin(from, hi->addrs[0]);
  1075. if (hi->n > 1)
  1076. bb_error_msg(
  1077. "warning: %s has multiple addresses; using %s",
  1078. source, inet_ntoa(from->sin_addr));
  1079. }
  1080. freehostinfo(hi);
  1081. }
  1082. outip->ip_src = from->sin_addr;
  1083. #ifndef IP_HDRINCL
  1084. xbind(sndsock, (struct sockaddr *)from, sizeof(*from));
  1085. #endif
  1086. printf("traceroute to %s (%s)", hostname, inet_ntoa(to->sin_addr));
  1087. if (op & OPT_SOURCE)
  1088. printf(" from %s", source);
  1089. printf(", %d hops max, %d byte packets\n", max_ttl, packlen);
  1090. fflush(stdout);
  1091. for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
  1092. uint32_t lastaddr = 0;
  1093. int gotlastaddr = 0;
  1094. int got_there = 0;
  1095. int unreachable = 0;
  1096. int sentfirst = 0;
  1097. printf("%2d ", ttl);
  1098. for (probe = 0; probe < nprobes; ++probe) {
  1099. int cc;
  1100. unsigned t1;
  1101. unsigned t2;
  1102. struct ip *ip;
  1103. if (sentfirst && pausemsecs > 0)
  1104. usleep(pausemsecs * 1000);
  1105. t1 = monotonic_us();
  1106. send_probe(++seq, ttl);
  1107. ++sentfirst;
  1108. while ((cc = wait_for_reply(rcvsock, from)) != 0) {
  1109. t2 = monotonic_us();
  1110. i = packet_ok(packet, cc, from, seq);
  1111. /* Skip short packet */
  1112. if (i == 0)
  1113. continue;
  1114. if (!gotlastaddr ||
  1115. from->sin_addr.s_addr != lastaddr) {
  1116. print(packet, cc, from);
  1117. lastaddr = from->sin_addr.s_addr;
  1118. ++gotlastaddr;
  1119. }
  1120. print_delta_ms(t1, t2);
  1121. ip = (struct ip *)packet;
  1122. if (op & OPT_TTL_FLAG)
  1123. printf(" (%d)", ip->ip_ttl);
  1124. if (i == -2) {
  1125. if (ip->ip_ttl <= 1)
  1126. printf(" !");
  1127. ++got_there;
  1128. break;
  1129. }
  1130. /* time exceeded in transit */
  1131. if (i == -1)
  1132. break;
  1133. code = i - 1;
  1134. switch (code) {
  1135. case ICMP_UNREACH_PORT:
  1136. if (ip->ip_ttl <= 1)
  1137. printf(" !");
  1138. ++got_there;
  1139. break;
  1140. case ICMP_UNREACH_NET:
  1141. ++unreachable;
  1142. printf(" !N");
  1143. break;
  1144. case ICMP_UNREACH_HOST:
  1145. ++unreachable;
  1146. printf(" !H");
  1147. break;
  1148. case ICMP_UNREACH_PROTOCOL:
  1149. ++got_there;
  1150. printf(" !P");
  1151. break;
  1152. case ICMP_UNREACH_NEEDFRAG:
  1153. ++unreachable;
  1154. printf(" !F-%d", pmtu);
  1155. break;
  1156. case ICMP_UNREACH_SRCFAIL:
  1157. ++unreachable;
  1158. printf(" !S");
  1159. break;
  1160. case ICMP_UNREACH_FILTER_PROHIB:
  1161. case ICMP_UNREACH_NET_PROHIB: /* misuse */
  1162. ++unreachable;
  1163. printf(" !A");
  1164. break;
  1165. case ICMP_UNREACH_HOST_PROHIB:
  1166. ++unreachable;
  1167. printf(" !C");
  1168. break;
  1169. case ICMP_UNREACH_HOST_PRECEDENCE:
  1170. ++unreachable;
  1171. printf(" !V");
  1172. break;
  1173. case ICMP_UNREACH_PRECEDENCE_CUTOFF:
  1174. ++unreachable;
  1175. printf(" !C");
  1176. break;
  1177. case ICMP_UNREACH_NET_UNKNOWN:
  1178. case ICMP_UNREACH_HOST_UNKNOWN:
  1179. ++unreachable;
  1180. printf(" !U");
  1181. break;
  1182. case ICMP_UNREACH_ISOLATED:
  1183. ++unreachable;
  1184. printf(" !I");
  1185. break;
  1186. case ICMP_UNREACH_TOSNET:
  1187. case ICMP_UNREACH_TOSHOST:
  1188. ++unreachable;
  1189. printf(" !T");
  1190. break;
  1191. default:
  1192. ++unreachable;
  1193. printf(" !<%d>", code);
  1194. break;
  1195. }
  1196. break;
  1197. }
  1198. if (cc == 0)
  1199. printf(" *");
  1200. (void)fflush(stdout);
  1201. }
  1202. bb_putchar('\n');
  1203. if (got_there ||
  1204. (unreachable > 0 && unreachable >= nprobes - 1))
  1205. break;
  1206. }
  1207. return 0;
  1208. }