3
0

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