3
0

zcip.c 16 KB

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