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>
42 #include <sys/socket.h>
44 #include <arpa/inet.h>
45 #include <netinet/in.h>
46 #include <netinet/ether.h>
47 #include <net/ethernet.h>
49 #include <net/if_arp.h>
51 #include <linux/if_packet.h>
52 #include <linux/sockios.h>
56 struct ether_header hdr;
57 // FIXME this part is netinet/if_ether.h "struct ether_arp"
59 struct ether_addr source_addr;
60 struct in_addr source_ip;
61 struct ether_addr target_addr;
62 struct in_addr target_ip;
67 LINKLOCAL_ADDR = 0xa9fe0000,
69 /* protocol timeout parameters, specified in seconds */
75 RATE_LIMIT_INTERVAL = 60,
78 ANNOUNCE_INTERVAL = 2,
82 static const unsigned char ZCIP_VERSION[] = "0.75 (18 April 2005)";
85 static const struct in_addr null_ip = { 0 };
86 static const struct ether_addr null_addr = { {0, 0, 0, 0, 0, 0} };
88 static int verbose = 0;
92 #define DBG(fmt,args...) \
93 fprintf(stderr, "%s: " fmt , prog , ## args)
94 #define VDBG(fmt,args...) do { \
95 if (verbose) fprintf(stderr, "%s: " fmt , prog ,## args); \
99 #define DBG(fmt,args...) \
105 * Pick a random link local IP address on 169.254/16, except that
106 * the first and last 256 addresses are reserved.
109 pick(struct in_addr *ip)
113 /* use cheaper math than lrand48() mod N */
115 tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
116 } while (tmp > (IN_CLASSB_HOST - 0x0200));
117 ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
121 * Broadcast an ARP packet.
124 arp(int fd, struct sockaddr *saddr, int op,
125 const struct ether_addr *source_addr, struct in_addr source_ip,
126 const struct ether_addr *target_addr, struct in_addr target_ip)
131 p.hdr.ether_type = htons(ETHERTYPE_ARP);
132 memcpy(p.hdr.ether_shost, source_addr, ETH_ALEN);
133 memset(p.hdr.ether_dhost, 0xff, ETH_ALEN);
136 p.arp.ar_hrd = htons(ARPHRD_ETHER);
137 p.arp.ar_pro = htons(ETHERTYPE_IP);
138 p.arp.ar_hln = ETH_ALEN;
140 p.arp.ar_op = htons(op);
141 memcpy(&p.source_addr, source_addr, ETH_ALEN);
142 memcpy(&p.source_ip, &source_ip, sizeof (p.source_ip));
143 memcpy(&p.target_addr, target_addr, ETH_ALEN);
144 memcpy(&p.target_ip, &target_ip, sizeof (p.target_ip));
147 if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
158 run(char *script, char *arg, char *intf, struct in_addr *ip)
163 if (script != NULL) {
164 VDBG("%s run %s %s\n", intf, script, arg);
166 char *addr = inet_ntoa(*ip);
167 setenv("ip", addr, 1);
168 syslog(LOG_INFO, "%s %s %s", arg, intf, addr);
172 if (pid < 0) { // error
175 } else if (pid == 0) { // child
176 execl(script, script, arg, NULL);
181 if (waitpid(pid, &status, 0) <= 0) {
185 if (WEXITSTATUS(status) != 0) {
186 fprintf(stderr, "%s: script %s failed, exit=%d\n",
187 prog, script, WEXITSTATUS(status));
194 syslog(LOG_ERR, "%s %s, %s error: %s",
195 arg, intf, why, strerror(errno));
204 * Print usage information.
206 static void ATTRIBUTE_NORETURN
207 zcip_usage(const char *msg)
209 fprintf(stderr, "%s: %s\n", prog, msg);
211 fprintf(stderr, "Usage: %s [OPTIONS] ifname script\n"
212 "\t-f foreground mode (implied by -v)\n"
213 "\t-q quit after address (no daemon)\n"
214 "\t-r 169.254.x.x request this address first\n"
215 "\t-v verbose; show version\n",
224 * Return milliseconds of random delay, up to "secs" seconds.
226 static inline unsigned
227 ms_rdelay(unsigned secs)
229 return lrand48() % (secs * 1000);
238 main(int argc, char *argv[])
239 __attribute__ ((weak, alias ("zcip_main")));
242 int zcip_main(int argc, char *argv[])
250 struct sockaddr saddr;
251 struct ether_addr addr;
252 struct in_addr ip = { 0 };
255 suseconds_t timeout = 0; // milliseconds
257 unsigned conflicts = 0;
258 unsigned nprobes = 0;
259 unsigned nclaims = 0;
262 // parse commandline: prog [options] ifname script
264 while ((t = getopt(argc, argv, "fqr:v")) != EOF) {
273 if (inet_aton(optarg, &ip) == 0
274 || (ntohl(ip.s_addr) & IN_CLASSB_NET)
276 zcip_usage("invalid link address");
281 printf("%s: version %s\n", prog, ZCIP_VERSION);
286 zcip_usage("bad option");
289 if (optind < argc - 1) {
290 intf = argv[optind++];
291 setenv("interface", intf, 1);
292 script = argv[optind++];
294 if (optind != argc || !intf)
295 zcip_usage("wrong number of arguments");
296 openlog(prog, 0, LOG_DAEMON);
298 // initialize the interface (modprobe, ifup, etc)
299 if (run(script, "init", intf, NULL) < 0)
303 memset(&saddr, 0, sizeof (saddr));
304 strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
306 // open an ARP socket
307 if ((fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) < 0) {
313 // bind to the interface's ARP socket
314 if (bind(fd, &saddr, sizeof (saddr)) < 0) {
319 unsigned short seed[3];
321 // get the interface's ethernet address
322 memset(&ifr, 0, sizeof (ifr));
323 strncpy(ifr.ifr_name, intf, sizeof (ifr.ifr_name));
324 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
325 why = "get ethernet address";
328 memcpy(&addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
330 // start with some stable ip address, either a function of
331 // the hardware address or else the last address we used.
332 // NOTE: the sequence of addresses we try changes only
333 // depending on when we detect conflicts.
334 memcpy(seed, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
340 // FIXME cases to handle:
341 // - zcip already running!
342 // - link already has local address... just defend/update
344 // daemonize now; don't delay system startup
346 if (daemon(0, verbose) < 0) {
350 syslog(LOG_INFO, "start, interface %s", intf);
353 // run the dynamic address negotiation protocol,
354 // restarting after address conflicts:
355 // - start with some address we want to try
356 // - short random delay
357 // - arp probes to see if another host else uses it
358 // - arp announcements that we're claiming it
360 // - defend it, within limits
362 struct pollfd fds[1];
367 fds[0].events = POLLIN;
370 // poll, being ready to adjust current timeout
372 gettimeofday(&tv1, NULL);
373 tv1.tv_usec += (timeout % 1000) * 1000;
374 while (tv1.tv_usec > 1000000) {
375 tv1.tv_usec -= 1000000;
378 tv1.tv_sec += timeout / 1000;
379 } else if (timeout == 0) {
380 timeout = ms_rdelay(PROBE_WAIT);
381 // FIXME setsockopt(fd, SO_ATTACH_FILTER, ...) to
382 // make the kernel filter out all packets except
383 // ones we'd care about.
385 VDBG("...wait %ld %s nprobes=%d, nclaims=%d\n",
386 timeout, intf, nprobes, nclaims);
387 switch (poll(fds, 1, timeout)) {
389 // timeouts trigger protocol transitions
392 if (nprobes < PROBE_NUM) {
394 VDBG("probe/%d %s@%s\n",
395 nprobes, intf, inet_ntoa(ip));
396 (void)arp(fd, &saddr, ARPOP_REQUEST,
399 if (nprobes < PROBE_NUM) {
400 timeout = PROBE_MIN * 1000;
401 timeout += ms_rdelay(PROBE_MAX
404 timeout = ANNOUNCE_WAIT * 1000;
406 // then announcements
407 else if (nclaims < ANNOUNCE_NUM) {
409 VDBG("announce/%d %s@%s\n",
410 nclaims, intf, inet_ntoa(ip));
411 (void)arp(fd, &saddr, ARPOP_REQUEST,
414 if (nclaims < ANNOUNCE_NUM) {
415 timeout = ANNOUNCE_INTERVAL * 1000;
417 // link is ok to use earlier
418 run(script, "config", intf, &ip);
423 // NOTE: all other exit paths
424 // should deconfig ...
427 // FIXME update filters
434 // maybe adjust timeout
438 gettimeofday(&tv2, NULL);
439 if (timercmp(&tv1, &tv2, <)) {
442 timersub(&tv1, &tv2, &tv1);
443 timeout = 1000 * tv1.tv_sec
444 + tv1.tv_usec / 1000;
447 if ((fds[0].revents & POLLIN) == 0) {
448 if (fds[0].revents & POLLERR) {
449 // FIXME: links routinely go down;
450 // this shouldn't necessarily exit.
451 fprintf(stderr, "%s %s: poll error\n",
454 run(script, "deconfig",
462 if (recv(fd, &p, sizeof (p), 0) < 0) {
466 if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
469 VDBG("%s recv arp type=%d, op=%d,\n",
470 intf, ntohs(p.hdr.ether_type),
472 VDBG("\tsource=%s %s\n",
473 ether_ntoa(&p.source_addr),
474 inet_ntoa(p.source_ip));
475 VDBG("\ttarget=%s %s\n",
476 ether_ntoa(&p.target_addr),
477 inet_ntoa(p.target_ip));
478 if (p.arp.ar_op != htons(ARPOP_REQUEST)
479 && p.arp.ar_op != htons(ARPOP_REPLY))
482 // some cases are always conflicts
483 if ((p.source_ip.s_addr == ip.s_addr)
484 && (memcmp(&addr, &p.source_addr,
487 VDBG("%s ARP conflict from %s\n", intf,
488 ether_ntoa(&p.source_addr));
490 time_t now = time(0);
492 if ((defend + DEFEND_INTERVAL)
495 (void)arp(fd, &saddr,
499 VDBG("%s defend\n", intf);
505 run(script, "deconfig", intf, &ip);
506 // FIXME rm filters: setsockopt(fd,
507 // SO_DETACH_FILTER, ...)
510 if (conflicts >= MAX_CONFLICTS) {
511 VDBG("%s ratelimit\n", intf);
512 sleep(RATE_LIMIT_INTERVAL);
514 // restart the whole protocol
520 // two hosts probing one address is a collision too
521 else if (p.target_ip.s_addr == ip.s_addr
523 && p.arp.ar_op == htons(ARPOP_REQUEST)
524 && memcmp(&addr, &p.target_addr,
539 syslog(LOG_ERR, "%s %s, %s error: %s",
540 prog, intf, why, strerror(errno));