zcip.c 15 KB

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