traceroute.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  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 "inet_common.h"
  205. #include <net/if.h>
  206. #include <arpa/inet.h>
  207. #include <netinet/in.h>
  208. #include <netinet/udp.h>
  209. #include <netinet/ip.h>
  210. #include <netinet/ip_icmp.h>
  211. #include "busybox.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. u_int32_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. struct timeval tv ATTRIBUTE_PACKED; /* time packet left */
  263. };
  264. struct IFADDRLIST {
  265. u_int32_t addr;
  266. char device[sizeof(struct ifreq)];
  267. };
  268. static const char route[] = "/proc/net/route";
  269. /* last inbound (icmp) packet */
  270. static unsigned char packet[512] ATTRIBUTE_ALIGNED(32);
  271. static struct ip *outip; /* last output (udp) packet */
  272. static struct udphdr *outudp; /* last output (udp) packet */
  273. static struct outdata *outdata; /* last output (udp) packet */
  274. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  275. static struct icmp *outicmp; /* last output (icmp) packet */
  276. #endif
  277. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  278. /* Maximum number of gateways (include room for one noop) */
  279. #define NGATEWAYS ((int)((MAX_IPOPTLEN - IPOPT_MINOFF - 1) / sizeof(u_int32_t)))
  280. /* loose source route gateway list (including room for final destination) */
  281. static u_int32_t gwlist[NGATEWAYS + 1];
  282. #endif
  283. static int s; /* receive (icmp) socket file descriptor */
  284. static int sndsock; /* send (udp/icmp) socket file descriptor */
  285. static struct sockaddr_storage whereto; /* Who to try to reach */
  286. static struct sockaddr_storage wherefrom; /* Who we are */
  287. static int packlen; /* total length of packet */
  288. static int minpacket; /* min ip packet size */
  289. static int maxpacket = 32 * 1024; /* max ip packet size */
  290. static int pmtu; /* Path MTU Discovery (RFC1191) */
  291. static char *hostname;
  292. static uint16_t ident;
  293. static uint16_t port = 32768 + 666; /* start udp dest port # for probe packets */
  294. static int waittime = 5; /* time to wait for response (in seconds) */
  295. static int nflag; /* print addresses numerically */
  296. static int doipcksum = 1; /* calculate ip checksums by default */
  297. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  298. static int optlen; /* length of ip options */
  299. #else
  300. #define optlen 0
  301. #endif
  302. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  303. static int useicmp; /* use icmp echo instead of udp packets */
  304. #endif
  305. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  306. static int verbose;
  307. #endif
  308. /*
  309. * Return the interface list
  310. */
  311. static int
  312. ifaddrlist(struct IFADDRLIST **ipaddrp)
  313. {
  314. int fd, nipaddr;
  315. #ifdef HAVE_SOCKADDR_SA_LEN
  316. int n;
  317. #endif
  318. struct ifreq *ifrp, *ifend, *ifnext;
  319. struct sockaddr_in *addr_sin;
  320. struct IFADDRLIST *al;
  321. struct ifconf ifc;
  322. struct ifreq ibuf[(32 * 1024) / sizeof(struct ifreq)], ifr;
  323. struct IFADDRLIST *st_ifaddrlist;
  324. fd = xsocket(AF_INET, SOCK_DGRAM, 0);
  325. ifc.ifc_len = sizeof(ibuf);
  326. ifc.ifc_buf = (caddr_t)ibuf;
  327. if (ioctl(fd, SIOCGIFCONF, (char *)&ifc) < 0 ||
  328. ifc.ifc_len < sizeof(struct ifreq)) {
  329. if (errno == EINVAL)
  330. bb_error_msg_and_die(
  331. "SIOCGIFCONF: ifreq struct too small (%d bytes)",
  332. (int)sizeof(ibuf));
  333. else
  334. bb_perror_msg_and_die("SIOCGIFCONF");
  335. }
  336. ifrp = ibuf;
  337. ifend = (struct ifreq *)((char *)ibuf + ifc.ifc_len);
  338. nipaddr = 1 + (ifc.ifc_len / sizeof(struct ifreq));
  339. st_ifaddrlist = xzalloc(nipaddr * sizeof(struct IFADDRLIST));
  340. al = st_ifaddrlist;
  341. nipaddr = 0;
  342. for (; ifrp < ifend; ifrp = ifnext) {
  343. #ifdef HAVE_SOCKADDR_SA_LEN
  344. n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
  345. if (n < sizeof(*ifrp))
  346. ifnext = ifrp + 1;
  347. else
  348. ifnext = (struct ifreq *)((char *)ifrp + n);
  349. if (ifrp->ifr_addr.sa_family != AF_INET)
  350. continue;
  351. #else
  352. ifnext = ifrp + 1;
  353. #endif
  354. /*
  355. * Need a template to preserve address info that is
  356. * used below to locate the next entry. (Otherwise,
  357. * SIOCGIFFLAGS stomps over it because the requests
  358. * are returned in a union.)
  359. */
  360. strncpy(ifr.ifr_name, ifrp->ifr_name, sizeof(ifr.ifr_name));
  361. if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
  362. if (errno == ENXIO)
  363. continue;
  364. bb_perror_msg_and_die("SIOCGIFFLAGS: %.*s",
  365. (int)sizeof(ifr.ifr_name), ifr.ifr_name);
  366. }
  367. /* Must be up */
  368. if ((ifr.ifr_flags & IFF_UP) == 0)
  369. continue;
  370. safe_strncpy(al->device, ifr.ifr_name, sizeof(ifr.ifr_name) + 1);
  371. #ifdef sun
  372. /* Ignore sun virtual interfaces */
  373. if (strchr(al->device, ':') != NULL)
  374. continue;
  375. #endif
  376. if (ioctl(fd, SIOCGIFADDR, (char *)&ifr) < 0)
  377. bb_perror_msg_and_die("SIOCGIFADDR: %s", al->device);
  378. addr_sin = (struct sockaddr_in *)&ifr.ifr_addr;
  379. al->addr = addr_sin->sin_addr.s_addr;
  380. ++al;
  381. ++nipaddr;
  382. }
  383. if (nipaddr == 0)
  384. bb_error_msg_and_die ("can't find any network interfaces");
  385. (void)close(fd);
  386. *ipaddrp = st_ifaddrlist;
  387. return nipaddr;
  388. }
  389. static void
  390. setsin(struct sockaddr_in *addr_sin, u_int32_t addr)
  391. {
  392. memset(addr_sin, 0, sizeof(*addr_sin));
  393. #ifdef HAVE_SOCKADDR_SA_LEN
  394. addr_sin->sin_len = sizeof(*addr_sin);
  395. #endif
  396. addr_sin->sin_family = AF_INET;
  397. addr_sin->sin_addr.s_addr = addr;
  398. }
  399. /*
  400. * Return the source address for the given destination address
  401. */
  402. static void
  403. findsaddr(const struct sockaddr_in *to, struct sockaddr_in *from)
  404. {
  405. int i, n;
  406. FILE *f;
  407. u_int32_t mask;
  408. u_int32_t dest, tmask;
  409. struct IFADDRLIST *al;
  410. char buf[256], tdevice[256], device[256];
  411. f = xfopen(route, "r");
  412. /* Find the appropriate interface */
  413. n = 0;
  414. mask = 0;
  415. device[0] = '\0';
  416. while (fgets(buf, sizeof(buf), f) != NULL) {
  417. ++n;
  418. if (n == 1 && strncmp(buf, "Iface", 5) == 0)
  419. continue;
  420. if ((i = sscanf(buf, "%255s %x %*s %*s %*s %*s %*s %x",
  421. tdevice, &dest, &tmask)) != 3)
  422. bb_error_msg_and_die ("junk in buffer");
  423. if ((to->sin_addr.s_addr & tmask) == dest &&
  424. (tmask > mask || mask == 0)) {
  425. mask = tmask;
  426. strcpy(device, tdevice);
  427. }
  428. }
  429. fclose(f);
  430. if (device[0] == '\0')
  431. bb_error_msg_and_die ("can't find interface");
  432. /* Get the interface address list */
  433. n = ifaddrlist(&al);
  434. /* Find our appropriate source address */
  435. for (i = n; i > 0; --i, ++al)
  436. if (strcmp(device, al->device) == 0)
  437. break;
  438. if (i <= 0)
  439. bb_error_msg_and_die("can't find interface %s", device);
  440. setsin(from, al->addr);
  441. }
  442. /*
  443. "Usage: %s [-dFIlnrvx] [-g gateway] [-i iface] [-f first_ttl]\n"
  444. "\t[-m max_ttl] [ -p port] [-q nqueries] [-s src_addr] [-t tos]\n"
  445. "\t[-w waittime] [-z pausemsecs] host [packetlen]"
  446. */
  447. /*
  448. * Subtract 2 timeval structs: out = out - in.
  449. * Out is assumed to be >= in.
  450. */
  451. static inline void
  452. tvsub(struct timeval *out, struct timeval *in)
  453. {
  454. if ((out->tv_usec -= in->tv_usec) < 0) {
  455. --out->tv_sec;
  456. out->tv_usec += 1000000;
  457. }
  458. out->tv_sec -= in->tv_sec;
  459. }
  460. static int
  461. wait_for_reply(int sock, struct sockaddr_in *fromp, const struct timeval *tp)
  462. {
  463. fd_set fds;
  464. struct timeval now, tvwait;
  465. struct timezone tz;
  466. int cc = 0;
  467. socklen_t fromlen = sizeof(*fromp);
  468. FD_ZERO(&fds);
  469. FD_SET(sock, &fds);
  470. tvwait.tv_sec = tp->tv_sec + waittime;
  471. tvwait.tv_usec = tp->tv_usec;
  472. (void)gettimeofday(&now, &tz);
  473. tvsub(&tvwait, &now);
  474. if (select(sock + 1, &fds, NULL, NULL, &tvwait) > 0)
  475. cc = recvfrom(sock, (char *)packet, sizeof(packet), 0,
  476. (struct sockaddr *)fromp, &fromlen);
  477. return cc;
  478. }
  479. /*
  480. * Checksum routine for Internet Protocol family headers (C Version)
  481. */
  482. static uint16_t
  483. in_cksum(uint16_t *addr, int len)
  484. {
  485. int nleft = len;
  486. uint16_t *w = addr;
  487. uint16_t answer;
  488. int sum = 0;
  489. /*
  490. * Our algorithm is simple, using a 32 bit accumulator (sum),
  491. * we add sequential 16 bit words to it, and at the end, fold
  492. * back all the carry bits from the top 16 bits into the lower
  493. * 16 bits.
  494. */
  495. while (nleft > 1) {
  496. sum += *w++;
  497. nleft -= 2;
  498. }
  499. /* mop up an odd byte, if necessary */
  500. if (nleft == 1)
  501. sum += *(unsigned char *)w;
  502. /*
  503. * add back carry outs from top 16 bits to low 16 bits
  504. */
  505. sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
  506. sum += (sum >> 16); /* add carry */
  507. answer = ~sum; /* truncate to 16 bits */
  508. return answer;
  509. }
  510. static void
  511. send_probe(int seq, int ttl, struct timeval *tp)
  512. {
  513. int cc;
  514. struct udpiphdr *ui, *oui;
  515. struct ip tip;
  516. outip->ip_ttl = ttl;
  517. outip->ip_id = htons(ident + seq);
  518. /*
  519. * In most cases, the kernel will recalculate the ip checksum.
  520. * But we must do it anyway so that the udp checksum comes out
  521. * right.
  522. */
  523. if (doipcksum) {
  524. outip->ip_sum =
  525. in_cksum((uint16_t *)outip, sizeof(*outip) + optlen);
  526. if (outip->ip_sum == 0)
  527. outip->ip_sum = 0xffff;
  528. }
  529. /* Payload */
  530. outdata->seq = seq;
  531. outdata->ttl = ttl;
  532. memcpy(&outdata->tv, tp, sizeof(outdata->tv));
  533. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  534. if (useicmp)
  535. outicmp->icmp_seq = htons(seq);
  536. else
  537. #endif
  538. outudp->dest = htons(port + seq);
  539. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  540. if (useicmp) {
  541. /* Always calculate checksum for icmp packets */
  542. outicmp->icmp_cksum = 0;
  543. outicmp->icmp_cksum = in_cksum((uint16_t *)outicmp,
  544. packlen - (sizeof(*outip) + optlen));
  545. if (outicmp->icmp_cksum == 0)
  546. outicmp->icmp_cksum = 0xffff;
  547. } else
  548. #endif
  549. if (doipcksum) {
  550. /* Checksum (we must save and restore ip header) */
  551. tip = *outip;
  552. ui = (struct udpiphdr *)outip;
  553. oui = (struct udpiphdr *)&tip;
  554. /* Easier to zero and put back things that are ok */
  555. memset((char *)ui, 0, sizeof(ui->ui_i));
  556. ui->ui_src = oui->ui_src;
  557. ui->ui_dst = oui->ui_dst;
  558. ui->ui_pr = oui->ui_pr;
  559. ui->ui_len = outudp->len;
  560. outudp->check = 0;
  561. outudp->check = in_cksum((uint16_t *)ui, packlen);
  562. if (outudp->check == 0)
  563. outudp->check = 0xffff;
  564. *outip = tip;
  565. }
  566. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  567. /* XXX undocumented debugging hack */
  568. if (verbose > 1) {
  569. const uint16_t *sp;
  570. int nshorts, i;
  571. sp = (uint16_t *)outip;
  572. nshorts = (u_int)packlen / sizeof(uint16_t);
  573. i = 0;
  574. printf("[ %d bytes", packlen);
  575. while (--nshorts >= 0) {
  576. if ((i++ % 8) == 0)
  577. printf("\n\t");
  578. printf(" %04x", ntohs(*sp));
  579. sp++;
  580. }
  581. if (packlen & 1) {
  582. if ((i % 8) == 0)
  583. printf("\n\t");
  584. printf(" %02x", *(unsigned char *)sp);
  585. }
  586. printf("]\n");
  587. }
  588. #endif
  589. #if !defined(IP_HDRINCL) && defined(IP_TTL)
  590. if (setsockopt(sndsock, IPPROTO_IP, IP_TTL,
  591. (char *)&ttl, sizeof(ttl)) < 0) {
  592. bb_perror_msg_and_die("setsockopt ttl %d", ttl);
  593. }
  594. #endif
  595. cc = sendto(sndsock, (char *)outip,
  596. packlen, 0, (struct sockaddr *)&whereto, sizeof(whereto));
  597. if (cc < 0 || cc != packlen) {
  598. if (cc < 0)
  599. bb_perror_msg_and_die("sendto");
  600. printf("%s: wrote %s %d chars, ret=%d\n",
  601. applet_name, hostname, packlen, cc);
  602. (void)fflush(stdout);
  603. }
  604. }
  605. static inline double
  606. deltaT(struct timeval *t1p, struct timeval *t2p)
  607. {
  608. double dt;
  609. dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
  610. (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
  611. return dt;
  612. }
  613. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  614. /*
  615. * Convert an ICMP "type" field to a printable string.
  616. */
  617. static inline const char *
  618. pr_type(unsigned char t)
  619. {
  620. static const char * const ttab[] = {
  621. "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
  622. "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
  623. "Echo", "Router Advert", "Router Solicit", "Time Exceeded",
  624. "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
  625. "Info Reply", "Mask Request", "Mask Reply"
  626. };
  627. if (t > 18)
  628. return "OUT-OF-RANGE";
  629. return ttab[t];
  630. }
  631. #endif
  632. static int
  633. packet_ok(unsigned char *buf, int cc, struct sockaddr_in *from, int seq)
  634. {
  635. struct icmp *icp;
  636. unsigned char type, code;
  637. int hlen;
  638. struct ip *ip;
  639. ip = (struct ip *) buf;
  640. hlen = ip->ip_hl << 2;
  641. if (cc < hlen + ICMP_MINLEN) {
  642. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  643. if (verbose)
  644. printf("packet too short (%d bytes) from %s\n", cc,
  645. inet_ntoa(from->sin_addr));
  646. #endif
  647. return 0;
  648. }
  649. cc -= hlen;
  650. icp = (struct icmp *)(buf + hlen);
  651. type = icp->icmp_type;
  652. code = icp->icmp_code;
  653. /* Path MTU Discovery (RFC1191) */
  654. if (code != ICMP_UNREACH_NEEDFRAG)
  655. pmtu = 0;
  656. else {
  657. pmtu = ntohs(icp->icmp_nextmtu);
  658. }
  659. if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS) ||
  660. type == ICMP_UNREACH || type == ICMP_ECHOREPLY) {
  661. struct ip *hip;
  662. struct udphdr *up;
  663. hip = &icp->icmp_ip;
  664. hlen = hip->ip_hl << 2;
  665. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  666. if (useicmp) {
  667. struct icmp *hicmp;
  668. /* XXX */
  669. if (type == ICMP_ECHOREPLY &&
  670. icp->icmp_id == htons(ident) &&
  671. icp->icmp_seq == htons(seq))
  672. return -2;
  673. hicmp = (struct icmp *)((unsigned char *)hip + hlen);
  674. /* XXX 8 is a magic number */
  675. if (hlen + 8 <= cc &&
  676. hip->ip_p == IPPROTO_ICMP &&
  677. hicmp->icmp_id == htons(ident) &&
  678. hicmp->icmp_seq == htons(seq))
  679. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  680. } else
  681. #endif
  682. {
  683. up = (struct udphdr *)((unsigned char *)hip + hlen);
  684. /* XXX 8 is a magic number */
  685. if (hlen + 12 <= cc &&
  686. hip->ip_p == IPPROTO_UDP &&
  687. up->source == htons(ident) &&
  688. up->dest == htons(port + seq))
  689. return (type == ICMP_TIMXCEED ? -1 : code + 1);
  690. }
  691. }
  692. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  693. if (verbose) {
  694. int i;
  695. u_int32_t *lp = (u_int32_t *)&icp->icmp_ip;
  696. printf("\n%d bytes from %s to "
  697. "%s: icmp type %d (%s) code %d\n",
  698. cc, inet_ntoa(from->sin_addr),
  699. inet_ntoa(ip->ip_dst), type, pr_type(type), icp->icmp_code);
  700. for (i = 4; i < cc ; i += sizeof(*lp))
  701. printf("%2d: x%8.8x\n", i, *lp++);
  702. }
  703. #endif
  704. return 0;
  705. }
  706. /*
  707. * Construct an Internet address representation.
  708. * If the nflag has been supplied, give
  709. * numeric value, otherwise try for symbolic name.
  710. */
  711. static inline void
  712. inetname(struct sockaddr_in *from)
  713. {
  714. const char *n = NULL;
  715. const char *ina;
  716. char name[257];
  717. if (!nflag && from->sin_addr.s_addr != INADDR_ANY) {
  718. if (INET_rresolve(name, sizeof(name), from, 0x4000, 0xffffffff) >= 0)
  719. n = name;
  720. }
  721. ina = inet_ntoa(from->sin_addr);
  722. if (nflag)
  723. printf(" %s", ina);
  724. else
  725. printf(" %s (%s)", (n ? n : ina), ina);
  726. }
  727. static inline void
  728. print(unsigned char *buf, int cc, struct sockaddr_in *from)
  729. {
  730. struct ip *ip;
  731. int hlen;
  732. ip = (struct ip *) buf;
  733. hlen = ip->ip_hl << 2;
  734. cc -= hlen;
  735. inetname(from);
  736. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  737. if (verbose)
  738. printf(" %d bytes to %s", cc, inet_ntoa (ip->ip_dst));
  739. #endif
  740. }
  741. static struct hostinfo *
  742. gethostinfo(const char *host)
  743. {
  744. int n;
  745. struct hostent *hp;
  746. struct hostinfo *hi;
  747. char **p;
  748. u_int32_t addr, *ap;
  749. hi = xzalloc(sizeof(*hi));
  750. addr = inet_addr(host);
  751. if ((int32_t)addr != -1) {
  752. hi->name = xstrdup(host);
  753. hi->n = 1;
  754. hi->addrs = xzalloc(sizeof(hi->addrs[0]));
  755. hi->addrs[0] = addr;
  756. return hi;
  757. }
  758. hp = xgethostbyname(host);
  759. if (hp->h_addrtype != AF_INET || hp->h_length != 4)
  760. bb_perror_msg_and_die("bad host %s", host);
  761. hi->name = xstrdup(hp->h_name);
  762. for (n = 0, p = hp->h_addr_list; *p != NULL; ++n, ++p)
  763. continue;
  764. hi->n = n;
  765. hi->addrs = xzalloc(n * sizeof(hi->addrs[0]));
  766. for (ap = hi->addrs, p = hp->h_addr_list; *p != NULL; ++ap, ++p)
  767. memcpy(ap, *p, sizeof(*ap));
  768. return hi;
  769. }
  770. static void
  771. freehostinfo(struct hostinfo *hi)
  772. {
  773. free(hi->name);
  774. hi->name = NULL;
  775. free((char *)hi->addrs);
  776. free((char *)hi);
  777. }
  778. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  779. static void
  780. getaddr(u_int32_t *ap, const char *host)
  781. {
  782. struct hostinfo *hi;
  783. hi = gethostinfo(host);
  784. *ap = hi->addrs[0];
  785. freehostinfo(hi);
  786. }
  787. #endif
  788. int
  789. traceroute_main(int argc, char *argv[])
  790. {
  791. static const int on = 1;
  792. int code, n;
  793. unsigned char *outp;
  794. u_int32_t *ap;
  795. struct sockaddr_in *from = (struct sockaddr_in *)&wherefrom;
  796. struct sockaddr_in *to = (struct sockaddr_in *)&whereto;
  797. struct hostinfo *hi;
  798. int ttl, probe, i;
  799. int seq = 0;
  800. int tos = 0;
  801. char *tos_str = NULL;
  802. char *source = NULL;
  803. unsigned long op;
  804. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  805. int lsrr = 0;
  806. #endif
  807. uint16_t off = 0;
  808. struct IFADDRLIST *al;
  809. char *device = NULL;
  810. int max_ttl = 30;
  811. char *max_ttl_str = NULL;
  812. char *port_str = NULL;
  813. int nprobes = 3;
  814. char *nprobes_str = NULL;
  815. char *waittime_str = NULL;
  816. u_int pausemsecs = 0;
  817. char *pausemsecs_str = NULL;
  818. int first_ttl = 1;
  819. char *first_ttl_str = NULL;
  820. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  821. llist_t *sourse_route_list = NULL;
  822. #endif
  823. opterr = 0;
  824. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  825. opt_complementary = "x-x:g::";
  826. #else
  827. opt_complementary = "x-x";
  828. #endif
  829. op = getopt32(argc, argv, "FIlnrdvxt:i:m:p:q:s:w:z:f:"
  830. #define USAGE_OP_DONT_FRAGMNT (1<<0) /* F */
  831. #define USAGE_OP_USE_ICMP (1<<1) /* I */
  832. #define USAGE_OP_TTL_FLAG (1<<2) /* l */
  833. #define USAGE_OP_ADDR_NUM (1<<3) /* n */
  834. #define USAGE_OP_BYPASS_ROUTE (1<<4) /* r */
  835. #define USAGE_OP_DEBUG (1<<5) /* d */
  836. #define USAGE_OP_VERBOSE (1<<6) /* v */
  837. #define USAGE_OP_IP_CHKSUM (1<<7) /* x */
  838. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  839. "g:"
  840. #endif
  841. , &tos_str, &device, &max_ttl_str, &port_str, &nprobes_str,
  842. &source, &waittime_str, &pausemsecs_str, &first_ttl_str
  843. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  844. , &sourse_route_list
  845. #endif
  846. );
  847. if (op & USAGE_OP_DONT_FRAGMNT)
  848. off = IP_DF;
  849. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  850. useicmp = op & USAGE_OP_USE_ICMP;
  851. #endif
  852. nflag = op & USAGE_OP_ADDR_NUM;
  853. #if ENABLE_FEATURE_TRACEROUTE_VERBOSE
  854. verbose = op & USAGE_OP_VERBOSE;
  855. #endif
  856. if (op & USAGE_OP_IP_CHKSUM) {
  857. doipcksum = 0;
  858. bb_error_msg("warning: ip checksums disabled");
  859. }
  860. if (tos_str)
  861. tos = xatoul_range(tos_str, 0, 255);
  862. if (max_ttl_str)
  863. max_ttl = xatoul_range(max_ttl_str, 1, 255);
  864. if (port_str)
  865. port = xatou16(port_str);
  866. if (nprobes_str)
  867. nprobes = xatoul_range(nprobes_str, 1, INT_MAX);
  868. if (source) {
  869. /*
  870. * set the ip source address of the outbound
  871. * probe (e.g., on a multi-homed host).
  872. */
  873. if (getuid()) bb_error_msg_and_die("-s %s: permission denied", source);
  874. }
  875. if (waittime_str)
  876. waittime = xatoul_range(waittime_str, 2, 24 * 60 * 60);
  877. if (pausemsecs_str)
  878. pausemsecs = xatoul_range(pausemsecs_str, 0, 60 * 60 * 1000);
  879. if (first_ttl_str)
  880. first_ttl = xatoul_range(first_ttl_str, 1, 255);
  881. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  882. if (sourse_route_list) {
  883. llist_t *l_sr;
  884. for (l_sr = sourse_route_list; l_sr; ) {
  885. if (lsrr >= NGATEWAYS)
  886. bb_error_msg_and_die("no more than %d gateways", NGATEWAYS);
  887. getaddr(gwlist + lsrr, l_sr->data);
  888. ++lsrr;
  889. l_sr = l_sr->link;
  890. free(sourse_route_list);
  891. sourse_route_list = l_sr;
  892. }
  893. optlen = (lsrr + 1) * sizeof(gwlist[0]);
  894. }
  895. #endif
  896. if (first_ttl > max_ttl) {
  897. bb_error_msg_and_die(
  898. "first ttl (%d) may not be greater than max ttl (%d)",
  899. first_ttl, max_ttl);
  900. }
  901. minpacket = sizeof(*outip) + sizeof(*outdata) + optlen;
  902. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  903. if (useicmp)
  904. minpacket += 8; /* XXX magic number */
  905. else
  906. #endif
  907. minpacket += sizeof(*outudp);
  908. packlen = minpacket; /* minimum sized packet */
  909. /* Process destination and optional packet size */
  910. switch (argc - optind) {
  911. case 2:
  912. packlen = xatoul_range(argv[optind + 1], minpacket, maxpacket);
  913. /* Fall through */
  914. case 1:
  915. hostname = argv[optind];
  916. hi = gethostinfo(hostname);
  917. setsin(to, hi->addrs[0]);
  918. if (hi->n > 1)
  919. bb_error_msg("warning: %s has multiple addresses; using %s",
  920. hostname, inet_ntoa(to->sin_addr));
  921. hostname = hi->name;
  922. hi->name = NULL;
  923. freehostinfo(hi);
  924. break;
  925. default:
  926. bb_show_usage();
  927. }
  928. /* Insure the socket fds won't be 0, 1 or 2 */
  929. do n = xopen(bb_dev_null, O_RDONLY); while (n < 2);
  930. if (n > 2)
  931. close(n);
  932. s = xsocket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  933. #if TRACEROUTE_SO_DEBUG
  934. if (op & USAGE_OP_DEBUG)
  935. (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&on,
  936. sizeof(on));
  937. #endif
  938. if (op & USAGE_OP_BYPASS_ROUTE)
  939. (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&on,
  940. sizeof(on));
  941. sndsock = xsocket(AF_INET, SOCK_RAW, IPPROTO_RAW);
  942. #if ENABLE_FEATURE_TRACEROUTE_SOURCE_ROUTE
  943. #if defined(IP_OPTIONS)
  944. if (lsrr > 0) {
  945. unsigned char optlist[MAX_IPOPTLEN];
  946. /* final hop */
  947. gwlist[lsrr] = to->sin_addr.s_addr;
  948. ++lsrr;
  949. /* force 4 byte alignment */
  950. optlist[0] = IPOPT_NOP;
  951. /* loose source route option */
  952. optlist[1] = IPOPT_LSRR;
  953. i = lsrr * sizeof(gwlist[0]);
  954. optlist[2] = i + 3;
  955. /* Pointer to LSRR addresses */
  956. optlist[3] = IPOPT_MINOFF;
  957. memcpy(optlist + 4, gwlist, i);
  958. if ((setsockopt(sndsock, IPPROTO_IP, IP_OPTIONS,
  959. (char *)optlist, i + sizeof(gwlist[0]))) < 0) {
  960. bb_perror_msg_and_die("IP_OPTIONS");
  961. }
  962. }
  963. #endif /* IP_OPTIONS */
  964. #endif /* CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE */
  965. #ifdef SO_SNDBUF
  966. if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&packlen,
  967. sizeof(packlen)) < 0) {
  968. bb_perror_msg_and_die("SO_SNDBUF");
  969. }
  970. #endif
  971. #ifdef IP_HDRINCL
  972. if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL, (char *)&on,
  973. sizeof(on)) < 0 && errno != ENOPROTOOPT) {
  974. bb_perror_msg_and_die("IP_HDRINCL");
  975. }
  976. #else
  977. #ifdef IP_TOS
  978. if (tos_str && setsockopt(sndsock, IPPROTO_IP, IP_TOS,
  979. (char *)&tos, sizeof(tos)) < 0) {
  980. bb_perror_msg_and_die("setsockopt tos %d", tos);
  981. }
  982. #endif
  983. #endif
  984. #if TRACEROUTE_SO_DEBUG
  985. if (op & USAGE_OP_DEBUG)
  986. (void)setsockopt(sndsock, SOL_SOCKET, SO_DEBUG, (char *)&on,
  987. sizeof(on));
  988. #endif
  989. if (op & USAGE_OP_BYPASS_ROUTE)
  990. (void)setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE, (char *)&on,
  991. sizeof(on));
  992. /* Revert to non-privileged user after opening sockets */
  993. xsetgid(getgid());
  994. xsetuid(getuid());
  995. outip = xzalloc(packlen);
  996. outip->ip_v = IPVERSION;
  997. if (tos_str)
  998. outip->ip_tos = tos;
  999. outip->ip_len = htons(packlen);
  1000. outip->ip_off = htons(off);
  1001. outp = (unsigned char *)(outip + 1);
  1002. outip->ip_dst = to->sin_addr;
  1003. outip->ip_hl = (outp - (unsigned char *)outip) >> 2;
  1004. ident = (getpid() & 0xffff) | 0x8000;
  1005. #if ENABLE_FEATURE_TRACEROUTE_USE_ICMP
  1006. if (useicmp) {
  1007. outip->ip_p = IPPROTO_ICMP;
  1008. outicmp = (struct icmp *)outp;
  1009. outicmp->icmp_type = ICMP_ECHO;
  1010. outicmp->icmp_id = htons(ident);
  1011. outdata = (struct outdata *)(outp + 8); /* XXX magic number */
  1012. } else
  1013. #endif
  1014. {
  1015. outip->ip_p = IPPROTO_UDP;
  1016. outudp = (struct udphdr *)outp;
  1017. outudp->source = htons(ident);
  1018. outudp->len = htons((uint16_t)(packlen - (sizeof(*outip) + optlen)));
  1019. outdata = (struct outdata *)(outudp + 1);
  1020. }
  1021. /* Get the interface address list */
  1022. n = ifaddrlist(&al);
  1023. /* Look for a specific device */
  1024. if (device != NULL) {
  1025. for (i = n; i > 0; --i, ++al)
  1026. if (strcmp(device, al->device) == 0)
  1027. break;
  1028. if (i <= 0) {
  1029. bb_error_msg_and_die("can't find interface %s", device);
  1030. }
  1031. }
  1032. /* Determine our source address */
  1033. if (source == NULL) {
  1034. /*
  1035. * If a device was specified, use the interface address.
  1036. * Otherwise, try to determine our source address.
  1037. */
  1038. if (device != NULL)
  1039. setsin(from, al->addr);
  1040. findsaddr(to, from);
  1041. } else {
  1042. hi = gethostinfo(source);
  1043. source = hi->name;
  1044. hi->name = NULL;
  1045. /*
  1046. * If the device was specified make sure it
  1047. * corresponds to the source address specified.
  1048. * Otherwise, use the first address (and warn if
  1049. * there are more than one).
  1050. */
  1051. if (device != NULL) {
  1052. for (i = hi->n, ap = hi->addrs; i > 0; --i, ++ap)
  1053. if (*ap == al->addr)
  1054. break;
  1055. if (i <= 0) {
  1056. bb_error_msg_and_die(
  1057. "%s is not on interface %s",
  1058. source, device);
  1059. }
  1060. setsin(from, *ap);
  1061. } else {
  1062. setsin(from, hi->addrs[0]);
  1063. if (hi->n > 1)
  1064. bb_error_msg(
  1065. "Warning: %s has multiple addresses; using %s",
  1066. source, inet_ntoa(from->sin_addr));
  1067. }
  1068. freehostinfo(hi);
  1069. }
  1070. outip->ip_src = from->sin_addr;
  1071. #ifndef IP_HDRINCL
  1072. xbind(sndsock, (struct sockaddr *)from, sizeof(*from));
  1073. #endif
  1074. fprintf(stderr, "traceroute to %s (%s)", hostname, inet_ntoa(to->sin_addr));
  1075. if (source)
  1076. fprintf(stderr, " from %s", source);
  1077. fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl, packlen);
  1078. (void)fflush(stderr);
  1079. for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
  1080. u_int32_t lastaddr = 0;
  1081. int gotlastaddr = 0;
  1082. int got_there = 0;
  1083. int unreachable = 0;
  1084. int sentfirst = 0;
  1085. printf("%2d ", ttl);
  1086. for (probe = 0; probe < nprobes; ++probe) {
  1087. int cc;
  1088. struct timeval t1, t2;
  1089. struct timezone tz;
  1090. struct ip *ip;
  1091. if (sentfirst && pausemsecs > 0)
  1092. usleep(pausemsecs * 1000);
  1093. (void)gettimeofday(&t1, &tz);
  1094. send_probe(++seq, ttl, &t1);
  1095. ++sentfirst;
  1096. while ((cc = wait_for_reply(s, from, &t1)) != 0) {
  1097. (void)gettimeofday(&t2, &tz);
  1098. i = packet_ok(packet, cc, from, seq);
  1099. /* Skip short packet */
  1100. if (i == 0)
  1101. continue;
  1102. if (!gotlastaddr ||
  1103. from->sin_addr.s_addr != lastaddr) {
  1104. print(packet, cc, from);
  1105. lastaddr = from->sin_addr.s_addr;
  1106. ++gotlastaddr;
  1107. }
  1108. printf(" %.3f ms", deltaT(&t1, &t2));
  1109. ip = (struct ip *)packet;
  1110. if (op & USAGE_OP_TTL_FLAG)
  1111. printf(" (%d)", ip->ip_ttl);
  1112. if (i == -2) {
  1113. if (ip->ip_ttl <= 1)
  1114. printf(" !");
  1115. ++got_there;
  1116. break;
  1117. }
  1118. /* time exceeded in transit */
  1119. if (i == -1)
  1120. break;
  1121. code = i - 1;
  1122. switch (code) {
  1123. case ICMP_UNREACH_PORT:
  1124. if (ip->ip_ttl <= 1)
  1125. printf(" !");
  1126. ++got_there;
  1127. break;
  1128. case ICMP_UNREACH_NET:
  1129. ++unreachable;
  1130. printf(" !N");
  1131. break;
  1132. case ICMP_UNREACH_HOST:
  1133. ++unreachable;
  1134. printf(" !H");
  1135. break;
  1136. case ICMP_UNREACH_PROTOCOL:
  1137. ++got_there;
  1138. printf(" !P");
  1139. break;
  1140. case ICMP_UNREACH_NEEDFRAG:
  1141. ++unreachable;
  1142. printf(" !F-%d", pmtu);
  1143. break;
  1144. case ICMP_UNREACH_SRCFAIL:
  1145. ++unreachable;
  1146. printf(" !S");
  1147. break;
  1148. case ICMP_UNREACH_FILTER_PROHIB:
  1149. case ICMP_UNREACH_NET_PROHIB: /* misuse */
  1150. ++unreachable;
  1151. printf(" !A");
  1152. break;
  1153. case ICMP_UNREACH_HOST_PROHIB:
  1154. ++unreachable;
  1155. printf(" !C");
  1156. break;
  1157. case ICMP_UNREACH_HOST_PRECEDENCE:
  1158. ++unreachable;
  1159. printf(" !V");
  1160. break;
  1161. case ICMP_UNREACH_PRECEDENCE_CUTOFF:
  1162. ++unreachable;
  1163. printf(" !C");
  1164. break;
  1165. case ICMP_UNREACH_NET_UNKNOWN:
  1166. case ICMP_UNREACH_HOST_UNKNOWN:
  1167. ++unreachable;
  1168. printf(" !U");
  1169. break;
  1170. case ICMP_UNREACH_ISOLATED:
  1171. ++unreachable;
  1172. printf(" !I");
  1173. break;
  1174. case ICMP_UNREACH_TOSNET:
  1175. case ICMP_UNREACH_TOSHOST:
  1176. ++unreachable;
  1177. printf(" !T");
  1178. break;
  1179. default:
  1180. ++unreachable;
  1181. printf(" !<%d>", code);
  1182. break;
  1183. }
  1184. break;
  1185. }
  1186. if (cc == 0)
  1187. printf(" *");
  1188. (void)fflush(stdout);
  1189. }
  1190. putchar('\n');
  1191. if (got_there ||
  1192. (unreachable > 0 && unreachable >= nprobes - 1))
  1193. break;
  1194. }
  1195. return 0;
  1196. }