3
0

zcip.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 GPLv2 or later, see file LICENSE in this source tree.
  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. //usage:#define zcip_trivial_usage
  23. //usage: "[OPTIONS] IFACE SCRIPT"
  24. //usage:#define zcip_full_usage "\n\n"
  25. //usage: "Manage a ZeroConf IPv4 link-local address\n"
  26. //usage: "\n -f Run in foreground"
  27. //usage: "\n -q Quit after obtaining address"
  28. //usage: "\n -r 169.254.x.x Request this address first"
  29. //usage: "\n -v Verbose"
  30. //usage: "\n"
  31. //usage: "\nWith no -q, runs continuously monitoring for ARP conflicts,"
  32. //usage: "\nexits only on I/O errors (link down etc)"
  33. #include "libbb.h"
  34. #include <netinet/ether.h>
  35. #include <net/if.h>
  36. #include <net/if_arp.h>
  37. #include <linux/sockios.h>
  38. #include <syslog.h>
  39. /* We don't need more than 32 bits of the counter */
  40. #define MONOTONIC_US() ((unsigned)monotonic_us())
  41. struct arp_packet {
  42. struct ether_header eth;
  43. struct ether_arp arp;
  44. } PACKED;
  45. enum {
  46. /* 169.254.0.0 */
  47. LINKLOCAL_ADDR = 0xa9fe0000,
  48. /* protocol timeout parameters, specified in seconds */
  49. PROBE_WAIT = 1,
  50. PROBE_MIN = 1,
  51. PROBE_MAX = 2,
  52. PROBE_NUM = 3,
  53. MAX_CONFLICTS = 10,
  54. RATE_LIMIT_INTERVAL = 60,
  55. ANNOUNCE_WAIT = 2,
  56. ANNOUNCE_NUM = 2,
  57. ANNOUNCE_INTERVAL = 2,
  58. DEFEND_INTERVAL = 10
  59. };
  60. /* States during the configuration process. */
  61. enum {
  62. PROBE = 0,
  63. RATE_LIMIT_PROBE,
  64. ANNOUNCE,
  65. MONITOR,
  66. DEFEND
  67. };
  68. #define VDBG(...) do { } while (0)
  69. enum {
  70. sock_fd = 3
  71. };
  72. struct globals {
  73. struct sockaddr saddr;
  74. struct ether_addr eth_addr;
  75. } FIX_ALIASING;
  76. #define G (*(struct globals*)&bb_common_bufsiz1)
  77. #define saddr (G.saddr )
  78. #define eth_addr (G.eth_addr)
  79. #define INIT_G() do { } while (0)
  80. /**
  81. * Pick a random link local IP address on 169.254/16, except that
  82. * the first and last 256 addresses are reserved.
  83. */
  84. static uint32_t pick(void)
  85. {
  86. unsigned tmp;
  87. do {
  88. tmp = rand() & IN_CLASSB_HOST;
  89. } while (tmp > (IN_CLASSB_HOST - 0x0200));
  90. return htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
  91. }
  92. /**
  93. * Broadcast an ARP packet.
  94. */
  95. static void arp(
  96. /* int op, - always ARPOP_REQUEST */
  97. /* const struct ether_addr *source_eth, - always &eth_addr */
  98. struct in_addr source_ip,
  99. const struct ether_addr *target_eth, struct in_addr target_ip)
  100. {
  101. enum { op = ARPOP_REQUEST };
  102. #define source_eth (&eth_addr)
  103. struct arp_packet p;
  104. memset(&p, 0, sizeof(p));
  105. // ether header
  106. p.eth.ether_type = htons(ETHERTYPE_ARP);
  107. memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
  108. memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
  109. // arp request
  110. p.arp.arp_hrd = htons(ARPHRD_ETHER);
  111. p.arp.arp_pro = htons(ETHERTYPE_IP);
  112. p.arp.arp_hln = ETH_ALEN;
  113. p.arp.arp_pln = 4;
  114. p.arp.arp_op = htons(op);
  115. memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
  116. memcpy(&p.arp.arp_spa, &source_ip, sizeof(p.arp.arp_spa));
  117. memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
  118. memcpy(&p.arp.arp_tpa, &target_ip, sizeof(p.arp.arp_tpa));
  119. // send it
  120. // Even though sock_fd is already bound to saddr, just send()
  121. // won't work, because "socket is not connected"
  122. // (and connect() won't fix that, "operation not supported").
  123. // Thus we sendto() to saddr. I wonder which sockaddr
  124. // (from bind() or from sendto()?) kernel actually uses
  125. // to determine iface to emit the packet from...
  126. xsendto(sock_fd, &p, sizeof(p), &saddr, sizeof(saddr));
  127. #undef source_eth
  128. }
  129. /**
  130. * Run a script.
  131. * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
  132. */
  133. static int run(char *argv[3], const char *param, struct in_addr *ip)
  134. {
  135. int status;
  136. char *addr = addr; /* for gcc */
  137. const char *fmt = "%s %s %s" + 3;
  138. argv[2] = (char*)param;
  139. VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
  140. if (ip) {
  141. addr = inet_ntoa(*ip);
  142. xsetenv("ip", addr);
  143. fmt -= 3;
  144. }
  145. bb_info_msg(fmt, argv[2], argv[0], addr);
  146. status = spawn_and_wait(argv + 1);
  147. if (status < 0) {
  148. bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
  149. return -errno;
  150. }
  151. if (status != 0)
  152. bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status & 0xff);
  153. return status;
  154. }
  155. /**
  156. * Return milliseconds of random delay, up to "secs" seconds.
  157. */
  158. static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
  159. {
  160. return rand() % (secs * 1000);
  161. }
  162. /**
  163. * main program
  164. */
  165. int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  166. int zcip_main(int argc UNUSED_PARAM, char **argv)
  167. {
  168. int state;
  169. char *r_opt;
  170. unsigned opts;
  171. // ugly trick, but I want these zeroed in one go
  172. struct {
  173. const struct in_addr null_ip;
  174. const struct ether_addr null_addr;
  175. struct in_addr ip;
  176. struct ifreq ifr;
  177. int timeout_ms; /* must be signed */
  178. unsigned conflicts;
  179. unsigned nprobes;
  180. unsigned nclaims;
  181. int ready;
  182. int verbose;
  183. } L;
  184. #define null_ip (L.null_ip )
  185. #define null_addr (L.null_addr )
  186. #define ip (L.ip )
  187. #define ifr (L.ifr )
  188. #define timeout_ms (L.timeout_ms)
  189. #define conflicts (L.conflicts )
  190. #define nprobes (L.nprobes )
  191. #define nclaims (L.nclaims )
  192. #define ready (L.ready )
  193. #define verbose (L.verbose )
  194. memset(&L, 0, sizeof(L));
  195. INIT_G();
  196. #define FOREGROUND (opts & 1)
  197. #define QUIT (opts & 2)
  198. // parse commandline: prog [options] ifname script
  199. // exactly 2 args; -v accumulates and implies -f
  200. opt_complementary = "=2:vv:vf";
  201. opts = getopt32(argv, "fqr:v", &r_opt, &verbose);
  202. #if !BB_MMU
  203. // on NOMMU reexec early (or else we will rerun things twice)
  204. if (!FOREGROUND)
  205. bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
  206. #endif
  207. // open an ARP socket
  208. // (need to do it before openlog to prevent openlog from taking
  209. // fd 3 (sock_fd==3))
  210. xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
  211. if (!FOREGROUND) {
  212. // do it before all bb_xx_msg calls
  213. openlog(applet_name, 0, LOG_DAEMON);
  214. logmode |= LOGMODE_SYSLOG;
  215. }
  216. if (opts & 4) { // -r n.n.n.n
  217. if (inet_aton(r_opt, &ip) == 0
  218. || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR
  219. ) {
  220. bb_error_msg_and_die("invalid link address");
  221. }
  222. }
  223. argv += optind - 1;
  224. /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
  225. /* We need to make space for script argument: */
  226. argv[0] = argv[1];
  227. argv[1] = argv[2];
  228. /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
  229. #define argv_intf (argv[0])
  230. xsetenv("interface", argv_intf);
  231. // initialize the interface (modprobe, ifup, etc)
  232. if (run(argv, "init", NULL))
  233. return EXIT_FAILURE;
  234. // initialize saddr
  235. // saddr is: { u16 sa_family; u8 sa_data[14]; }
  236. //memset(&saddr, 0, sizeof(saddr));
  237. //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
  238. safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data));
  239. // bind to the interface's ARP socket
  240. xbind(sock_fd, &saddr, sizeof(saddr));
  241. // get the interface's ethernet address
  242. //memset(&ifr, 0, sizeof(ifr));
  243. strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
  244. xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
  245. memcpy(&eth_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
  246. // start with some stable ip address, either a function of
  247. // the hardware address or else the last address we used.
  248. // we are taking low-order four bytes, as top-order ones
  249. // aren't random enough.
  250. // NOTE: the sequence of addresses we try changes only
  251. // depending on when we detect conflicts.
  252. {
  253. uint32_t t;
  254. move_from_unaligned32(t, ((char *)&eth_addr + 2));
  255. srand(t);
  256. }
  257. if (ip.s_addr == 0)
  258. ip.s_addr = pick();
  259. // FIXME cases to handle:
  260. // - zcip already running!
  261. // - link already has local address... just defend/update
  262. // daemonize now; don't delay system startup
  263. if (!FOREGROUND) {
  264. #if BB_MMU
  265. bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
  266. #endif
  267. bb_info_msg("start, interface %s", argv_intf);
  268. }
  269. // run the dynamic address negotiation protocol,
  270. // restarting after address conflicts:
  271. // - start with some address we want to try
  272. // - short random delay
  273. // - arp probes to see if another host uses it
  274. // - arp announcements that we're claiming it
  275. // - use it
  276. // - defend it, within limits
  277. // exit if:
  278. // - address is successfully obtained and -q was given:
  279. // run "<script> config", then exit with exitcode 0
  280. // - poll error (when does this happen?)
  281. // - read error (when does this happen?)
  282. // - sendto error (in arp()) (when does this happen?)
  283. // - revents & POLLERR (link down). run "<script> deconfig" first
  284. state = PROBE;
  285. while (1) {
  286. struct pollfd fds[1];
  287. unsigned deadline_us;
  288. struct arp_packet p;
  289. int source_ip_conflict;
  290. int target_ip_conflict;
  291. fds[0].fd = sock_fd;
  292. fds[0].events = POLLIN;
  293. fds[0].revents = 0;
  294. // poll, being ready to adjust current timeout
  295. if (!timeout_ms) {
  296. timeout_ms = random_delay_ms(PROBE_WAIT);
  297. // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
  298. // make the kernel filter out all packets except
  299. // ones we'd care about.
  300. }
  301. // set deadline_us to the point in time when we timeout
  302. deadline_us = MONOTONIC_US() + timeout_ms * 1000;
  303. VDBG("...wait %d %s nprobes=%u, nclaims=%u\n",
  304. timeout_ms, argv_intf, nprobes, nclaims);
  305. switch (safe_poll(fds, 1, timeout_ms)) {
  306. default:
  307. //bb_perror_msg("poll"); - done in safe_poll
  308. return EXIT_FAILURE;
  309. // timeout
  310. case 0:
  311. VDBG("state = %d\n", state);
  312. switch (state) {
  313. case PROBE:
  314. // timeouts in the PROBE state mean no conflicting ARP packets
  315. // have been received, so we can progress through the states
  316. if (nprobes < PROBE_NUM) {
  317. nprobes++;
  318. VDBG("probe/%u %s@%s\n",
  319. nprobes, argv_intf, inet_ntoa(ip));
  320. arp(/* ARPOP_REQUEST, */
  321. /* &eth_addr, */ null_ip,
  322. &null_addr, ip);
  323. timeout_ms = PROBE_MIN * 1000;
  324. timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
  325. }
  326. else {
  327. // Switch to announce state.
  328. state = ANNOUNCE;
  329. nclaims = 0;
  330. VDBG("announce/%u %s@%s\n",
  331. nclaims, argv_intf, inet_ntoa(ip));
  332. arp(/* ARPOP_REQUEST, */
  333. /* &eth_addr, */ ip,
  334. &eth_addr, ip);
  335. timeout_ms = ANNOUNCE_INTERVAL * 1000;
  336. }
  337. break;
  338. case RATE_LIMIT_PROBE:
  339. // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
  340. // have been received, so we can move immediately to the announce state
  341. state = ANNOUNCE;
  342. nclaims = 0;
  343. VDBG("announce/%u %s@%s\n",
  344. nclaims, argv_intf, inet_ntoa(ip));
  345. arp(/* ARPOP_REQUEST, */
  346. /* &eth_addr, */ ip,
  347. &eth_addr, ip);
  348. timeout_ms = ANNOUNCE_INTERVAL * 1000;
  349. break;
  350. case ANNOUNCE:
  351. // timeouts in the ANNOUNCE state mean no conflicting ARP packets
  352. // have been received, so we can progress through the states
  353. if (nclaims < ANNOUNCE_NUM) {
  354. nclaims++;
  355. VDBG("announce/%u %s@%s\n",
  356. nclaims, argv_intf, inet_ntoa(ip));
  357. arp(/* ARPOP_REQUEST, */
  358. /* &eth_addr, */ ip,
  359. &eth_addr, ip);
  360. timeout_ms = ANNOUNCE_INTERVAL * 1000;
  361. }
  362. else {
  363. // Switch to monitor state.
  364. state = MONITOR;
  365. // link is ok to use earlier
  366. // FIXME update filters
  367. run(argv, "config", &ip);
  368. ready = 1;
  369. conflicts = 0;
  370. timeout_ms = -1; // Never timeout in the monitor state.
  371. // NOTE: all other exit paths
  372. // should deconfig ...
  373. if (QUIT)
  374. return EXIT_SUCCESS;
  375. }
  376. break;
  377. case DEFEND:
  378. // We won! No ARP replies, so just go back to monitor.
  379. state = MONITOR;
  380. timeout_ms = -1;
  381. conflicts = 0;
  382. break;
  383. default:
  384. // Invalid, should never happen. Restart the whole protocol.
  385. state = PROBE;
  386. ip.s_addr = pick();
  387. timeout_ms = 0;
  388. nprobes = 0;
  389. nclaims = 0;
  390. break;
  391. } // switch (state)
  392. break; // case 0 (timeout)
  393. // packets arriving, or link went down
  394. case 1:
  395. // We need to adjust the timeout in case we didn't receive
  396. // a conflicting packet.
  397. if (timeout_ms > 0) {
  398. unsigned diff = deadline_us - MONOTONIC_US();
  399. if ((int)(diff) < 0) {
  400. // Current time is greater than the expected timeout time.
  401. // Should never happen.
  402. VDBG("missed an expected timeout\n");
  403. timeout_ms = 0;
  404. } else {
  405. VDBG("adjusting timeout\n");
  406. timeout_ms = (diff / 1000) | 1; /* never 0 */
  407. }
  408. }
  409. if ((fds[0].revents & POLLIN) == 0) {
  410. if (fds[0].revents & POLLERR) {
  411. // FIXME: links routinely go down;
  412. // this shouldn't necessarily exit.
  413. bb_error_msg("iface %s is down", argv_intf);
  414. if (ready) {
  415. run(argv, "deconfig", &ip);
  416. }
  417. return EXIT_FAILURE;
  418. }
  419. continue;
  420. }
  421. // read ARP packet
  422. if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
  423. bb_perror_msg_and_die(bb_msg_read_error);
  424. }
  425. if (p.eth.ether_type != htons(ETHERTYPE_ARP))
  426. continue;
  427. #ifdef DEBUG
  428. {
  429. struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
  430. struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
  431. struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
  432. struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
  433. VDBG("%s recv arp type=%d, op=%d,\n",
  434. argv_intf, ntohs(p.eth.ether_type),
  435. ntohs(p.arp.arp_op));
  436. VDBG("\tsource=%s %s\n",
  437. ether_ntoa(sha),
  438. inet_ntoa(*spa));
  439. VDBG("\ttarget=%s %s\n",
  440. ether_ntoa(tha),
  441. inet_ntoa(*tpa));
  442. }
  443. #endif
  444. if (p.arp.arp_op != htons(ARPOP_REQUEST)
  445. && p.arp.arp_op != htons(ARPOP_REPLY))
  446. continue;
  447. source_ip_conflict = 0;
  448. target_ip_conflict = 0;
  449. if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0
  450. && memcmp(&p.arp.arp_sha, &eth_addr, ETH_ALEN) != 0
  451. ) {
  452. source_ip_conflict = 1;
  453. }
  454. if (p.arp.arp_op == htons(ARPOP_REQUEST)
  455. && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0
  456. && memcmp(&p.arp.arp_tha, &eth_addr, ETH_ALEN) != 0
  457. ) {
  458. target_ip_conflict = 1;
  459. }
  460. VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
  461. state, source_ip_conflict, target_ip_conflict);
  462. switch (state) {
  463. case PROBE:
  464. case ANNOUNCE:
  465. // When probing or announcing, check for source IP conflicts
  466. // and other hosts doing ARP probes (target IP conflicts).
  467. if (source_ip_conflict || target_ip_conflict) {
  468. conflicts++;
  469. if (conflicts >= MAX_CONFLICTS) {
  470. VDBG("%s ratelimit\n", argv_intf);
  471. timeout_ms = RATE_LIMIT_INTERVAL * 1000;
  472. state = RATE_LIMIT_PROBE;
  473. }
  474. // restart the whole protocol
  475. ip.s_addr = pick();
  476. timeout_ms = 0;
  477. nprobes = 0;
  478. nclaims = 0;
  479. }
  480. break;
  481. case MONITOR:
  482. // If a conflict, we try to defend with a single ARP probe.
  483. if (source_ip_conflict) {
  484. VDBG("monitor conflict -- defending\n");
  485. state = DEFEND;
  486. timeout_ms = DEFEND_INTERVAL * 1000;
  487. arp(/* ARPOP_REQUEST, */
  488. /* &eth_addr, */ ip,
  489. &eth_addr, ip);
  490. }
  491. break;
  492. case DEFEND:
  493. // Well, we tried. Start over (on conflict).
  494. if (source_ip_conflict) {
  495. state = PROBE;
  496. VDBG("defend conflict -- starting over\n");
  497. ready = 0;
  498. run(argv, "deconfig", &ip);
  499. // restart the whole protocol
  500. ip.s_addr = pick();
  501. timeout_ms = 0;
  502. nprobes = 0;
  503. nclaims = 0;
  504. }
  505. break;
  506. default:
  507. // Invalid, should never happen. Restart the whole protocol.
  508. VDBG("invalid state -- starting over\n");
  509. state = PROBE;
  510. ip.s_addr = pick();
  511. timeout_ms = 0;
  512. nprobes = 0;
  513. nclaims = 0;
  514. break;
  515. } // switch state
  516. break; // case 1 (packets arriving)
  517. } // switch poll
  518. } // while (1)
  519. #undef argv_intf
  520. }