zcip.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. };
  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 = wait4pid(spawn(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);
  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, 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. argc -= optind;
  213. argv += optind - 1;
  214. /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
  215. /* We need to make space for script argument: */
  216. argv[0] = argv[1];
  217. argv[1] = argv[2];
  218. /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
  219. #define argv_intf (argv[0])
  220. xsetenv("interface", argv_intf);
  221. // initialize the interface (modprobe, ifup, etc)
  222. if (run(argv, "init", NULL))
  223. return EXIT_FAILURE;
  224. // initialize saddr
  225. // saddr is: { u16 sa_family; u8 sa_data[14]; }
  226. //memset(&saddr, 0, sizeof(saddr));
  227. //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
  228. safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data));
  229. // bind to the interface's ARP socket
  230. xbind(sock_fd, &saddr, sizeof(saddr));
  231. // get the interface's ethernet address
  232. //memset(&ifr, 0, sizeof(ifr));
  233. strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
  234. xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
  235. memcpy(&eth_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
  236. // start with some stable ip address, either a function of
  237. // the hardware address or else the last address we used.
  238. // we are taking low-order four bytes, as top-order ones
  239. // aren't random enough.
  240. // NOTE: the sequence of addresses we try changes only
  241. // depending on when we detect conflicts.
  242. {
  243. uint32_t t;
  244. move_from_unaligned32(t, ((char *)&eth_addr + 2));
  245. srand(t);
  246. }
  247. if (ip.s_addr == 0)
  248. ip.s_addr = pick();
  249. // FIXME cases to handle:
  250. // - zcip already running!
  251. // - link already has local address... just defend/update
  252. // daemonize now; don't delay system startup
  253. if (!FOREGROUND) {
  254. #if BB_MMU
  255. bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
  256. #endif
  257. bb_info_msg("start, interface %s", argv_intf);
  258. }
  259. // run the dynamic address negotiation protocol,
  260. // restarting after address conflicts:
  261. // - start with some address we want to try
  262. // - short random delay
  263. // - arp probes to see if another host uses it
  264. // - arp announcements that we're claiming it
  265. // - use it
  266. // - defend it, within limits
  267. // exit if:
  268. // - address is successfully obtained and -q was given:
  269. // run "<script> config", then exit with exitcode 0
  270. // - poll error (when does this happen?)
  271. // - read error (when does this happen?)
  272. // - sendto error (in arp()) (when does this happen?)
  273. // - revents & POLLERR (link down). run "<script> deconfig" first
  274. state = PROBE;
  275. while (1) {
  276. struct pollfd fds[1];
  277. unsigned deadline_us;
  278. struct arp_packet p;
  279. int source_ip_conflict;
  280. int target_ip_conflict;
  281. fds[0].fd = sock_fd;
  282. fds[0].events = POLLIN;
  283. fds[0].revents = 0;
  284. // poll, being ready to adjust current timeout
  285. if (!timeout_ms) {
  286. timeout_ms = random_delay_ms(PROBE_WAIT);
  287. // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
  288. // make the kernel filter out all packets except
  289. // ones we'd care about.
  290. }
  291. // set deadline_us to the point in time when we timeout
  292. deadline_us = MONOTONIC_US() + timeout_ms * 1000;
  293. VDBG("...wait %d %s nprobes=%u, nclaims=%u\n",
  294. timeout_ms, argv_intf, nprobes, nclaims);
  295. switch (safe_poll(fds, 1, timeout_ms)) {
  296. default:
  297. //bb_perror_msg("poll"); - done in safe_poll
  298. return EXIT_FAILURE;
  299. // timeout
  300. case 0:
  301. VDBG("state = %d\n", state);
  302. switch (state) {
  303. case PROBE:
  304. // timeouts in the PROBE state mean no conflicting ARP packets
  305. // have been received, so we can progress through the states
  306. if (nprobes < PROBE_NUM) {
  307. nprobes++;
  308. VDBG("probe/%u %s@%s\n",
  309. nprobes, argv_intf, inet_ntoa(ip));
  310. arp(/* ARPOP_REQUEST, */
  311. /* &eth_addr, */ null_ip,
  312. &null_addr, ip);
  313. timeout_ms = PROBE_MIN * 1000;
  314. timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
  315. }
  316. else {
  317. // Switch to announce state.
  318. state = ANNOUNCE;
  319. nclaims = 0;
  320. VDBG("announce/%u %s@%s\n",
  321. nclaims, argv_intf, inet_ntoa(ip));
  322. arp(/* ARPOP_REQUEST, */
  323. /* &eth_addr, */ ip,
  324. &eth_addr, ip);
  325. timeout_ms = ANNOUNCE_INTERVAL * 1000;
  326. }
  327. break;
  328. case RATE_LIMIT_PROBE:
  329. // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
  330. // have been received, so we can move immediately to the announce state
  331. state = ANNOUNCE;
  332. nclaims = 0;
  333. VDBG("announce/%u %s@%s\n",
  334. nclaims, argv_intf, inet_ntoa(ip));
  335. arp(/* ARPOP_REQUEST, */
  336. /* &eth_addr, */ ip,
  337. &eth_addr, ip);
  338. timeout_ms = ANNOUNCE_INTERVAL * 1000;
  339. break;
  340. case ANNOUNCE:
  341. // timeouts in the ANNOUNCE state mean no conflicting ARP packets
  342. // have been received, so we can progress through the states
  343. if (nclaims < ANNOUNCE_NUM) {
  344. nclaims++;
  345. VDBG("announce/%u %s@%s\n",
  346. nclaims, argv_intf, inet_ntoa(ip));
  347. arp(/* ARPOP_REQUEST, */
  348. /* &eth_addr, */ ip,
  349. &eth_addr, ip);
  350. timeout_ms = ANNOUNCE_INTERVAL * 1000;
  351. }
  352. else {
  353. // Switch to monitor state.
  354. state = MONITOR;
  355. // link is ok to use earlier
  356. // FIXME update filters
  357. run(argv, "config", &ip);
  358. ready = 1;
  359. conflicts = 0;
  360. timeout_ms = -1; // Never timeout in the monitor state.
  361. // NOTE: all other exit paths
  362. // should deconfig ...
  363. if (QUIT)
  364. return EXIT_SUCCESS;
  365. }
  366. break;
  367. case DEFEND:
  368. // We won! No ARP replies, so just go back to monitor.
  369. state = MONITOR;
  370. timeout_ms = -1;
  371. conflicts = 0;
  372. break;
  373. default:
  374. // Invalid, should never happen. Restart the whole protocol.
  375. state = PROBE;
  376. ip.s_addr = pick();
  377. timeout_ms = 0;
  378. nprobes = 0;
  379. nclaims = 0;
  380. break;
  381. } // switch (state)
  382. break; // case 0 (timeout)
  383. // packets arriving, or link went down
  384. case 1:
  385. // We need to adjust the timeout in case we didn't receive
  386. // a conflicting packet.
  387. if (timeout_ms > 0) {
  388. unsigned diff = deadline_us - MONOTONIC_US();
  389. if ((int)(diff) < 0) {
  390. // Current time is greater than the expected timeout time.
  391. // Should never happen.
  392. VDBG("missed an expected timeout\n");
  393. timeout_ms = 0;
  394. } else {
  395. VDBG("adjusting timeout\n");
  396. timeout_ms = (diff / 1000) | 1; /* never 0 */
  397. }
  398. }
  399. if ((fds[0].revents & POLLIN) == 0) {
  400. if (fds[0].revents & POLLERR) {
  401. // FIXME: links routinely go down;
  402. // this shouldn't necessarily exit.
  403. bb_error_msg("iface %s is down", argv_intf);
  404. if (ready) {
  405. run(argv, "deconfig", &ip);
  406. }
  407. return EXIT_FAILURE;
  408. }
  409. continue;
  410. }
  411. // read ARP packet
  412. if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
  413. bb_perror_msg_and_die(bb_msg_read_error);
  414. }
  415. if (p.eth.ether_type != htons(ETHERTYPE_ARP))
  416. continue;
  417. #ifdef DEBUG
  418. {
  419. struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
  420. struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
  421. struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
  422. struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
  423. VDBG("%s recv arp type=%d, op=%d,\n",
  424. argv_intf, ntohs(p.eth.ether_type),
  425. ntohs(p.arp.arp_op));
  426. VDBG("\tsource=%s %s\n",
  427. ether_ntoa(sha),
  428. inet_ntoa(*spa));
  429. VDBG("\ttarget=%s %s\n",
  430. ether_ntoa(tha),
  431. inet_ntoa(*tpa));
  432. }
  433. #endif
  434. if (p.arp.arp_op != htons(ARPOP_REQUEST)
  435. && p.arp.arp_op != htons(ARPOP_REPLY))
  436. continue;
  437. source_ip_conflict = 0;
  438. target_ip_conflict = 0;
  439. if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0
  440. && memcmp(&p.arp.arp_sha, &eth_addr, ETH_ALEN) != 0
  441. ) {
  442. source_ip_conflict = 1;
  443. }
  444. if (p.arp.arp_op == htons(ARPOP_REQUEST)
  445. && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0
  446. && memcmp(&p.arp.arp_tha, &eth_addr, ETH_ALEN) != 0
  447. ) {
  448. target_ip_conflict = 1;
  449. }
  450. VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
  451. state, source_ip_conflict, target_ip_conflict);
  452. switch (state) {
  453. case PROBE:
  454. case ANNOUNCE:
  455. // When probing or announcing, check for source IP conflicts
  456. // and other hosts doing ARP probes (target IP conflicts).
  457. if (source_ip_conflict || target_ip_conflict) {
  458. conflicts++;
  459. if (conflicts >= MAX_CONFLICTS) {
  460. VDBG("%s ratelimit\n", argv_intf);
  461. timeout_ms = RATE_LIMIT_INTERVAL * 1000;
  462. state = RATE_LIMIT_PROBE;
  463. }
  464. // restart the whole protocol
  465. ip.s_addr = pick();
  466. timeout_ms = 0;
  467. nprobes = 0;
  468. nclaims = 0;
  469. }
  470. break;
  471. case MONITOR:
  472. // If a conflict, we try to defend with a single ARP probe.
  473. if (source_ip_conflict) {
  474. VDBG("monitor conflict -- defending\n");
  475. state = DEFEND;
  476. timeout_ms = DEFEND_INTERVAL * 1000;
  477. arp(/* ARPOP_REQUEST, */
  478. /* &eth_addr, */ ip,
  479. &eth_addr, ip);
  480. }
  481. break;
  482. case DEFEND:
  483. // Well, we tried. Start over (on conflict).
  484. if (source_ip_conflict) {
  485. state = PROBE;
  486. VDBG("defend conflict -- starting over\n");
  487. ready = 0;
  488. run(argv, "deconfig", &ip);
  489. // restart the whole protocol
  490. ip.s_addr = pick();
  491. timeout_ms = 0;
  492. nprobes = 0;
  493. nclaims = 0;
  494. }
  495. break;
  496. default:
  497. // Invalid, should never happen. Restart the whole protocol.
  498. VDBG("invalid state -- starting over\n");
  499. state = PROBE;
  500. ip.s_addr = pick();
  501. timeout_ms = 0;
  502. nprobes = 0;
  503. nclaims = 0;
  504. break;
  505. } // switch state
  506. break; // case 1 (packets arriving)
  507. } // switch poll
  508. } // while (1)
  509. #undef argv_intf
  510. }