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