zcip: code shrink
[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 nsent;
221                 int verbose;
222         } L;
223 #define null_addr  (L.null_addr )
224 #define ifr        (L.ifr       )
225 #define chosen_nip (L.chosen_nip)
226 #define timeout_ms (L.timeout_ms)
227 #define conflicts  (L.conflicts )
228 #define nsent      (L.nsent     )
229 #define verbose    (L.verbose   )
230
231         memset(&L, 0, sizeof(L));
232         INIT_G();
233
234 #define FOREGROUND (opts & 1)
235 #define QUIT       (opts & 2)
236         // parse commandline: prog [options] ifname script
237         // exactly 2 args; -v accumulates and implies -f
238         opt_complementary = "=2:vv:vf";
239         opts = getopt32(argv, "fqr:l:v", &r_opt, &l_opt, &verbose);
240 #if !BB_MMU
241         // on NOMMU reexec early (or else we will rerun things twice)
242         if (!FOREGROUND)
243                 bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv);
244 #endif
245         // open an ARP socket
246         // (need to do it before openlog to prevent openlog from taking
247         // fd 3 (sock_fd==3))
248         xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd);
249         if (!FOREGROUND) {
250                 // do it before all bb_xx_msg calls
251                 openlog(applet_name, 0, LOG_DAEMON);
252                 logmode |= LOGMODE_SYSLOG;
253         }
254         bb_logenv_override();
255
256         { // -l n.n.n.n
257                 struct in_addr net;
258                 if (inet_aton(l_opt, &net) == 0
259                  || (net.s_addr & htonl(IN_CLASSB_NET)) != net.s_addr
260                 ) {
261                         bb_error_msg_and_die("invalid network address");
262                 }
263                 G.localnet_ip = ntohl(net.s_addr);
264         }
265         if (opts & 4) { // -r n.n.n.n
266                 struct in_addr ip;
267                 if (inet_aton(r_opt, &ip) == 0
268                  || (ntohl(ip.s_addr) & IN_CLASSB_NET) != G.localnet_ip
269                 ) {
270                         bb_error_msg_and_die("invalid link address");
271                 }
272                 chosen_nip = ip.s_addr;
273         }
274         argv += optind - 1;
275
276         /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
277         /* We need to make space for script argument: */
278         argv[0] = argv[1];
279         argv[1] = argv[2];
280         /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
281 #define argv_intf (argv[0])
282
283         xsetenv("interface", argv_intf);
284
285         // initialize the interface (modprobe, ifup, etc)
286         if (run(argv, "init", 0))
287                 return EXIT_FAILURE;
288
289         // initialize G.iface_sockaddr
290         // G.iface_sockaddr is: { u16 sa_family; u8 sa_data[14]; }
291         //memset(&G.iface_sockaddr, 0, sizeof(G.iface_sockaddr));
292         //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
293         safe_strncpy(G.iface_sockaddr.sa_data, argv_intf, sizeof(G.iface_sockaddr.sa_data));
294
295         // bind to the interface's ARP socket
296         xbind(sock_fd, &G.iface_sockaddr, sizeof(G.iface_sockaddr));
297
298         // get the interface's ethernet address
299         //memset(&ifr, 0, sizeof(ifr));
300         strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
301         xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
302         memcpy(&G.eth_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
303
304         // start with some stable ip address, either a function of
305         // the hardware address or else the last address we used.
306         // we are taking low-order four bytes, as top-order ones
307         // aren't random enough.
308         // NOTE: the sequence of addresses we try changes only
309         // depending on when we detect conflicts.
310         {
311                 uint32_t t;
312                 move_from_unaligned32(t, ((char *)&G.eth_addr + 2));
313                 srand(t);
314         }
315         if (chosen_nip == 0)
316                 chosen_nip = pick_nip();
317
318         // FIXME cases to handle:
319         //  - zcip already running!
320         //  - link already has local address... just defend/update
321
322         // daemonize now; don't delay system startup
323         if (!FOREGROUND) {
324 #if BB_MMU
325                 bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
326 #endif
327                 bb_info_msg("start, interface %s", argv_intf);
328         }
329
330         // run the dynamic address negotiation protocol,
331         // restarting after address conflicts:
332         //  - start with some address we want to try
333         //  - short random delay
334         //  - arp probes to see if another host uses it
335         //    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
336         //  - arp announcements that we're claiming it
337         //    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
338         //  - use it
339         //  - defend it, within limits
340         // exit if:
341         // - address is successfully obtained and -q was given:
342         //   run "<script> config", then exit with exitcode 0
343         // - poll error (when does this happen?)
344         // - read error (when does this happen?)
345         // - sendto error (in arp()) (when does this happen?)
346         // - revents & POLLERR (link down). run "<script> deconfig" first
347         state = PROBE;
348         while (1) {
349                 struct pollfd fds[1];
350                 unsigned deadline_us;
351                 struct arp_packet p;
352                 int ip_conflict;
353
354                 fds[0].fd = sock_fd;
355                 fds[0].events = POLLIN;
356                 fds[0].revents = 0;
357
358                 // poll, being ready to adjust current timeout
359                 if (!timeout_ms) {
360                         timeout_ms = random_delay_ms(PROBE_WAIT);
361                         // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
362                         // make the kernel filter out all packets except
363                         // ones we'd care about.
364                 }
365                 // set deadline_us to the point in time when we timeout
366                 deadline_us = MONOTONIC_US() + timeout_ms * 1000;
367
368                 VDBG("...wait %d %s nsent=%u\n",
369                                 timeout_ms, argv_intf, nsent);
370
371                 switch (safe_poll(fds, 1, timeout_ms)) {
372
373                 default:
374                         //bb_perror_msg("poll"); - done in safe_poll
375                         return EXIT_FAILURE;
376
377                 // timeout
378                 case 0:
379                         VDBG("state = %d\n", state);
380                         switch (state) {
381                         case PROBE:
382                                 // timeouts in the PROBE state mean no conflicting ARP packets
383                                 // have been received, so we can progress through the states
384                                 if (nsent < PROBE_NUM) {
385                                         nsent++;
386                                         VDBG("probe/%u %s@%s\n",
387                                                         nsent, argv_intf, nip_to_a(chosen_nip));
388                                         timeout_ms = PROBE_MIN * 1000;
389                                         timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
390                                         arp(/* ARPOP_REQUEST, */
391                                                         /* &G.eth_addr, */ 0,
392                                                         &null_addr, chosen_nip);
393                                         break;
394                                 }
395                                 // Switch to announce state
396                                 nsent = 0;
397                                 state = ANNOUNCE;
398                                 goto send_announce;
399                         case ANNOUNCE:
400                                 // timeouts in the ANNOUNCE state mean no conflicting ARP packets
401                                 // have been received, so we can progress through the states
402                                 if (nsent < ANNOUNCE_NUM) {
403  send_announce:
404                                         nsent++;
405                                         VDBG("announce/%u %s@%s\n",
406                                                         nsent, argv_intf, nip_to_a(chosen_nip));
407                                         timeout_ms = ANNOUNCE_INTERVAL * 1000;
408                                         arp(/* ARPOP_REQUEST, */
409                                                         /* &G.eth_addr, */ chosen_nip,
410                                                         &G.eth_addr, chosen_nip);
411                                         break;
412                                 }
413                                 // Switch to monitor state
414                                 // FIXME update filters
415                                 run(argv, "config", chosen_nip);
416                                 // NOTE: all other exit paths should deconfig...
417                                 if (QUIT)
418                                         return EXIT_SUCCESS;
419                                 conflicts = 0;
420                                 timeout_ms = -1; // Never timeout in the monitor state.
421                                 state = MONITOR;
422                                 break;
423                         case DEFEND:
424                                 // Defend period ended with no ARP replies - we won
425                                 conflicts = 0;
426                                 timeout_ms = -1;
427                                 state = MONITOR;
428                                 break;
429                         } // switch (state)
430                         break; // case 0 (timeout)
431
432                 // packets arriving, or link went down
433                 case 1:
434                         // We need to adjust the timeout in case we didn't receive
435                         // a conflicting packet.
436                         if (timeout_ms > 0) {
437                                 unsigned diff = deadline_us - MONOTONIC_US();
438                                 if ((int)(diff) < 0) {
439                                         // Current time is greater than the expected timeout time.
440                                         diff = 0;
441                                 }
442                                 VDBG("adjusting timeout\n");
443                                 timeout_ms = (diff / 1000) | 1; // never 0
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                                         bb_error_msg("iface %s is down", argv_intf);
451                                         if (state >= MONITOR) {
452                                                 // only if we are in MONITOR or DEFEND
453                                                 run(argv, "deconfig", chosen_nip);
454                                         }
455                                         return EXIT_FAILURE;
456                                 }
457                                 continue;
458                         }
459
460                         // read ARP packet
461                         if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
462                                 bb_perror_msg_and_die(bb_msg_read_error);
463                         }
464
465                         if (p.eth.ether_type != htons(ETHERTYPE_ARP))
466                                 continue;
467                         if (p.arp.arp_op != htons(ARPOP_REQUEST)
468                          && p.arp.arp_op != htons(ARPOP_REPLY)
469                         ) {
470                                 continue;
471                         }
472 #ifdef DEBUG
473                         {
474                                 struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
475                                 struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
476                                 struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
477                                 struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
478                                 VDBG("source=%s %s\n", ether_ntoa(sha), inet_ntoa(*spa));
479                                 VDBG("target=%s %s\n", ether_ntoa(tha), inet_ntoa(*tpa));
480                         }
481 #endif
482                         ip_conflict = 0;
483                         if (memcmp(&p.arp.arp_sha, &G.eth_addr, ETH_ALEN) != 0) {
484                                 if (memcmp(p.arp.arp_spa, &chosen_nip, 4) == 0) {
485                                         // A probe or reply with source_ip == chosen ip
486                                         ip_conflict = 1;
487                                 }
488                                 if (p.arp.arp_op == htons(ARPOP_REQUEST)
489                                  && memcmp(p.arp.arp_spa, &const_int_0, 4) == 0
490                                  && memcmp(p.arp.arp_tpa, &chosen_nip, 4) == 0
491                                 ) {
492                                         // A probe with source_ip == 0.0.0.0, target_ip == chosen ip:
493                                         // another host trying to claim this ip!
494                                         ip_conflict |= 2;
495                                 }
496                         }
497                         VDBG("state:%d ip_conflict:%d\n", state, ip_conflict);
498                         if (!ip_conflict)
499                                 break;
500
501                         // Either src or target IP conflict exists
502                         if (state <= ANNOUNCE) {
503                                 // PROBE or ANNOUNCE
504                                 conflicts++;
505                                 timeout_ms = PROBE_MIN * 1000
506                                         + CONFLICT_MULTIPLIER * random_delay_ms(conflicts);
507                                 chosen_nip = pick_nip();
508                                 nsent = 0;
509                                 state = PROBE;
510                                 break;
511                         }
512                         // MONITOR or DEFEND: only src IP conflict is a problem
513                         if (ip_conflict & 1) {
514                                 if (state == MONITOR) {
515                                         // Src IP conflict, defend with a single ARP probe
516                                         VDBG("monitor conflict - defending\n");
517                                         timeout_ms = DEFEND_INTERVAL * 1000;
518                                         state = DEFEND;
519                                         arp(/* ARPOP_REQUEST, */
520                                                 /* &G.eth_addr, */ chosen_nip,
521                                                 &G.eth_addr, chosen_nip);
522                                         break;
523                                 }
524                                 // state == DEFEND
525                                 // Another src IP conflict, start over
526                                 VDBG("defend conflict - starting over\n");
527                                 run(argv, "deconfig", chosen_nip);
528
529                                 // restart the whole protocol
530                                 timeout_ms = 0;
531                                 chosen_nip = pick_nip();
532                                 nsent = 0;
533                                 state = PROBE;
534                         }
535                         break; // case 1 (packet arrived)
536                 } // switch (poll)
537         } // while (1)
538 #undef argv_intf
539 }