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 the GPL v2 or later, see the file LICENSE in this tarball.
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 #include <netinet/ether.h>
27 #include <net/ethernet.h>
29 #include <net/if_arp.h>
30 #include <linux/if_packet.h>
31 #include <linux/sockios.h>
36 /* We don't need more than 32 bits of the counter */
37 #define MONOTONIC_US() ((unsigned)monotonic_us())
40 struct ether_header eth;
46 LINKLOCAL_ADDR = 0xa9fe0000,
48 /* protocol timeout parameters, specified in seconds */
54 RATE_LIMIT_INTERVAL = 60,
57 ANNOUNCE_INTERVAL = 2,
61 /* States during the configuration process. */
70 #define VDBG(...) do { } while (0)
78 struct sockaddr saddr;
79 struct ether_addr eth_addr;
81 #define G (*(struct globals*)&bb_common_bufsiz1)
82 #define saddr (G.saddr )
83 #define eth_addr (G.eth_addr)
87 * Pick a random link local IP address on 169.254/16, except that
88 * the first and last 256 addresses are reserved.
90 static uint32_t pick(void)
95 tmp = rand() & IN_CLASSB_HOST;
96 } while (tmp > (IN_CLASSB_HOST - 0x0200));
97 return htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
101 * Broadcast an ARP packet.
104 /* int op, - always ARPOP_REQUEST */
105 /* const struct ether_addr *source_eth, - always ð_addr */
106 struct in_addr source_ip,
107 const struct ether_addr *target_eth, struct in_addr target_ip)
109 enum { op = ARPOP_REQUEST };
110 #define source_eth (ð_addr)
113 memset(&p, 0, sizeof(p));
116 p.eth.ether_type = htons(ETHERTYPE_ARP);
117 memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
118 memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
121 p.arp.arp_hrd = htons(ARPHRD_ETHER);
122 p.arp.arp_pro = htons(ETHERTYPE_IP);
123 p.arp.arp_hln = ETH_ALEN;
125 p.arp.arp_op = htons(op);
126 memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
127 memcpy(&p.arp.arp_spa, &source_ip, sizeof(p.arp.arp_spa));
128 memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
129 memcpy(&p.arp.arp_tpa, &target_ip, sizeof(p.arp.arp_tpa));
132 // Even though sock_fd is already bound to saddr, just send()
133 // won't work, because "socket is not connected"
134 // (and connect() won't fix that, "operation not supported").
135 // Thus we sendto() to saddr. I wonder which sockaddr
136 // (from bind() or from sendto()?) kernel actually uses
137 // to determine iface to emit the packet from...
138 xsendto(sock_fd, &p, sizeof(p), &saddr, sizeof(saddr));
144 * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
146 static int run(char *argv[3], const char *param, struct in_addr *ip)
149 char *addr = addr; /* for gcc */
150 const char *fmt = "%s %s %s" + 3;
152 argv[2] = (char*)param;
154 VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
157 addr = inet_ntoa(*ip);
161 bb_info_msg(fmt, argv[2], argv[0], addr);
163 status = wait4pid(spawn(argv + 1));
165 bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
169 bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status);
174 * Return milliseconds of random delay, up to "secs" seconds.
176 static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
178 return rand() % (secs * 1000);
184 int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
185 int zcip_main(int argc, char **argv)
191 // ugly trick, but I want these zeroed in one go
193 const struct in_addr null_ip;
194 const struct ether_addr null_addr;
197 int timeout_ms; /* must be signed */
204 #define null_ip (L.null_ip )
205 #define null_addr (L.null_addr )
208 #define timeout_ms (L.timeout_ms)
209 #define conflicts (L.conflicts )
210 #define nprobes (L.nprobes )
211 #define nclaims (L.nclaims )
212 #define ready (L.ready )
213 #define verbose (L.verbose )
215 memset(&L, 0, sizeof(L));
217 #define FOREGROUND (opts & 1)
218 #define QUIT (opts & 2)
219 // parse commandline: prog [options] ifname script
220 // exactly 2 args; -v accumulates and implies -f
221 opt_complementary = "=2:vv:vf";
222 opts = getopt32(argv, "fqr:v", &r_opt, &verbose);
224 // on NOMMU reexec early (or else we will rerun things twice)
226 bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
228 // open an ARP socket
229 // (need to do it before openlog to prevent openlog from taking
230 // fd 3 (sock_fd==3))
231 xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
233 // do it before all bb_xx_msg calls
234 openlog(applet_name, 0, LOG_DAEMON);
235 logmode |= LOGMODE_SYSLOG;
237 if (opts & 4) { // -r n.n.n.n
238 if (inet_aton(r_opt, &ip) == 0
239 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR
241 bb_error_msg_and_die("invalid link address");
247 /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
248 /* We need to make space for script argument: */
251 /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
252 #define argv_intf (argv[0])
254 xsetenv("interface", argv_intf);
256 // initialize the interface (modprobe, ifup, etc)
257 if (run(argv, "init", NULL))
261 // saddr is: { u16 sa_family; u8 sa_data[14]; }
262 //memset(&saddr, 0, sizeof(saddr));
263 //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
264 safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data));
266 // bind to the interface's ARP socket
267 xbind(sock_fd, &saddr, sizeof(saddr));
269 // get the interface's ethernet address
270 //memset(&ifr, 0, sizeof(ifr));
271 strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
272 xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
273 memcpy(ð_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
275 // start with some stable ip address, either a function of
276 // the hardware address or else the last address we used.
277 // we are taking low-order four bytes, as top-order ones
278 // aren't random enough.
279 // NOTE: the sequence of addresses we try changes only
280 // depending on when we detect conflicts.
283 move_from_unaligned32(t, ((char *)ð_addr + 2));
289 // FIXME cases to handle:
290 // - zcip already running!
291 // - link already has local address... just defend/update
293 // daemonize now; don't delay system startup
296 bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
298 bb_info_msg("start, interface %s", argv_intf);
301 // run the dynamic address negotiation protocol,
302 // restarting after address conflicts:
303 // - start with some address we want to try
304 // - short random delay
305 // - arp probes to see if another host uses it
306 // - arp announcements that we're claiming it
308 // - defend it, within limits
310 // - address is successfully obtained and -q was given:
311 // run "<script> config", then exit with exitcode 0
312 // - poll error (when does this happen?)
313 // - read error (when does this happen?)
314 // - sendto error (in arp()) (when does this happen?)
315 // - revents & POLLERR (link down). run "<script> deconfig" first
318 struct pollfd fds[1];
319 unsigned deadline_us;
321 int source_ip_conflict;
322 int target_ip_conflict;
325 fds[0].events = POLLIN;
328 // poll, being ready to adjust current timeout
330 timeout_ms = random_delay_ms(PROBE_WAIT);
331 // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
332 // make the kernel filter out all packets except
333 // ones we'd care about.
335 // set deadline_us to the point in time when we timeout
336 deadline_us = MONOTONIC_US() + timeout_ms * 1000;
338 VDBG("...wait %d %s nprobes=%u, nclaims=%u\n",
339 timeout_ms, argv_intf, nprobes, nclaims);
341 switch (safe_poll(fds, 1, timeout_ms)) {
344 //bb_perror_msg("poll"); - done in safe_poll
349 VDBG("state = %d\n", state);
352 // timeouts in the PROBE state mean no conflicting ARP packets
353 // have been received, so we can progress through the states
354 if (nprobes < PROBE_NUM) {
356 VDBG("probe/%u %s@%s\n",
357 nprobes, argv_intf, inet_ntoa(ip));
358 arp(/* ARPOP_REQUEST, */
359 /* ð_addr, */ null_ip,
361 timeout_ms = PROBE_MIN * 1000;
362 timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
365 // Switch to announce state.
368 VDBG("announce/%u %s@%s\n",
369 nclaims, argv_intf, inet_ntoa(ip));
370 arp(/* ARPOP_REQUEST, */
373 timeout_ms = ANNOUNCE_INTERVAL * 1000;
376 case RATE_LIMIT_PROBE:
377 // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
378 // have been received, so we can move immediately to the announce state
381 VDBG("announce/%u %s@%s\n",
382 nclaims, argv_intf, inet_ntoa(ip));
383 arp(/* ARPOP_REQUEST, */
386 timeout_ms = ANNOUNCE_INTERVAL * 1000;
389 // timeouts in the ANNOUNCE state mean no conflicting ARP packets
390 // have been received, so we can progress through the states
391 if (nclaims < ANNOUNCE_NUM) {
393 VDBG("announce/%u %s@%s\n",
394 nclaims, argv_intf, inet_ntoa(ip));
395 arp(/* ARPOP_REQUEST, */
398 timeout_ms = ANNOUNCE_INTERVAL * 1000;
401 // Switch to monitor state.
403 // link is ok to use earlier
404 // FIXME update filters
405 run(argv, "config", &ip);
408 timeout_ms = -1; // Never timeout in the monitor state.
410 // NOTE: all other exit paths
411 // should deconfig ...
417 // We won! No ARP replies, so just go back to monitor.
423 // Invalid, should never happen. Restart the whole protocol.
431 break; // case 0 (timeout)
433 // packets arriving, or link went down
435 // We need to adjust the timeout in case we didn't receive
436 // a conflicting packet.
437 if (timeout_ms > 0) {
438 unsigned diff = deadline_us - MONOTONIC_US();
439 if ((int)(diff) < 0) {
440 // Current time is greater than the expected timeout time.
441 // Should never happen.
442 VDBG("missed an expected timeout\n");
445 VDBG("adjusting timeout\n");
446 timeout_ms = (diff / 1000) | 1; /* never 0 */
450 if ((fds[0].revents & POLLIN) == 0) {
451 if (fds[0].revents & POLLERR) {
452 // FIXME: links routinely go down;
453 // this shouldn't necessarily exit.
454 bb_error_msg("iface %s is down", argv_intf);
456 run(argv, "deconfig", &ip);
464 if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
465 bb_perror_msg_and_die(bb_msg_read_error);
467 if (p.eth.ether_type != htons(ETHERTYPE_ARP))
471 struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
472 struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
473 struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
474 struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
475 VDBG("%s recv arp type=%d, op=%d,\n",
476 argv_intf, ntohs(p.eth.ether_type),
477 ntohs(p.arp.arp_op));
478 VDBG("\tsource=%s %s\n",
481 VDBG("\ttarget=%s %s\n",
486 if (p.arp.arp_op != htons(ARPOP_REQUEST)
487 && p.arp.arp_op != htons(ARPOP_REPLY))
490 source_ip_conflict = 0;
491 target_ip_conflict = 0;
493 if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0
494 && memcmp(&p.arp.arp_sha, ð_addr, ETH_ALEN) != 0
496 source_ip_conflict = 1;
498 if (p.arp.arp_op == htons(ARPOP_REQUEST)
499 && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0
500 && memcmp(&p.arp.arp_tha, ð_addr, ETH_ALEN) != 0
502 target_ip_conflict = 1;
505 VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
506 state, source_ip_conflict, target_ip_conflict);
510 // When probing or announcing, check for source IP conflicts
511 // and other hosts doing ARP probes (target IP conflicts).
512 if (source_ip_conflict || target_ip_conflict) {
514 if (conflicts >= MAX_CONFLICTS) {
515 VDBG("%s ratelimit\n", argv_intf);
516 timeout_ms = RATE_LIMIT_INTERVAL * 1000;
517 state = RATE_LIMIT_PROBE;
520 // restart the whole protocol
528 // If a conflict, we try to defend with a single ARP probe.
529 if (source_ip_conflict) {
530 VDBG("monitor conflict -- defending\n");
532 timeout_ms = DEFEND_INTERVAL * 1000;
533 arp(/* ARPOP_REQUEST, */
539 // Well, we tried. Start over (on conflict).
540 if (source_ip_conflict) {
542 VDBG("defend conflict -- starting over\n");
544 run(argv, "deconfig", &ip);
546 // restart the whole protocol
554 // Invalid, should never happen. Restart the whole protocol.
555 VDBG("invalid state -- starting over\n");
563 break; // case 1 (packets arriving)