de9ea7675dfca8168ac984e0a390aff486227079
[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 /* TODO:
35  - more real-world usage/testing, especially daemon mode
36  - kernel packet filters to reduce scheduling noise
37  - avoid silent script failures, especially under load...
38  - link status monitoring (restart on link-up; stop on link-down)
39 */
40 #include <errno.h>
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <syslog.h>
45 #include <poll.h>
46 #include <time.h>
47 #include <unistd.h>
48
49 #include <sys/ioctl.h>
50 #include <sys/types.h>
51 #include <sys/wait.h>
52 #include <sys/time.h>
53 #include <sys/socket.h>
54
55 #include <arpa/inet.h>
56 #include <netinet/in.h>
57 #include <netinet/ether.h>
58 #include <net/ethernet.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61
62 #include <linux/if_packet.h>
63 #include <linux/sockios.h>
64 #include "busybox.h"
65 #include "libbb.h"
66
67 struct arp_packet {
68         struct ether_header hdr;
69         /* FIXME this part is netinet/if_ether.h "struct ether_arp" */
70         struct arphdr arp;
71         struct ether_addr source_addr;
72         struct in_addr source_ip;
73         struct ether_addr target_addr;
74         struct in_addr target_ip;
75 } __attribute__ ((__packed__));
76
77 /* 169.254.0.0 */
78 static const uint32_t LINKLOCAL_ADDR = 0xa9fe0000;
79
80 /* protocol timeout parameters, specified in seconds */
81 static const unsigned PROBE_WAIT = 1;
82 static const unsigned PROBE_MIN = 1;
83 static const unsigned PROBE_MAX = 2;
84 static const unsigned PROBE_NUM = 3;
85 static const unsigned MAX_CONFLICTS = 10;
86 static const unsigned RATE_LIMIT_INTERVAL = 60;
87 static const unsigned ANNOUNCE_WAIT = 2;
88 static const unsigned ANNOUNCE_NUM = 2;
89 static const unsigned ANNOUNCE_INTERVAL = 2;
90 static const time_t DEFEND_INTERVAL = 10;
91
92 #define ZCIP_VERSION     "0.75 (18 April 2005)"
93
94 static const struct in_addr null_ip = { 0 };
95 static const struct ether_addr null_addr = { {0, 0, 0, 0, 0, 0} };
96
97
98 /*
99  * Pick a random link local IP address on 169.254/16, except that
100  * the first and last 256 addresses are reserved.
101  */
102 static void
103 pick(struct in_addr *ip)
104 {
105         unsigned        tmp;
106
107         /* use cheaper math than lrand48() mod N */
108         do {
109                 tmp = (lrand48() >> 16) & IN_CLASSB_HOST;
110         } while (tmp > (IN_CLASSB_HOST - 0x0200));
111         ip->s_addr = htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
112 }
113
114 /*
115  * Broadcast an ARP packet.
116  */
117 static int
118 arp(int fd, struct sockaddr *saddr, int op,
119         const struct ether_addr *source_addr, struct in_addr source_ip,
120         const struct ether_addr *target_addr, struct in_addr target_ip)
121 {
122         struct arp_packet p;
123
124         /* ether header */
125         p.hdr.ether_type = htons(ETHERTYPE_ARP);
126         memcpy(p.hdr.ether_shost, source_addr, ETH_ALEN);
127         memset(p.hdr.ether_dhost, 0xff, ETH_ALEN);
128
129         /* arp request */
130         p.arp.ar_hrd = htons(ARPHRD_ETHER);
131         p.arp.ar_pro = htons(ETHERTYPE_IP);
132         p.arp.ar_hln = ETH_ALEN;
133         p.arp.ar_pln = 4;
134         p.arp.ar_op = htons(op);
135         memcpy(&p.source_addr, source_addr, ETH_ALEN);
136         memcpy(&p.source_ip, &source_ip, sizeof (p.source_ip));
137         memcpy(&p.target_addr, target_addr, ETH_ALEN);
138         memcpy(&p.target_ip, &target_ip, sizeof (p.target_ip));
139
140         /* send it */
141         if (sendto(fd, &p, sizeof (p), 0, saddr, sizeof (*saddr)) < 0) {
142                 bb_perror_msg("sendto");
143                 return -errno;
144         }
145         return 0;
146 }
147
148 /*
149  * Run a script.
150  */
151 static int
152 run(char *script, char *arg, char *intf, struct in_addr *ip)
153 {
154         int pid, status;
155         char *why;
156
157         if (script != NULL) {
158                 if (ip != NULL) {
159                         char *addr = inet_ntoa(*ip);
160                         xsetenv("ip", addr);
161                         syslog(LOG_INFO, "%s %s %s", arg, intf, addr);
162                 }
163
164                 pid = vfork();
165                 if (pid < 0) {                  /* error */
166                         why = "vfork";
167                         goto bad;
168                 } else if (pid == 0) {          /* child */
169                         execl(script, script, arg, NULL);
170                         bb_perror_msg_and_die("execl");
171                 } 
172
173                 if (waitpid(pid, &status, 0) <= 0) {
174                         why = "waitpid";
175                         goto bad;
176                 }
177                 if (WEXITSTATUS(status) != 0) {
178                         bb_perror_msg("script %s failed, exit=%d", script, WEXITSTATUS(status));
179                         return -errno;
180                 }
181         }
182         return 0;
183 bad:
184         status = -errno;
185         syslog(LOG_ERR, "%s %s, %s error: %s",
186                 arg, intf, why, strerror(errno));
187         return status;
188 }
189
190 /*
191  * Return milliseconds of random delay, up to "secs" seconds.
192  */
193 static inline unsigned
194 ms_rdelay(unsigned secs)
195 {
196         return lrand48() % (secs * 1000);
197 }
198
199 /*
200  * main program
201  */
202
203 #define FOREGROUND        1
204 #define QUIT              2
205 #define REQUEST           4
206 #define VERBOSE           8
207
208 int zcip_main(int argc, char *argv[])
209 {
210         char *intf = NULL;
211         char *script = NULL;
212         char *why;
213         struct sockaddr saddr;
214         struct ether_addr addr;
215         struct in_addr ip = { 0 };
216         int fd;
217         int ready = 0;
218         suseconds_t timeout = 0;        /* milliseconds */
219         time_t defend = 0;
220         unsigned conflicts = 0;
221         unsigned nprobes = 0;
222         unsigned nclaims = 0;
223         unsigned long t;
224
225         bb_opt_complementaly = "vf";
226         /* parse commandline: prog [options] ifname script */
227         t = bb_getopt_ulflags(argc, argv, "fqr:v", &why); /* reuse char* why */
228         
229         argc -= optind;
230         argv += optind;
231         
232         if ((t & 0x80000000UL) || (argc < 1) || (argc > 2)) {
233                 bb_show_usage();
234         }
235         
236         if (t & VERBOSE) {
237                 bb_printf("%s: version %s\n", bb_applet_name, ZCIP_VERSION);
238         }
239         if ((t & REQUEST) && (inet_aton(why, &ip) == 0 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR)) {
240                 bb_perror_msg_and_die("invalid link address");
241         }
242         
243         intf = argv[0];
244         xsetenv("interface", intf);
245         script = argv[1]; /* Could be NULL ? */
246         
247         openlog(bb_applet_name, 0, LOG_DAEMON);
248
249         /* initialize the interface (modprobe, ifup, etc) */
250         if (run(script, "init", intf, NULL) < 0)
251                 return EXIT_FAILURE;
252
253         /* initialize saddr */
254         memset(&saddr, 0, sizeof (saddr));
255         strncpy(saddr.sa_data, intf, sizeof (saddr.sa_data));
256
257         /* open an ARP socket */
258         if ((fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP))) < 0) {
259                 why = "open";
260 fail:
261                 t |= FOREGROUND;
262                 goto bad;
263         }
264         /* bind to the interface's ARP socket */
265         if (bind(fd, &saddr, sizeof (saddr)) < 0) {
266                 why = "bind";
267                 goto fail;
268         } else {
269                 struct ifreq ifr;
270                 short seed[3];
271
272                 /* get the interface's ethernet address */
273                 memset(&ifr, 0, sizeof (ifr));
274                 strncpy(ifr.ifr_name, intf, sizeof (ifr.ifr_name));
275                 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
276                         why = "get ethernet address";
277                         goto fail;
278                 }
279                 memcpy(&addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
280
281                 /* start with some stable ip address, either a function of
282                    the hardware address or else the last address we used.
283                    NOTE: the sequence of addresses we try changes only
284                    depending on when we detect conflicts. */
285                 memcpy(seed, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
286                 seed48(seed);
287                 if (ip.s_addr == 0)
288                         pick(&ip);
289         }
290
291         /* FIXME cases to handle:
292             - zcip already running!
293             - link already has local address... just defend/update */
294
295         /* daemonize now; don't delay system startup */
296         if (!(t & FOREGROUND)) {
297                 if (daemon(0, (t & VERBOSE)) < 0) {
298                         why = "daemon";
299                         goto bad;
300                 }
301                 syslog(LOG_INFO, "start, interface %s", intf);
302         }
303
304         /* run the dynamic address negotiation protocol,
305            restarting after address conflicts:
306             - start with some address we want to try
307             - short random delay
308             - arp probes to see if another host else uses it
309             - arp announcements that we're claiming it
310             - use it
311             - defend it, within limits */
312         while (1) {
313                 struct pollfd fds[1];
314                 struct timeval tv1;
315                 struct arp_packet p;
316
317                 fds[0].fd = fd;
318                 fds[0].events = POLLIN;
319                 fds[0].revents = 0;
320
321                 /* poll, being ready to adjust current timeout */ 
322                 if (timeout > 0) {
323                         gettimeofday(&tv1, NULL);
324                         tv1.tv_usec += (timeout % 1000) * 1000;
325                         while (tv1.tv_usec > 1000000) {
326                                 tv1.tv_usec -= 1000000;
327                                 tv1.tv_sec++;
328                         }
329                         tv1.tv_sec += timeout / 1000;
330                 } else if (timeout == 0) {
331                         timeout = ms_rdelay(PROBE_WAIT);
332                         /* FIXME setsockopt(fd, SO_ATTACH_FILTER, ...) to
333                            make the kernel filter out all packets except
334                            ones we'd care about. */
335                 }
336                 switch (poll(fds, 1, timeout)) {
337
338                 /* timeouts trigger protocol transitions */
339                 case 0:
340                         /* probes */
341                         if (nprobes < PROBE_NUM) {
342                                 nprobes++;
343                                 (void)arp(fd, &saddr, ARPOP_REQUEST,
344                                                 &addr, null_ip,
345                                                 &null_addr, ip);
346                                 if (nprobes < PROBE_NUM) {
347                                         timeout = PROBE_MIN * 1000;
348                                         timeout += ms_rdelay(PROBE_MAX
349                                                         - PROBE_MIN);
350                                 } else
351                                         timeout = ANNOUNCE_WAIT * 1000;
352                         }
353                         /* then announcements */
354                         else if (nclaims < ANNOUNCE_NUM) {
355                                 nclaims++;
356                                 (void)arp(fd, &saddr, ARPOP_REQUEST,
357                                                 &addr, ip,
358                                                 &addr, ip);
359                                 if (nclaims < ANNOUNCE_NUM) {
360                                         timeout = ANNOUNCE_INTERVAL * 1000;
361                                 } else {
362                                         /* link is ok to use earlier */
363                                         run(script, "config", intf, &ip);
364                                         ready = 1;
365                                         conflicts = 0;
366                                         timeout = -1;
367
368                                         /* NOTE:  all other exit paths
369                                            should deconfig ... */
370                                         if (t & QUIT)
371                                                 return EXIT_SUCCESS;
372                                         /* FIXME update filters */
373                                 }
374                         }
375                         break;
376
377                 /* packets arriving */
378                 case 1:
379                         /* maybe adjust timeout */
380                         if (timeout > 0) {
381                                 struct timeval tv2;
382                                 
383                                 gettimeofday(&tv2, NULL);
384                                 if (timercmp(&tv1, &tv2, <)) {
385                                         timeout = -1;
386                                 } else {
387                                         timersub(&tv1, &tv2, &tv1);
388                                         timeout = 1000 * tv1.tv_sec
389                                                         + tv1.tv_usec / 1000;
390                                 }
391                         }
392                         if ((fds[0].revents & POLLIN) == 0) {
393                                 if (fds[0].revents & POLLERR) {
394                                         /* FIXME: links routinely go down;
395                                            this shouldn't necessarily exit. */
396                                         bb_perror_msg("%s: poll error", intf);
397                                         if (ready) {
398                                                 run(script, "deconfig", intf, &ip);
399                                         }
400                                         return EXIT_FAILURE;
401                                 }
402                                 continue;
403                         }
404                         /* read ARP packet */
405                         if (recv(fd, &p, sizeof (p), 0) < 0) {
406                                 why = "recv";
407                                 goto bad;
408                         }
409                         if (p.hdr.ether_type != htons(ETHERTYPE_ARP))
410                                 continue;
411                         
412                         if (p.arp.ar_op != htons(ARPOP_REQUEST)
413                                         && p.arp.ar_op != htons(ARPOP_REPLY))
414                                 continue;
415
416                         /* some cases are always conflicts */ 
417                         if ((p.source_ip.s_addr == ip.s_addr)
418                                         && (memcmp(&addr, &p.source_addr,
419                                                         ETH_ALEN) != 0)) {
420 collision:
421                                 if (ready) {
422                                         time_t now = time(0);
423
424                                         if ((defend + DEFEND_INTERVAL)
425                                                         < now) {
426                                                 defend = now;
427                                                 (void)arp(fd, &saddr,
428                                                                 ARPOP_REQUEST,
429                                                                 &addr, ip,
430                                                                 &addr, ip);
431                                                 timeout = -1;
432                                                 continue;
433                                         }
434                                         defend = now;
435                                         ready = 0;
436                                         run(script, "deconfig", intf, &ip);
437                                         /* FIXME rm filters: setsockopt(fd,
438                                            SO_DETACH_FILTER, ...) */
439                                 }
440                                 conflicts++;
441                                 if (conflicts >= MAX_CONFLICTS) {
442                                         sleep(RATE_LIMIT_INTERVAL);
443                                 }
444                                 /* restart the whole protocol */
445                                 pick(&ip);
446                                 timeout = 0;
447                                 nprobes = 0;
448                                 nclaims = 0;
449                         }
450                         /* two hosts probing one address is a collision too */
451                         else if (p.target_ip.s_addr == ip.s_addr
452                                         && nclaims == 0
453                                         && p.arp.ar_op == htons(ARPOP_REQUEST)
454                                         && memcmp(&addr, &p.target_addr,
455                                                         ETH_ALEN) != 0) {
456                                 goto collision;
457                         }
458                         break;
459
460                 default:
461                         why = "poll";
462                         goto bad;
463                 }
464         }
465 bad:
466         if ( t & FOREGROUND) {
467                 bb_perror_msg(why);
468         } else { 
469                 syslog(LOG_ERR, "%s %s, %s error: %s",
470                         bb_applet_name, intf, why, strerror(errno));
471         }
472         return EXIT_FAILURE;
473 }