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