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)
35 #include <netinet/ether.h>
36 #include <net/ethernet.h>
38 #include <net/if_arp.h>
40 #include <linux/if_packet.h>
41 #include <linux/sockios.h>
45 struct ether_header hdr;
51 LINKLOCAL_ADDR = 0xa9fe0000,
53 /* protocol timeout parameters, specified in seconds */
59 RATE_LIMIT_INTERVAL = 60,
62 ANNOUNCE_INTERVAL = 2,
66 /* States during the configuration process. */
75 #define VDBG(fmt,args...) \
79 #define FOREGROUND (opts & 1)
80 #define QUIT (opts & 2)
83 * Pick a random link local IP address on 169.254/16, except that
84 * the first and last 256 addresses are reserved.
86 static void pick(struct in_addr *ip)
90 /* use cheaper math than lrand48() mod N */
92 tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
93 } while (tmp > (IN_CLASSB_HOST - 0x0200));
94 ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
97 /* TODO: we need a flag to direct bb_[p]error_msg output to stderr. */
100 * Broadcast an ARP packet.
102 static void arp(int fd, struct sockaddr *saddr, int op,
103 const struct ether_addr *source_addr, struct in_addr source_ip,
104 const struct ether_addr *target_addr, struct in_addr target_ip)
107 memset(&p, 0, sizeof(p));
110 p.hdr.ether_type = htons(ETHERTYPE_ARP);
111 memcpy(p.hdr.ether_shost, source_addr, ETH_ALEN);
112 memset(p.hdr.ether_dhost, 0xff, ETH_ALEN);
115 p.arp.arp_hrd = htons(ARPHRD_ETHER);
116 p.arp.arp_pro = htons(ETHERTYPE_IP);
117 p.arp.arp_hln = ETH_ALEN;
119 p.arp.arp_op = htons(op);
120 memcpy(&p.arp.arp_sha, source_addr, ETH_ALEN);
121 memcpy(&p.arp.arp_spa, &source_ip, sizeof (p.arp.arp_spa));
122 memcpy(&p.arp.arp_tha, target_addr, ETH_ALEN);
123 memcpy(&p.arp.arp_tpa, &target_ip, sizeof (p.arp.arp_tpa));
126 if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
127 bb_perror_msg("sendto");
130 // Currently all callers ignore errors, that's why returns are
138 static int run(char *script, char *arg, char *intf, struct in_addr *ip)
143 if(1) { //always true: if (script != NULL)
144 VDBG("%s run %s %s\n", intf, script, arg);
146 char *addr = inet_ntoa(*ip);
147 setenv("ip", addr, 1);
148 bb_info_msg("%s %s %s", arg, intf, addr);
152 if (pid < 0) { // error
155 } else if (pid == 0) { // child
156 execl(script, script, arg, NULL);
157 bb_perror_msg("execl");
161 if (waitpid(pid, &status, 0) <= 0) {
165 if (WEXITSTATUS(status) != 0) {
166 bb_error_msg("script %s failed, exit=%d",
167 script, WEXITSTATUS(status));
174 bb_perror_msg("%s %s, %s", arg, intf, why);
180 * Return milliseconds of random delay, up to "secs" seconds.
182 static unsigned ATTRIBUTE_ALWAYS_INLINE ms_rdelay(unsigned secs)
184 return lrand48() % (secs * 1000);
191 /* Used to be auto variables on main() stack, but
192 * most of them were zero-inited. Moving them to bss
193 * is more space-efficient.
195 static const struct in_addr null_ip; // = { 0 };
196 static const struct ether_addr null_addr; // = { {0, 0, 0, 0, 0, 0} };
198 static struct sockaddr saddr; // memset(0);
199 static struct in_addr ip; // = { 0 };
200 static struct ifreq ifr; //memset(0);
202 static char *intf; // = NULL;
203 static char *script; // = NULL;
204 static suseconds_t timeout; // = 0; // milliseconds
205 static unsigned conflicts; // = 0;
206 static unsigned nprobes; // = 0;
207 static unsigned nclaims; // = 0;
208 static int ready; // = 0;
209 static int verbose; // = 0;
210 static int state = PROBE;
212 int zcip_main(int argc, char *argv[])
214 struct ether_addr eth_addr;
218 // parse commandline: prog [options] ifname script
220 opt_complementary = "vv:vf"; // -v accumulates and implies -f
221 opts = getopt32(argc, argv, "fqr:v", &r_opt, &verbose);
223 /* Do it early, before all bb_xx_msg calls */
224 logmode = LOGMODE_SYSLOG;
225 openlog(applet_name, 0, LOG_DAEMON);
227 if (opts & 4) { // -r n.n.n.n
228 if (inet_aton(r_opt, &ip) == 0
229 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR) {
230 bb_error_msg_and_die("invalid link address");
239 setenv("interface", intf, 1);
241 // initialize the interface (modprobe, ifup, etc)
242 if (run(script, "init", intf, NULL) < 0)
246 //memset(&saddr, 0, sizeof (saddr));
247 safe_strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
249 // open an ARP socket
250 fd = xsocket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP));
251 // bind to the interface's ARP socket
252 xbind(fd, &saddr, sizeof (saddr));
254 // get the interface's ethernet address
255 //memset(&ifr, 0, sizeof (ifr));
256 strncpy(ifr.ifr_name, intf, sizeof (ifr.ifr_name));
257 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
258 bb_perror_msg_and_die("get ethernet address");
260 memcpy(ð_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
262 // start with some stable ip address, either a function of
263 // the hardware address or else the last address we used.
264 // NOTE: the sequence of addresses we try changes only
265 // depending on when we detect conflicts.
266 // (SVID 3 bogon: who says that "short" is always 16 bits?)
267 seed48( (unsigned short*)&ifr.ifr_hwaddr.sa_data );
271 // FIXME cases to handle:
272 // - zcip already running!
273 // - link already has local address... just defend/update
275 // daemonize now; don't delay system startup
279 bb_info_msg("start, interface %s", intf);
282 // run the dynamic address negotiation protocol,
283 // restarting after address conflicts:
284 // - start with some address we want to try
285 // - short random delay
286 // - arp probes to see if another host else uses it
287 // - arp announcements that we're claiming it
289 // - defend it, within limits
291 struct pollfd fds[1];
295 int source_ip_conflict = 0;
296 int target_ip_conflict = 0;
299 fds[0].events = POLLIN;
302 // poll, being ready to adjust current timeout
304 timeout = ms_rdelay(PROBE_WAIT);
305 // FIXME setsockopt(fd, SO_ATTACH_FILTER, ...) to
306 // make the kernel filter out all packets except
307 // ones we'd care about.
309 // set tv1 to the point in time when we timeout
310 gettimeofday(&tv1, NULL);
311 tv1.tv_usec += (timeout % 1000) * 1000;
312 while (tv1.tv_usec > 1000000) {
313 tv1.tv_usec -= 1000000;
316 tv1.tv_sec += timeout / 1000;
318 VDBG("...wait %ld %s nprobes=%d, nclaims=%d\n",
319 timeout, intf, nprobes, nclaims);
320 switch (poll(fds, 1, timeout)) {
324 VDBG("state = %d\n", state);
327 // timeouts in the PROBE state mean no conflicting ARP packets
328 // have been received, so we can progress through the states
329 if (nprobes < PROBE_NUM) {
331 VDBG("probe/%d %s@%s\n",
332 nprobes, intf, inet_ntoa(ip));
333 arp(fd, &saddr, ARPOP_REQUEST,
336 timeout = PROBE_MIN * 1000;
337 timeout += ms_rdelay(PROBE_MAX
341 // Switch to announce state.
344 VDBG("announce/%d %s@%s\n",
345 nclaims, intf, inet_ntoa(ip));
346 arp(fd, &saddr, ARPOP_REQUEST,
349 timeout = ANNOUNCE_INTERVAL * 1000;
352 case RATE_LIMIT_PROBE:
353 // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
354 // have been received, so we can move immediately to the announce state
357 VDBG("announce/%d %s@%s\n",
358 nclaims, intf, inet_ntoa(ip));
359 arp(fd, &saddr, ARPOP_REQUEST,
362 timeout = ANNOUNCE_INTERVAL * 1000;
365 // timeouts in the ANNOUNCE state mean no conflicting ARP packets
366 // have been received, so we can progress through the states
367 if (nclaims < ANNOUNCE_NUM) {
369 VDBG("announce/%d %s@%s\n",
370 nclaims, intf, inet_ntoa(ip));
371 arp(fd, &saddr, ARPOP_REQUEST,
374 timeout = ANNOUNCE_INTERVAL * 1000;
377 // Switch to monitor state.
379 // link is ok to use earlier
380 // FIXME update filters
381 run(script, "config", intf, &ip);
384 timeout = -1; // Never timeout in the monitor state.
386 // NOTE: all other exit paths
387 // should deconfig ...
393 // We won! No ARP replies, so just go back to monitor.
399 // Invalid, should never happen. Restart the whole protocol.
407 break; // case 0 (timeout)
410 // We need to adjust the timeout in case we didn't receive
411 // a conflicting packet.
415 gettimeofday(&tv2, NULL);
416 if (timercmp(&tv1, &tv2, <)) {
417 // Current time is greater than the expected timeout time.
418 // Should never happen.
419 VDBG("missed an expected timeout\n");
422 VDBG("adjusting timeout\n");
423 timersub(&tv1, &tv2, &tv1);
424 timeout = 1000 * tv1.tv_sec
425 + tv1.tv_usec / 1000;
429 if ((fds[0].revents & POLLIN) == 0) {
430 if (fds[0].revents & POLLERR) {
431 // FIXME: links routinely go down;
432 // this shouldn't necessarily exit.
433 bb_error_msg("%s: poll error", intf);
435 run(script, "deconfig",
444 if (recv(fd, &p, sizeof (p), 0) < 0) {
448 if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
453 struct ether_addr * sha = (struct ether_addr *) p.arp.arp_sha;
454 struct ether_addr * tha = (struct ether_addr *) p.arp.arp_tha;
455 struct in_addr * spa = (struct in_addr *) p.arp.arp_spa;
456 struct in_addr * tpa = (struct in_addr *) p.arp.arp_tpa;
457 VDBG("%s recv arp type=%d, op=%d,\n",
458 intf, ntohs(p.hdr.ether_type),
459 ntohs(p.arp.arp_op));
460 VDBG("\tsource=%s %s\n",
463 VDBG("\ttarget=%s %s\n",
468 if (p.arp.arp_op != htons(ARPOP_REQUEST)
469 && p.arp.arp_op != htons(ARPOP_REPLY))
472 if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0 &&
473 memcmp(ð_addr, &p.arp.arp_sha, ETH_ALEN) != 0) {
474 source_ip_conflict = 1;
476 if (memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0 &&
477 p.arp.arp_op == htons(ARPOP_REQUEST) &&
478 memcmp(ð_addr, &p.arp.arp_tha, ETH_ALEN) != 0) {
479 target_ip_conflict = 1;
482 VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
483 state, source_ip_conflict, target_ip_conflict);
487 // When probing or announcing, check for source IP conflicts
488 // and other hosts doing ARP probes (target IP conflicts).
489 if (source_ip_conflict || target_ip_conflict) {
491 if (conflicts >= MAX_CONFLICTS) {
492 VDBG("%s ratelimit\n", intf);
493 timeout = RATE_LIMIT_INTERVAL * 1000;
494 state = RATE_LIMIT_PROBE;
497 // restart the whole protocol
505 // If a conflict, we try to defend with a single ARP probe.
506 if (source_ip_conflict) {
507 VDBG("monitor conflict -- defending\n");
509 timeout = DEFEND_INTERVAL * 1000;
517 // Well, we tried. Start over (on conflict).
518 if (source_ip_conflict) {
520 VDBG("defend conflict -- starting over\n");
522 run(script, "deconfig", intf, &ip);
524 // restart the whole protocol
532 // Invalid, should never happen. Restart the whole protocol.
533 VDBG("invalid state -- starting over\n");
542 break; // case 1 (packets arriving)
549 bb_perror_msg("%s, %s", intf, why);