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 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
25 * This can build as part of BusyBox or by itself:
27 * $(CROSS_COMPILE)cc -Os -Wall -DNO_BUSYBOX -DDEBUG -o zcip zcip.c
29 * ZCIP just manages the 169.254.*.* addresses. That network is not
30 * routed at the IP level, though various proxies or bridges can
31 * certainly be used. Its naming is built over multicast DNS.
37 // - more real-world usage/testing, especially daemon mode
38 // - kernel packet filters to reduce scheduling noise
39 // - avoid silent script failures, especially under load...
40 // - link status monitoring (restart on link-up; stop on link-down)
51 #include <sys/ioctl.h>
52 #include <sys/types.h>
55 #include <sys/socket.h>
57 #include <arpa/inet.h>
58 #include <netinet/in.h>
59 #include <netinet/ether.h>
60 #include <net/ethernet.h>
62 #include <net/if_arp.h>
64 #include <linux/if_packet.h>
65 #include <linux/sockios.h>
69 struct ether_header hdr;
70 // FIXME this part is netinet/if_ether.h "struct ether_arp"
72 struct ether_addr source_addr;
73 struct in_addr source_ip;
74 struct ether_addr target_addr;
75 struct in_addr target_ip;
76 } __attribute__ ((__packed__));
79 static const uint32_t LINKLOCAL_ADDR = 0xa9fe0000;
81 /* protocol timeout parameters, specified in seconds */
82 static const unsigned PROBE_WAIT = 1;
83 static const unsigned PROBE_MIN = 1;
84 static const unsigned PROBE_MAX = 2;
85 static const unsigned PROBE_NUM = 3;
86 static const unsigned MAX_CONFLICTS = 10;
87 static const unsigned RATE_LIMIT_INTERVAL = 60;
88 static const unsigned ANNOUNCE_WAIT = 2;
89 static const unsigned ANNOUNCE_NUM = 2;
90 static const unsigned ANNOUNCE_INTERVAL = 2;
91 static const time_t DEFEND_INTERVAL = 10;
93 static const unsigned char ZCIP_VERSION[] = "0.75 (18 April 2005)";
96 static const struct in_addr null_ip = { 0 };
97 static const struct ether_addr null_addr = { {0, 0, 0, 0, 0, 0} };
99 static int verbose = 0;
103 #define DBG(fmt,args...) \
104 fprintf(stderr, "%s: " fmt , prog , ## args)
105 #define VDBG(fmt,args...) do { \
106 if (verbose) fprintf(stderr, "%s: " fmt , prog ,## args); \
110 #define DBG(fmt,args...) \
116 * Pick a random link local IP address on 169.254/16, except that
117 * the first and last 256 addresses are reserved.
120 pick(struct in_addr *ip)
124 /* use cheaper math than lrand48() mod N */
126 tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
127 } while (tmp > (IN_CLASSB_HOST - 0x0200));
128 ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
132 * Broadcast an ARP packet.
135 arp(int fd, struct sockaddr *saddr, int op,
136 const struct ether_addr *source_addr, struct in_addr source_ip,
137 const struct ether_addr *target_addr, struct in_addr target_ip)
142 p.hdr.ether_type = htons(ETHERTYPE_ARP);
143 memcpy(p.hdr.ether_shost, source_addr, ETH_ALEN);
144 memset(p.hdr.ether_dhost, 0xff, ETH_ALEN);
147 p.arp.ar_hrd = htons(ARPHRD_ETHER);
148 p.arp.ar_pro = htons(ETHERTYPE_IP);
149 p.arp.ar_hln = ETH_ALEN;
151 p.arp.ar_op = htons(op);
152 memcpy(&p.source_addr, source_addr, ETH_ALEN);
153 memcpy(&p.source_ip, &source_ip, sizeof (p.source_ip));
154 memcpy(&p.target_addr, target_addr, ETH_ALEN);
155 memcpy(&p.target_ip, &target_ip, sizeof (p.target_ip));
158 if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
169 run(char *script, char *arg, char *intf, struct in_addr *ip)
174 if (script != NULL) {
175 VDBG("%s run %s %s\n", intf, script, arg);
177 char *addr = inet_ntoa(*ip);
178 setenv("ip", addr, 1);
179 syslog(LOG_INFO, "%s %s %s", arg, intf, addr);
183 if (pid < 0) { // error
186 } else if (pid == 0) { // child
187 execl(script, script, arg, NULL);
192 if (waitpid(pid, &status, 0) <= 0) {
196 if (WEXITSTATUS(status) != 0) {
197 fprintf(stderr, "%s: script %s failed, exit=%d\n",
198 prog, script, WEXITSTATUS(status));
205 syslog(LOG_ERR, "%s %s, %s error: %s",
206 arg, intf, why, strerror(errno));
215 * Print usage information.
217 static void __attribute__((noreturn))
218 zcip_usage(const char *msg)
220 fprintf(stderr, "%s: %s\n", prog, msg);
222 fprintf(stderr, "Usage: %s [OPTIONS] ifname script\n"
223 "\t-f foreground mode (implied by -v)\n"
224 "\t-q quit after address (no daemon)\n"
225 "\t-r 169.254.x.x request this address first\n"
226 "\t-v verbose; show version\n",
235 * Return milliseconds of random delay, up to "secs" seconds.
237 static inline unsigned
238 ms_rdelay(unsigned secs)
240 return lrand48() % (secs * 1000);
249 main(int argc, char *argv[])
250 __attribute__ ((weak, alias ("zcip_main")));
253 int zcip_main(int argc, char *argv[])
261 struct sockaddr saddr;
262 struct ether_addr addr;
263 struct in_addr ip = { 0 };
266 suseconds_t timeout = 0; // milliseconds
268 unsigned conflicts = 0;
269 unsigned nprobes = 0;
270 unsigned nclaims = 0;
273 // parse commandline: prog [options] ifname script
275 while ((t = getopt(argc, argv, "fqr:v")) != EOF) {
284 if (inet_aton(optarg, &ip) == 0
285 || (ntohl(ip.s_addr) & IN_CLASSB_NET)
287 zcip_usage("invalid link address");
292 printf("%s: version %s\n", prog, ZCIP_VERSION);
297 zcip_usage("bad option");
300 if (optind < argc - 1) {
301 intf = argv[optind++];
302 setenv("interface", intf, 1);
303 script = argv[optind++];
305 if (optind != argc || !intf)
306 zcip_usage("wrong number of arguments");
307 openlog(prog, 0, LOG_DAEMON);
309 // initialize the interface (modprobe, ifup, etc)
310 if (run(script, "init", intf, NULL) < 0)
314 memset(&saddr, 0, sizeof (saddr));
315 strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
317 // open an ARP socket
318 if ((fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) < 0) {
324 // bind to the interface's ARP socket
325 if (bind(fd, &saddr, sizeof (saddr)) < 0) {
332 // get the interface's ethernet address
333 memset(&ifr, 0, sizeof (ifr));
334 strncpy(ifr.ifr_name, intf, sizeof (ifr.ifr_name));
335 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
336 why = "get ethernet address";
339 memcpy(&addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
341 // start with some stable ip address, either a function of
342 // the hardware address or else the last address we used.
343 // NOTE: the sequence of addresses we try changes only
344 // depending on when we detect conflicts.
345 memcpy(seed, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
351 // FIXME cases to handle:
352 // - zcip already running!
353 // - link already has local address... just defend/update
355 // daemonize now; don't delay system startup
357 if (daemon(0, verbose) < 0) {
361 syslog(LOG_INFO, "start, interface %s", intf);
364 // run the dynamic address negotiation protocol,
365 // restarting after address conflicts:
366 // - start with some address we want to try
367 // - short random delay
368 // - arp probes to see if another host else uses it
369 // - arp announcements that we're claiming it
371 // - defend it, within limits
373 struct pollfd fds[1];
378 fds[0].events = POLLIN;
381 // poll, being ready to adjust current timeout
383 gettimeofday(&tv1, NULL);
384 tv1.tv_usec += (timeout % 1000) * 1000;
385 while (tv1.tv_usec > 1000000) {
386 tv1.tv_usec -= 1000000;
389 tv1.tv_sec += timeout / 1000;
390 } else if (timeout == 0) {
391 timeout = ms_rdelay(PROBE_WAIT);
392 // FIXME setsockopt(fd, SO_ATTACH_FILTER, ...) to
393 // make the kernel filter out all packets except
394 // ones we'd care about.
396 VDBG("...wait %ld %s nprobes=%d, nclaims=%d\n",
397 timeout, intf, nprobes, nclaims);
398 switch (poll(fds, 1, timeout)) {
400 // timeouts trigger protocol transitions
403 if (nprobes < PROBE_NUM) {
405 VDBG("probe/%d %s@%s\n",
406 nprobes, intf, inet_ntoa(ip));
407 (void)arp(fd, &saddr, ARPOP_REQUEST,
410 if (nprobes < PROBE_NUM) {
411 timeout = PROBE_MIN * 1000;
412 timeout += ms_rdelay(PROBE_MAX
415 timeout = ANNOUNCE_WAIT * 1000;
417 // then announcements
418 else if (nclaims < ANNOUNCE_NUM) {
420 VDBG("announce/%d %s@%s\n",
421 nclaims, intf, inet_ntoa(ip));
422 (void)arp(fd, &saddr, ARPOP_REQUEST,
425 if (nclaims < ANNOUNCE_NUM) {
426 timeout = ANNOUNCE_INTERVAL * 1000;
428 // link is ok to use earlier
429 run(script, "config", intf, &ip);
434 // NOTE: all other exit paths
435 // should deconfig ...
438 // FIXME update filters
445 // maybe adjust timeout
449 gettimeofday(&tv2, NULL);
450 if (timercmp(&tv1, &tv2, <)) {
453 timersub(&tv1, &tv2, &tv1);
454 timeout = 1000 * tv1.tv_sec
455 + tv1.tv_usec / 1000;
458 if ((fds[0].revents & POLLIN) == 0) {
459 if (fds[0].revents & POLLERR) {
460 // FIXME: links routinely go down;
461 // this shouldn't necessarily exit.
462 fprintf(stderr, "%s %s: poll error\n",
465 run(script, "deconfig",
473 if (recv(fd, &p, sizeof (p), 0) < 0) {
477 if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
480 VDBG("%s recv arp type=%d, op=%d,\n",
481 intf, ntohs(p.hdr.ether_type),
483 VDBG("\tsource=%s %s\n",
484 ether_ntoa(&p.source_addr),
485 inet_ntoa(p.source_ip));
486 VDBG("\ttarget=%s %s\n",
487 ether_ntoa(&p.target_addr),
488 inet_ntoa(p.target_ip));
489 if (p.arp.ar_op != htons(ARPOP_REQUEST)
490 && p.arp.ar_op != htons(ARPOP_REPLY))
493 // some cases are always conflicts
494 if ((p.source_ip.s_addr == ip.s_addr)
495 && (memcmp(&addr, &p.source_addr,
498 VDBG("%s ARP conflict from %s\n", intf,
499 ether_ntoa(&p.source_addr));
501 time_t now = time(0);
503 if ((defend + DEFEND_INTERVAL)
506 (void)arp(fd, &saddr,
510 VDBG("%s defend\n", intf);
516 run(script, "deconfig", intf, &ip);
517 // FIXME rm filters: setsockopt(fd,
518 // SO_DETACH_FILTER, ...)
521 if (conflicts >= MAX_CONFLICTS) {
522 VDBG("%s ratelimit\n", intf);
523 sleep(RATE_LIMIT_INTERVAL);
525 // restart the whole protocol
531 // two hosts probing one address is a collision too
532 else if (p.target_ip.s_addr == ip.s_addr
534 && p.arp.ar_op == htons(ARPOP_REQUEST)
535 && memcmp(&addr, &p.target_addr,
550 syslog(LOG_ERR, "%s %s, %s error: %s",
551 prog, intf, why, strerror(errno));