virnetdevbridge.c 29.5 KB
Newer Older
1
/*
2
 * Copyright (C) 2007-2015 Red Hat, Inc.
3 4 5 6 7 8 9 10 11 12 13 14
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with this library.  If not, see
O
Osier Yang 已提交
16
 * <http://www.gnu.org/licenses/>.
17 18 19 20 21
 */

#include <config.h>

#include "virnetdevbridge.h"
22
#include "virnetdev.h"
23
#include "virerror.h"
24
#include "virutil.h"
25
#include "virfile.h"
26
#include "viralloc.h"
27
#include "virlog.h"
28
#include "intprops.h"
29
#include "virstring.h"
30 31

#include <sys/ioctl.h>
32
#include <sys/socket.h>
33
#include <net/if.h>
34
#include <netinet/in.h>
35

36
#ifdef __linux__
37 38 39
# if defined(HAVE_LIBNL)
#  include "virnetlink.h"
# endif
40 41
# include <linux/sockios.h>
# include <linux/param.h>     /* HZ                 */
42
# if NETINET_LINUX_WORKAROUND
43 44 45 46
/* Depending on the version of kernel vs. glibc, there may be a collision
 * between <net/in.h> and kernel IPv6 structures.  The different types
 * are ABI compatible, but choke the C type system; work around it by
 * using temporary redefinitions.  */
47 48 49 50 51 52
#  define in6_addr in6_addr_
#  define sockaddr_in6 sockaddr_in6_
#  define ipv6_mreq ipv6_mreq_
#  define in6addr_any in6addr_any_
#  define in6addr_loopback in6addr_loopback_
# endif
53
# include <linux/in6.h>
54
# include <linux/if_bridge.h> /* SYSFS_BRIDGE_ATTR  */
55 56 57 58 59 60 61
# if NETINET_LINUX_WORKAROUND
#  undef in6_addr
#  undef sockaddr_in6
#  undef ipv6_mreq
#  undef in6addr_any
#  undef in6addr_loopback
# endif
62 63 64 65 66

# define JIFFIES_TO_MS(j) (((j)*1000)/HZ)
# define MS_TO_JIFFIES(ms) (((ms)*HZ)/1000)
#endif

67 68 69 70 71
#if defined(HAVE_BSD_BRIDGE_MGMT)
# include <net/ethernet.h>
# include <net/if_bridgevar.h>
#endif

72 73
#define VIR_FROM_THIS VIR_FROM_NONE

74
VIR_LOG_INIT("util.netdevbridge");
75

76 77 78 79 80 81 82
#if defined(HAVE_BSD_BRIDGE_MGMT)
static int virNetDevBridgeCmd(const char *brname,
                              u_long op,
                              void *arg,
                              size_t argsize)
{
    struct ifdrv ifd;
83
    VIR_AUTOCLOSE s = -1;
84 85 86 87 88 89 90 91 92

    memset(&ifd, 0, sizeof(ifd));

    if ((s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0) {
        virReportSystemError(errno, "%s",
                             _("Cannot open network interface control socket"));
        return -1;
    }

93
    if (virStrcpyStatic(ifd.ifd_name, brname) < 0) {
94 95 96
       virReportSystemError(ERANGE,
                            _("Network interface name '%s' is too long"),
                            brname);
97
       return -1;
98 99 100 101 102 103
    }

    ifd.ifd_cmd = op;
    ifd.ifd_len = argsize;
    ifd.ifd_data = arg;

104
    return ioctl(s, SIOCSDRVSPEC, &ifd);
105 106 107
}
#endif

108
#if defined(HAVE_STRUCT_IFREQ) && defined(__linux__)
109 110 111 112 113
/*
 * Bridge parameters can be set via sysfs on newish kernels,
 * or by  ioctl on older kernels. Perhaps we could just use
 * ioctl for every kernel, but its not clear what the long
 * term lifespan of the ioctl interface is...
114 115
 * Fall back to ioctl if sysfs interface is not available or
 * failing (e.g. due to container isolation).
116 117 118 119 120 121 122
 */
static int virNetDevBridgeSet(const char *brname,
                              const char *paramname,  /* sysfs param name */
                              unsigned long value,    /* new value */
                              int fd,                 /* control socket */
                              struct ifreq *ifr)      /* pre-filled bridge name */
{
123
    g_autofree char *path = NULL;
124

125
    if (virAsprintf(&path, SYSFS_NET_DIR "%s/bridge/%s", brname, paramname) < 0)
126 127 128 129 130
        return -1;

    if (virFileExists(path)) {
        char valuestr[INT_BUFSIZE_BOUND(value)];
        snprintf(valuestr, sizeof(valuestr), "%lu", value);
131 132 133 134 135 136 137 138 139 140
        if (virFileWriteStr(path, valuestr, 0) >= 0)
            return 0;
        VIR_DEBUG("Unable to set bridge %s %s via sysfs", brname, paramname);
    }

    unsigned long paramid;
    if (STREQ(paramname, "stp_state")) {
        paramid = BRCTL_SET_BRIDGE_STP_STATE;
    } else if (STREQ(paramname, "forward_delay")) {
        paramid = BRCTL_SET_BRIDGE_FORWARD_DELAY;
141
    } else {
142 143 144 145 146 147 148 149 150 151 152 153
        virReportSystemError(EINVAL,
                             _("Unable to set bridge %s %s via ioctl"),
                             brname, paramname);
        return -1;
    }
    unsigned long args[] = { paramid, value, 0, 0 };
    ifr->ifr_data = (char*)&args;
    if (ioctl(fd, SIOCDEVPRIVATE, ifr) < 0) {
        virReportSystemError(errno,
                             _("Failed to set bridge %s %s via ioctl"),
                             brname, paramname);
        return -1;
154 155
    }

156
    return 0;
157 158 159 160 161
}


static int virNetDevBridgeGet(const char *brname,
                              const char *paramname,  /* sysfs param name */
162
                              unsigned long *value)   /* current value */
163
{
164
    struct ifreq ifr;
165
    g_autofree char *path = NULL;
166
    VIR_AUTOCLOSE fd = -1;
167

168
    if (virAsprintf(&path, SYSFS_NET_DIR "%s/bridge/%s", brname, paramname) < 0)
169 170 171
        return -1;

    if (virFileExists(path)) {
172
        g_autofree char *valuestr = NULL;
173

174 175
        if (virFileReadAll(path, INT_BUFSIZE_BOUND(unsigned long),
                           &valuestr) < 0)
176
            return -1;
177 178 179

        if (virStrToLong_ul(valuestr, NULL, 10, value) < 0) {
            virReportSystemError(EINVAL,
180 181
                                 _("Unable to get bridge %s %s"),
                                 brname, paramname);
182
            return -1;
183 184 185 186
        }
    } else {
        struct __bridge_info info;
        unsigned long args[] = { BRCTL_GET_BRIDGE_INFO, (unsigned long)&info, 0, 0 };
187 188

        if ((fd = virNetDevSetupControl(brname, &ifr)) < 0)
189
            return -1;
190 191

        ifr.ifr_data = (char*)&args;
192 193 194
        if (ioctl(fd, SIOCDEVPRIVATE, ifr) < 0) {
            virReportSystemError(errno,
                                 _("Unable to get bridge %s %s"), brname, paramname);
195
            return -1;
196 197 198 199 200 201 202 203 204
        }

        if (STREQ(paramname, "stp_state")) {
            *value = info.stp_enabled;
        } else if (STREQ(paramname, "forward_delay")) {
            *value = info.forward_delay;
        } else {
            virReportSystemError(EINVAL,
                                 _("Unable to get bridge %s %s"), brname, paramname);
205
            return -1;
206 207 208
        }
    }

209
    return 0;
210 211 212
}
#endif /* __linux__ */

213 214 215 216 217 218 219 220 221
#if defined(__linux__)
static int
virNetDevBridgePortSet(const char *brname,
                       const char *ifname,
                       const char *paramname,
                       unsigned long value)
{
    char valuestr[INT_BUFSIZE_BOUND(value)];
    int ret = -1;
222
    g_autofree char *path = NULL;
223 224 225

    snprintf(valuestr, sizeof(valuestr), "%lu", value);

226 227
    if (virAsprintf(&path, SYSFS_NET_DIR "%s/brif/%s/%s",
                    brname, ifname, paramname) < 0)
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        return -1;

    if (!virFileExists(path))
        errno = EINVAL;
    else
        ret = virFileWriteStr(path, valuestr, 0);

    if (ret < 0) {
        virReportSystemError(errno,
                             _("Unable to set bridge %s port %s %s to %s"),
                             brname, ifname, paramname, valuestr);
    }

    return ret;
}


static int
virNetDevBridgePortGet(const char *brname,
                       const char *ifname,
                       const char *paramname,
                       unsigned long *value)
{
251 252
    g_autofree char *path = NULL;
    g_autofree char *valuestr = NULL;
253

254 255
    if (virAsprintf(&path, SYSFS_NET_DIR "%s/brif/%s/%s",
                    brname, ifname, paramname) < 0)
256 257 258
        return -1;

    if (virFileReadAll(path, INT_BUFSIZE_BOUND(unsigned long), &valuestr) < 0)
259
        return -1;
260 261 262 263 264

    if (virStrToLong_ul(valuestr, NULL, 10, value) < 0) {
        virReportSystemError(EINVAL,
                             _("Unable to get bridge %s port %s %s"),
                             brname, ifname, paramname);
265
        return -1;
266 267
    }

268
    return 0;
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
}


int
virNetDevBridgePortGetLearning(const char *brname,
                               const char *ifname,
                               bool *enable)
{
    int ret = -1;
    unsigned long value;

    if (virNetDevBridgePortGet(brname, ifname, "learning", &value) < 0)
       goto cleanup;

    *enable = !!value;
    ret = 0;
 cleanup:
    return ret;
}


int
virNetDevBridgePortSetLearning(const char *brname,
                               const char *ifname,
                               bool enable)
{
    return virNetDevBridgePortSet(brname, ifname, "learning", enable ? 1 : 0);
}


int
virNetDevBridgePortGetUnicastFlood(const char *brname,
                                   const char *ifname,
                                   bool *enable)
{
    int ret = -1;
    unsigned long value;

    if (virNetDevBridgePortGet(brname, ifname, "unicast_flood", &value) < 0)
       goto cleanup;

    *enable = !!value;
    ret = 0;
 cleanup:
    return ret;
}


int
virNetDevBridgePortSetUnicastFlood(const char *brname,
                                   const char *ifname,
                                   bool enable)
{
    return virNetDevBridgePortSet(brname, ifname, "unicast_flood", enable ? 1 : 0);
}


#else
int
J
Ján Tomko 已提交
328 329 330
virNetDevBridgePortGetLearning(const char *brname G_GNUC_UNUSED,
                               const char *ifname G_GNUC_UNUSED,
                               bool *enable G_GNUC_UNUSED)
331 332 333 334 335 336 337 338
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to get bridge port learning on this platform"));
    return -1;
}


int
J
Ján Tomko 已提交
339 340 341
virNetDevBridgePortSetLearning(const char *brname G_GNUC_UNUSED,
                               const char *ifname G_GNUC_UNUSED,
                               bool enable G_GNUC_UNUSED)
342 343 344 345 346 347 348 349
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to set bridge port learning on this platform"));
    return -1;
}


int
J
Ján Tomko 已提交
350 351 352
virNetDevBridgePortGetUnicastFlood(const char *brname G_GNUC_UNUSED,
                                   const char *ifname G_GNUC_UNUSED,
                                   bool *enable G_GNUC_UNUSED)
353 354 355 356 357 358 359 360
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to get bridge port unicast_flood on this platform"));
    return -1;
}


int
J
Ján Tomko 已提交
361 362 363
virNetDevBridgePortSetUnicastFlood(const char *brname G_GNUC_UNUSED,
                                   const char *ifname G_GNUC_UNUSED,
                                   bool enable G_GNUC_UNUSED)
364 365 366 367 368 369 370
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to set bridge port unicast_flood on this platform"));
    return -1;
}
#endif

371 372 373 374 375 376 377 378 379

/**
 * virNetDevBridgeCreate:
 * @brname: the bridge name
 *
 * This function register a new bridge
 *
 * Returns 0 in case of success or -1 on failure
 */
380 381
#if defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRADDBR)
static int
382 383
virNetDevBridgeCreateWithIoctl(const char *brname,
                               const virMacAddr *mac)
384
{
385
    VIR_AUTOCLOSE fd = -1;
386 387 388 389 390 391 392

    if ((fd = virNetDevSetupControl(NULL, NULL)) < 0)
        return -1;

    if (ioctl(fd, SIOCBRADDBR, brname) < 0) {
        virReportSystemError(errno,
                             _("Unable to create bridge %s"), brname);
393
        return -1;
394 395
    }

396 397 398 399 400 401 402 403 404
    if (virNetDevSetMAC(brname, mac) < 0) {
        virErrorPtr savederr;

        virErrorPreserveLast(&savederr);
        ignore_value(ioctl(fd, SIOCBRDELBR, brname));
        virErrorRestore(&savederr);
        return -1;
    }

405
    return 0;
406 407 408
}
#endif

409
#if defined(__linux__) && defined(HAVE_LIBNL)
410
int
411 412
virNetDevBridgeCreate(const char *brname,
                      const virMacAddr *mac)
413 414
{
    /* use a netlink RTM_NEWLINK message to create the bridge */
415
    int error = 0;
416 417 418 419
    virNetlinkNewLinkData data = {
        .mac = mac,
    };

420

421
    if (virNetlinkNewLink(brname, "bridge", &data, &error) < 0) {
422
# if defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRADDBR)
423 424
        if (error == -EOPNOTSUPP) {
            /* fallback to ioctl if netlink doesn't support creating bridges */
425
            return virNetDevBridgeCreateWithIoctl(brname, mac);
426
        }
427
# endif
428 429
        if (error < 0)
            virReportSystemError(-error, _("error creating bridge interface %s"),
430 431
                                 brname);

432
        return -1;
433 434
    }

435
    return 0;
436
}
437 438


439 440
#elif defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRADDBR)
int
441 442
virNetDevBridgeCreate(const char *brname,
                      const virMacAddr *mac)
443
{
444
    return virNetDevBridgeCreateWithIoctl(brname, mac);
445
}
446 447


448
#elif defined(HAVE_STRUCT_IFREQ) && defined(SIOCIFCREATE2)
449
int
450 451
virNetDevBridgeCreate(const char *brname,
                      const virMacAddr *mac)
452 453
{
    struct ifreq ifr;
454
    VIR_AUTOCLOSE s = -1;
455 456 457 458 459 460 461

    if ((s = virNetDevSetupControl("bridge", &ifr)) < 0)
        return -1;

    if (ioctl(s, SIOCIFCREATE2, &ifr) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to create bridge device"));
462
        return -1;
463 464
    }

465
    if (virNetDevSetName(ifr.ifr_name, brname) == -1)
466
        return -1;
467

468 469 470 471 472 473 474 475 476
    if (virNetDevSetMAC(brname, mac) < 0) {
        virErrorPtr savederr;

        virErrorPreserveLast(&savederr);
        ignore_value(virNetDevBridgeDelete(brname));
        virErrorRestore(&savederr);
        return -1;
    }

477
    return 0;
478
}
479
#else
480 481 482
int
virNetDevBridgeCreate(const char *brname,
                      const virMacAddr *mac G_GNUC_UNUSED)
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
{
    virReportSystemError(ENOSYS,
                         _("Unable to create bridge %s"), brname);
    return -1;
}
#endif

/**
 * virNetDevBridgeDelete:
 * @brname: the bridge name
 *
 * Remove a bridge from the layer.
 *
 * Returns 0 in case of success or an errno code in case of failure.
 */
498 499 500
#if defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRDELBR)
static int
virNetDevBridgeDeleteWithIoctl(const char *brname)
501
{
502
    VIR_AUTOCLOSE fd = -1;
503

504 505
    ignore_value(virNetDevSetOnline(brname, false));

506 507 508 509 510 511
    if ((fd = virNetDevSetupControl(NULL, NULL)) < 0)
        return -1;

    if (ioctl(fd, SIOCBRDELBR, brname) < 0) {
        virReportSystemError(errno,
                             _("Unable to delete bridge %s"), brname);
512
        return -1;
513 514
    }

515
    return 0;
516
}
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
#endif


#if defined(__linux__) && defined(HAVE_LIBNL)
int
virNetDevBridgeDelete(const char *brname)
{
    /* If netlink is available, use it, as it is successful at
     * deleting a bridge even if it is currently IFF_UP. fallback to
     * using ioctl(SIOCBRDELBR) if netlink fails with EOPNOTSUPP.
     */
# if defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRDELBR)
    return virNetlinkDelLink(brname, virNetDevBridgeDeleteWithIoctl);
# else
    return virNetlinkDelLink(brname, NULL);
# endif
}


#elif defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRDELBR)
int
virNetDevBridgeDelete(const char *brname)
{
    return virNetDevBridgeDeleteWithIoctl(brname);
}


544
#elif defined(HAVE_STRUCT_IFREQ) && defined(SIOCIFDESTROY)
545 546
int
virNetDevBridgeDelete(const char *brname)
547 548
{
    struct ifreq ifr;
549
    VIR_AUTOCLOSE s = -1;
550 551 552 553 554 555 556 557

    if ((s = virNetDevSetupControl(brname, &ifr)) < 0)
        return -1;

    if (ioctl(s, SIOCIFDESTROY, &ifr) < 0) {
        virReportSystemError(errno,
                             _("Unable to remove bridge %s"),
                             brname);
558
        return -1;
559 560
    }

561
    return 0;
562
}
563
#else
J
Ján Tomko 已提交
564
int virNetDevBridgeDelete(const char *brname G_GNUC_UNUSED)
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
{
    virReportSystemError(ENOSYS,
                         _("Unable to delete bridge %s"), brname);
    return EINVAL;
}
#endif

/**
 * virNetDevBridgeAddPort:
 * @brname: the bridge name
 * @ifname: the network interface name
 *
 * Adds an interface to a bridge
 *
 * Returns 0 in case of success or an errno code in case of failure.
 */
581
#if defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRADDIF)
582 583 584 585
int virNetDevBridgeAddPort(const char *brname,
                           const char *ifname)
{
    struct ifreq ifr;
586
    VIR_AUTOCLOSE fd = -1;
587 588 589 590 591 592 593

    if ((fd = virNetDevSetupControl(brname, &ifr)) < 0)
        return -1;

    if (!(ifr.ifr_ifindex = if_nametoindex(ifname))) {
        virReportSystemError(ENODEV,
                             _("Unable to get interface index for %s"), ifname);
594
        return -1;
595 596 597 598 599
    }

    if (ioctl(fd, SIOCBRADDIF, &ifr) < 0) {
        virReportSystemError(errno,
                             _("Unable to add bridge %s port %s"), brname, ifname);
600
        return -1;
601 602
    }

603
    return 0;
604
}
605 606 607 608 609 610 611
#elif defined(HAVE_BSD_BRIDGE_MGMT)
int virNetDevBridgeAddPort(const char *brname,
                           const char *ifname)
{
    struct ifbreq req;

    memset(&req, 0, sizeof(req));
612
    if (virStrcpyStatic(req.ifbr_ifsname, ifname) < 0) {
613 614 615 616 617 618 619 620 621 622 623 624 625 626
        virReportSystemError(ERANGE,
                             _("Network interface name '%s' is too long"),
                             ifname);
        return -1;
    }

    if (virNetDevBridgeCmd(brname, BRDGADD, &req, sizeof(req)) < 0) {
        virReportSystemError(errno,
                             _("Unable to add bridge %s port %s"), brname, ifname);
        return -1;
    }

    return 0;
}
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
#else
int virNetDevBridgeAddPort(const char *brname,
                           const char *ifname)
{
    virReportSystemError(ENOSYS,
                         _("Unable to add bridge %s port %s"), brname, ifname);
    return -1;
}
#endif

/**
 * virNetDevBridgeRemovePort:
 * @brname: the bridge name
 * @ifname: the network interface name
 *
 * Removes an interface from a bridge
 *
 * Returns 0 in case of success or an errno code in case of failure.
 */
646
#if defined(HAVE_STRUCT_IFREQ) && defined(SIOCBRDELIF)
647 648 649 650
int virNetDevBridgeRemovePort(const char *brname,
                              const char *ifname)
{
    struct ifreq ifr;
651
    VIR_AUTOCLOSE fd = -1;
652 653 654 655 656 657 658 659

    if ((fd = virNetDevSetupControl(brname, &ifr)) < 0)
        return -1;

    if (!(ifr.ifr_ifindex = if_nametoindex(ifname))) {
        virReportSystemError(ENODEV,
                             _("Unable to get interface index for %s"), ifname);

660
        return -1;
661 662 663 664 665
    }

    if (ioctl(fd, SIOCBRDELIF, &ifr) < 0) {
        virReportSystemError(errno,
                             _("Unable to remove bridge %s port %s"), brname, ifname);
666
        return -1;
667 668
    }

669
    return 0;
670
}
671 672
#elif defined(HAVE_BSD_BRIDGE_MGMT)
int virNetDevBridgeRemovePort(const char *brname,
673
                              const char *ifname)
674 675 676 677
{
    struct ifbreq req;

    memset(&req, 0, sizeof(req));
678
    if (virStrcpyStatic(req.ifbr_ifsname, ifname) < 0) {
679 680 681 682 683 684 685 686 687 688 689 690 691 692
        virReportSystemError(ERANGE,
                             _("Network interface name '%s' is too long"),
                             ifname);
        return -1;
    }

    if (virNetDevBridgeCmd(brname, BRDGDEL, &req, sizeof(req)) < 0) {
        virReportSystemError(errno,
                             _("Unable to remove bridge %s port %s"), brname, ifname);
       return -1;
    }

    return 0;
}
693 694 695 696 697 698 699 700 701 702 703
#else
int virNetDevBridgeRemovePort(const char *brname,
                              const char *ifname)
{
    virReportSystemError(ENOSYS,
                         _("Unable to remove bridge %s port %s"), brname, ifname);
    return -1;
}
#endif


704
#if defined(HAVE_STRUCT_IFREQ) && defined(__linux__)
705 706 707
/**
 * virNetDevBridgeSetSTPDelay:
 * @brname: the bridge name
708
 * @delay: delay in milliseconds
709 710 711 712 713 714 715 716 717 718
 *
 * Set the bridge forward delay
 *
 * Returns 0 in case of success or -1 on failure
 */

int virNetDevBridgeSetSTPDelay(const char *brname,
                               int delay)
{
    struct ifreq ifr;
719
    VIR_AUTOCLOSE fd = -1;
720 721

    if ((fd = virNetDevSetupControl(brname, &ifr)) < 0)
722
        return -1;
723

724 725
    return virNetDevBridgeSet(brname, "forward_delay", MS_TO_JIFFIES(delay),
                              fd, &ifr);
726 727 728 729 730 731 732 733
}


/**
 * virNetDevBridgeGetSTPDelay:
 * @brname: the bridge device name
 * @delayms: the forward delay in milliseconds
 *
734
 * Retrieves the forward delay for the bridge device @brname
735 736 737 738 739 740 741 742 743
 * storing it in @delayms. The forward delay is only meaningful
 * if STP is enabled
 *
 * Returns 0 on success, -1 on error+
 */
int virNetDevBridgeGetSTPDelay(const char *brname,
                               int *delayms)
{
    int ret = -1;
744
    unsigned long val = 0;
745

746
    ret = virNetDevBridgeGet(brname, "forward_delay", &val);
747
    *delayms = JIFFIES_TO_MS(val);
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766

    return ret;
}


/**
 * virNetDevBridgeSetSTP:
 * @brname: the bridge name
 * @enable: 1 to enable, 0 to disable
 *
 * Control whether the bridge participates in the spanning tree protocol,
 * in general don't disable it without good reasons.
 *
 * Returns 0 in case of success or -1 on failure
 */
int virNetDevBridgeSetSTP(const char *brname,
                          bool enable)
{
    struct ifreq ifr;
767
    VIR_AUTOCLOSE fd = -1;
768 769

    if ((fd = virNetDevSetupControl(brname, &ifr)) < 0)
770
        return -1;
771

772 773
    return virNetDevBridgeSet(brname, "stp_state", enable ? 1 : 0,
                              fd, &ifr);
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
}


/**
 * virNetDevBridgeGetSTP:
 * @brname: the bridge device name
 * @enabled: returns the STP state
 *
 * Determine the state of the spanning tree protocol on
 * the device @brname, returning the state in @enabled
 *
 * Returns 0 on success, -1 on error
 */
int virNetDevBridgeGetSTP(const char *brname,
                          bool *enabled)
{
    int ret = -1;
791
    unsigned long val = 0;
792

793
    ret = virNetDevBridgeGet(brname, "stp_state", &val);
794
    *enabled = val ? true : false;
795 796 797

    return ret;
}
798 799 800 801 802
#elif defined(HAVE_BSD_BRIDGE_MGMT)
int virNetDevBridgeSetSTPDelay(const char *brname,
                               int delay)
{
    struct ifbrparam param;
803
    u_long delay_seconds = delay / 1000;
804 805

    /* FreeBSD doesn't allow setting STP delay < 4 */
806 807
    delay_seconds = delay_seconds < 4 ? 4 : delay_seconds;
    param.ifbrp_fwddelay = delay_seconds & 0xff;
808 809 810 811 812 813 814 815 816 817

    if (virNetDevBridgeCmd(brname, BRDGSFD, &param, sizeof(param)) < 0) {
        virReportSystemError(errno,
                             _("Unable to set STP delay on %s"), brname);
        return -1;
    }

    return 0;
}
int virNetDevBridgeGetSTPDelay(const char *brname,
J
Ján Tomko 已提交
818
                               int *delay G_GNUC_UNUSED)
819 820 821 822 823 824 825
{
    virReportSystemError(ENOSYS,
                         _("Unable to get STP delay on %s on this platform"),
                         brname);
    return -1;
}

J
Ján Tomko 已提交
826 827
int virNetDevBridgeSetSTP(const char *brname G_GNUC_UNUSED,
                          bool enable G_GNUC_UNUSED)
828 829 830 831 832 833 834

{
    /* FreeBSD doesn't allow to set STP per bridge,
     * only per-device in bridge */
    return 0;
}
int virNetDevBridgeGetSTP(const char *brname,
J
Ján Tomko 已提交
835
                          bool *enable G_GNUC_UNUSED)
836 837 838 839 840 841 842
{
    virReportSystemError(ENOSYS,
                         _("Unable to get STP on %s on this platform"),
                         brname);
    return -1;
}
#else
843
int virNetDevBridgeSetSTPDelay(const char *brname,
J
Ján Tomko 已提交
844
                               int delay G_GNUC_UNUSED)
845 846 847 848 849 850 851
{
    virReportSystemError(ENOSYS,
                         _("Unable to set STP delay on %s on this platform"),
                         brname);
    return -1;
}
int virNetDevBridgeGetSTPDelay(const char *brname,
J
Ján Tomko 已提交
852
                               int *delay G_GNUC_UNUSED)
853 854 855 856 857 858 859 860
{
    virReportSystemError(ENOSYS,
                         _("Unable to get STP delay on %s on this platform"),
                         brname);
    return -1;
}

int virNetDevBridgeSetSTP(const char *brname,
J
Ján Tomko 已提交
861
                          bool enable G_GNUC_UNUSED)
862 863 864 865 866 867 868 869

{
    virReportSystemError(ENOSYS,
                         _("Unable to set STP on %s on this platform"),
                         brname);
    return -1;
}
int virNetDevBridgeGetSTP(const char *brname,
J
Ján Tomko 已提交
870
                          bool *enable G_GNUC_UNUSED)
871 872 873 874 875 876
{
    virReportSystemError(ENOSYS,
                         _("Unable to get STP on %s on this platform"),
                         brname);
    return -1;
}
877
#endif
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896

#if defined(HAVE_STRUCT_IFREQ) && defined(__linux__)
/**
 * virNetDevBridgeGetVlanFiltering:
 * @brname: the bridge device name
 * @enable: true or false
 *
 * Retrieves the vlan_filtering setting for the bridge device @brname
 * storing it in @enable.
 *
 * Returns 0 on success, -1 on error
 */
int
virNetDevBridgeGetVlanFiltering(const char *brname,
                                bool *enable)
{
    int ret = -1;
    unsigned long value;

897
    if (virNetDevBridgeGet(brname, "vlan_filtering", &value) < 0)
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
        goto cleanup;

    *enable = !!value;
    ret = 0;
 cleanup:
    return ret;
}


/**
 * virNetDevBridgeSetVlanFiltering:
 * @brname: the bridge name
 * @enable: true or false
 *
 * Set the bridge vlan_filtering mode
 *
 * Returns 0 in case of success or -1 on failure
 */

int
virNetDevBridgeSetVlanFiltering(const char *brname,
                                bool enable)
{
    return virNetDevBridgeSet(brname, "vlan_filtering", enable ? 1 : 0, -1, NULL);
}


#else
int
J
Ján Tomko 已提交
927 928
virNetDevBridgeGetVlanFiltering(const char *brname G_GNUC_UNUSED,
                                bool *enable G_GNUC_UNUSED)
929 930 931 932 933 934 935 936
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to get bridge vlan_filtering on this platform"));
    return -1;
}


int
J
Ján Tomko 已提交
937 938
virNetDevBridgeSetVlanFiltering(const char *brname G_GNUC_UNUSED,
                                bool enable G_GNUC_UNUSED)
939 940 941 942 943 944
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to set bridge vlan_filtering on this platform"));
    return -1;
}
#endif
945 946 947


#if defined(__linux__) && defined(HAVE_LIBNL)
948 949 950 951 952 953 954 955 956

# ifndef NTF_SELF
#  define NTF_SELF 0x02
# endif

# ifndef NTF_MASTER
#  define NTF_MASTER 0x04
# endif

957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
/* virNetDevBridgeFDBAddDel:
 * @mac: the MAC address being added to the table
 * @ifname: name of the port (interface) of the bridge that wants this MAC
 * @flags: any of virNetDevBridgeFDBFlags ORed together.
 * @isAdd: true if adding the entry, fals if deleting
 *
 * Use netlink RTM_NEWNEIGH and RTM_DELNEIGH messages to add and
 * delete entries from a bridge's fdb. The bridge itself is not
 * referenced in the arguments to the function, only the name of the
 * device that is attached to the bridge (since a device can only be
 * attached to one bridge at a time, and must be attached for this
 * function to make sense, the kernel easily infers which bridge's fdb
 * is being modified by looking at the device name/index).
 *
 * Attempting to add an existing entry, or delete a non-existing entry
 * *is* an error.
 *
 * returns 0 on success, -1 on failure.
 */
static int
virNetDevBridgeFDBAddDel(const virMacAddr *mac, const char *ifname,
                         unsigned int flags, bool isAdd)
{
    struct nlmsgerr *err;
    unsigned int recvbuflen;
    struct ndmsg ndm = { .ndm_family = PF_BRIDGE, .ndm_state = NUD_NOARP };
J
Ján Tomko 已提交
983
    g_autoptr(virNetlinkMsg) nl_msg = NULL;
984
    g_autofree struct nlmsghdr *resp = NULL;
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

    if (virNetDevGetIndex(ifname, &ndm.ndm_ifindex) < 0)
        return -1;

    if (flags & VIR_NETDEVBRIDGE_FDB_FLAG_ROUTER)
        ndm.ndm_flags |= NTF_ROUTER;
    if (flags & VIR_NETDEVBRIDGE_FDB_FLAG_SELF)
        ndm.ndm_flags |= NTF_SELF;
    if (flags & VIR_NETDEVBRIDGE_FDB_FLAG_MASTER)
        ndm.ndm_flags |= NTF_MASTER;
    /* default self (same as iproute2's bridge command */
    if (!(ndm.ndm_flags & (NTF_MASTER | NTF_SELF)))
        ndm.ndm_flags |= NTF_SELF;

    if (flags & VIR_NETDEVBRIDGE_FDB_FLAG_PERMANENT)
        ndm.ndm_state |= NUD_PERMANENT;
    if (flags & VIR_NETDEVBRIDGE_FDB_FLAG_TEMP)
        ndm.ndm_state |= NUD_REACHABLE;
    /* default permanent, same as iproute2's bridge command */
    if (!(ndm.ndm_state & (NUD_PERMANENT | NUD_REACHABLE)))
        ndm.ndm_state |= NUD_PERMANENT;

    nl_msg = nlmsg_alloc_simple(isAdd ? RTM_NEWNEIGH : RTM_DELNEIGH,
                                NLM_F_REQUEST |
                                (isAdd ? (NLM_F_CREATE | NLM_F_EXCL) : 0));
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }

    if (nlmsg_append(nl_msg, &ndm, sizeof(ndm), NLMSG_ALIGNTO) < 0)
        goto buffer_too_small;
    if (nla_put(nl_msg, NDA_LLADDR, VIR_MAC_BUFLEN, mac) < 0)
        goto buffer_too_small;

    /* NB: this message can also accept a Destination IP, a port, a
     * vlan tag, and a via (see iproute2/bridge/fdb.c:fdb_modify()),
     * but those aren't required for our application
     */

    if (virNetlinkCommand(nl_msg, &resp, &recvbuflen, 0, 0,
                          NETLINK_ROUTE, 0) < 0) {
1027
        return -1;
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    }
    if (recvbuflen < NLMSG_LENGTH(0) || resp == NULL)
        goto malformed_resp;

    switch (resp->nlmsg_type) {
    case NLMSG_ERROR:
        err = (struct nlmsgerr *)NLMSG_DATA(resp);
        if (resp->nlmsg_len < NLMSG_LENGTH(sizeof(*err)))
            goto malformed_resp;
        if (err->error) {
            virReportSystemError(-err->error,
                                 _("error adding fdb entry for %s"), ifname);
1040
            return -1;
1041 1042 1043 1044 1045 1046 1047 1048 1049
        }
        break;
    case NLMSG_DONE:
        break;

    default:
        goto malformed_resp;
    }

1050
    return 0;
1051 1052 1053 1054

 malformed_resp:
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("malformed netlink response message"));
1055
    return -1;
1056 1057 1058 1059

 buffer_too_small:
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("allocated netlink buffer is too small"));
1060
    return -1;
1061 1062 1063 1064 1065
}


#else
static int
J
Ján Tomko 已提交
1066 1067 1068 1069
virNetDevBridgeFDBAddDel(const virMacAddr *mac G_GNUC_UNUSED,
                         const char *ifname G_GNUC_UNUSED,
                         unsigned int fdbFlags G_GNUC_UNUSED,
                         bool isAdd G_GNUC_UNUSED)
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to add/delete fdb entries on this platform"));
    return -1;
}


#endif

int
virNetDevBridgeFDBAdd(const virMacAddr *mac, const char *ifname,
                      unsigned int flags)
{
    return virNetDevBridgeFDBAddDel(mac, ifname, flags, true);
}


int
virNetDevBridgeFDBDel(const virMacAddr *mac, const char *ifname,
                      unsigned int flags)
{
    return virNetDevBridgeFDBAddDel(mac, ifname, flags, false);
}