zcip.c 16 KB

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