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