3
0

zcip.c 15 KB

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