sulogin: use bb_error_msg instead of bb_info_msg; better message
[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         /* 0-1 seconds before sending 1st probe */
60         PROBE_WAIT = 1,
61         /* 1-2 seconds between probes */
62         PROBE_MIN = 1,
63         PROBE_MAX = 2,
64         PROBE_NUM = 3,          /* total probes to send */
65         ANNOUNCE_INTERVAL = 2,  /* 2 seconds between announces */
66         ANNOUNCE_NUM = 3,       /* announces to send */
67         /* if probe/announce sees a conflict, multiply RANDOM(NUM_CONFLICT) by... */
68         CONFLICT_MULTIPLIER = 2,
69         /* if we monitor and see a conflict, how long is defend state? */
70         DEFEND_INTERVAL = 10,
71 };
72
73 /* States during the configuration process. */
74 enum {
75         PROBE = 0,
76         ANNOUNCE,
77         MONITOR,
78         DEFEND
79 };
80
81 #define VDBG(...) do { } while (0)
82
83
84 enum {
85         sock_fd = 3
86 };
87
88 struct globals {
89         struct sockaddr iface_sockaddr;
90         struct ether_addr our_ethaddr;
91         uint32_t localnet_ip;
92 } FIX_ALIASING;
93 #define G (*(struct globals*)&bb_common_bufsiz1)
94 #define INIT_G() do { } while (0)
95
96
97 /**
98  * Pick a random link local IP address on 169.254/16, except that
99  * the first and last 256 addresses are reserved.
100  */
101 static uint32_t pick_nip(void)
102 {
103         unsigned tmp;
104
105         do {
106                 tmp = rand() & IN_CLASSB_HOST;
107         } while (tmp > (IN_CLASSB_HOST - 0x0200));
108         return htonl((G.localnet_ip + 0x0100) + tmp);
109 }
110
111 static const char *nip_to_a(uint32_t nip)
112 {
113         struct in_addr in;
114         in.s_addr = nip;
115         return inet_ntoa(in);
116 }
117
118 /**
119  * Broadcast an ARP packet.
120  */
121 static void send_arp_request(
122         /* int op, - always ARPOP_REQUEST */
123         /* const struct ether_addr *source_eth, - always &G.our_ethaddr */
124                                         uint32_t source_nip,
125         const struct ether_addr *target_eth, uint32_t target_nip)
126 {
127         enum { op = ARPOP_REQUEST };
128 #define source_eth (&G.our_ethaddr)
129
130         struct arp_packet p;
131         memset(&p, 0, sizeof(p));
132
133         // ether header
134         p.eth.ether_type = htons(ETHERTYPE_ARP);
135         memcpy(p.eth.ether_shost, source_eth, ETH_ALEN);
136         memset(p.eth.ether_dhost, 0xff, ETH_ALEN);
137
138         // arp request
139         p.arp.arp_hrd = htons(ARPHRD_ETHER);
140         p.arp.arp_pro = htons(ETHERTYPE_IP);
141         p.arp.arp_hln = ETH_ALEN;
142         p.arp.arp_pln = 4;
143         p.arp.arp_op = htons(op);
144         memcpy(&p.arp.arp_sha, source_eth, ETH_ALEN);
145         memcpy(&p.arp.arp_spa, &source_nip, 4);
146         memcpy(&p.arp.arp_tha, target_eth, ETH_ALEN);
147         memcpy(&p.arp.arp_tpa, &target_nip, 4);
148
149         // send it
150         // Even though sock_fd is already bound to G.iface_sockaddr, just send()
151         // won't work, because "socket is not connected"
152         // (and connect() won't fix that, "operation not supported").
153         // Thus we sendto() to G.iface_sockaddr. I wonder which sockaddr
154         // (from bind() or from sendto()?) kernel actually uses
155         // to determine iface to emit the packet from...
156         xsendto(sock_fd, &p, sizeof(p), &G.iface_sockaddr, sizeof(G.iface_sockaddr));
157 #undef source_eth
158 }
159
160 /**
161  * Run a script.
162  * argv[0]:intf argv[1]:script_name argv[2]:junk argv[3]:NULL
163  */
164 static int run(char *argv[3], const char *param, uint32_t nip)
165 {
166         int status;
167         const char *addr = addr; /* for gcc */
168         const char *fmt = "%s %s %s" + 3;
169
170         argv[2] = (char*)param;
171
172         VDBG("%s run %s %s\n", argv[0], argv[1], argv[2]);
173
174         if (nip != 0) {
175                 addr = nip_to_a(nip);
176                 xsetenv("ip", addr);
177                 fmt -= 3;
178         }
179         bb_error_msg(fmt, argv[2], argv[0], addr);
180
181         status = spawn_and_wait(argv + 1);
182         if (status < 0) {
183                 bb_perror_msg("%s %s %s" + 3, argv[2], argv[0]);
184                 return -errno;
185         }
186         if (status != 0)
187                 bb_error_msg("script %s %s failed, exitcode=%d", argv[1], argv[2], status & 0xff);
188         return status;
189 }
190
191 /**
192  * Return milliseconds of random delay, up to "secs" seconds.
193  */
194 static ALWAYS_INLINE unsigned random_delay_ms(unsigned secs)
195 {
196         return (unsigned)rand() % (secs * 1000);
197 }
198
199 /**
200  * main program
201  */
202 int zcip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
203 int zcip_main(int argc UNUSED_PARAM, char **argv)
204 {
205         char *r_opt;
206         const char *l_opt = "169.254.0.0";
207         int state;
208         int nsent;
209         unsigned opts;
210
211         // Ugly trick, but I want these zeroed in one go
212         struct {
213                 const struct ether_addr null_ethaddr;
214                 struct ifreq ifr;
215                 uint32_t chosen_nip;
216                 int conflicts;
217                 int timeout_ms; // must be signed
218                 int verbose;
219         } L;
220 #define null_ethaddr (L.null_ethaddr)
221 #define ifr          (L.ifr         )
222 #define chosen_nip   (L.chosen_nip  )
223 #define conflicts    (L.conflicts   )
224 #define timeout_ms   (L.timeout_ms  )
225 #define verbose      (L.verbose     )
226
227         memset(&L, 0, sizeof(L));
228         INIT_G();
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:l:v", &r_opt, &l_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         bb_logenv_override();
251
252         { // -l n.n.n.n
253                 struct in_addr net;
254                 if (inet_aton(l_opt, &net) == 0
255                  || (net.s_addr & htonl(IN_CLASSB_NET)) != net.s_addr
256                 ) {
257                         bb_error_msg_and_die("invalid network address");
258                 }
259                 G.localnet_ip = ntohl(net.s_addr);
260         }
261         if (opts & 4) { // -r n.n.n.n
262                 struct in_addr ip;
263                 if (inet_aton(r_opt, &ip) == 0
264                  || (ntohl(ip.s_addr) & IN_CLASSB_NET) != G.localnet_ip
265                 ) {
266                         bb_error_msg_and_die("invalid link address");
267                 }
268                 chosen_nip = ip.s_addr;
269         }
270         argv += optind - 1;
271
272         /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */
273         /* We need to make space for script argument: */
274         argv[0] = argv[1];
275         argv[1] = argv[2];
276         /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */
277 #define argv_intf (argv[0])
278
279         xsetenv("interface", argv_intf);
280
281         // Initialize the interface (modprobe, ifup, etc)
282         if (run(argv, "init", 0))
283                 return EXIT_FAILURE;
284
285         // Initialize G.iface_sockaddr
286         // G.iface_sockaddr is: { u16 sa_family; u8 sa_data[14]; }
287         //memset(&G.iface_sockaddr, 0, sizeof(G.iface_sockaddr));
288         //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?!
289         safe_strncpy(G.iface_sockaddr.sa_data, argv_intf, sizeof(G.iface_sockaddr.sa_data));
290
291         // Bind to the interface's ARP socket
292         xbind(sock_fd, &G.iface_sockaddr, sizeof(G.iface_sockaddr));
293
294         // Get the interface's ethernet address
295         //memset(&ifr, 0, sizeof(ifr));
296         strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf);
297         xioctl(sock_fd, SIOCGIFHWADDR, &ifr);
298         memcpy(&G.our_ethaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
299
300         // Start with some stable ip address, either a function of
301         // the hardware address or else the last address we used.
302         // we are taking low-order four bytes, as top-order ones
303         // aren't random enough.
304         // NOTE: the sequence of addresses we try changes only
305         // depending on when we detect conflicts.
306         {
307                 uint32_t t;
308                 move_from_unaligned32(t, ((char *)&G.our_ethaddr + 2));
309                 srand(t);
310         }
311         // FIXME cases to handle:
312         //  - zcip already running!
313         //  - link already has local address... just defend/update
314
315         // Daemonize now; don't delay system startup
316         if (!FOREGROUND) {
317 #if BB_MMU
318                 bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/);
319 #endif
320                 bb_error_msg("start, interface %s", argv_intf);
321         }
322
323         // Run the dynamic address negotiation protocol,
324         // restarting after address conflicts:
325         //  - start with some address we want to try
326         //  - short random delay
327         //  - arp probes to see if another host uses it
328         //    00:04:e2:64:23:c2 > ff:ff:ff:ff:ff:ff arp who-has 169.254.194.171 tell 0.0.0.0
329         //  - arp announcements that we're claiming it
330         //    00:04:e2:64:23:c2 > ff:ff:ff:ff:ff:ff arp who-has 169.254.194.171 (00:04:e2:64:23:c2) tell 169.254.194.171
331         //  - use it
332         //  - defend it, within limits
333         // exit if:
334         // - address is successfully obtained and -q was given:
335         //   run "<script> config", then exit with exitcode 0
336         // - poll error (when does this happen?)
337         // - read error (when does this happen?)
338         // - sendto error (in send_arp_request()) (when does this happen?)
339         // - revents & POLLERR (link down). run "<script> deconfig" first
340         if (chosen_nip == 0) {
341  new_nip_and_PROBE:
342                 chosen_nip = pick_nip();
343         }
344         nsent = 0;
345         state = PROBE;
346         while (1) {
347                 struct pollfd fds[1];
348                 unsigned deadline_us = deadline_us;
349                 struct arp_packet p;
350                 int ip_conflict;
351                 int n;
352
353                 fds[0].fd = sock_fd;
354                 fds[0].events = POLLIN;
355                 fds[0].revents = 0;
356
357                 // Poll, being ready to adjust current timeout
358                 if (!timeout_ms) {
359                         timeout_ms = random_delay_ms(PROBE_WAIT);
360                         // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to
361                         // make the kernel filter out all packets except
362                         // ones we'd care about.
363                 }
364                 if (timeout_ms >= 0) {
365                         // Set deadline_us to the point in time when we timeout
366                         deadline_us = MONOTONIC_US() + timeout_ms * 1000;
367                 }
368
369                 VDBG("...wait %d %s nsent=%u\n",
370                                 timeout_ms, argv_intf, nsent);
371
372                 n = safe_poll(fds, 1, timeout_ms);
373                 if (n < 0) {
374                         //bb_perror_msg("poll"); - done in safe_poll
375                         return EXIT_FAILURE;
376                 }
377                 if (n == 0) { // timed out?
378                         VDBG("state:%d\n", state);
379                         switch (state) {
380                         case PROBE:
381                                 // No conflicting ARP packets were seen:
382                                 // we can progress through the states
383                                 if (nsent < PROBE_NUM) {
384                                         nsent++;
385                                         VDBG("probe/%u %s@%s\n",
386                                                         nsent, argv_intf, nip_to_a(chosen_nip));
387                                         timeout_ms = PROBE_MIN * 1000;
388                                         timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN);
389                                         send_arp_request(0, &null_ethaddr, chosen_nip);
390                                         continue;
391                                 }
392                                 // Switch to announce state
393                                 nsent = 0;
394                                 state = ANNOUNCE;
395                                 goto send_announce;
396                         case ANNOUNCE:
397                                 // No conflicting ARP packets were seen:
398                                 // we can progress through the states
399                                 if (nsent < ANNOUNCE_NUM) {
400  send_announce:
401                                         nsent++;
402                                         VDBG("announce/%u %s@%s\n",
403                                                         nsent, argv_intf, nip_to_a(chosen_nip));
404                                         timeout_ms = ANNOUNCE_INTERVAL * 1000;
405                                         send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip);
406                                         continue;
407                                 }
408                                 // Switch to monitor state
409                                 // FIXME update filters
410                                 run(argv, "config", chosen_nip);
411                                 // NOTE: all other exit paths should deconfig...
412                                 if (QUIT)
413                                         return EXIT_SUCCESS;
414                                 // fall through: switch to MONITOR
415                         default:
416                         // case DEFEND:
417                         // case MONITOR: (shouldn't happen, MONITOR timeout is infinite)
418                                 // Defend period ended with no ARP replies - we won
419                                 timeout_ms = -1; // never timeout in monitor state
420                                 state = MONITOR;
421                                 continue;
422                         }
423                 }
424
425                 // Packet arrived, or link went down.
426                 // We need to adjust the timeout in case we didn't receive
427                 // a conflicting packet.
428                 if (timeout_ms > 0) {
429                         unsigned diff = deadline_us - MONOTONIC_US();
430                         if ((int)(diff) < 0) {
431                                 // Current time is greater than the expected timeout time.
432                                 diff = 0;
433                         }
434                         VDBG("adjusting timeout\n");
435                         timeout_ms = (diff / 1000) | 1; // never 0
436                 }
437
438                 if ((fds[0].revents & POLLIN) == 0) {
439                         if (fds[0].revents & POLLERR) {
440                                 // FIXME: links routinely go down;
441                                 // this shouldn't necessarily exit.
442                                 bb_error_msg("iface %s is down", argv_intf);
443                                 if (state >= MONITOR) {
444                                         // Only if we are in MONITOR or DEFEND
445                                         run(argv, "deconfig", chosen_nip);
446                                 }
447                                 return EXIT_FAILURE;
448                         }
449                         continue;
450                 }
451
452                 // Read ARP packet
453                 if (safe_read(sock_fd, &p, sizeof(p)) < 0) {
454                         bb_perror_msg_and_die(bb_msg_read_error);
455                 }
456
457                 if (p.eth.ether_type != htons(ETHERTYPE_ARP))
458                         continue;
459                 if (p.arp.arp_op != htons(ARPOP_REQUEST)
460                  && p.arp.arp_op != htons(ARPOP_REPLY)
461                 ) {
462                         continue;
463                 }
464 #ifdef DEBUG
465                 {
466                         struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha;
467                         struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha;
468                         struct in_addr *spa = (struct in_addr *) p.arp.arp_spa;
469                         struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa;
470                         VDBG("source=%s %s\n", ether_ntoa(sha), inet_ntoa(*spa));
471                         VDBG("target=%s %s\n", ether_ntoa(tha), inet_ntoa(*tpa));
472                 }
473 #endif
474                 ip_conflict = 0;
475                 if (memcmp(&p.arp.arp_sha, &G.our_ethaddr, ETH_ALEN) != 0) {
476                         if (memcmp(p.arp.arp_spa, &chosen_nip, 4) == 0) {
477                                 // A probe or reply with source_ip == chosen ip
478                                 ip_conflict = 1;
479                         }
480                         if (p.arp.arp_op == htons(ARPOP_REQUEST)
481                          && memcmp(p.arp.arp_spa, &const_int_0, 4) == 0
482                          && memcmp(p.arp.arp_tpa, &chosen_nip, 4) == 0
483                         ) {
484                                 // A probe with source_ip == 0.0.0.0, target_ip == chosen ip:
485                                 // another host trying to claim this ip!
486                                 ip_conflict |= 2;
487                         }
488                 }
489                 VDBG("state:%d ip_conflict:%d\n", state, ip_conflict);
490                 if (!ip_conflict)
491                         continue;
492
493                 // Either src or target IP conflict exists
494                 if (state <= ANNOUNCE) {
495                         // PROBE or ANNOUNCE
496                         conflicts++;
497                         timeout_ms = PROBE_MIN * 1000
498                                 + CONFLICT_MULTIPLIER * random_delay_ms(conflicts);
499                         goto new_nip_and_PROBE;
500                 }
501
502                 // MONITOR or DEFEND: only src IP conflict is a problem
503                 if (ip_conflict & 1) {
504                         if (state == MONITOR) {
505                                 // Src IP conflict, defend with a single ARP probe
506                                 VDBG("monitor conflict - defending\n");
507                                 timeout_ms = DEFEND_INTERVAL * 1000;
508                                 state = DEFEND;
509                                 send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip);
510                                 continue;
511                         }
512                         // state == DEFEND
513                         // Another src IP conflict, start over
514                         VDBG("defend conflict - starting over\n");
515                         run(argv, "deconfig", chosen_nip);
516                         conflicts = 0;
517                         timeout_ms = 0;
518                         goto new_nip_and_PROBE;
519                 }
520                 // Note: if we only have a target IP conflict here (ip_conflict & 2),
521                 // IOW: if we just saw this sort of ARP packet:
522                 //  aa:bb:cc:dd:ee:ff > xx:xx:xx:xx:xx:xx arp who-has <chosen_nip> tell 0.0.0.0
523                 // we expect _kernel_ to respond to that, because <chosen_nip>
524                 // is (expected to be) configured on this iface.
525         } // while (1)
526 #undef argv_intf
527 }