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