zcip.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * RFC3927 ZeroConf IPv4 Link-Local addressing
  4. * (see <http://www.zeroconf.org/>)
  5. *
  6. * Copyright (C) 2003 by Arthur van Hoff (avh@strangeberry.com)
  7. * Copyright (C) 2004 by David Brownell
  8. *
  9. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  10. */
  11. /*
  12. * ZCIP just manages the 169.254.*.* addresses. That network is not
  13. * routed at the IP level, though various proxies or bridges can
  14. * certainly be used. Its naming is built over multicast DNS.
  15. */
  16. //#define DEBUG
  17. // TODO:
  18. // - more real-world usage/testing, especially daemon mode
  19. // - kernel packet filters to reduce scheduling noise
  20. // - avoid silent script failures, especially under load...
  21. // - link status monitoring (restart on link-up; stop on link-down)
  22. #include "busybox.h"
  23. #include <syslog.h>
  24. #include <poll.h>
  25. #include <sys/wait.h>
  26. #include <netinet/ether.h>
  27. #include <net/ethernet.h>
  28. #include <net/if.h>
  29. #include <net/if_arp.h>
  30. #include <linux/if_packet.h>
  31. #include <linux/sockios.h>
  32. struct arp_packet {
  33. struct ether_header hdr;
  34. struct ether_arp arp;
  35. } ATTRIBUTE_PACKED;
  36. enum {
  37. /* 169.254.0.0 */
  38. LINKLOCAL_ADDR = 0xa9fe0000,
  39. /* protocol timeout parameters, specified in seconds */
  40. PROBE_WAIT = 1,
  41. PROBE_MIN = 1,
  42. PROBE_MAX = 2,
  43. PROBE_NUM = 3,
  44. MAX_CONFLICTS = 10,
  45. RATE_LIMIT_INTERVAL = 60,
  46. ANNOUNCE_WAIT = 2,
  47. ANNOUNCE_NUM = 2,
  48. ANNOUNCE_INTERVAL = 2,
  49. DEFEND_INTERVAL = 10
  50. };
  51. /* States during the configuration process. */
  52. enum {
  53. PROBE = 0,
  54. RATE_LIMIT_PROBE,
  55. ANNOUNCE,
  56. MONITOR,
  57. DEFEND
  58. };
  59. #define VDBG(fmt,args...) \
  60. do { } while (0)
  61. static unsigned opts;
  62. #define FOREGROUND (opts & 1)
  63. #define QUIT (opts & 2)
  64. /**
  65. * Pick a random link local IP address on 169.254/16, except that
  66. * the first and last 256 addresses are reserved.
  67. */
  68. static void pick(struct in_addr *ip)
  69. {
  70. unsigned tmp;
  71. /* use cheaper math than lrand48() mod N */
  72. do {
  73. tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
  74. } while (tmp > (IN_CLASSB_HOST - 0x0200));
  75. ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
  76. }
  77. /* TODO: we need a flag to direct bb_[p]error_msg output to stderr. */
  78. /**
  79. * Broadcast an ARP packet.
  80. */
  81. static void arp(int fd, struct sockaddr *saddr, int op,
  82. const struct ether_addr *source_addr, struct in_addr source_ip,
  83. const struct ether_addr *target_addr, struct in_addr target_ip)
  84. {
  85. struct arp_packet p;
  86. memset(&p, 0, sizeof(p));
  87. // ether header
  88. p.hdr.ether_type = htons(ETHERTYPE_ARP);
  89. memcpy(p.hdr.ether_shost, source_addr, ETH_ALEN);
  90. memset(p.hdr.ether_dhost, 0xff, ETH_ALEN);
  91. // arp request
  92. p.arp.arp_hrd = htons(ARPHRD_ETHER);
  93. p.arp.arp_pro = htons(ETHERTYPE_IP);
  94. p.arp.arp_hln = ETH_ALEN;
  95. p.arp.arp_pln = 4;
  96. p.arp.arp_op = htons(op);
  97. memcpy(&p.arp.arp_sha, source_addr, ETH_ALEN);
  98. memcpy(&p.arp.arp_spa, &source_ip, sizeof (p.arp.arp_spa));
  99. memcpy(&p.arp.arp_tha, target_addr, ETH_ALEN);
  100. memcpy(&p.arp.arp_tpa, &target_ip, sizeof (p.arp.arp_tpa));
  101. // send it
  102. if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
  103. bb_perror_msg("sendto");
  104. //return -errno;
  105. }
  106. // Currently all callers ignore errors, that's why returns are
  107. // commented out...
  108. //return 0;
  109. }
  110. /**
  111. * Run a script.
  112. */
  113. static int run(char *script, char *arg, char *intf, struct in_addr *ip)
  114. {
  115. int pid, status;
  116. char *why;
  117. if(1) { //always true: if (script != NULL)
  118. VDBG("%s run %s %s\n", intf, script, arg);
  119. if (ip != NULL) {
  120. char *addr = inet_ntoa(*ip);
  121. setenv("ip", addr, 1);
  122. bb_info_msg("%s %s %s", arg, intf, addr);
  123. }
  124. pid = vfork();
  125. if (pid < 0) { // error
  126. why = "vfork";
  127. goto bad;
  128. } else if (pid == 0) { // child
  129. execl(script, script, arg, NULL);
  130. bb_perror_msg("execl");
  131. _exit(EXIT_FAILURE);
  132. }
  133. if (waitpid(pid, &status, 0) <= 0) {
  134. why = "waitpid";
  135. goto bad;
  136. }
  137. if (WEXITSTATUS(status) != 0) {
  138. bb_error_msg("script %s failed, exit=%d",
  139. script, WEXITSTATUS(status));
  140. return -errno;
  141. }
  142. }
  143. return 0;
  144. bad:
  145. status = -errno;
  146. bb_perror_msg("%s %s, %s", arg, intf, why);
  147. return status;
  148. }
  149. /**
  150. * Return milliseconds of random delay, up to "secs" seconds.
  151. */
  152. static unsigned ATTRIBUTE_ALWAYS_INLINE ms_rdelay(unsigned secs)
  153. {
  154. return lrand48() % (secs * 1000);
  155. }
  156. /**
  157. * main program
  158. */
  159. /* Used to be auto variables on main() stack, but
  160. * most of them were zero-inited. Moving them to bss
  161. * is more space-efficient.
  162. */
  163. static const struct in_addr null_ip; // = { 0 };
  164. static const struct ether_addr null_addr; // = { {0, 0, 0, 0, 0, 0} };
  165. static struct sockaddr saddr; // memset(0);
  166. static struct in_addr ip; // = { 0 };
  167. static struct ifreq ifr; //memset(0);
  168. static char *intf; // = NULL;
  169. static char *script; // = NULL;
  170. static suseconds_t timeout; // = 0; // milliseconds
  171. static unsigned conflicts; // = 0;
  172. static unsigned nprobes; // = 0;
  173. static unsigned nclaims; // = 0;
  174. static int ready; // = 0;
  175. static int verbose; // = 0;
  176. static int state = PROBE;
  177. int zcip_main(int argc, char *argv[])
  178. {
  179. struct ether_addr eth_addr;
  180. char *why;
  181. int fd;
  182. // parse commandline: prog [options] ifname script
  183. char *r_opt;
  184. opt_complementary = "vv:vf"; // -v accumulates and implies -f
  185. opts = getopt32(argc, argv, "fqr:v", &r_opt, &verbose);
  186. if (!FOREGROUND) {
  187. /* Do it early, before all bb_xx_msg calls */
  188. logmode = LOGMODE_SYSLOG;
  189. openlog(applet_name, 0, LOG_DAEMON);
  190. }
  191. if (opts & 4) { // -r n.n.n.n
  192. if (inet_aton(r_opt, &ip) == 0
  193. || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR
  194. ) {
  195. bb_error_msg_and_die("invalid link address");
  196. }
  197. }
  198. argc -= optind;
  199. argv += optind;
  200. if (argc != 2)
  201. bb_show_usage();
  202. intf = argv[0];
  203. script = argv[1];
  204. setenv("interface", intf, 1);
  205. // initialize the interface (modprobe, ifup, etc)
  206. if (run(script, "init", intf, NULL) < 0)
  207. return EXIT_FAILURE;
  208. // initialize saddr
  209. //memset(&saddr, 0, sizeof (saddr));
  210. safe_strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
  211. // open an ARP socket
  212. fd = xsocket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP));
  213. // bind to the interface's ARP socket
  214. xbind(fd, &saddr, sizeof (saddr));
  215. // get the interface's ethernet address
  216. //memset(&ifr, 0, sizeof (ifr));
  217. strncpy(ifr.ifr_name, intf, sizeof (ifr.ifr_name));
  218. if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
  219. bb_perror_msg_and_die("get ethernet address");
  220. }
  221. memcpy(&eth_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
  222. // start with some stable ip address, either a function of
  223. // the hardware address or else the last address we used.
  224. // NOTE: the sequence of addresses we try changes only
  225. // depending on when we detect conflicts.
  226. // (SVID 3 bogon: who says that "short" is always 16 bits?)
  227. seed48( (unsigned short*)&ifr.ifr_hwaddr.sa_data );
  228. if (ip.s_addr == 0)
  229. pick(&ip);
  230. // FIXME cases to handle:
  231. // - zcip already running!
  232. // - link already has local address... just defend/update
  233. // daemonize now; don't delay system startup
  234. if (!FOREGROUND) {
  235. setsid();
  236. bb_daemonize();
  237. bb_info_msg("start, interface %s", intf);
  238. }
  239. // run the dynamic address negotiation protocol,
  240. // restarting after address conflicts:
  241. // - start with some address we want to try
  242. // - short random delay
  243. // - arp probes to see if another host else uses it
  244. // - arp announcements that we're claiming it
  245. // - use it
  246. // - defend it, within limits
  247. while (1) {
  248. struct pollfd fds[1];
  249. struct timeval tv1;
  250. struct arp_packet p;
  251. int source_ip_conflict = 0;
  252. int target_ip_conflict = 0;
  253. fds[0].fd = fd;
  254. fds[0].events = POLLIN;
  255. fds[0].revents = 0;
  256. // poll, being ready to adjust current timeout
  257. if (!timeout) {
  258. timeout = ms_rdelay(PROBE_WAIT);
  259. // FIXME setsockopt(fd, SO_ATTACH_FILTER, ...) to
  260. // make the kernel filter out all packets except
  261. // ones we'd care about.
  262. }
  263. // set tv1 to the point in time when we timeout
  264. gettimeofday(&tv1, NULL);
  265. tv1.tv_usec += (timeout % 1000) * 1000;
  266. while (tv1.tv_usec > 1000000) {
  267. tv1.tv_usec -= 1000000;
  268. tv1.tv_sec++;
  269. }
  270. tv1.tv_sec += timeout / 1000;
  271. VDBG("...wait %ld %s nprobes=%d, nclaims=%d\n",
  272. timeout, intf, nprobes, nclaims);
  273. switch (poll(fds, 1, timeout)) {
  274. // timeout
  275. case 0:
  276. VDBG("state = %d\n", state);
  277. switch (state) {
  278. case PROBE:
  279. // timeouts in the PROBE state mean no conflicting ARP packets
  280. // have been received, so we can progress through the states
  281. if (nprobes < PROBE_NUM) {
  282. nprobes++;
  283. VDBG("probe/%d %s@%s\n",
  284. nprobes, intf, inet_ntoa(ip));
  285. arp(fd, &saddr, ARPOP_REQUEST,
  286. &eth_addr, null_ip,
  287. &null_addr, ip);
  288. timeout = PROBE_MIN * 1000;
  289. timeout += ms_rdelay(PROBE_MAX
  290. - PROBE_MIN);
  291. }
  292. else {
  293. // Switch to announce state.
  294. state = ANNOUNCE;
  295. nclaims = 0;
  296. VDBG("announce/%d %s@%s\n",
  297. nclaims, intf, inet_ntoa(ip));
  298. arp(fd, &saddr, ARPOP_REQUEST,
  299. &eth_addr, ip,
  300. &eth_addr, ip);
  301. timeout = ANNOUNCE_INTERVAL * 1000;
  302. }
  303. break;
  304. case RATE_LIMIT_PROBE:
  305. // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
  306. // have been received, so we can move immediately to the announce state
  307. state = ANNOUNCE;
  308. nclaims = 0;
  309. VDBG("announce/%d %s@%s\n",
  310. nclaims, intf, inet_ntoa(ip));
  311. arp(fd, &saddr, ARPOP_REQUEST,
  312. &eth_addr, ip,
  313. &eth_addr, ip);
  314. timeout = ANNOUNCE_INTERVAL * 1000;
  315. break;
  316. case ANNOUNCE:
  317. // timeouts in the ANNOUNCE state mean no conflicting ARP packets
  318. // have been received, so we can progress through the states
  319. if (nclaims < ANNOUNCE_NUM) {
  320. nclaims++;
  321. VDBG("announce/%d %s@%s\n",
  322. nclaims, intf, inet_ntoa(ip));
  323. arp(fd, &saddr, ARPOP_REQUEST,
  324. &eth_addr, ip,
  325. &eth_addr, ip);
  326. timeout = ANNOUNCE_INTERVAL * 1000;
  327. }
  328. else {
  329. // Switch to monitor state.
  330. state = MONITOR;
  331. // link is ok to use earlier
  332. // FIXME update filters
  333. run(script, "config", intf, &ip);
  334. ready = 1;
  335. conflicts = 0;
  336. timeout = -1; // Never timeout in the monitor state.
  337. // NOTE: all other exit paths
  338. // should deconfig ...
  339. if (QUIT)
  340. return EXIT_SUCCESS;
  341. }
  342. break;
  343. case DEFEND:
  344. // We won! No ARP replies, so just go back to monitor.
  345. state = MONITOR;
  346. timeout = -1;
  347. conflicts = 0;
  348. break;
  349. default:
  350. // Invalid, should never happen. Restart the whole protocol.
  351. state = PROBE;
  352. pick(&ip);
  353. timeout = 0;
  354. nprobes = 0;
  355. nclaims = 0;
  356. break;
  357. } // switch (state)
  358. break; // case 0 (timeout)
  359. // packets arriving
  360. case 1:
  361. // We need to adjust the timeout in case we didn't receive
  362. // a conflicting packet.
  363. if (timeout > 0) {
  364. struct timeval tv2;
  365. gettimeofday(&tv2, NULL);
  366. if (timercmp(&tv1, &tv2, <)) {
  367. // Current time is greater than the expected timeout time.
  368. // Should never happen.
  369. VDBG("missed an expected timeout\n");
  370. timeout = 0;
  371. } else {
  372. VDBG("adjusting timeout\n");
  373. timersub(&tv1, &tv2, &tv1);
  374. timeout = 1000 * tv1.tv_sec
  375. + tv1.tv_usec / 1000;
  376. }
  377. }
  378. if ((fds[0].revents & POLLIN) == 0) {
  379. if (fds[0].revents & POLLERR) {
  380. // FIXME: links routinely go down;
  381. // this shouldn't necessarily exit.
  382. bb_error_msg("%s: poll error", intf);
  383. if (ready) {
  384. run(script, "deconfig",
  385. intf, &ip);
  386. }
  387. return EXIT_FAILURE;
  388. }
  389. continue;
  390. }
  391. // read ARP packet
  392. if (recv(fd, &p, sizeof (p), 0) < 0) {
  393. why = "recv";
  394. goto bad;
  395. }
  396. if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
  397. continue;
  398. #ifdef DEBUG
  399. {
  400. struct ether_addr * sha = (struct ether_addr *) p.arp.arp_sha;
  401. struct ether_addr * tha = (struct ether_addr *) p.arp.arp_tha;
  402. struct in_addr * spa = (struct in_addr *) p.arp.arp_spa;
  403. struct in_addr * tpa = (struct in_addr *) p.arp.arp_tpa;
  404. VDBG("%s recv arp type=%d, op=%d,\n",
  405. intf, ntohs(p.hdr.ether_type),
  406. ntohs(p.arp.arp_op));
  407. VDBG("\tsource=%s %s\n",
  408. ether_ntoa(sha),
  409. inet_ntoa(*spa));
  410. VDBG("\ttarget=%s %s\n",
  411. ether_ntoa(tha),
  412. inet_ntoa(*tpa));
  413. }
  414. #endif
  415. if (p.arp.arp_op != htons(ARPOP_REQUEST)
  416. && p.arp.arp_op != htons(ARPOP_REPLY))
  417. continue;
  418. if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0 &&
  419. memcmp(&eth_addr, &p.arp.arp_sha, ETH_ALEN) != 0) {
  420. source_ip_conflict = 1;
  421. }
  422. if (memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0 &&
  423. p.arp.arp_op == htons(ARPOP_REQUEST) &&
  424. memcmp(&eth_addr, &p.arp.arp_tha, ETH_ALEN) != 0) {
  425. target_ip_conflict = 1;
  426. }
  427. VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
  428. state, source_ip_conflict, target_ip_conflict);
  429. switch (state) {
  430. case PROBE:
  431. case ANNOUNCE:
  432. // When probing or announcing, check for source IP conflicts
  433. // and other hosts doing ARP probes (target IP conflicts).
  434. if (source_ip_conflict || target_ip_conflict) {
  435. conflicts++;
  436. if (conflicts >= MAX_CONFLICTS) {
  437. VDBG("%s ratelimit\n", intf);
  438. timeout = RATE_LIMIT_INTERVAL * 1000;
  439. state = RATE_LIMIT_PROBE;
  440. }
  441. // restart the whole protocol
  442. pick(&ip);
  443. timeout = 0;
  444. nprobes = 0;
  445. nclaims = 0;
  446. }
  447. break;
  448. case MONITOR:
  449. // If a conflict, we try to defend with a single ARP probe.
  450. if (source_ip_conflict) {
  451. VDBG("monitor conflict -- defending\n");
  452. state = DEFEND;
  453. timeout = DEFEND_INTERVAL * 1000;
  454. arp(fd, &saddr,
  455. ARPOP_REQUEST,
  456. &eth_addr, ip,
  457. &eth_addr, ip);
  458. }
  459. break;
  460. case DEFEND:
  461. // Well, we tried. Start over (on conflict).
  462. if (source_ip_conflict) {
  463. state = PROBE;
  464. VDBG("defend conflict -- starting over\n");
  465. ready = 0;
  466. run(script, "deconfig", intf, &ip);
  467. // restart the whole protocol
  468. pick(&ip);
  469. timeout = 0;
  470. nprobes = 0;
  471. nclaims = 0;
  472. }
  473. break;
  474. default:
  475. // Invalid, should never happen. Restart the whole protocol.
  476. VDBG("invalid state -- starting over\n");
  477. state = PROBE;
  478. pick(&ip);
  479. timeout = 0;
  480. nprobes = 0;
  481. nclaims = 0;
  482. break;
  483. } // switch state
  484. break; // case 1 (packets arriving)
  485. default:
  486. why = "poll";
  487. goto bad;
  488. } // switch poll
  489. }
  490. bad:
  491. bb_perror_msg("%s, %s", intf, why);
  492. return EXIT_FAILURE;
  493. }