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