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;
66 static const uint32_t LINKLOCAL_ADDR = 0xa9fe0000;
68 /* protocol timeout parameters, specified in seconds */
69 static const unsigned PROBE_WAIT = 1;
70 static const unsigned PROBE_MIN = 1;
71 static const unsigned PROBE_MAX = 2;
72 static const unsigned PROBE_NUM = 3;
73 static const unsigned MAX_CONFLICTS = 10;
74 static const unsigned RATE_LIMIT_INTERVAL = 60;
75 static const unsigned ANNOUNCE_WAIT = 2;
76 static const unsigned ANNOUNCE_NUM = 2;
77 static const unsigned ANNOUNCE_INTERVAL = 2;
78 static const time_t DEFEND_INTERVAL = 10;
80 static const unsigned char ZCIP_VERSION[] = "0.75 (18 April 2005)";
83 static const struct in_addr null_ip = { 0 };
84 static const struct ether_addr null_addr = { {0, 0, 0, 0, 0, 0} };
86 static int verbose = 0;
90 #define DBG(fmt,args...) \
91 fprintf(stderr, "%s: " fmt , prog , ## args)
92 #define VDBG(fmt,args...) do { \
93 if (verbose) fprintf(stderr, "%s: " fmt , prog ,## args); \
97 #define DBG(fmt,args...) \
103 * Pick a random link local IP address on 169.254/16, except that
104 * the first and last 256 addresses are reserved.
107 pick(struct in_addr *ip)
111 /* use cheaper math than lrand48() mod N */
113 tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
114 } while (tmp > (IN_CLASSB_HOST - 0x0200));
115 ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
119 * Broadcast an ARP packet.
122 arp(int fd, struct sockaddr *saddr, int op,
123 const struct ether_addr *source_addr, struct in_addr source_ip,
124 const struct ether_addr *target_addr, struct in_addr target_ip)
129 p.hdr.ether_type = htons(ETHERTYPE_ARP);
130 memcpy(p.hdr.ether_shost, source_addr, ETH_ALEN);
131 memset(p.hdr.ether_dhost, 0xff, ETH_ALEN);
134 p.arp.ar_hrd = htons(ARPHRD_ETHER);
135 p.arp.ar_pro = htons(ETHERTYPE_IP);
136 p.arp.ar_hln = ETH_ALEN;
138 p.arp.ar_op = htons(op);
139 memcpy(&p.source_addr, source_addr, ETH_ALEN);
140 memcpy(&p.source_ip, &source_ip, sizeof (p.source_ip));
141 memcpy(&p.target_addr, target_addr, ETH_ALEN);
142 memcpy(&p.target_ip, &target_ip, sizeof (p.target_ip));
145 if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
156 run(char *script, char *arg, char *intf, struct in_addr *ip)
161 if (script != NULL) {
162 VDBG("%s run %s %s\n", intf, script, arg);
164 char *addr = inet_ntoa(*ip);
165 setenv("ip", addr, 1);
166 syslog(LOG_INFO, "%s %s %s", arg, intf, addr);
170 if (pid < 0) { // error
173 } else if (pid == 0) { // child
174 execl(script, script, arg, NULL);
179 if (waitpid(pid, &status, 0) <= 0) {
183 if (WEXITSTATUS(status) != 0) {
184 fprintf(stderr, "%s: script %s failed, exit=%d\n",
185 prog, script, WEXITSTATUS(status));
192 syslog(LOG_ERR, "%s %s, %s error: %s",
193 arg, intf, why, strerror(errno));
202 * Print usage information.
204 static void ATTRIBUTE_NORETURN
205 zcip_usage(const char *msg)
207 fprintf(stderr, "%s: %s\n", prog, msg);
209 fprintf(stderr, "Usage: %s [OPTIONS] ifname script\n"
210 "\t-f foreground mode (implied by -v)\n"
211 "\t-q quit after address (no daemon)\n"
212 "\t-r 169.254.x.x request this address first\n"
213 "\t-v verbose; show version\n",
222 * Return milliseconds of random delay, up to "secs" seconds.
224 static inline unsigned
225 ms_rdelay(unsigned secs)
227 return lrand48() % (secs * 1000);
236 main(int argc, char *argv[])
237 __attribute__ ((weak, alias ("zcip_main")));
240 int zcip_main(int argc, char *argv[])
248 struct sockaddr saddr;
249 struct ether_addr addr;
250 struct in_addr ip = { 0 };
253 suseconds_t timeout = 0; // milliseconds
255 unsigned conflicts = 0;
256 unsigned nprobes = 0;
257 unsigned nclaims = 0;
260 // parse commandline: prog [options] ifname script
262 while ((t = getopt(argc, argv, "fqr:v")) != EOF) {
271 if (inet_aton(optarg, &ip) == 0
272 || (ntohl(ip.s_addr) & IN_CLASSB_NET)
274 zcip_usage("invalid link address");
279 printf("%s: version %s\n", prog, ZCIP_VERSION);
284 zcip_usage("bad option");
287 if (optind < argc - 1) {
288 intf = argv[optind++];
289 setenv("interface", intf, 1);
290 script = argv[optind++];
292 if (optind != argc || !intf)
293 zcip_usage("wrong number of arguments");
294 openlog(prog, 0, LOG_DAEMON);
296 // initialize the interface (modprobe, ifup, etc)
297 if (run(script, "init", intf, NULL) < 0)
301 memset(&saddr, 0, sizeof (saddr));
302 strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
304 // open an ARP socket
305 if ((fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) < 0) {
311 // bind to the interface's ARP socket
312 if (bind(fd, &saddr, sizeof (saddr)) < 0) {
319 // get the interface's ethernet address
320 memset(&ifr, 0, sizeof (ifr));
321 strncpy(ifr.ifr_name, intf, sizeof (ifr.ifr_name));
322 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
323 why = "get ethernet address";
326 memcpy(&addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
328 // start with some stable ip address, either a function of
329 // the hardware address or else the last address we used.
330 // NOTE: the sequence of addresses we try changes only
331 // depending on when we detect conflicts.
332 memcpy(seed, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
338 // FIXME cases to handle:
339 // - zcip already running!
340 // - link already has local address... just defend/update
342 // daemonize now; don't delay system startup
344 if (daemon(0, verbose) < 0) {
348 syslog(LOG_INFO, "start, interface %s", intf);
351 // run the dynamic address negotiation protocol,
352 // restarting after address conflicts:
353 // - start with some address we want to try
354 // - short random delay
355 // - arp probes to see if another host else uses it
356 // - arp announcements that we're claiming it
358 // - defend it, within limits
360 struct pollfd fds[1];
365 fds[0].events = POLLIN;
368 // poll, being ready to adjust current timeout
370 gettimeofday(&tv1, NULL);
371 tv1.tv_usec += (timeout % 1000) * 1000;
372 while (tv1.tv_usec > 1000000) {
373 tv1.tv_usec -= 1000000;
376 tv1.tv_sec += timeout / 1000;
377 } else if (timeout == 0) {
378 timeout = ms_rdelay(PROBE_WAIT);
379 // FIXME setsockopt(fd, SO_ATTACH_FILTER, ...) to
380 // make the kernel filter out all packets except
381 // ones we'd care about.
383 VDBG("...wait %ld %s nprobes=%d, nclaims=%d\n",
384 timeout, intf, nprobes, nclaims);
385 switch (poll(fds, 1, timeout)) {
387 // timeouts trigger protocol transitions
390 if (nprobes < PROBE_NUM) {
392 VDBG("probe/%d %s@%s\n",
393 nprobes, intf, inet_ntoa(ip));
394 (void)arp(fd, &saddr, ARPOP_REQUEST,
397 if (nprobes < PROBE_NUM) {
398 timeout = PROBE_MIN * 1000;
399 timeout += ms_rdelay(PROBE_MAX
402 timeout = ANNOUNCE_WAIT * 1000;
404 // then announcements
405 else if (nclaims < ANNOUNCE_NUM) {
407 VDBG("announce/%d %s@%s\n",
408 nclaims, intf, inet_ntoa(ip));
409 (void)arp(fd, &saddr, ARPOP_REQUEST,
412 if (nclaims < ANNOUNCE_NUM) {
413 timeout = ANNOUNCE_INTERVAL * 1000;
415 // link is ok to use earlier
416 run(script, "config", intf, &ip);
421 // NOTE: all other exit paths
422 // should deconfig ...
425 // FIXME update filters
432 // maybe adjust timeout
436 gettimeofday(&tv2, NULL);
437 if (timercmp(&tv1, &tv2, <)) {
440 timersub(&tv1, &tv2, &tv1);
441 timeout = 1000 * tv1.tv_sec
442 + tv1.tv_usec / 1000;
445 if ((fds[0].revents & POLLIN) == 0) {
446 if (fds[0].revents & POLLERR) {
447 // FIXME: links routinely go down;
448 // this shouldn't necessarily exit.
449 fprintf(stderr, "%s %s: poll error\n",
452 run(script, "deconfig",
460 if (recv(fd, &p, sizeof (p), 0) < 0) {
464 if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
467 VDBG("%s recv arp type=%d, op=%d,\n",
468 intf, ntohs(p.hdr.ether_type),
470 VDBG("\tsource=%s %s\n",
471 ether_ntoa(&p.source_addr),
472 inet_ntoa(p.source_ip));
473 VDBG("\ttarget=%s %s\n",
474 ether_ntoa(&p.target_addr),
475 inet_ntoa(p.target_ip));
476 if (p.arp.ar_op != htons(ARPOP_REQUEST)
477 && p.arp.ar_op != htons(ARPOP_REPLY))
480 // some cases are always conflicts
481 if ((p.source_ip.s_addr == ip.s_addr)
482 && (memcmp(&addr, &p.source_addr,
485 VDBG("%s ARP conflict from %s\n", intf,
486 ether_ntoa(&p.source_addr));
488 time_t now = time(0);
490 if ((defend + DEFEND_INTERVAL)
493 (void)arp(fd, &saddr,
497 VDBG("%s defend\n", intf);
503 run(script, "deconfig", intf, &ip);
504 // FIXME rm filters: setsockopt(fd,
505 // SO_DETACH_FILTER, ...)
508 if (conflicts >= MAX_CONFLICTS) {
509 VDBG("%s ratelimit\n", intf);
510 sleep(RATE_LIMIT_INTERVAL);
512 // restart the whole protocol
518 // two hosts probing one address is a collision too
519 else if (p.target_ip.s_addr == ip.s_addr
521 && p.arp.ar_op == htons(ARPOP_REQUEST)
522 && memcmp(&addr, &p.target_addr,
537 syslog(LOG_ERR, "%s %s, %s error: %s",
538 prog, intf, why, strerror(errno));