traceroute.c 37 KB

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