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