zcip.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. //config:config ZCIP
  17. //config: bool "zcip (8.4 kb)"
  18. //config: default y
  19. //config: select PLATFORM_LINUX
  20. //config: select FEATURE_SYSLOG
  21. //config: help
  22. //config: ZCIP provides ZeroConf IPv4 address selection, according to RFC 3927.
  23. //config: It's a daemon that allocates and defends a dynamically assigned
  24. //config: address on the 169.254/16 network, requiring no system administrator.
  25. //config:
  26. //config: See http://www.zeroconf.org for further details, and "zcip.script"
  27. //config: in the busybox examples.
  28. //applet:IF_ZCIP(APPLET(zcip, BB_DIR_SBIN, BB_SUID_DROP))
  29. //kbuild:lib-$(CONFIG_ZCIP) += zcip.o
  30. //#define DEBUG
  31. // TODO:
  32. // - more real-world usage/testing, especially daemon mode
  33. // - kernel packet filters to reduce scheduling noise
  34. // - avoid silent script failures, especially under load...
  35. // - link status monitoring (restart on link-up; stop on link-down)
  36. //usage:#define zcip_trivial_usage
  37. //usage: "[OPTIONS] IFACE SCRIPT"
  38. //usage:#define zcip_full_usage "\n\n"
  39. //usage: "Manage a ZeroConf IPv4 link-local address\n"
  40. //usage: "\n -f Run in foreground"
  41. //usage: "\n -q Quit after obtaining address"
  42. //usage: "\n -r 169.254.x.x Request this address first"
  43. //usage: "\n -l x.x.0.0 Use this range instead of 169.254"
  44. //usage: "\n -v Verbose"
  45. //usage: "\n"
  46. //usage: "\n$LOGGING=none Suppress logging"
  47. //usage: "\n$LOGGING=syslog Log to syslog"
  48. //usage: "\n"
  49. //usage: "\nWith no -q, runs continuously monitoring for ARP conflicts,"
  50. //usage: "\nexits only on I/O errors (link down etc)"
  51. #include "libbb.h"
  52. #include "common_bufsiz.h"
  53. #include <netinet/ether.h>
  54. #include <net/if.h>
  55. #include <net/if_arp.h>
  56. #include <linux/sockios.h>
  57. #include <syslog.h>
  58. /* We don't need more than 32 bits of the counter */
  59. #define MONOTONIC_US() ((unsigned)monotonic_us())
  60. struct arp_packet {
  61. struct ether_header eth;
  62. struct ether_arp arp;
  63. } PACKED;
  64. enum {
  65. /* 0-1 seconds before sending 1st probe */
  66. PROBE_WAIT = 1,
  67. /* 1-2 seconds between probes */
  68. PROBE_MIN = 1,
  69. PROBE_MAX = 2,
  70. PROBE_NUM = 3, /* total probes to send */
  71. ANNOUNCE_INTERVAL = 2, /* 2 seconds between announces */
  72. ANNOUNCE_NUM = 3, /* announces to send */
  73. /* if probe/announce sees a conflict, multiply RANDOM(NUM_CONFLICT) by... */
  74. CONFLICT_MULTIPLIER = 2,
  75. /* if we monitor and see a conflict, how long is defend state? */
  76. DEFEND_INTERVAL = 10,
  77. };
  78. /* States during the configuration process. */
  79. enum {
  80. PROBE = 0,
  81. ANNOUNCE,
  82. MONITOR,
  83. DEFEND
  84. };
  85. #define VDBG(...) do { } while (0)
  86. enum {
  87. sock_fd = 3
  88. };
  89. struct globals {
  90. struct sockaddr iface_sockaddr;
  91. struct ether_addr our_ethaddr;
  92. uint32_t localnet_ip;
  93. } FIX_ALIASING;
  94. #define G (*(struct globals*)bb_common_bufsiz1)
  95. #define INIT_G() do { setup_common_bufsiz(); } while (0)
  96. /**
  97. * Pick a random link local IP address on 169.254/16, except that
  98. * the first and last 256 addresses are reserved.
  99. */
  100. static uint32_t pick_nip(void)
  101. {
  102. unsigned tmp;
  103. do {
  104. tmp = rand() & IN_CLASSB_HOST;
  105. } while (tmp > (IN_CLASSB_HOST - 0x0200));
  106. return htonl((G.localnet_ip + 0x0100) + tmp);
  107. }
  108. static const char *nip_to_a(uint32_t nip)
  109. {
  110. struct in_addr in;
  111. in.s_addr = nip;
  112. return inet_ntoa(in);
  113. }
  114. /**
  115. * Broadcast an ARP packet.
  116. */
  117. static void send_arp_request(
  118. /* int op, - always ARPOP_REQUEST */
  119. /* const struct ether_addr *source_eth, - always &G.our_ethaddr */
  120. uint32_t source_nip,
  121. const struct ether_addr *target_eth, uint32_t target_nip)
  122. {
  123. enum { op = ARPOP_REQUEST };
  124. #define source_eth (&G.our_ethaddr)
  125. struct arp_packet p;
  126. memset(&p, 0, sizeof(p));
  127. // ether header
  128. p.eth.ether_type = htons(ETHERTYPE_ARP);
  129. memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
  130. memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
  131. // arp request
  132. p.arp.arp_hrd = htons(ARPHRD_ETHER);
  133. p.arp.arp_pro = htons(ETHERTYPE_IP);
  134. p.arp.arp_hln = ETH_ALEN;
  135. p.arp.arp_pln = 4;
  136. p.arp.arp_op = htons(op);
  137. memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
  138. memcpy(&p.arp.arp_spa, &source_nip, 4);
  139. memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
  140. memcpy(&p.arp.arp_tpa, &target_nip, 4);
  141. // send it
  142. // Even though sock_fd is already bound to G.iface_sockaddr, just send()
  143. // won't work, because "socket is not connected"
  144. // (and connect() won't fix that, "operation not supported").
  145. // Thus we sendto() to G.iface_sockaddr. I wonder which sockaddr
  146. // (from bind() or from sendto()?) kernel actually uses
  147. // to determine iface to emit the packet from...
  148. xsendto(sock_fd, &p, sizeof(p), &G.iface_sockaddr, sizeof(G.iface_sockaddr));
  149. #undef source_eth
  150. }
  151. /**
  152. * Run a script.
  153. * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
  154. */
  155. static int run(char *argv[3], const char *param, uint32_t nip)
  156. {
  157. int status;
  158. const char *addr = addr; /* for gcc */
  159. const char *fmt = "%s %s %s" + 3;
  160. char *env_ip = env_ip;
  161. argv[2] = (char*)param;
  162. VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
  163. if (nip != 0) {
  164. addr = nip_to_a(nip);
  165. /* Must not use setenv() repeatedly, it leaks memory. Use putenv() */
  166. env_ip = xasprintf("ip=%s", addr);
  167. putenv(env_ip);
  168. fmt -= 3;
  169. }
  170. bb_info_msg(fmt, argv[2], argv[0], addr);
  171. status = spawn_and_wait(argv + 1);
  172. if (nip != 0)
  173. bb_unsetenv_and_free(env_ip);
  174. if (status < 0) {
  175. bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
  176. return -errno;
  177. }
  178. if (status != 0)
  179. bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status & 0xff);
  180. return status;
  181. }
  182. /**
  183. * Return milliseconds of random delay, up to "secs" seconds.
  184. */
  185. static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
  186. {
  187. return (unsigned)rand() % (secs * 1000);
  188. }
  189. /**
  190. * main program
  191. */
  192. int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  193. int zcip_main(int argc UNUSED_PARAM, char **argv)
  194. {
  195. char *r_opt;
  196. const char *l_opt = "169.254.0.0";
  197. int state;
  198. int nsent;
  199. unsigned opts;
  200. // Ugly trick, but I want these zeroed in one go
  201. struct {
  202. const struct ether_addr null_ethaddr;
  203. struct ifreq ifr;
  204. uint32_t chosen_nip;
  205. int conflicts;
  206. int timeout_ms; // must be signed
  207. int verbose;
  208. } L;
  209. #define null_ethaddr (L.null_ethaddr)
  210. #define ifr (L.ifr )
  211. #define chosen_nip (L.chosen_nip )
  212. #define conflicts (L.conflicts )
  213. #define timeout_ms (L.timeout_ms )
  214. #define verbose (L.verbose )
  215. memset(&L, 0, sizeof(L));
  216. INIT_G();
  217. #define FOREGROUND (opts & 1)
  218. #define QUIT (opts & 2)
  219. // Parse commandline: prog [options] ifname script
  220. // exactly 2 args; -v accumulates and implies -f
  221. opts = getopt32(argv, "^" "fqr:l:v" "\0" "=2:vv:vf",
  222. &r_opt, &l_opt, &verbose
  223. );
  224. #if !BB_MMU
  225. // on NOMMU reexec early (or else we will rerun things twice)
  226. if (!FOREGROUND)
  227. bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
  228. #endif
  229. // Open an ARP socket
  230. // (need to do it before openlog to prevent openlog from taking
  231. // fd 3 (sock_fd==3))
  232. xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
  233. if (!FOREGROUND) {
  234. // do it before all bb_xx_msg calls
  235. openlog(applet_name, 0, LOG_DAEMON);
  236. logmode |= LOGMODE_SYSLOG;
  237. }
  238. bb_logenv_override();
  239. { // -l n.n.n.n
  240. struct in_addr net;
  241. if (inet_aton(l_opt, &net) == 0
  242. || (net.s_addr & htonl(IN_CLASSB_NET)) != net.s_addr
  243. ) {
  244. bb_simple_error_msg_and_die("invalid network address");
  245. }
  246. G.localnet_ip = ntohl(net.s_addr);
  247. }
  248. if (opts & 4) { // -r n.n.n.n
  249. struct in_addr ip;
  250. if (inet_aton(r_opt, &ip) == 0
  251. || (ntohl(ip.s_addr) & IN_CLASSB_NET) != G.localnet_ip
  252. ) {
  253. bb_simple_error_msg_and_die("invalid link address");
  254. }
  255. chosen_nip = ip.s_addr;
  256. }
  257. argv += optind - 1;
  258. /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
  259. /* We need to make space for script argument: */
  260. argv[0] = argv[1];
  261. argv[1] = argv[2];
  262. /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
  263. #define argv_intf (argv[0])
  264. xsetenv("interface", argv_intf);
  265. // Initialize the interface (modprobe, ifup, etc)
  266. if (run(argv, "init", 0))
  267. return EXIT_FAILURE;
  268. // Initialize G.iface_sockaddr
  269. // G.iface_sockaddr is: { u16 sa_family; u8 sa_data[14]; }
  270. //memset(&G.iface_sockaddr, 0, sizeof(G.iface_sockaddr));
  271. //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
  272. safe_strncpy(G.iface_sockaddr.sa_data, argv_intf, sizeof(G.iface_sockaddr.sa_data));
  273. // Bind to the interface's ARP socket
  274. xbind(sock_fd, &G.iface_sockaddr, sizeof(G.iface_sockaddr));
  275. // Get the interface's ethernet address
  276. //memset(&ifr, 0, sizeof(ifr));
  277. strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
  278. xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
  279. memcpy(&G.our_ethaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
  280. // Start with some stable ip address, either a function of
  281. // the hardware address or else the last address we used.
  282. // we are taking low-order four bytes, as top-order ones
  283. // aren't random enough.
  284. // NOTE: the sequence of addresses we try changes only
  285. // depending on when we detect conflicts.
  286. {
  287. uint32_t t;
  288. move_from_unaligned32(t, ((char *)&G.our_ethaddr + 2));
  289. srand(t);
  290. }
  291. // FIXME cases to handle:
  292. // - zcip already running!
  293. // - link already has local address... just defend/update
  294. // Daemonize now; don't delay system startup
  295. if (!FOREGROUND) {
  296. #if BB_MMU
  297. bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
  298. #endif
  299. bb_info_msg("start, interface %s", argv_intf);
  300. }
  301. // Run the dynamic address negotiation protocol,
  302. // restarting after address conflicts:
  303. // - start with some address we want to try
  304. // - short random delay
  305. // - arp probes to see if another host uses it
  306. // 00:04:e2:64:23:c2 > ff:ff:ff:ff:ff:ff arp who-has 169.254.194.171 tell 0.0.0.0
  307. // - arp announcements that we're claiming it
  308. // 00:04:e2:64:23:c2 > ff:ff:ff:ff:ff:ff arp who-has 169.254.194.171 (00:04:e2:64:23:c2) tell 169.254.194.171
  309. // - use it
  310. // - defend it, within limits
  311. // exit if:
  312. // - address is successfully obtained and -q was given:
  313. // run "<script> config", then exit with exitcode 0
  314. // - poll error (when does this happen?)
  315. // - read error (when does this happen?)
  316. // - sendto error (in send_arp_request()) (when does this happen?)
  317. // - revents & POLLERR (link down). run "<script> deconfig" first
  318. if (chosen_nip == 0) {
  319. new_nip_and_PROBE:
  320. chosen_nip = pick_nip();
  321. }
  322. nsent = 0;
  323. state = PROBE;
  324. while (1) {
  325. struct pollfd fds[1];
  326. unsigned deadline_us = deadline_us;
  327. struct arp_packet p;
  328. int ip_conflict;
  329. int n;
  330. fds[0].fd = sock_fd;
  331. fds[0].events = POLLIN;
  332. fds[0].revents = 0;
  333. // Poll, being ready to adjust current timeout
  334. if (!timeout_ms) {
  335. timeout_ms = random_delay_ms(PROBE_WAIT);
  336. // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
  337. // make the kernel filter out all packets except
  338. // ones we'd care about.
  339. }
  340. if (timeout_ms >= 0) {
  341. // Set deadline_us to the point in time when we timeout
  342. deadline_us = MONOTONIC_US() + timeout_ms * 1000;
  343. }
  344. VDBG("...wait %d %s nsent=%u\n",
  345. timeout_ms, argv_intf, nsent);
  346. n = safe_poll(fds, 1, timeout_ms);
  347. if (n < 0) {
  348. //bb_perror_msg("poll"); - done in safe_poll
  349. return EXIT_FAILURE;
  350. }
  351. if (n == 0) { // timed out?
  352. VDBG("state:%d\n", state);
  353. switch (state) {
  354. case PROBE:
  355. // No conflicting ARP packets were seen:
  356. // we can progress through the states
  357. if (nsent < PROBE_NUM) {
  358. nsent++;
  359. VDBG("probe/%u %s@%s\n",
  360. nsent, argv_intf, nip_to_a(chosen_nip));
  361. timeout_ms = PROBE_MIN * 1000;
  362. timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
  363. send_arp_request(0, &null_ethaddr, chosen_nip);
  364. continue;
  365. }
  366. // Switch to announce state
  367. nsent = 0;
  368. state = ANNOUNCE;
  369. goto send_announce;
  370. case ANNOUNCE:
  371. // No conflicting ARP packets were seen:
  372. // we can progress through the states
  373. if (nsent < ANNOUNCE_NUM) {
  374. send_announce:
  375. nsent++;
  376. VDBG("announce/%u %s@%s\n",
  377. nsent, argv_intf, nip_to_a(chosen_nip));
  378. timeout_ms = ANNOUNCE_INTERVAL * 1000;
  379. send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip);
  380. continue;
  381. }
  382. // Switch to monitor state
  383. // FIXME update filters
  384. run(argv, "config", chosen_nip);
  385. // NOTE: all other exit paths should deconfig...
  386. if (QUIT)
  387. return EXIT_SUCCESS;
  388. // fall through: switch to MONITOR
  389. default:
  390. // case DEFEND:
  391. // case MONITOR: (shouldn't happen, MONITOR timeout is infinite)
  392. // Defend period ended with no ARP replies - we won
  393. timeout_ms = -1; // never timeout in monitor state
  394. state = MONITOR;
  395. continue;
  396. }
  397. }
  398. // Packet arrived, or link went down.
  399. // We need to adjust the timeout in case we didn't receive
  400. // a conflicting packet.
  401. if (timeout_ms > 0) {
  402. unsigned diff = deadline_us - MONOTONIC_US();
  403. if ((int)(diff) < 0) {
  404. // Current time is greater than the expected timeout time.
  405. diff = 0;
  406. }
  407. VDBG("adjusting timeout\n");
  408. timeout_ms = (diff / 1000) | 1; // never 0
  409. }
  410. if ((fds[0].revents & POLLIN) == 0) {
  411. if (fds[0].revents & POLLERR) {
  412. // FIXME: links routinely go down;
  413. // this shouldn't necessarily exit.
  414. bb_error_msg("iface %s is down", argv_intf);
  415. if (state >= MONITOR) {
  416. // Only if we are in MONITOR or DEFEND
  417. run(argv, "deconfig", chosen_nip);
  418. }
  419. return EXIT_FAILURE;
  420. }
  421. continue;
  422. }
  423. // Read ARP packet
  424. if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
  425. bb_simple_perror_msg_and_die(bb_msg_read_error);
  426. }
  427. if (p.eth.ether_type != htons(ETHERTYPE_ARP))
  428. continue;
  429. if (p.arp.arp_op != htons(ARPOP_REQUEST)
  430. && p.arp.arp_op != htons(ARPOP_REPLY)
  431. ) {
  432. continue;
  433. }
  434. #ifdef DEBUG
  435. {
  436. struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
  437. struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
  438. struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
  439. struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
  440. VDBG("source=%s %s\n", ether_ntoa(sha), inet_ntoa(*spa));
  441. VDBG("target=%s %s\n", ether_ntoa(tha), inet_ntoa(*tpa));
  442. }
  443. #endif
  444. ip_conflict = 0;
  445. if (memcmp(&p.arp.arp_sha, &G.our_ethaddr, ETH_ALEN) != 0) {
  446. if (memcmp(p.arp.arp_spa, &chosen_nip, 4) == 0) {
  447. // A probe or reply with source_ip == chosen ip
  448. ip_conflict = 1;
  449. }
  450. if (p.arp.arp_op == htons(ARPOP_REQUEST)
  451. && memcmp(p.arp.arp_spa, &const_int_0, 4) == 0
  452. && memcmp(p.arp.arp_tpa, &chosen_nip, 4) == 0
  453. ) {
  454. // A probe with source_ip == 0.0.0.0, target_ip == chosen ip:
  455. // another host trying to claim this ip!
  456. ip_conflict |= 2;
  457. }
  458. }
  459. VDBG("state:%d ip_conflict:%d\n", state, ip_conflict);
  460. if (!ip_conflict)
  461. continue;
  462. // Either src or target IP conflict exists
  463. if (state <= ANNOUNCE) {
  464. // PROBE or ANNOUNCE
  465. conflicts++;
  466. timeout_ms = PROBE_MIN * 1000
  467. + CONFLICT_MULTIPLIER * random_delay_ms(conflicts);
  468. goto new_nip_and_PROBE;
  469. }
  470. // MONITOR or DEFEND: only src IP conflict is a problem
  471. if (ip_conflict & 1) {
  472. if (state == MONITOR) {
  473. // Src IP conflict, defend with a single ARP probe
  474. VDBG("monitor conflict - defending\n");
  475. timeout_ms = DEFEND_INTERVAL * 1000;
  476. state = DEFEND;
  477. send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip);
  478. continue;
  479. }
  480. // state == DEFEND
  481. // Another src IP conflict, start over
  482. VDBG("defend conflict - starting over\n");
  483. run(argv, "deconfig", chosen_nip);
  484. conflicts = 0;
  485. timeout_ms = 0;
  486. goto new_nip_and_PROBE;
  487. }
  488. // Note: if we only have a target IP conflict here (ip_conflict & 2),
  489. // IOW: if we just saw this sort of ARP packet:
  490. // aa:bb:cc:dd:ee:ff > xx:xx:xx:xx:xx:xx arp who-has <chosen_nip> tell 0.0.0.0
  491. // we expect _kernel_ to respond to that, because <chosen_nip>
  492. // is (expected to be) configured on this iface.
  493. } // while (1)
  494. #undef argv_intf
  495. }