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.
13 * ZCIP just manages the 169.254.*.* addresses. That network is not
14 * routed at the IP level, though various proxies or bridges can
15 * certainly be used. Its naming is built over multicast DNS.
21 // - more real-world usage/testing, especially daemon mode
22 // - kernel packet filters to reduce scheduling noise
23 // - avoid silent script failures, especially under load...
24 // - link status monitoring (restart on link-up; stop on link-down)
26 //usage:#define zcip_trivial_usage
27 //usage: "[OPTIONS] IFACE SCRIPT"
28 //usage:#define zcip_full_usage "\n\n"
29 //usage: "Manage a ZeroConf IPv4 link-local address\n"
30 //usage: "\n -f Run in foreground"
31 //usage: "\n -q Quit after obtaining address"
32 //usage: "\n -r 169.254.x.x Request this address first"
33 //usage: "\n -l x.x.0.0 Use this range instead of 169.254"
34 //usage: "\n -v Verbose"
36 //usage: "\n$LOGGING=none Suppress logging"
37 //usage: "\n$LOGGING=syslog Log to syslog"
39 //usage: "\nWith no -q, runs continuously monitoring for ARP conflicts,"
40 //usage: "\nexits only on I/O errors (link down etc)"
43 #include <netinet/ether.h>
45 #include <net/if_arp.h>
46 #include <linux/sockios.h>
50 /* We don't need more than 32 bits of the counter */
51 #define MONOTONIC_US() ((unsigned)monotonic_us())
54 struct ether_header eth;
60 LINKLOCAL_ADDR = 0xa9fe0000,
62 /* protocol timeout parameters, specified in seconds */
68 RATE_LIMIT_INTERVAL = 60,
71 ANNOUNCE_INTERVAL = 2,
75 /* States during the configuration process. */
84 #define VDBG(...) do { } while (0)
92 struct sockaddr saddr;
93 struct ether_addr eth_addr;
96 #define G (*(struct globals*)&bb_common_bufsiz1)
97 #define saddr (G.saddr )
98 #define eth_addr (G.eth_addr)
99 #define INIT_G() do { } while (0)
103 * Pick a random link local IP address on 169.254/16, except that
104 * the first and last 256 addresses are reserved.
106 static uint32_t pick_nip(void)
111 tmp = rand() & IN_CLASSB_HOST;
112 } while (tmp > (IN_CLASSB_HOST - 0x0200));
113 return htonl((G.localnet_ip + 0x0100) + tmp);
117 * Broadcast an ARP packet.
120 /* int op, - always ARPOP_REQUEST */
121 /* const struct ether_addr *source_eth, - always ð_addr */
122 struct in_addr source_ip,
123 const struct ether_addr *target_eth, struct in_addr target_ip)
125 enum { op = ARPOP_REQUEST };
126 #define source_eth (ð_addr)
129 memset(&p, 0, sizeof(p));
132 p.eth.ether_type = htons(ETHERTYPE_ARP);
133 memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
134 memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
137 p.arp.arp_hrd = htons(ARPHRD_ETHER);
138 p.arp.arp_pro = htons(ETHERTYPE_IP);
139 p.arp.arp_hln = ETH_ALEN;
141 p.arp.arp_op = htons(op);
142 memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
143 memcpy(&p.arp.arp_spa, &source_ip, sizeof(p.arp.arp_spa));
144 memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
145 memcpy(&p.arp.arp_tpa, &target_ip, sizeof(p.arp.arp_tpa));
148 // Even though sock_fd is already bound to saddr, just send()
149 // won't work, because "socket is not connected"
150 // (and connect() won't fix that, "operation not supported").
151 // Thus we sendto() to saddr. I wonder which sockaddr
152 // (from bind() or from sendto()?) kernel actually uses
153 // to determine iface to emit the packet from...
154 xsendto(sock_fd, &p, sizeof(p), &saddr, sizeof(saddr));
160 * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
162 static int run(char *argv[3], const char *param, struct in_addr *ip)
165 char *addr = addr; /* for gcc */
166 const char *fmt = "%s %s %s" + 3;
168 argv[2] = (char*)param;
170 VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
173 addr = inet_ntoa(*ip);
177 bb_info_msg(fmt, argv[2], argv[0], addr);
179 status = spawn_and_wait(argv + 1);
181 bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
185 bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status & 0xff);
190 * Return milliseconds of random delay, up to "secs" seconds.
192 static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
194 return rand() % (secs * 1000);
200 int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
201 int zcip_main(int argc UNUSED_PARAM, char **argv)
205 const char *l_opt = "169.254.0.0";
208 // ugly trick, but I want these zeroed in one go
210 const struct in_addr null_ip;
211 const struct ether_addr null_addr;
214 int timeout_ms; /* must be signed */
221 #define null_ip (L.null_ip )
222 #define null_addr (L.null_addr )
225 #define timeout_ms (L.timeout_ms)
226 #define conflicts (L.conflicts )
227 #define nprobes (L.nprobes )
228 #define nclaims (L.nclaims )
229 #define ready (L.ready )
230 #define verbose (L.verbose )
232 memset(&L, 0, sizeof(L));
235 #define FOREGROUND (opts & 1)
236 #define QUIT (opts & 2)
237 // parse commandline: prog [options] ifname script
238 // exactly 2 args; -v accumulates and implies -f
239 opt_complementary = "=2:vv:vf";
240 opts = getopt32(argv, "fqr:l:v", &r_opt, &l_opt, &verbose);
242 // on NOMMU reexec early (or else we will rerun things twice)
244 bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
246 // open an ARP socket
247 // (need to do it before openlog to prevent openlog from taking
248 // fd 3 (sock_fd==3))
249 xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
251 // do it before all bb_xx_msg calls
252 openlog(applet_name, 0, LOG_DAEMON);
253 logmode |= LOGMODE_SYSLOG;
255 bb_logenv_override();
259 if (inet_aton(l_opt, &net) == 0
260 || (net.s_addr & htonl(IN_CLASSB_NET)) != net.s_addr
262 bb_error_msg_and_die("invalid network address");
264 G.localnet_ip = ntohl(net.s_addr);
266 if (opts & 4) { // -r n.n.n.n
267 if (inet_aton(r_opt, &ip) == 0
268 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != G.localnet_ip
270 bb_error_msg_and_die("invalid link address");
275 /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
276 /* We need to make space for script argument: */
279 /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
280 #define argv_intf (argv[0])
282 xsetenv("interface", argv_intf);
284 // initialize the interface (modprobe, ifup, etc)
285 if (run(argv, "init", NULL))
289 // saddr is: { u16 sa_family; u8 sa_data[14]; }
290 //memset(&saddr, 0, sizeof(saddr));
291 //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
292 safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data));
294 // bind to the interface's ARP socket
295 xbind(sock_fd, &saddr, sizeof(saddr));
297 // get the interface's ethernet address
298 //memset(&ifr, 0, sizeof(ifr));
299 strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
300 xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
301 memcpy(ð_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
303 // start with some stable ip address, either a function of
304 // the hardware address or else the last address we used.
305 // we are taking low-order four bytes, as top-order ones
306 // aren't random enough.
307 // NOTE: the sequence of addresses we try changes only
308 // depending on when we detect conflicts.
311 move_from_unaligned32(t, ((char *)ð_addr + 2));
315 ip.s_addr = pick_nip();
317 // FIXME cases to handle:
318 // - zcip already running!
319 // - link already has local address... just defend/update
321 // daemonize now; don't delay system startup
324 bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
326 bb_info_msg("start, interface %s", argv_intf);
329 // run the dynamic address negotiation protocol,
330 // restarting after address conflicts:
331 // - start with some address we want to try
332 // - short random delay
333 // - arp probes to see if another host uses it
334 // - arp announcements that we're claiming it
336 // - defend it, within limits
338 // - address is successfully obtained and -q was given:
339 // run "<script> config", then exit with exitcode 0
340 // - poll error (when does this happen?)
341 // - read error (when does this happen?)
342 // - sendto error (in arp()) (when does this happen?)
343 // - revents & POLLERR (link down). run "<script> deconfig" first
346 struct pollfd fds[1];
347 unsigned deadline_us;
349 int source_ip_conflict;
350 int target_ip_conflict;
353 fds[0].events = POLLIN;
356 // poll, being ready to adjust current timeout
358 timeout_ms = random_delay_ms(PROBE_WAIT);
359 // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
360 // make the kernel filter out all packets except
361 // ones we'd care about.
363 // set deadline_us to the point in time when we timeout
364 deadline_us = MONOTONIC_US() + timeout_ms * 1000;
366 VDBG("...wait %d %s nprobes=%u, nclaims=%u\n",
367 timeout_ms, argv_intf, nprobes, nclaims);
369 switch (safe_poll(fds, 1, timeout_ms)) {
372 //bb_perror_msg("poll"); - done in safe_poll
377 VDBG("state = %d\n", state);
380 // timeouts in the PROBE state mean no conflicting ARP packets
381 // have been received, so we can progress through the states
382 if (nprobes < PROBE_NUM) {
384 VDBG("probe/%u %s@%s\n",
385 nprobes, argv_intf, inet_ntoa(ip));
386 timeout_ms = PROBE_MIN * 1000;
387 timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
388 arp(/* ARPOP_REQUEST, */
389 /* ð_addr, */ null_ip,
393 // Switch to announce state.
396 VDBG("announce/%u %s@%s\n",
397 nclaims, argv_intf, inet_ntoa(ip));
398 timeout_ms = ANNOUNCE_INTERVAL * 1000;
399 arp(/* ARPOP_REQUEST, */
404 case RATE_LIMIT_PROBE:
405 // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
406 // have been received, so we can move immediately to the announce state
409 VDBG("announce/%u %s@%s\n",
410 nclaims, argv_intf, inet_ntoa(ip));
411 timeout_ms = ANNOUNCE_INTERVAL * 1000;
412 arp(/* ARPOP_REQUEST, */
417 // timeouts in the ANNOUNCE state mean no conflicting ARP packets
418 // have been received, so we can progress through the states
419 if (nclaims < ANNOUNCE_NUM) {
421 VDBG("announce/%u %s@%s\n",
422 nclaims, argv_intf, inet_ntoa(ip));
423 timeout_ms = ANNOUNCE_INTERVAL * 1000;
424 arp(/* ARPOP_REQUEST, */
429 // Switch to monitor state.
431 // link is ok to use earlier
432 // FIXME update filters
433 run(argv, "config", &ip);
436 timeout_ms = -1; // Never timeout in the monitor state.
438 // NOTE: all other exit paths
439 // should deconfig ...
445 // We won! No ARP replies, so just go back to monitor.
451 // Invalid, should never happen. Restart the whole protocol.
453 ip.s_addr = pick_nip();
459 break; // case 0 (timeout)
461 // packets arriving, or link went down
463 // We need to adjust the timeout in case we didn't receive
464 // a conflicting packet.
465 if (timeout_ms > 0) {
466 unsigned diff = deadline_us - MONOTONIC_US();
467 if ((int)(diff) < 0) {
468 // Current time is greater than the expected timeout time.
469 // Should never happen.
470 VDBG("missed an expected timeout\n");
473 VDBG("adjusting timeout\n");
474 timeout_ms = (diff / 1000) | 1; /* never 0 */
478 if ((fds[0].revents & POLLIN) == 0) {
479 if (fds[0].revents & POLLERR) {
480 // FIXME: links routinely go down;
481 // this shouldn't necessarily exit.
482 bb_error_msg("iface %s is down", argv_intf);
484 run(argv, "deconfig", &ip);
492 if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
493 bb_perror_msg_and_die(bb_msg_read_error);
495 if (p.eth.ether_type != htons(ETHERTYPE_ARP))
499 struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
500 struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
501 struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
502 struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
503 VDBG("%s recv arp type=%d, op=%d,\n",
504 argv_intf, ntohs(p.eth.ether_type),
505 ntohs(p.arp.arp_op));
506 VDBG("\tsource=%s %s\n",
509 VDBG("\ttarget=%s %s\n",
514 if (p.arp.arp_op != htons(ARPOP_REQUEST)
515 && p.arp.arp_op != htons(ARPOP_REPLY)
520 source_ip_conflict = 0;
521 target_ip_conflict = 0;
523 if (memcmp(&p.arp.arp_sha, ð_addr, ETH_ALEN) != 0) {
524 if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr))) {
525 /* A probe or reply with source_ip == chosen ip */
526 source_ip_conflict = 1;
528 if (p.arp.arp_op == htons(ARPOP_REQUEST)
529 && memcmp(p.arp.arp_spa, &null_ip, sizeof(struct in_addr)) == 0
530 && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0
532 /* A probe with source_ip == 0.0.0.0, target_ip == chosen ip:
533 * another host trying to claim this ip!
535 target_ip_conflict = 1;
539 VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
540 state, source_ip_conflict, target_ip_conflict);
544 // When probing or announcing, check for source IP conflicts
545 // and other hosts doing ARP probes (target IP conflicts).
546 if (source_ip_conflict || target_ip_conflict) {
548 if (conflicts >= MAX_CONFLICTS) {
549 VDBG("%s ratelimit\n", argv_intf);
550 timeout_ms = RATE_LIMIT_INTERVAL * 1000;
551 state = RATE_LIMIT_PROBE;
554 // restart the whole protocol
555 ip.s_addr = pick_nip();
562 // If a conflict, we try to defend with a single ARP probe.
563 if (source_ip_conflict) {
564 VDBG("monitor conflict -- defending\n");
566 timeout_ms = DEFEND_INTERVAL * 1000;
567 arp(/* ARPOP_REQUEST, */
573 // Well, we tried. Start over (on conflict).
574 if (source_ip_conflict) {
576 VDBG("defend conflict -- starting over\n");
578 run(argv, "deconfig", &ip);
580 // restart the whole protocol
581 ip.s_addr = pick_nip();
588 // Invalid, should never happen. Restart the whole protocol.
589 VDBG("invalid state -- starting over\n");
591 ip.s_addr = pick_nip();
597 break; // case 1 (packets arriving)