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