7250fb2fd09e46241c1b0395413135a2555fe19e
[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 GPLv2 or later, see file LICENSE in this source tree.
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 //usage:#define zcip_trivial_usage
27 //usage:       "[OPTIONS] IFACE SCRIPT"
28 //usage:#define zcip_full_usage "\n\n"
29 //usage:       "Manage a ZeroConf IPv4 link-local address\n"
30 //usage:     "\nOptions:"
31 //usage:     "\n        -f              Run in foreground"
32 //usage:     "\n        -q              Quit after obtaining address"
33 //usage:     "\n        -r 169.254.x.x  Request this address first"
34 //usage:     "\n        -v              Verbose"
35 //usage:     "\n"
36 //usage:     "\nWith no -q, runs continuously monitoring for ARP conflicts,"
37 //usage:     "\nexits only on I/O errors (link down etc)"
38
39 #include <netinet/ether.h>
40 #include <net/ethernet.h>
41 #include <net/if.h>
42 #include <net/if_arp.h>
43 #include <linux/if_packet.h>
44 #include <linux/sockios.h>
45
46 #include "libbb.h"
47 #include <syslog.h>
48
49 /* We don't need more than 32 bits of the counter */
50 #define MONOTONIC_US() ((unsigned)monotonic_us())
51
52 struct arp_packet {
53         struct ether_header eth;
54         struct ether_arp arp;
55 } PACKED;
56
57 enum {
58 /* 169.254.0.0 */
59         LINKLOCAL_ADDR = 0xa9fe0000,
60
61 /* protocol timeout parameters, specified in seconds */
62         PROBE_WAIT = 1,
63         PROBE_MIN = 1,
64         PROBE_MAX = 2,
65         PROBE_NUM = 3,
66         MAX_CONFLICTS = 10,
67         RATE_LIMIT_INTERVAL = 60,
68         ANNOUNCE_WAIT = 2,
69         ANNOUNCE_NUM = 2,
70         ANNOUNCE_INTERVAL = 2,
71         DEFEND_INTERVAL = 10
72 };
73
74 /* States during the configuration process. */
75 enum {
76         PROBE = 0,
77         RATE_LIMIT_PROBE,
78         ANNOUNCE,
79         MONITOR,
80         DEFEND
81 };
82
83 #define VDBG(...) do { } while (0)
84
85
86 enum {
87         sock_fd = 3
88 };
89
90 struct globals {
91         struct sockaddr saddr;
92         struct ether_addr eth_addr;
93 } FIX_ALIASING;
94 #define G (*(struct globals*)&bb_common_bufsiz1)
95 #define saddr    (G.saddr   )
96 #define eth_addr (G.eth_addr)
97
98
99 /**
100  * Pick a random link local IP address on 169.254/16, except that
101  * the first and last 256 addresses are reserved.
102  */
103 static uint32_t pick(void)
104 {
105         unsigned tmp;
106
107         do {
108                 tmp = rand() & IN_CLASSB_HOST;
109         } while (tmp > (IN_CLASSB_HOST - 0x0200));
110         return htonl((LINKLOCAL_ADDR + 0x0100) + tmp);
111 }
112
113 /**
114  * Broadcast an ARP packet.
115  */
116 static void arp(
117         /* int op, - always ARPOP_REQUEST */
118         /* const struct ether_addr *source_eth, - always &eth_addr */
119                                         struct in_addr source_ip,
120         const struct ether_addr *target_eth, struct in_addr target_ip)
121 {
122         enum { op = ARPOP_REQUEST };
123 #define source_eth (&eth_addr)
124
125         struct arp_packet p;
126         memset(&p, 0, sizeof(p));
127
128         // ether header
129         p.eth.ether_type = htons(ETHERTYPE_ARP);
130         memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
131         memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
132
133         // arp request
134         p.arp.arp_hrd = htons(ARPHRD_ETHER);
135         p.arp.arp_pro = htons(ETHERTYPE_IP);
136         p.arp.arp_hln = ETH_ALEN;
137         p.arp.arp_pln = 4;
138         p.arp.arp_op = htons(op);
139         memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
140         memcpy(&p.arp.arp_spa, &source_ip, sizeof(p.arp.arp_spa));
141         memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
142         memcpy(&p.arp.arp_tpa, &target_ip, sizeof(p.arp.arp_tpa));
143
144         // send it
145         // Even though sock_fd is already bound to saddr, just send()
146         // won't work, because "socket is not connected"
147         // (and connect() won't fix that, "operation not supported").
148         // Thus we sendto() to saddr. I wonder which sockaddr
149         // (from bind() or from sendto()?) kernel actually uses
150         // to determine iface to emit the packet from...
151         xsendto(sock_fd, &p, sizeof(p), &saddr, sizeof(saddr));
152 #undef source_eth
153 }
154
155 /**
156  * Run a script.
157  * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
158  */
159 static int run(char *argv[3], const char *param, struct in_addr *ip)
160 {
161         int status;
162         char *addr = addr; /* for gcc */
163         const char *fmt = "%s %s %s" + 3;
164
165         argv[2] = (char*)param;
166
167         VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
168
169         if (ip) {
170                 addr = inet_ntoa(*ip);
171                 xsetenv("ip", addr);
172                 fmt -= 3;
173         }
174         bb_info_msg(fmt, argv[2], argv[0], addr);
175
176         status = spawn_and_wait(argv + 1);
177         if (status < 0) {
178                 bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
179                 return -errno;
180         }
181         if (status != 0)
182                 bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status & 0xff);
183         return status;
184 }
185
186 /**
187  * Return milliseconds of random delay, up to "secs" seconds.
188  */
189 static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
190 {
191         return rand() % (secs * 1000);
192 }
193
194 /**
195  * main program
196  */
197 int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
198 int zcip_main(int argc UNUSED_PARAM, char **argv)
199 {
200         int state;
201         char *r_opt;
202         unsigned opts;
203
204         // ugly trick, but I want these zeroed in one go
205         struct {
206                 const struct in_addr null_ip;
207                 const struct ether_addr null_addr;
208                 struct in_addr ip;
209                 struct ifreq ifr;
210                 int timeout_ms; /* must be signed */
211                 unsigned conflicts;
212                 unsigned nprobes;
213                 unsigned nclaims;
214                 int ready;
215                 int verbose;
216         } L;
217 #define null_ip    (L.null_ip   )
218 #define null_addr  (L.null_addr )
219 #define ip         (L.ip        )
220 #define ifr        (L.ifr       )
221 #define timeout_ms (L.timeout_ms)
222 #define conflicts  (L.conflicts )
223 #define nprobes    (L.nprobes   )
224 #define nclaims    (L.nclaims   )
225 #define ready      (L.ready     )
226 #define verbose    (L.verbose   )
227
228         memset(&L, 0, sizeof(L));
229
230 #define FOREGROUND (opts & 1)
231 #define QUIT       (opts & 2)
232         // parse commandline: prog [options] ifname script
233         // exactly 2 args; -v accumulates and implies -f
234         opt_complementary = "=2:vv:vf";
235         opts = getopt32(argv, "fqr:v", &r_opt, &verbose);
236 #if !BB_MMU
237         // on NOMMU reexec early (or else we will rerun things twice)
238         if (!FOREGROUND)
239                 bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
240 #endif
241         // open an ARP socket
242         // (need to do it before openlog to prevent openlog from taking
243         // fd 3 (sock_fd==3))
244         xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
245         if (!FOREGROUND) {
246                 // do it before all bb_xx_msg calls
247                 openlog(applet_name, 0, LOG_DAEMON);
248                 logmode |= LOGMODE_SYSLOG;
249         }
250         if (opts & 4) { // -r n.n.n.n
251                 if (inet_aton(r_opt, &ip) == 0
252                  || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR
253                 ) {
254                         bb_error_msg_and_die("invalid link address");
255                 }
256         }
257         argv += optind - 1;
258
259         /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
260         /* We need to make space for script argument: */
261         argv[0] = argv[1];
262         argv[1] = argv[2];
263         /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
264 #define argv_intf (argv[0])
265
266         xsetenv("interface", argv_intf);
267
268         // initialize the interface (modprobe, ifup, etc)
269         if (run(argv, "init", NULL))
270                 return EXIT_FAILURE;
271
272         // initialize saddr
273         // saddr is: { u16 sa_family; u8 sa_data[14]; }
274         //memset(&saddr, 0, sizeof(saddr));
275         //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
276         safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data));
277
278         // bind to the interface's ARP socket
279         xbind(sock_fd, &saddr, sizeof(saddr));
280
281         // get the interface's ethernet address
282         //memset(&ifr, 0, sizeof(ifr));
283         strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
284         xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
285         memcpy(&eth_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
286
287         // start with some stable ip address, either a function of
288         // the hardware address or else the last address we used.
289         // we are taking low-order four bytes, as top-order ones
290         // aren't random enough.
291         // NOTE: the sequence of addresses we try changes only
292         // depending on when we detect conflicts.
293         {
294                 uint32_t t;
295                 move_from_unaligned32(t, ((char *)&eth_addr + 2));
296                 srand(t);
297         }
298         if (ip.s_addr == 0)
299                 ip.s_addr = pick();
300
301         // FIXME cases to handle:
302         //  - zcip already running!
303         //  - link already has local address... just defend/update
304
305         // daemonize now; don't delay system startup
306         if (!FOREGROUND) {
307 #if BB_MMU
308                 bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
309 #endif
310                 bb_info_msg("start, interface %s", argv_intf);
311         }
312
313         // run the dynamic address negotiation protocol,
314         // restarting after address conflicts:
315         //  - start with some address we want to try
316         //  - short random delay
317         //  - arp probes to see if another host uses it
318         //  - arp announcements that we're claiming it
319         //  - use it
320         //  - defend it, within limits
321         // exit if:
322         // - address is successfully obtained and -q was given:
323         //   run "<script> config", then exit with exitcode 0
324         // - poll error (when does this happen?)
325         // - read error (when does this happen?)
326         // - sendto error (in arp()) (when does this happen?)
327         // - revents & POLLERR (link down). run "<script> deconfig" first
328         state = PROBE;
329         while (1) {
330                 struct pollfd fds[1];
331                 unsigned deadline_us;
332                 struct arp_packet p;
333                 int source_ip_conflict;
334                 int target_ip_conflict;
335
336                 fds[0].fd = sock_fd;
337                 fds[0].events = POLLIN;
338                 fds[0].revents = 0;
339
340                 // poll, being ready to adjust current timeout
341                 if (!timeout_ms) {
342                         timeout_ms = random_delay_ms(PROBE_WAIT);
343                         // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
344                         // make the kernel filter out all packets except
345                         // ones we'd care about.
346                 }
347                 // set deadline_us to the point in time when we timeout
348                 deadline_us = MONOTONIC_US() + timeout_ms * 1000;
349
350                 VDBG("...wait %d %s nprobes=%u, nclaims=%u\n",
351                                 timeout_ms, argv_intf, nprobes, nclaims);
352
353                 switch (safe_poll(fds, 1, timeout_ms)) {
354
355                 default:
356                         //bb_perror_msg("poll"); - done in safe_poll
357                         return EXIT_FAILURE;
358
359                 // timeout
360                 case 0:
361                         VDBG("state = %d\n", state);
362                         switch (state) {
363                         case PROBE:
364                                 // timeouts in the PROBE state mean no conflicting ARP packets
365                                 // have been received, so we can progress through the states
366                                 if (nprobes < PROBE_NUM) {
367                                         nprobes++;
368                                         VDBG("probe/%u %s@%s\n",
369                                                         nprobes, argv_intf, inet_ntoa(ip));
370                                         arp(/* ARPOP_REQUEST, */
371                                                         /* &eth_addr, */ null_ip,
372                                                         &null_addr, ip);
373                                         timeout_ms = PROBE_MIN * 1000;
374                                         timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
375                                 }
376                                 else {
377                                         // Switch to announce state.
378                                         state = ANNOUNCE;
379                                         nclaims = 0;
380                                         VDBG("announce/%u %s@%s\n",
381                                                         nclaims, argv_intf, inet_ntoa(ip));
382                                         arp(/* ARPOP_REQUEST, */
383                                                         /* &eth_addr, */ ip,
384                                                         &eth_addr, ip);
385                                         timeout_ms = ANNOUNCE_INTERVAL * 1000;
386                                 }
387                                 break;
388                         case RATE_LIMIT_PROBE:
389                                 // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets
390                                 // have been received, so we can move immediately to the announce state
391                                 state = ANNOUNCE;
392                                 nclaims = 0;
393                                 VDBG("announce/%u %s@%s\n",
394                                                 nclaims, argv_intf, inet_ntoa(ip));
395                                 arp(/* ARPOP_REQUEST, */
396                                                 /* &eth_addr, */ ip,
397                                                 &eth_addr, ip);
398                                 timeout_ms = ANNOUNCE_INTERVAL * 1000;
399                                 break;
400                         case ANNOUNCE:
401                                 // timeouts in the ANNOUNCE state mean no conflicting ARP packets
402                                 // have been received, so we can progress through the states
403                                 if (nclaims < ANNOUNCE_NUM) {
404                                         nclaims++;
405                                         VDBG("announce/%u %s@%s\n",
406                                                         nclaims, argv_intf, inet_ntoa(ip));
407                                         arp(/* ARPOP_REQUEST, */
408                                                         /* &eth_addr, */ ip,
409                                                         &eth_addr, ip);
410                                         timeout_ms = ANNOUNCE_INTERVAL * 1000;
411                                 }
412                                 else {
413                                         // Switch to monitor state.
414                                         state = MONITOR;
415                                         // link is ok to use earlier
416                                         // FIXME update filters
417                                         run(argv, "config", &ip);
418                                         ready = 1;
419                                         conflicts = 0;
420                                         timeout_ms = -1; // Never timeout in the monitor state.
421
422                                         // NOTE: all other exit paths
423                                         // should deconfig ...
424                                         if (QUIT)
425                                                 return EXIT_SUCCESS;
426                                 }
427                                 break;
428                         case DEFEND:
429                                 // We won!  No ARP replies, so just go back to monitor.
430                                 state = MONITOR;
431                                 timeout_ms = -1;
432                                 conflicts = 0;
433                                 break;
434                         default:
435                                 // Invalid, should never happen.  Restart the whole protocol.
436                                 state = PROBE;
437                                 ip.s_addr = pick();
438                                 timeout_ms = 0;
439                                 nprobes = 0;
440                                 nclaims = 0;
441                                 break;
442                         } // switch (state)
443                         break; // case 0 (timeout)
444
445                 // packets arriving, or link went down
446                 case 1:
447                         // We need to adjust the timeout in case we didn't receive
448                         // a conflicting packet.
449                         if (timeout_ms > 0) {
450                                 unsigned diff = deadline_us - MONOTONIC_US();
451                                 if ((int)(diff) < 0) {
452                                         // Current time is greater than the expected timeout time.
453                                         // Should never happen.
454                                         VDBG("missed an expected timeout\n");
455                                         timeout_ms = 0;
456                                 } else {
457                                         VDBG("adjusting timeout\n");
458                                         timeout_ms = (diff / 1000) | 1; /* never 0 */
459                                 }
460                         }
461
462                         if ((fds[0].revents & POLLIN) == 0) {
463                                 if (fds[0].revents & POLLERR) {
464                                         // FIXME: links routinely go down;
465                                         // this shouldn't necessarily exit.
466                                         bb_error_msg("iface %s is down", argv_intf);
467                                         if (ready) {
468                                                 run(argv, "deconfig", &ip);
469                                         }
470                                         return EXIT_FAILURE;
471                                 }
472                                 continue;
473                         }
474
475                         // read ARP packet
476                         if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
477                                 bb_perror_msg_and_die(bb_msg_read_error);
478                         }
479                         if (p.eth.ether_type != htons(ETHERTYPE_ARP))
480                                 continue;
481 #ifdef DEBUG
482                         {
483                                 struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
484                                 struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
485                                 struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
486                                 struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
487                                 VDBG("%s recv arp type=%d, op=%d,\n",
488                                         argv_intf, ntohs(p.eth.ether_type),
489                                         ntohs(p.arp.arp_op));
490                                 VDBG("\tsource=%s %s\n",
491                                         ether_ntoa(sha),
492                                         inet_ntoa(*spa));
493                                 VDBG("\ttarget=%s %s\n",
494                                         ether_ntoa(tha),
495                                         inet_ntoa(*tpa));
496                         }
497 #endif
498                         if (p.arp.arp_op != htons(ARPOP_REQUEST)
499                          && p.arp.arp_op != htons(ARPOP_REPLY))
500                                 continue;
501
502                         source_ip_conflict = 0;
503                         target_ip_conflict = 0;
504
505                         if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0
506                          && memcmp(&p.arp.arp_sha, &eth_addr, ETH_ALEN) != 0
507                         ) {
508                                 source_ip_conflict = 1;
509                         }
510                         if (p.arp.arp_op == htons(ARPOP_REQUEST)
511                          && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0
512                          && memcmp(&p.arp.arp_tha, &eth_addr, ETH_ALEN) != 0
513                         ) {
514                                 target_ip_conflict = 1;
515                         }
516
517                         VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n",
518                                 state, source_ip_conflict, target_ip_conflict);
519                         switch (state) {
520                         case PROBE:
521                         case ANNOUNCE:
522                                 // When probing or announcing, check for source IP conflicts
523                                 // and other hosts doing ARP probes (target IP conflicts).
524                                 if (source_ip_conflict || target_ip_conflict) {
525                                         conflicts++;
526                                         if (conflicts >= MAX_CONFLICTS) {
527                                                 VDBG("%s ratelimit\n", argv_intf);
528                                                 timeout_ms = RATE_LIMIT_INTERVAL * 1000;
529                                                 state = RATE_LIMIT_PROBE;
530                                         }
531
532                                         // restart the whole protocol
533                                         ip.s_addr = pick();
534                                         timeout_ms = 0;
535                                         nprobes = 0;
536                                         nclaims = 0;
537                                 }
538                                 break;
539                         case MONITOR:
540                                 // If a conflict, we try to defend with a single ARP probe.
541                                 if (source_ip_conflict) {
542                                         VDBG("monitor conflict -- defending\n");
543                                         state = DEFEND;
544                                         timeout_ms = DEFEND_INTERVAL * 1000;
545                                         arp(/* ARPOP_REQUEST, */
546                                                 /* &eth_addr, */ ip,
547                                                 &eth_addr, ip);
548                                 }
549                                 break;
550                         case DEFEND:
551                                 // Well, we tried.  Start over (on conflict).
552                                 if (source_ip_conflict) {
553                                         state = PROBE;
554                                         VDBG("defend conflict -- starting over\n");
555                                         ready = 0;
556                                         run(argv, "deconfig", &ip);
557
558                                         // restart the whole protocol
559                                         ip.s_addr = pick();
560                                         timeout_ms = 0;
561                                         nprobes = 0;
562                                         nclaims = 0;
563                                 }
564                                 break;
565                         default:
566                                 // Invalid, should never happen.  Restart the whole protocol.
567                                 VDBG("invalid state -- starting over\n");
568                                 state = PROBE;
569                                 ip.s_addr = pick();
570                                 timeout_ms = 0;
571                                 nprobes = 0;
572                                 nclaims = 0;
573                                 break;
574                         } // switch state
575                         break; // case 1 (packets arriving)
576                 } // switch poll
577         } // while (1)
578 #undef argv_intf
579 }