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