Rob Sullivan sent in some cleanups, which I beat on slightly.
[oweals/busybox.git] / networking / zcip.c
1 /*
2  * RFC3927 ZeroConf IPv4 Link-Local addressing
3  * (see <http://www.zeroconf.org/>)
4  *
5  * Copyright (C) 2003 by Arthur van Hoff (avh@strangeberry.com)
6  * Copyright (C) 2004 by David Brownell
7  *
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.
12  *
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.
17  *
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
21  * 02111-1307 USA
22  */
23
24 /*
25  * This can build as part of BusyBox or by itself:
26  *
27  *      $(CROSS_COMPILE)cc -Os -Wall -DNO_BUSYBOX -DDEBUG -o zcip zcip.c
28  *
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.
32  */
33
34 // #define      DEBUG
35
36 // TODO:
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)
41
42 #include <errno.h>
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <syslog.h>
47 #include <poll.h>
48 #include <time.h>
49 #include <unistd.h>
50
51 #include <sys/ioctl.h>
52 #include <sys/types.h>
53 #include <sys/wait.h>
54 #include <sys/time.h>
55 #include <sys/socket.h>
56
57 #include <arpa/inet.h>
58 #include <netinet/in.h>
59 #include <netinet/ether.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_arp.h>
63
64 #include <linux/if_packet.h>
65 #include <linux/sockios.h>
66
67
68 struct arp_packet {
69         struct ether_header hdr;
70         // FIXME this part is netinet/if_ether.h "struct ether_arp"
71         struct arphdr 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__));
77
78 /* 169.254.0.0 */
79 static const uint32_t LINKLOCAL_ADDR = 0xa9fe0000;
80
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;
92
93 static const unsigned char ZCIP_VERSION[] = "0.75 (18 April 2005)";
94 static char *prog;
95
96 static const struct in_addr null_ip = { 0 };
97 static const struct ether_addr null_addr = { {0, 0, 0, 0, 0, 0} };
98
99 static int verbose = 0;
100
101 #ifdef DEBUG
102
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); \
107         } while (0)
108 #else
109
110 #define DBG(fmt,args...) \
111         do { } while (0)
112 #define VDBG    DBG
113 #endif                          /* DEBUG */
114
115 /**
116  * Pick a random link local IP address on 169.254/16, except that
117  * the first and last 256 addresses are reserved.
118  */
119 static void
120 pick(struct in_addr *ip)
121 {
122         unsigned        tmp;
123
124         /* use cheaper math than lrand48() mod N */
125         do {
126                 tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
127         } while (tmp > (IN_CLASSB_HOST - 0x0200));
128         ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
129 }
130
131 /**
132  * Broadcast an ARP packet.
133  */
134 static int
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)
138 {
139         struct arp_packet p;
140
141         // ether header
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);
145
146         // arp request
147         p.arp.ar_hrd = htons(ARPHRD_ETHER);
148         p.arp.ar_pro = htons(ETHERTYPE_IP);
149         p.arp.ar_hln = ETH_ALEN;
150         p.arp.ar_pln = 4;
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));
156
157         // send it
158         if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
159                 perror("sendto");
160                 return -errno;
161         }
162         return 0;
163 }
164
165 /**
166  * Run a script.
167  */
168 static int
169 run(char *script, char *arg, char *intf, struct in_addr *ip)
170 {
171         int pid, status;
172         char *why;
173
174         if (script != NULL) {
175                 VDBG("%s run %s %s\n", intf, script, arg);
176                 if (ip != NULL) {
177                         char *addr = inet_ntoa(*ip);
178                         setenv("ip", addr, 1);
179                         syslog(LOG_INFO, "%s %s %s", arg, intf, addr);
180                 }
181
182                 pid = vfork();
183                 if (pid < 0) {                  // error
184                         why = "vfork";
185                         goto bad;
186                 } else if (pid == 0) {          // child
187                         execl(script, script, arg, NULL);
188                         perror("execl");
189                         _exit(EXIT_FAILURE);
190                 } 
191
192                 if (waitpid(pid, &status, 0) <= 0) {
193                         why = "waitpid";
194                         goto bad;
195                 }
196                 if (WEXITSTATUS(status) != 0) {
197                         fprintf(stderr, "%s: script %s failed, exit=%d\n",
198                                         prog, script, WEXITSTATUS(status));
199                         return -errno;
200                 }
201         }
202         return 0;
203 bad:
204         status = -errno;
205         syslog(LOG_ERR, "%s %s, %s error: %s",
206                 arg, intf, why, strerror(errno));
207         return status;
208 }
209
210 #ifndef NO_BUSYBOX
211 #include "busybox.h"
212 #endif
213
214 /**
215  * Print usage information.
216  */
217 static void __attribute__ ((noreturn))
218 usage(const char *msg)
219 {
220         fprintf(stderr, "%s: %s\n", prog, msg);
221 #ifdef  NO_BUSYBOX
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",
227                         prog);
228         exit(0);
229 #else
230         bb_show_usage();
231 #endif
232 }
233
234 /**
235  * Return milliseconds of random delay, up to "secs" seconds.
236  */
237 static inline unsigned
238 ms_rdelay(unsigned secs)
239 {
240         return lrand48() % (secs * 1000);
241 }
242
243 /**
244  * main program
245  */
246
247 #ifdef  NO_BUSYBOX
248 int
249 main(int argc, char *argv[])
250         __attribute__ ((weak, alias ("zcip_main")));
251 #endif
252
253 int zcip_main(int argc, char *argv[])
254 {
255         char *intf = NULL;
256         char *script = NULL;
257         int quit = 0;
258         int foreground = 0;
259
260         char *why;
261         struct sockaddr saddr;
262         struct ether_addr addr;
263         struct in_addr ip = { 0 };
264         int fd;
265         int ready = 0;
266         suseconds_t timeout = 0;        // milliseconds
267         time_t defend = 0;
268         unsigned conflicts = 0;
269         unsigned nprobes = 0;
270         unsigned nclaims = 0;
271         int t;
272
273         // parse commandline: prog [options] ifname script
274         prog = argv[0];
275         while ((t = getopt(argc, argv, "fqr:v")) != EOF) {
276                 switch (t) {
277                 case 'f':
278                         foreground = 1;
279                         continue;
280                 case 'q':
281                         quit = 1;
282                         continue;
283                 case 'r':
284                         if (inet_aton(optarg, &ip) == 0
285                                         || (ntohl(ip.s_addr) & IN_CLASSB_NET)
286                                                 != LINKLOCAL_ADDR) {
287                                 usage("invalid link address");
288                         }
289                         continue;
290                 case 'v':
291                         if (!verbose)
292                                 printf("%s: version %s\n", prog, ZCIP_VERSION);
293                         verbose++;
294                         foreground = 1;
295                         continue;
296                 default:
297                         usage("bad option");
298                 }
299         }
300         if (optind < argc - 1) {
301                 intf = argv[optind++];
302                 setenv("interface", intf, 1);
303                 script = argv[optind++];
304         }
305         if (optind != argc || !intf)
306                 usage("wrong number of arguments");
307         openlog(prog, 0, LOG_DAEMON);
308
309         // initialize the interface (modprobe, ifup, etc)
310         if (run(script, "init", intf, NULL) < 0)
311                 return EXIT_FAILURE;
312
313         // initialize saddr
314         memset(&saddr, 0, sizeof (saddr));
315         strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
316
317         // open an ARP socket
318         if ((fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) < 0) {
319                 why = "open";
320 fail:
321                 foreground = 1;
322                 goto bad;
323         }
324         // bind to the interface's ARP socket
325         if (bind(fd, &saddr, sizeof (saddr)) < 0) {
326                 why = "bind";
327                 goto fail;
328         } else {
329                 struct ifreq ifr;
330                 short seed[3];
331
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";
337                         goto fail;
338                 }
339                 memcpy(&addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
340
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);
346                 seed48(seed);
347                 if (ip.s_addr == 0)
348                         pick(&ip);
349         }
350
351         // FIXME cases to handle:
352         //  - zcip already running!
353         //  - link already has local address... just defend/update
354
355         // daemonize now; don't delay system startup
356         if (!foreground) {
357                 if (daemon(0, verbose) < 0) {
358                         why = "daemon";
359                         goto bad;
360                 }
361                 syslog(LOG_INFO, "start, interface %s", intf);
362         }
363
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
370         //  - use it
371         //  - defend it, within limits
372         while (1) {
373                 struct pollfd fds[1];
374                 struct timeval tv1;
375                 struct arp_packet p;
376
377                 fds[0].fd = fd;
378                 fds[0].events = POLLIN;
379                 fds[0].revents = 0;
380
381                 // poll, being ready to adjust current timeout 
382                 if (timeout > 0) {
383                         gettimeofday(&tv1, NULL);
384                         tv1.tv_usec += (timeout % 1000) * 1000;
385                         while (tv1.tv_usec > 1000000) {
386                                 tv1.tv_usec -= 1000000;
387                                 tv1.tv_sec++;
388                         }
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.
395                 }
396                 VDBG("...wait %ld %s nprobes=%d, nclaims=%d\n",
397                                 timeout, intf, nprobes, nclaims);
398                 switch (poll(fds, 1, timeout)) {
399
400                 // timeouts trigger protocol transitions
401                 case 0:
402                         // probes
403                         if (nprobes < PROBE_NUM) {
404                                 nprobes++;
405                                 VDBG("probe/%d %s@%s\n",
406                                                 nprobes, intf, inet_ntoa(ip));
407                                 (void)arp(fd, &saddr, ARPOP_REQUEST,
408                                                 &addr, null_ip,
409                                                 &null_addr, ip);
410                                 if (nprobes < PROBE_NUM) {
411                                         timeout = PROBE_MIN * 1000;
412                                         timeout += ms_rdelay(PROBE_MAX
413                                                         - PROBE_MIN);
414                                 } else
415                                         timeout = ANNOUNCE_WAIT * 1000;
416                         }
417                         // then announcements
418                         else if (nclaims < ANNOUNCE_NUM) {
419                                 nclaims++;
420                                 VDBG("announce/%d %s@%s\n",
421                                                 nclaims, intf, inet_ntoa(ip));
422                                 (void)arp(fd, &saddr, ARPOP_REQUEST,
423                                                 &addr, ip,
424                                                 &addr, ip);
425                                 if (nclaims < ANNOUNCE_NUM) {
426                                         timeout = ANNOUNCE_INTERVAL * 1000;
427                                 } else {
428                                         // link is ok to use earlier
429                                         run(script, "config", intf, &ip);
430                                         ready = 1;
431                                         conflicts = 0;
432                                         timeout = -1;
433
434                                         // NOTE:  all other exit paths
435                                         // should deconfig ...
436                                         if (quit)
437                                                 return EXIT_SUCCESS;
438                                         // FIXME update filters
439                                 }
440                         }
441                         break;
442
443                 // packets arriving
444                 case 1:
445                         // maybe adjust timeout
446                         if (timeout > 0) {
447                                 struct timeval tv2;
448
449                                 gettimeofday(&tv2, NULL);
450                                 if (timercmp(&tv1, &tv2, <)) {
451                                         timeout = -1;
452                                 } else {
453                                         timersub(&tv1, &tv2, &tv1);
454                                         timeout = 1000 * tv1.tv_sec
455                                                         + tv1.tv_usec / 1000;
456                                 }
457                         }
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",
463                                                         prog, intf);
464                                         if (ready) {
465                                                 run(script, "deconfig",
466                                                                 intf, &ip);
467                                         }
468                                         return EXIT_FAILURE;
469                                 }
470                                 continue;
471                         }
472                         // read ARP packet
473                         if (recv(fd, &p, sizeof (p), 0) < 0) {
474                                 why = "recv";
475                                 goto bad;
476                         }
477                         if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
478                                 continue;
479
480                         VDBG("%s recv arp type=%d, op=%d,\n",
481                                         intf, ntohs(p.hdr.ether_type),
482                                         ntohs(p.arp.ar_op));
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))
491                                 continue;
492
493                         // some cases are always conflicts 
494                         if ((p.source_ip.s_addr == ip.s_addr)
495                                         && (memcmp(&addr, &p.source_addr,
496                                                         ETH_ALEN) != 0)) {
497 collision:
498                                 VDBG("%s ARP conflict from %s\n", intf,
499                                                 ether_ntoa(&p.source_addr));
500                                 if (ready) {
501                                         time_t now = time(0);
502
503                                         if ((defend + DEFEND_INTERVAL)
504                                                         < now) {
505                                                 defend = now;
506                                                 (void)arp(fd, &saddr,
507                                                                 ARPOP_REQUEST,
508                                                                 &addr, ip,
509                                                                 &addr, ip);
510                                                 VDBG("%s defend\n", intf);
511                                                 timeout = -1;
512                                                 continue;
513                                         }
514                                         defend = now;
515                                         ready = 0;
516                                         run(script, "deconfig", intf, &ip);
517                                         // FIXME rm filters: setsockopt(fd,
518                                         // SO_DETACH_FILTER, ...)
519                                 }
520                                 conflicts++;
521                                 if (conflicts >= MAX_CONFLICTS) {
522                                         VDBG("%s ratelimit\n", intf);
523                                         sleep(RATE_LIMIT_INTERVAL);
524                                 }
525                                 // restart the whole protocol
526                                 pick(&ip);
527                                 timeout = 0;
528                                 nprobes = 0;
529                                 nclaims = 0;
530                         }
531                         // two hosts probing one address is a collision too
532                         else if (p.target_ip.s_addr == ip.s_addr
533                                         && nclaims == 0
534                                         && p.arp.ar_op == htons(ARPOP_REQUEST)
535                                         && memcmp(&addr, &p.target_addr,
536                                                         ETH_ALEN) != 0) {
537                                 goto collision;
538                         }
539                         break;
540
541                 default:
542                         why = "poll";
543                         goto bad;
544                 }
545         }
546 bad:
547         if (foreground)
548                 perror(why);
549         else 
550                 syslog(LOG_ERR, "%s %s, %s error: %s",
551                         prog, intf, why, strerror(errno));
552         return EXIT_FAILURE;
553 }