2 * RFC3927 ZeroConf IPv4 Link-Local addressing
3 * (see <http://www.zeroconf.org/>)
5 * Copyright (C) 2003 by Arthur van Hoff (avh@strangeberry.com)
6 * Copyright (C) 2004 by David Brownell
8 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
12 * This can build as part of BusyBox or by itself:
14 * $(CROSS_COMPILE)cc -Os -Wall -DNO_BUSYBOX -DDEBUG -o zcip zcip.c
16 * ZCIP just manages the 169.254.*.* addresses. That network is not
17 * routed at the IP level, though various proxies or bridges can
18 * certainly be used. Its naming is built over multicast DNS.
24 // - more real-world usage/testing, especially daemon mode
25 // - kernel packet filters to reduce scheduling noise
26 // - avoid silent script failures, especially under load...
27 // - link status monitoring (restart on link-up; stop on link-down)
38 #include <sys/ioctl.h>
39 #include <sys/types.h>
41 #include <sys/socket.h>
43 #include <arpa/inet.h>
44 #include <netinet/in.h>
45 #include <netinet/ether.h>
46 #include <net/ethernet.h>
48 #include <net/if_arp.h>
50 #include <linux/if_packet.h>
51 #include <linux/sockios.h>
55 struct ether_header hdr;
56 // FIXME this part is netinet/if_ether.h "struct ether_arp"
58 struct ether_addr source_addr;
59 struct in_addr source_ip;
60 struct ether_addr target_addr;
61 struct in_addr target_ip;
66 LINKLOCAL_ADDR = 0xa9fe0000,
68 /* protocol timeout parameters, specified in seconds */
74 RATE_LIMIT_INTERVAL = 60,
77 ANNOUNCE_INTERVAL = 2,
81 static const unsigned char ZCIP_VERSION[] = "0.75 (18 April 2005)";
84 static const struct in_addr null_ip = { 0 };
85 static const struct ether_addr null_addr = { {0, 0, 0, 0, 0, 0} };
87 static int verbose = 0;
91 #define DBG(fmt,args...) \
92 fprintf(stderr, "%s: " fmt , prog , ## args)
93 #define VDBG(fmt,args...) do { \
94 if (verbose) fprintf(stderr, "%s: " fmt , prog ,## args); \
98 #define DBG(fmt,args...) \
104 * Pick a random link local IP address on 169.254/16, except that
105 * the first and last 256 addresses are reserved.
108 pick(struct in_addr *ip)
112 /* use cheaper math than lrand48() mod N */
114 tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
115 } while (tmp > (IN_CLASSB_HOST - 0x0200));
116 ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
120 * Broadcast an ARP packet.
123 arp(int fd, struct sockaddr *saddr, int op,
124 const struct ether_addr *source_addr, struct in_addr source_ip,
125 const struct ether_addr *target_addr, struct in_addr target_ip)
130 p.hdr.ether_type = htons(ETHERTYPE_ARP);
131 memcpy(p.hdr.ether_shost, source_addr, ETH_ALEN);
132 memset(p.hdr.ether_dhost, 0xff, ETH_ALEN);
135 p.arp.ar_hrd = htons(ARPHRD_ETHER);
136 p.arp.ar_pro = htons(ETHERTYPE_IP);
137 p.arp.ar_hln = ETH_ALEN;
139 p.arp.ar_op = htons(op);
140 memcpy(&p.source_addr, source_addr, ETH_ALEN);
141 memcpy(&p.source_ip, &source_ip, sizeof (p.source_ip));
142 memcpy(&p.target_addr, target_addr, ETH_ALEN);
143 memcpy(&p.target_ip, &target_ip, sizeof (p.target_ip));
146 if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
157 run(char *script, char *arg, char *intf, struct in_addr *ip)
162 if (script != NULL) {
163 VDBG("%s run %s %s\n", intf, script, arg);
165 char *addr = inet_ntoa(*ip);
166 setenv("ip", addr, 1);
167 syslog(LOG_INFO, "%s %s %s", arg, intf, addr);
171 if (pid < 0) { // error
174 } else if (pid == 0) { // child
175 execl(script, script, arg, NULL);
180 if (waitpid(pid, &status, 0) <= 0) {
184 if (WEXITSTATUS(status) != 0) {
185 fprintf(stderr, "%s: script %s failed, exit=%d\n",
186 prog, script, WEXITSTATUS(status));
193 syslog(LOG_ERR, "%s %s, %s error: %s",
194 arg, intf, why, strerror(errno));
203 * Print usage information.
205 static void ATTRIBUTE_NORETURN
206 zcip_usage(const char *msg)
208 fprintf(stderr, "%s: %s\n", prog, msg);
210 fprintf(stderr, "Usage: %s [OPTIONS] ifname script\n"
211 "\t-f foreground mode (implied by -v)\n"
212 "\t-q quit after address (no daemon)\n"
213 "\t-r 169.254.x.x request this address first\n"
214 "\t-v verbose; show version\n",
223 * Return milliseconds of random delay, up to "secs" seconds.
225 static inline unsigned
226 ms_rdelay(unsigned secs)
228 return lrand48() % (secs * 1000);
237 main(int argc, char *argv[])
238 __attribute__ ((weak, alias ("zcip_main")));
241 int zcip_main(int argc, char *argv[])
249 struct sockaddr saddr;
250 struct ether_addr addr;
251 struct in_addr ip = { 0 };
254 suseconds_t timeout = 0; // milliseconds
256 unsigned conflicts = 0;
257 unsigned nprobes = 0;
258 unsigned nclaims = 0;
261 // parse commandline: prog [options] ifname script
263 while ((t = getopt(argc, argv, "fqr:v")) != EOF) {
272 if (inet_aton(optarg, &ip) == 0
273 || (ntohl(ip.s_addr) & IN_CLASSB_NET)
275 zcip_usage("invalid link address");
280 printf("%s: version %s\n", prog, ZCIP_VERSION);
285 zcip_usage("bad option");
288 if (optind < argc - 1) {
289 intf = argv[optind++];
290 setenv("interface", intf, 1);
291 script = argv[optind++];
293 if (optind != argc || !intf)
294 zcip_usage("wrong number of arguments");
295 openlog(prog, 0, LOG_DAEMON);
297 // initialize the interface (modprobe, ifup, etc)
298 if (run(script, "init", intf, NULL) < 0)
302 memset(&saddr, 0, sizeof (saddr));
303 strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
305 // open an ARP socket
306 if ((fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) < 0) {
312 // bind to the interface's ARP socket
313 if (bind(fd, &saddr, sizeof (saddr)) < 0) {
318 unsigned short seed[3];
320 // get the interface's ethernet address
321 memset(&ifr, 0, sizeof (ifr));
322 strncpy(ifr.ifr_name, intf, sizeof (ifr.ifr_name));
323 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
324 why = "get ethernet address";
327 memcpy(&addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
329 // start with some stable ip address, either a function of
330 // the hardware address or else the last address we used.
331 // NOTE: the sequence of addresses we try changes only
332 // depending on when we detect conflicts.
333 memcpy(seed, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
339 // FIXME cases to handle:
340 // - zcip already running!
341 // - link already has local address... just defend/update
343 // daemonize now; don't delay system startup
345 if (daemon(0, verbose) < 0) {
349 syslog(LOG_INFO, "start, interface %s", intf);
352 // run the dynamic address negotiation protocol,
353 // restarting after address conflicts:
354 // - start with some address we want to try
355 // - short random delay
356 // - arp probes to see if another host else uses it
357 // - arp announcements that we're claiming it
359 // - defend it, within limits
361 struct pollfd fds[1];
366 fds[0].events = POLLIN;
369 // poll, being ready to adjust current timeout
371 gettimeofday(&tv1, NULL);
372 tv1.tv_usec += (timeout % 1000) * 1000;
373 while (tv1.tv_usec > 1000000) {
374 tv1.tv_usec -= 1000000;
377 tv1.tv_sec += timeout / 1000;
378 } else if (timeout == 0) {
379 timeout = ms_rdelay(PROBE_WAIT);
380 // FIXME setsockopt(fd, SO_ATTACH_FILTER, ...) to
381 // make the kernel filter out all packets except
382 // ones we'd care about.
384 VDBG("...wait %ld %s nprobes=%d, nclaims=%d\n",
385 timeout, intf, nprobes, nclaims);
386 switch (poll(fds, 1, timeout)) {
388 // timeouts trigger protocol transitions
391 if (nprobes < PROBE_NUM) {
393 VDBG("probe/%d %s@%s\n",
394 nprobes, intf, inet_ntoa(ip));
395 (void)arp(fd, &saddr, ARPOP_REQUEST,
398 if (nprobes < PROBE_NUM) {
399 timeout = PROBE_MIN * 1000;
400 timeout += ms_rdelay(PROBE_MAX
403 timeout = ANNOUNCE_WAIT * 1000;
405 // then announcements
406 else if (nclaims < ANNOUNCE_NUM) {
408 VDBG("announce/%d %s@%s\n",
409 nclaims, intf, inet_ntoa(ip));
410 (void)arp(fd, &saddr, ARPOP_REQUEST,
413 if (nclaims < ANNOUNCE_NUM) {
414 timeout = ANNOUNCE_INTERVAL * 1000;
416 // link is ok to use earlier
417 run(script, "config", intf, &ip);
422 // NOTE: all other exit paths
423 // should deconfig ...
426 // FIXME update filters
433 // maybe adjust timeout
437 gettimeofday(&tv2, NULL);
438 if (timercmp(&tv1, &tv2, <)) {
441 timersub(&tv1, &tv2, &tv1);
442 timeout = 1000 * tv1.tv_sec
443 + tv1.tv_usec / 1000;
446 if ((fds[0].revents & POLLIN) == 0) {
447 if (fds[0].revents & POLLERR) {
448 // FIXME: links routinely go down;
449 // this shouldn't necessarily exit.
450 fprintf(stderr, "%s %s: poll error\n",
453 run(script, "deconfig",
461 if (recv(fd, &p, sizeof (p), 0) < 0) {
465 if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
468 VDBG("%s recv arp type=%d, op=%d,\n",
469 intf, ntohs(p.hdr.ether_type),
471 VDBG("\tsource=%s %s\n",
472 ether_ntoa(&p.source_addr),
473 inet_ntoa(p.source_ip));
474 VDBG("\ttarget=%s %s\n",
475 ether_ntoa(&p.target_addr),
476 inet_ntoa(p.target_ip));
477 if (p.arp.ar_op != htons(ARPOP_REQUEST)
478 && p.arp.ar_op != htons(ARPOP_REPLY))
481 // some cases are always conflicts
482 if ((p.source_ip.s_addr == ip.s_addr)
483 && (memcmp(&addr, &p.source_addr,
486 VDBG("%s ARP conflict from %s\n", intf,
487 ether_ntoa(&p.source_addr));
489 time_t now = time(0);
491 if ((defend + DEFEND_INTERVAL)
494 (void)arp(fd, &saddr,
498 VDBG("%s defend\n", intf);
504 run(script, "deconfig", intf, &ip);
505 // FIXME rm filters: setsockopt(fd,
506 // SO_DETACH_FILTER, ...)
509 if (conflicts >= MAX_CONFLICTS) {
510 VDBG("%s ratelimit\n", intf);
511 sleep(RATE_LIMIT_INTERVAL);
513 // restart the whole protocol
519 // two hosts probing one address is a collision too
520 else if (p.target_ip.s_addr == ip.s_addr
522 && p.arp.ar_op == htons(ARPOP_REQUEST)
523 && memcmp(&addr, &p.target_addr,
538 syslog(LOG_ERR, "%s %s, %s error: %s",
539 prog, intf, why, strerror(errno));