1 /* vi: set sw=4 ts=4: */
3 * RFC3927 ZeroConf IPv4 Link-Local addressing
4 * (see <http://www.zeroconf.org/>)
6 * Copyright (C) 2003 by Arthur van Hoff (avh@strangeberry.com)
7 * Copyright (C) 2004 by David Brownell
9 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
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.
17 //config: bool "zcip (7.8 kb)"
19 //config: select PLATFORM_LINUX
20 //config: select FEATURE_SYSLOG
22 //config: ZCIP provides ZeroConf IPv4 address selection, according to RFC 3927.
23 //config: It's a daemon that allocates and defends a dynamically assigned
24 //config: address on the 169.254/16 network, requiring no system administrator.
26 //config: See http://www.zeroconf.org for further details, and "zcip.script"
27 //config: in the busybox examples.
29 //applet:IF_ZCIP(APPLET(zcip, BB_DIR_SBIN, BB_SUID_DROP))
31 //kbuild:lib-$(CONFIG_ZCIP) += zcip.o
36 // - more real-world usage/testing, especially daemon mode
37 // - kernel packet filters to reduce scheduling noise
38 // - avoid silent script failures, especially under load...
39 // - link status monitoring (restart on link-up; stop on link-down)
41 //usage:#define zcip_trivial_usage
42 //usage: "[OPTIONS] IFACE SCRIPT"
43 //usage:#define zcip_full_usage "\n\n"
44 //usage: "Manage a ZeroConf IPv4 link-local address\n"
45 //usage: "\n -f Run in foreground"
46 //usage: "\n -q Quit after obtaining address"
47 //usage: "\n -r 169.254.x.x Request this address first"
48 //usage: "\n -l x.x.0.0 Use this range instead of 169.254"
49 //usage: "\n -v Verbose"
51 //usage: "\n$LOGGING=none Suppress logging"
52 //usage: "\n$LOGGING=syslog Log to syslog"
54 //usage: "\nWith no -q, runs continuously monitoring for ARP conflicts,"
55 //usage: "\nexits only on I/O errors (link down etc)"
58 #include "common_bufsiz.h"
59 #include <netinet/ether.h>
61 #include <net/if_arp.h>
62 #include <linux/sockios.h>
66 /* We don't need more than 32 bits of the counter */
67 #define MONOTONIC_US() ((unsigned)monotonic_us())
70 struct ether_header eth;
75 /* 0-1 seconds before sending 1st probe */
77 /* 1-2 seconds between probes */
80 PROBE_NUM = 3, /* total probes to send */
81 ANNOUNCE_INTERVAL = 2, /* 2 seconds between announces */
82 ANNOUNCE_NUM = 3, /* announces to send */
83 /* if probe/announce sees a conflict, multiply RANDOM(NUM_CONFLICT) by... */
84 CONFLICT_MULTIPLIER = 2,
85 /* if we monitor and see a conflict, how long is defend state? */
89 /* States during the configuration process. */
97 #define VDBG(...) do { } while (0)
105 struct sockaddr iface_sockaddr;
106 struct ether_addr our_ethaddr;
107 uint32_t localnet_ip;
109 #define G (*(struct globals*)bb_common_bufsiz1)
110 #define INIT_G() do { setup_common_bufsiz(); } while (0)
114 * Pick a random link local IP address on 169.254/16, except that
115 * the first and last 256 addresses are reserved.
117 static uint32_t pick_nip(void)
122 tmp = rand() & IN_CLASSB_HOST;
123 } while (tmp > (IN_CLASSB_HOST - 0x0200));
124 return htonl((G.localnet_ip + 0x0100) + tmp);
127 static const char *nip_to_a(uint32_t nip)
131 return inet_ntoa(in);
135 * Broadcast an ARP packet.
137 static void send_arp_request(
138 /* int op, - always ARPOP_REQUEST */
139 /* const struct ether_addr *source_eth, - always &G.our_ethaddr */
141 const struct ether_addr *target_eth, uint32_t target_nip)
143 enum { op = ARPOP_REQUEST };
144 #define source_eth (&G.our_ethaddr)
147 memset(&p, 0, sizeof(p));
150 p.eth.ether_type = htons(ETHERTYPE_ARP);
151 memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
152 memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
155 p.arp.arp_hrd = htons(ARPHRD_ETHER);
156 p.arp.arp_pro = htons(ETHERTYPE_IP);
157 p.arp.arp_hln = ETH_ALEN;
159 p.arp.arp_op = htons(op);
160 memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
161 memcpy(&p.arp.arp_spa, &source_nip, 4);
162 memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
163 memcpy(&p.arp.arp_tpa, &target_nip, 4);
166 // Even though sock_fd is already bound to G.iface_sockaddr, just send()
167 // won't work, because "socket is not connected"
168 // (and connect() won't fix that, "operation not supported").
169 // Thus we sendto() to G.iface_sockaddr. I wonder which sockaddr
170 // (from bind() or from sendto()?) kernel actually uses
171 // to determine iface to emit the packet from...
172 xsendto(sock_fd, &p, sizeof(p), &G.iface_sockaddr, sizeof(G.iface_sockaddr));
178 * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
180 static int run(char *argv[3], const char *param, uint32_t nip)
183 const char *addr = addr; /* for gcc */
184 const char *fmt = "%s %s %s" + 3;
185 char *env_ip = env_ip;
187 argv[2] = (char*)param;
189 VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
192 addr = nip_to_a(nip);
193 /* Must not use setenv() repeatedly, it leaks memory. Use putenv() */
194 env_ip = xasprintf("ip=%s", addr);
198 bb_error_msg(fmt, argv[2], argv[0], addr);
199 status = spawn_and_wait(argv + 1);
201 bb_unsetenv_and_free(env_ip);
204 bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
208 bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status & 0xff);
213 * Return milliseconds of random delay, up to "secs" seconds.
215 static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
217 return (unsigned)rand() % (secs * 1000);
223 int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
224 int zcip_main(int argc UNUSED_PARAM, char **argv)
227 const char *l_opt = "169.254.0.0";
232 // Ugly trick, but I want these zeroed in one go
234 const struct ether_addr null_ethaddr;
238 int timeout_ms; // must be signed
241 #define null_ethaddr (L.null_ethaddr)
243 #define chosen_nip (L.chosen_nip )
244 #define conflicts (L.conflicts )
245 #define timeout_ms (L.timeout_ms )
246 #define verbose (L.verbose )
248 memset(&L, 0, sizeof(L));
251 #define FOREGROUND (opts & 1)
252 #define QUIT (opts & 2)
253 // Parse commandline: prog [options] ifname script
254 // exactly 2 args; -v accumulates and implies -f
255 opts = getopt32(argv, "^" "fqr:l:v" "\0" "=2:vv:vf",
256 &r_opt, &l_opt, &verbose
259 // on NOMMU reexec early (or else we will rerun things twice)
261 bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
263 // Open an ARP socket
264 // (need to do it before openlog to prevent openlog from taking
265 // fd 3 (sock_fd==3))
266 xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
268 // do it before all bb_xx_msg calls
269 openlog(applet_name, 0, LOG_DAEMON);
270 logmode |= LOGMODE_SYSLOG;
272 bb_logenv_override();
276 if (inet_aton(l_opt, &net) == 0
277 || (net.s_addr & htonl(IN_CLASSB_NET)) != net.s_addr
279 bb_error_msg_and_die("invalid network address");
281 G.localnet_ip = ntohl(net.s_addr);
283 if (opts & 4) { // -r n.n.n.n
285 if (inet_aton(r_opt, &ip) == 0
286 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != G.localnet_ip
288 bb_error_msg_and_die("invalid link address");
290 chosen_nip = ip.s_addr;
294 /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
295 /* We need to make space for script argument: */
298 /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
299 #define argv_intf (argv[0])
301 xsetenv("interface", argv_intf);
303 // Initialize the interface (modprobe, ifup, etc)
304 if (run(argv, "init", 0))
307 // Initialize G.iface_sockaddr
308 // G.iface_sockaddr is: { u16 sa_family; u8 sa_data[14]; }
309 //memset(&G.iface_sockaddr, 0, sizeof(G.iface_sockaddr));
310 //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
311 safe_strncpy(G.iface_sockaddr.sa_data, argv_intf, sizeof(G.iface_sockaddr.sa_data));
313 // Bind to the interface's ARP socket
314 xbind(sock_fd, &G.iface_sockaddr, sizeof(G.iface_sockaddr));
316 // Get the interface's ethernet address
317 //memset(&ifr, 0, sizeof(ifr));
318 strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
319 xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
320 memcpy(&G.our_ethaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
322 // Start with some stable ip address, either a function of
323 // the hardware address or else the last address we used.
324 // we are taking low-order four bytes, as top-order ones
325 // aren't random enough.
326 // NOTE: the sequence of addresses we try changes only
327 // depending on when we detect conflicts.
330 move_from_unaligned32(t, ((char *)&G.our_ethaddr + 2));
333 // FIXME cases to handle:
334 // - zcip already running!
335 // - link already has local address... just defend/update
337 // Daemonize now; don't delay system startup
340 bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
342 bb_error_msg("start, interface %s", argv_intf);
345 // Run the dynamic address negotiation protocol,
346 // restarting after address conflicts:
347 // - start with some address we want to try
348 // - short random delay
349 // - arp probes to see if another host uses it
350 // 00:04:e2:64:23:c2 > ff:ff:ff:ff:ff:ff arp who-has 169.254.194.171 tell 0.0.0.0
351 // - arp announcements that we're claiming it
352 // 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
354 // - defend it, within limits
356 // - address is successfully obtained and -q was given:
357 // run "<script> config", then exit with exitcode 0
358 // - poll error (when does this happen?)
359 // - read error (when does this happen?)
360 // - sendto error (in send_arp_request()) (when does this happen?)
361 // - revents & POLLERR (link down). run "<script> deconfig" first
362 if (chosen_nip == 0) {
364 chosen_nip = pick_nip();
369 struct pollfd fds[1];
370 unsigned deadline_us = deadline_us;
376 fds[0].events = POLLIN;
379 // Poll, being ready to adjust current timeout
381 timeout_ms = random_delay_ms(PROBE_WAIT);
382 // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
383 // make the kernel filter out all packets except
384 // ones we'd care about.
386 if (timeout_ms >= 0) {
387 // Set deadline_us to the point in time when we timeout
388 deadline_us = MONOTONIC_US() + timeout_ms * 1000;
391 VDBG("...wait %d %s nsent=%u\n",
392 timeout_ms, argv_intf, nsent);
394 n = safe_poll(fds, 1, timeout_ms);
396 //bb_perror_msg("poll"); - done in safe_poll
399 if (n == 0) { // timed out?
400 VDBG("state:%d\n", state);
403 // No conflicting ARP packets were seen:
404 // we can progress through the states
405 if (nsent < PROBE_NUM) {
407 VDBG("probe/%u %s@%s\n",
408 nsent, argv_intf, nip_to_a(chosen_nip));
409 timeout_ms = PROBE_MIN * 1000;
410 timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
411 send_arp_request(0, &null_ethaddr, chosen_nip);
414 // Switch to announce state
419 // No conflicting ARP packets were seen:
420 // we can progress through the states
421 if (nsent < ANNOUNCE_NUM) {
424 VDBG("announce/%u %s@%s\n",
425 nsent, argv_intf, nip_to_a(chosen_nip));
426 timeout_ms = ANNOUNCE_INTERVAL * 1000;
427 send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip);
430 // Switch to monitor state
431 // FIXME update filters
432 run(argv, "config", chosen_nip);
433 // NOTE: all other exit paths should deconfig...
436 // fall through: switch to MONITOR
439 // case MONITOR: (shouldn't happen, MONITOR timeout is infinite)
440 // Defend period ended with no ARP replies - we won
441 timeout_ms = -1; // never timeout in monitor state
447 // Packet arrived, or link went down.
448 // We need to adjust the timeout in case we didn't receive
449 // a conflicting packet.
450 if (timeout_ms > 0) {
451 unsigned diff = deadline_us - MONOTONIC_US();
452 if ((int)(diff) < 0) {
453 // Current time is greater than the expected timeout time.
456 VDBG("adjusting timeout\n");
457 timeout_ms = (diff / 1000) | 1; // never 0
460 if ((fds[0].revents & POLLIN) == 0) {
461 if (fds[0].revents & POLLERR) {
462 // FIXME: links routinely go down;
463 // this shouldn't necessarily exit.
464 bb_error_msg("iface %s is down", argv_intf);
465 if (state >= MONITOR) {
466 // Only if we are in MONITOR or DEFEND
467 run(argv, "deconfig", chosen_nip);
475 if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
476 bb_perror_msg_and_die(bb_msg_read_error);
479 if (p.eth.ether_type != htons(ETHERTYPE_ARP))
481 if (p.arp.arp_op != htons(ARPOP_REQUEST)
482 && p.arp.arp_op != htons(ARPOP_REPLY)
488 struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
489 struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
490 struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
491 struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
492 VDBG("source=%s %s\n", ether_ntoa(sha), inet_ntoa(*spa));
493 VDBG("target=%s %s\n", ether_ntoa(tha), inet_ntoa(*tpa));
497 if (memcmp(&p.arp.arp_sha, &G.our_ethaddr, ETH_ALEN) != 0) {
498 if (memcmp(p.arp.arp_spa, &chosen_nip, 4) == 0) {
499 // A probe or reply with source_ip == chosen ip
502 if (p.arp.arp_op == htons(ARPOP_REQUEST)
503 && memcmp(p.arp.arp_spa, &const_int_0, 4) == 0
504 && memcmp(p.arp.arp_tpa, &chosen_nip, 4) == 0
506 // A probe with source_ip == 0.0.0.0, target_ip == chosen ip:
507 // another host trying to claim this ip!
511 VDBG("state:%d ip_conflict:%d\n", state, ip_conflict);
515 // Either src or target IP conflict exists
516 if (state <= ANNOUNCE) {
519 timeout_ms = PROBE_MIN * 1000
520 + CONFLICT_MULTIPLIER * random_delay_ms(conflicts);
521 goto new_nip_and_PROBE;
524 // MONITOR or DEFEND: only src IP conflict is a problem
525 if (ip_conflict & 1) {
526 if (state == MONITOR) {
527 // Src IP conflict, defend with a single ARP probe
528 VDBG("monitor conflict - defending\n");
529 timeout_ms = DEFEND_INTERVAL * 1000;
531 send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip);
535 // Another src IP conflict, start over
536 VDBG("defend conflict - starting over\n");
537 run(argv, "deconfig", chosen_nip);
540 goto new_nip_and_PROBE;
542 // Note: if we only have a target IP conflict here (ip_conflict & 2),
543 // IOW: if we just saw this sort of ARP packet:
544 // aa:bb:cc:dd:ee:ff > xx:xx:xx:xx:xx:xx arp who-has <chosen_nip> tell 0.0.0.0
545 // we expect _kernel_ to respond to that, because <chosen_nip>
546 // is (expected to be) configured on this iface.