interface_backend_udev.c 32.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * interface_backend_udev.c: udev backend for virInterface
 *
 * Copyright (C) 2012 Doug Goldstein <cardoe@cardoe.com>
 *
 * 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
 * License along with this library;  If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <config.h>

22 23
#include <errno.h>
#include <dirent.h>
24 25
#include <libudev.h>

26
#include "virerror.h"
27
#include "c-ctype.h"
28
#include "datatypes.h"
29
#include "domain_conf.h"
30 31
#include "interface_driver.h"
#include "interface_conf.h"
32
#include "viralloc.h"
33
#include "virstring.h"
34 35 36 37 38 39 40 41 42 43 44 45 46

#define VIR_FROM_THIS VIR_FROM_INTERFACE

struct udev_iface_driver {
    struct udev *udev;
};

typedef enum {
    VIR_UDEV_IFACE_ACTIVE,
    VIR_UDEV_IFACE_INACTIVE,
    VIR_UDEV_IFACE_ALL
} virUdevStatus ;

47
static virInterfaceDef *udevGetIfaceDef(struct udev *udev, const char *name);
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
static const char *
virUdevStatusString(virUdevStatus status)
{
    switch (status) {
        case VIR_UDEV_IFACE_ACTIVE:
            return "active";
        case VIR_UDEV_IFACE_INACTIVE:
            return "inactive";
        case VIR_UDEV_IFACE_ALL:
            return "all";
    }

    return "";
}

static struct udev_enumerate * ATTRIBUTE_NONNULL(1)
65
udevGetDevices(struct udev *udev, virUdevStatus status)
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
{
    struct udev_enumerate *enumerate;

    /* Create a new enumeration to create a list */
    enumerate = udev_enumerate_new(udev);

    if (!enumerate)
        return NULL;

    /* Enumerate all network subsystem devices */
    udev_enumerate_add_match_subsystem(enumerate, "net");

    /* Ignore devices that are part of a bridge */
    udev_enumerate_add_nomatch_sysattr(enumerate, "brport/state", NULL);

    /* State of the device */
    switch (status) {
        case VIR_UDEV_IFACE_ACTIVE:
            udev_enumerate_add_match_sysattr(enumerate, "operstate", "up");
            break;

        case VIR_UDEV_IFACE_INACTIVE:
            udev_enumerate_add_match_sysattr(enumerate, "operstate", "down");
            break;

        case VIR_UDEV_IFACE_ALL:
            break;
    }

    /* We don't want to see the TUN devices that QEMU creates for other guests
     * running on this machine. By saying nomatch NULL, we just are getting
     * devices without the tun_flags sysattr.
     */
    udev_enumerate_add_nomatch_sysattr(enumerate, "tun_flags", NULL);

    return enumerate;
}

static virDrvOpenStatus
105 106 107
udevInterfaceOpen(virConnectPtr conn,
                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                  unsigned int flags)
108 109 110 111 112 113 114
{
    struct udev_iface_driver *driverState = NULL;

    virCheckFlags(0, VIR_DRV_OPEN_ERROR);

    if (VIR_ALLOC(driverState) < 0) {
        virReportOOMError();
115
        goto cleanup;
116 117 118 119 120 121
    }

    driverState->udev = udev_new();
    if (!driverState->udev) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create udev context"));
122
        goto cleanup;
123 124 125 126 127 128
    }

    conn->interfacePrivateData = driverState;

    return VIR_DRV_OPEN_SUCCESS;

129
cleanup:
130 131 132 133 134 135
    VIR_FREE(driverState);

    return VIR_DRV_OPEN_ERROR;
}

static int
136
udevInterfaceClose(virConnectPtr conn)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
{
    struct udev_iface_driver *driverState;

    if (conn->interfacePrivateData != NULL) {
        driverState = conn->interfacePrivateData;

        udev_unref(driverState->udev);

        VIR_FREE(driverState);
    }

    conn->interfacePrivateData = NULL;
    return 0;
}

static int
153
udevNumOfInterfacesByStatus(virConnectPtr conn, virUdevStatus status)
154 155 156 157 158 159 160 161
{
    struct udev_iface_driver *driverState = conn->interfacePrivateData;
    struct udev *udev = udev_ref(driverState->udev);
    struct udev_enumerate *enumerate = NULL;
    struct udev_list_entry *devices;
    struct udev_list_entry *dev_entry;
    int count = 0;

162
    enumerate = udevGetDevices(udev, status);
163 164 165 166 167 168

    if (!enumerate) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to get number of %s interfaces on host"),
                       virUdevStatusString(status));
        count = -1;
169
        goto cleanup;
170 171 172 173 174 175 176 177 178 179 180 181 182
    }

    /* Do the scan to load up the enumeration */
    udev_enumerate_scan_devices(enumerate);

    /* Get a list we can walk */
    devices = udev_enumerate_get_list_entry(enumerate);

    /* For each item so we can count */
    udev_list_entry_foreach(dev_entry, devices) {
        count++;
    }

183
cleanup:
184 185 186 187 188 189 190 191
    if (enumerate)
        udev_enumerate_unref(enumerate);
    udev_unref(udev);

    return count;
}

static int
192 193 194 195
udevListInterfacesByStatus(virConnectPtr conn,
                           char **const names,
                           int names_len,
                           virUdevStatus status)
196 197 198 199 200 201 202 203
{
    struct udev_iface_driver *driverState = conn->interfacePrivateData;
    struct udev *udev = udev_ref(driverState->udev);
    struct udev_enumerate *enumerate = NULL;
    struct udev_list_entry *devices;
    struct udev_list_entry *dev_entry;
    int count = 0;

204
    enumerate = udevGetDevices(udev, status);
205 206 207 208 209

    if (!enumerate) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to get list of %s interfaces on host"),
                       virUdevStatusString(status));
210
        goto error;
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    }

    /* Do the scan to load up the enumeration */
    udev_enumerate_scan_devices(enumerate);

    /* Get a list we can walk */
    devices = udev_enumerate_get_list_entry(enumerate);

    /* For each item so we can count */
    udev_list_entry_foreach(dev_entry, devices) {
        struct udev_device *dev;
        const char *path;

        /* Ensure we won't exceed the size of our array */
        if (count > names_len)
            break;

        path = udev_list_entry_get_name(dev_entry);
        dev = udev_device_new_from_syspath(udev, path);
230 231
        if (VIR_STRDUP(names[count], udev_device_get_sysname(dev)) < 0) {
            udev_device_unref(dev);
232
            goto error;
233
        }
234
        udev_device_unref(dev);
235 236 237 238 239 240 241 242 243

        count++;
    }

    udev_enumerate_unref(enumerate);
    udev_unref(udev);

    return count;

244
error:
245 246 247 248 249 250 251 252 253 254 255
    if (enumerate)
        udev_enumerate_unref(enumerate);
    udev_unref(udev);

    for (names_len = 0; names_len < count; names_len++)
        VIR_FREE(names[names_len]);

    return -1;
}

static int
256
udevConnectNumOfInterfaces(virConnectPtr conn)
257
{
258
    return udevNumOfInterfacesByStatus(conn, VIR_UDEV_IFACE_ACTIVE);
259 260 261
}

static int
262 263 264
udevConnectListInterfaces(virConnectPtr conn,
                          char **const names,
                          int names_len)
265
{
266 267
    return udevListInterfacesByStatus(conn, names, names_len,
                                      VIR_UDEV_IFACE_ACTIVE);
268 269 270
}

static int
271
udevConnectNumOfDefinedInterfaces(virConnectPtr conn)
272
{
273
    return udevNumOfInterfacesByStatus(conn, VIR_UDEV_IFACE_INACTIVE);
274 275 276
}

static int
277 278 279
udevConnectListDefinedInterfaces(virConnectPtr conn,
                                 char **const names,
                                 int names_len)
280
{
281 282
    return udevListInterfacesByStatus(conn, names, names_len,
                                      VIR_UDEV_IFACE_INACTIVE);
283 284 285
}

static int
286 287 288
udevConnectListAllInterfaces(virConnectPtr conn,
                             virInterfacePtr **ifaces,
                             unsigned int flags)
289 290 291 292 293 294
{
    struct udev_iface_driver *driverState = conn->interfacePrivateData;
    struct udev *udev;
    struct udev_enumerate *enumerate = NULL;
    struct udev_list_entry *devices;
    struct udev_list_entry *dev_entry;
295
    virInterfacePtr *ifaces_list = NULL;
296 297 298 299 300 301 302 303 304 305 306 307 308
    virInterfacePtr iface_obj;
    int tmp_count;
    int count = 0;
    int status = 0;
    int ret;

    virCheckFlags(VIR_CONNECT_LIST_INTERFACES_ACTIVE |
                  VIR_CONNECT_LIST_INTERFACES_INACTIVE, -1);

    /* Grab a udev reference */
    udev = udev_ref(driverState->udev);

    /* List all interfaces in case we support more filter flags in the future */
309
    enumerate = udevGetDevices(udev, VIR_UDEV_IFACE_ALL);
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

    if (!enumerate) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to get list of %s interfaces on host"),
                       virUdevStatusString(status));
        ret = -1;
        goto cleanup;
    }

    /* Do the scan to load up the enumeration */
    udev_enumerate_scan_devices(enumerate);

    /* Get a list we can walk */
    devices = udev_enumerate_get_list_entry(enumerate);

    /* For each item so we can count */
    udev_list_entry_foreach(dev_entry, devices) {
        count++;
    }

    /* If we've got nothing, exit out */
    if (count == 0) {
        ret = 0;
        goto cleanup;
    }

    /* If we're asked for the ifaces then alloc up memory */
    if (ifaces) {
        if (VIR_ALLOC_N(ifaces_list, count + 1) < 0) {
            virReportOOMError();
            ret = -1;
            goto cleanup;
        }
    }

    /* Get a list we can walk */
    devices = udev_enumerate_get_list_entry(enumerate);

    /* reset our iterator */
    count = 0;

    /* Walk through each device */
    udev_list_entry_foreach(dev_entry, devices) {
        struct udev_device *dev;
        const char *path;
        const char *name;
        const char *macaddr;
357
        int add_to_list = 0;
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

        path = udev_list_entry_get_name(dev_entry);
        dev = udev_device_new_from_syspath(udev, path);
        name = udev_device_get_sysname(dev);
        macaddr = udev_device_get_sysattr_value(dev, "address");
        status = STREQ(udev_device_get_sysattr_value(dev, "operstate"), "up");

        /* Filter the results */
        if (status && (flags & VIR_CONNECT_LIST_INTERFACES_ACTIVE))
            add_to_list = 1;
        else if (!status && (flags & VIR_CONNECT_LIST_INTERFACES_INACTIVE))
            add_to_list = 1;

        /* If we matched a filter, then add it */
        if (add_to_list) {
            if (ifaces) {
                iface_obj = virGetInterface(conn, name, macaddr);
                ifaces_list[count] = iface_obj;
            }
            count++;
        }
379
        udev_device_unref(dev);
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    }

    /* Drop our refcounts */
    udev_enumerate_unref(enumerate);
    udev_unref(udev);

    /* Trim the array to its final size */
    if (ifaces) {
        ignore_value(VIR_REALLOC_N(ifaces_list, count + 1));
        *ifaces = ifaces_list;
    }

    return count;

cleanup:
    if (enumerate)
        udev_enumerate_unref(enumerate);
    udev_unref(udev);

    if (ifaces) {
        for (tmp_count = 0; tmp_count < count; tmp_count++)
            virInterfaceFree(ifaces_list[tmp_count]);
    }

    VIR_FREE(ifaces_list);

    return ret;

}

static virInterfacePtr
411
udevInterfaceLookupByName(virConnectPtr conn, const char *name)
412 413 414 415 416 417 418 419 420 421 422 423 424
{
    struct udev_iface_driver *driverState = conn->interfacePrivateData;
    struct udev *udev = udev_ref(driverState->udev);
    struct udev_device *dev;
    const char *macaddr;
    virInterfacePtr ret = NULL;

    /* get a device reference based on the device name */
    dev = udev_device_new_from_subsystem_sysname(udev, "net", name);
    if (!dev) {
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("couldn't find interface named '%s'"),
                       name);
425
        goto cleanup;
426 427 428 429 430 431
    }

    macaddr = udev_device_get_sysattr_value(dev, "address");
    ret = virGetInterface(conn, name, macaddr);
    udev_device_unref(dev);

432
cleanup:
433 434 435 436 437 438
    udev_unref(udev);

    return ret;
}

static virInterfacePtr
439
udevInterfaceLookupByMACString(virConnectPtr conn, const char *macstr)
440 441 442 443 444 445 446 447 448
{
    struct udev_iface_driver *driverState = conn->interfacePrivateData;
    struct udev *udev = udev_ref(driverState->udev);
    struct udev_enumerate *enumerate = NULL;
    struct udev_list_entry *dev_entry;
    struct udev_device *dev;
    const char *name;
    virInterfacePtr ret = NULL;

449
    enumerate = udevGetDevices(udev, VIR_UDEV_IFACE_ALL);
450 451 452 453 454

    if (!enumerate) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to lookup interface with MAC address '%s'"),
                       macstr);
455
        goto cleanup;
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    }

    /* Match on MAC */
    udev_enumerate_add_match_sysattr(enumerate, "address", macstr);

    /* Do the scan to load up the enumeration */
    udev_enumerate_scan_devices(enumerate);

    /* Get a list we can walk */
    dev_entry = udev_enumerate_get_list_entry(enumerate);

    /* Check that we got something back */
    if (!dev_entry) {
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("couldn't find interface with MAC address '%s'"),
                       macstr);
472
        goto cleanup;
473 474 475 476 477 478 479
    }

    /* Check that we didn't get multiple items back */
    if (udev_list_entry_get_next(dev_entry)) {
        virReportError(VIR_ERR_MULTIPLE_INTERFACES,
                       _("the MAC address '%s' matches multiple interfaces"),
                       macstr);
480
        goto cleanup;
481 482 483 484 485 486 487
    }

    dev = udev_device_new_from_syspath(udev, udev_list_entry_get_name(dev_entry));
    name = udev_device_get_sysname(dev);
    ret = virGetInterface(conn, name, macstr);
    udev_device_unref(dev);

488
cleanup:
489 490 491 492 493 494 495
    if (enumerate)
        udev_enumerate_unref(enumerate);
    udev_unref(udev);

    return ret;
}

496 497 498 499 500 501 502 503
/**
 * Helper function for finding bond slaves using scandir()
 *
 * @param entry - directory entry passed by scandir()
 *
 * @return 1 if we want to add it to scandir's list, 0 if not.
 */
static int
504
udevBondScanDirFilter(const struct dirent *entry)
505 506 507 508 509 510 511 512 513 514 515 516
{
    /* This is ugly so if anyone has a better suggestion, please improve
     * this. Unfortunately the kernel stores everything in the top level
     * interface sysfs entry and references the slaves as slave_eth0 for
     * example.
     */
    if (STRPREFIX(entry->d_name, "slave_"))
        return 1;

    return 0;
}

517
/**
518
 * Helper function for finding bridge members using scandir()
519 520 521 522 523 524
 *
 * @param entry - directory entry passed by scandir()
 *
 * @return 1 if we want to add it to scandir's list, 0 if not.
 */
static int
525
udevBridgeScanDirFilter(const struct dirent *entry)
526 527 528 529
{
    if (STREQ(entry->d_name, ".") || STREQ(entry->d_name, ".."))
        return 0;

530 531 532 533 534 535 536 537 538 539
    /* Omit the domain interfaces from the list of bridge attached
     * devices. All we can do is check for the device name matching
     * vnet%d. Improvements to this check are welcome.
     */
    if (strlen(entry->d_name) >= 5) {
        if (STRPREFIX(entry->d_name, VIR_NET_GENERATED_PREFIX) &&
            c_isdigit(entry->d_name[4]))
            return 0;
    }

540 541 542 543
    return 1;
}


544 545 546
static int
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
ATTRIBUTE_NONNULL(4) ATTRIBUTE_RETURN_CHECK
547 548 549 550
udevGetIfaceDefBond(struct udev *udev,
                    struct udev_device *dev,
                    const char *name,
                    virInterfaceDef *ifacedef)
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
{
    struct dirent **slave_list = NULL;
    int slave_count = 0;
    int i;
    const char *tmp_str;
    int tmp_int;

    /* Initial defaults */
    ifacedef->data.bond.target = NULL;
    ifacedef->data.bond.nbItf = 0;
    ifacedef->data.bond.itf = NULL;

    /* Set the bond specifics */
    tmp_str = udev_device_get_sysattr_value(dev, "bonding/downdelay");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/downdelay' for '%s'"), name);
568
        goto error;
569 570 571 572 573
    }
    if (virStrToLong_i(tmp_str, NULL, 10, &tmp_int) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bonding/downdelay' '%s' for '%s'"),
                tmp_str, name);
574
        goto error;
575 576 577 578 579 580 581
    }
    ifacedef->data.bond.downdelay = tmp_int;

    tmp_str = udev_device_get_sysattr_value(dev, "bonding/updelay");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/updelay' for '%s'"), name);
582
        goto error;
583 584 585 586 587
    }
    if (virStrToLong_i(tmp_str, NULL, 10, &tmp_int) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bonding/updelay' '%s' for '%s'"),
                tmp_str, name);
588
        goto error;
589 590 591 592 593 594 595
    }
    ifacedef->data.bond.updelay = tmp_int;

    tmp_str = udev_device_get_sysattr_value(dev, "bonding/miimon");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/miimon' for '%s'"), name);
596
        goto error;
597 598 599 600 601
    }
    if (virStrToLong_i(tmp_str, NULL, 10, &tmp_int) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bonding/miimon' '%s' for '%s'"),
                tmp_str, name);
602
        goto error;
603 604 605 606 607 608 609
    }
    ifacedef->data.bond.frequency = tmp_int;

    tmp_str = udev_device_get_sysattr_value(dev, "bonding/arp_interval");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/arp_interval' for '%s'"), name);
610
        goto error;
611 612 613 614 615
    }
    if (virStrToLong_i(tmp_str, NULL, 10, &tmp_int) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bonding/arp_interval' '%s' for '%s'"),
                tmp_str, name);
616
        goto error;
617 618 619 620 621 622 623 624 625 626 627 628
    }
    ifacedef->data.bond.interval = tmp_int;

    /* bonding/mode is in the format: "balance-rr 0" so we find the
     * space and increment the pointer to get the number and convert
     * it to an interger. libvirt uses 1 through 7 while the raw
     * number is 0 through 6 so increment it by 1.
     */
    tmp_str = udev_device_get_sysattr_value(dev, "bonding/mode");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/mode' for '%s'"), name);
629
        goto error;
630 631 632 633 634
    }
    tmp_str = strchr(tmp_str, ' ');
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Invalid format for 'bonding/mode' for '%s'"), name);
635
        goto error;
636 637 638 639 640
    }
    if (strlen(tmp_str) < 2) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Unable to find correct value in 'bonding/mode' for '%s'"),
                name);
641
        goto error;
642 643 644 645 646
    }
    if (virStrToLong_i(tmp_str + 1, NULL, 10, &tmp_int) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bonding/mode' '%s' for '%s'"),
                tmp_str, name);
647
        goto error;
648 649 650 651 652 653 654 655 656 657 658
    }
    ifacedef->data.bond.mode = tmp_int + 1;

    /* bonding/arp_validate is in the format: "none 0" so we find the
     * space and increment the pointer to get the number and convert
     * it to an interger.
     */
    tmp_str = udev_device_get_sysattr_value(dev, "bonding/arp_validate");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/arp_validate' for '%s'"), name);
659
        goto error;
660 661 662 663 664
    }
    tmp_str = strchr(tmp_str, ' ');
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Invalid format for 'bonding/arp_validate' for '%s'"), name);
665
        goto error;
666 667 668 669 670
    }
    if (strlen(tmp_str) < 2) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Unable to find correct value in 'bonding/arp_validate' "
                "for '%s'"), name);
671
        goto error;
672 673 674 675 676
    }
    if (virStrToLong_i(tmp_str + 1, NULL, 10, &tmp_int) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bonding/arp_validate' '%s' for '%s'"),
                tmp_str, name);
677
        goto error;
678 679 680 681 682 683 684 685
    }
    ifacedef->data.bond.validate = tmp_int;

    /* bonding/use_carrier is 0 or 1 and libvirt stores it as 1 or 2. */
    tmp_str = udev_device_get_sysattr_value(dev, "bonding/use_carrier");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/use_carrier' for '%s'"), name);
686
        goto error;
687 688 689 690 691
    }
    if (virStrToLong_i(tmp_str, NULL, 10, &tmp_int) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bonding/use_carrier' '%s' for '%s'"),
                tmp_str, name);
692
        goto error;
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    }
    ifacedef->data.bond.carrier = tmp_int + 1;

    /* MII or ARP Monitoring is based on arp_interval and miimon.
     * if arp_interval > 0 then ARP monitoring is in play, if
     * miimon > 0 then MII monitoring is in play.
     */
    if (ifacedef->data.bond.interval > 0)
        ifacedef->data.bond.monit = VIR_INTERFACE_BOND_MONIT_ARP;
    else if (ifacedef->data.bond.frequency > 0)
        ifacedef->data.bond.monit = VIR_INTERFACE_BOND_MONIT_MII;
    else
        ifacedef->data.bond.monit = VIR_INTERFACE_BOND_MONIT_NONE;

    tmp_str = udev_device_get_sysattr_value(dev, "bonding/arp_ip_target");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bonding/arp_ip_target' for '%s'"), name);
711
        goto error;
712
    }
713
    if (VIR_STRDUP(ifacedef->data.bond.target, tmp_str) < 0)
714
        goto error;
715 716 717 718

    /* Slaves of the bond */
    /* Get each slave in the bond */
    slave_count = scandir(udev_device_get_syspath(dev), &slave_list,
719
            udevBondScanDirFilter, alphasort);
720 721 722 723

    if (slave_count < 0) {
        virReportSystemError(errno,
                _("Could not get slaves of bond '%s'"), name);
724
        goto error;
725 726 727 728 729
    }

    /* Allocate our list of slave devices */
    if (VIR_ALLOC_N(ifacedef->data.bond.itf, slave_count) < 0) {
        virReportOOMError();
730
        goto error;
731 732 733 734 735 736 737 738
    }
    ifacedef->data.bond.nbItf = slave_count;

    for (i = 0; i < slave_count; i++) {
        /* Names are slave_interface. e.g. slave_eth0
         * so we use the part after the _
         */
        tmp_str = strchr(slave_list[i]->d_name, '_');
739 740 741 742
        if (!tmp_str || strlen(tmp_str) < 2) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid enslaved interface name '%s' seen for "
                             "bond '%s'"), slave_list[i]->d_name, name);
743
            goto error;
744 745
        }
        /* go past the _ */
746 747 748
        tmp_str++;

        ifacedef->data.bond.itf[i] =
749
            udevGetIfaceDef(udev, tmp_str);
750 751 752 753
        if (!ifacedef->data.bond.itf[i]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not get interface information for '%s', which is "
                  "a enslaved in bond '%s'"), slave_list[i]->d_name, name);
754
            goto error;
755 756 757 758 759 760 761 762
        }
        VIR_FREE(slave_list[i]);
    }

    VIR_FREE(slave_list);

    return 0;

763
error:
764 765 766 767 768 769 770 771
    for (i = 0; i < slave_count; i++) {
        VIR_FREE(slave_list[i]);
    }
    VIR_FREE(slave_list);

    return -1;
}

772 773 774
static int
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
ATTRIBUTE_NONNULL(4) ATTRIBUTE_RETURN_CHECK
775 776 777 778
udevGetIfaceDefBridge(struct udev *udev,
                      struct udev_device *dev,
                      const char *name,
                      virInterfaceDef *ifacedef)
779 780 781 782
{
    struct dirent **member_list = NULL;
    int member_count = 0;
    char *member_path;
783
    const char *tmp_str;
784 785 786 787 788 789
    int stp;
    int i;

    /* Set our type to Bridge  */
    ifacedef->type = VIR_INTERFACE_TYPE_BRIDGE;

790 791 792 793 794 795 796 797
    /* Retrieve the forward delay */
    tmp_str = udev_device_get_sysattr_value(dev, "bridge/forward_delay");
    if (!tmp_str) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not retrieve 'bridge/forward_delay' for '%s'"), name);
        goto error;
    }

798
    if (VIR_STRDUP(ifacedef->data.bridge.delay, tmp_str) < 0)
799
        goto error;
800

801 802 803
    /* Retrieve Spanning Tree State. Valid values = -1, 0, 1 */
    tmp_str = udev_device_get_sysattr_value(dev, "bridge/stp_state");
    if (!tmp_str) {
804
        virReportError(VIR_ERR_INTERNAL_ERROR,
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
            _("Could not retrieve 'bridge/stp_state' for '%s'"), name);
        goto error;
    }

    if (virStrToLong_i(tmp_str, NULL, 10, &stp) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse 'bridge/stp_state' '%s' for '%s'"),
                tmp_str, name);
        goto error;
    }

    switch (stp) {
    case -1:
    case 0:
    case 1:
        ifacedef->data.bridge.stp = stp;
        break;
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
            _("Invalid STP state value %d received for '%s'. Must be "
              "-1, 0, or 1."), stp, name);
        goto error;
827 828 829 830 831 832
    }

    /* Members of the bridge */
    if (virAsprintf(&member_path, "%s/%s",
                udev_device_get_syspath(dev), "brif") < 0) {
        virReportOOMError();
833
        goto error;
834 835 836 837
    }

    /* Get each member of the bridge */
    member_count = scandir(member_path, &member_list,
838
            udevBridgeScanDirFilter, alphasort);
839 840 841 842 843 844 845 846

    /* Don't need the path anymore */
    VIR_FREE(member_path);

    if (member_count < 0) {
        virReportSystemError(errno,
                _("Could not get members of bridge '%s'"),
                name);
847
        goto error;
848 849 850 851 852
    }

    /* Allocate our list of member devices */
    if (VIR_ALLOC_N(ifacedef->data.bridge.itf, member_count) < 0) {
        virReportOOMError();
853
        goto error;
854 855 856
    }
    ifacedef->data.bridge.nbItf = member_count;

857
    /* Get the interface defintions for each member of the bridge */
858 859
    for (i = 0; i < member_count; i++) {
        ifacedef->data.bridge.itf[i] =
860
            udevGetIfaceDef(udev, member_list[i]->d_name);
861 862 863 864 865 866
        if (!ifacedef->data.bridge.itf[i]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not get interface information for '%s', which is "
                  "a member of bridge '%s'"), member_list[i]->d_name, name);
            goto error;
        }
867 868 869 870 871 872 873
        VIR_FREE(member_list[i]);
    }

    VIR_FREE(member_list);

    return 0;

874
error:
875 876 877 878 879 880 881
    for (i = 0; i < member_count; i++) {
        VIR_FREE(member_list[i]);
    }
    VIR_FREE(member_list);

    return -1;
}
882

883 884 885
static int
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
ATTRIBUTE_NONNULL(4) ATTRIBUTE_RETURN_CHECK
886 887 888 889
udevGetIfaceDefVlan(struct udev *udev ATTRIBUTE_UNUSED,
                    struct udev_device *dev ATTRIBUTE_UNUSED,
                    const char *name,
                    virInterfaceDef *ifacedef)
890
{
891
    const char *vid;
892 893

    /* Find the DEVICE.VID again */
894
    vid = strrchr(name, '.');
895 896
    if (!vid) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
897 898 899 900
                       _("failed to find the VID for the VLAN device '%s'"),
                       name);
        return -1;
    }
901 902

    /* Set the VLAN specifics */
903
    if (VIR_STRDUP(ifacedef->data.vlan.tag, vid + 1) < 0)
904
        goto error;
905 906
    if (VIR_STRNDUP(ifacedef->data.vlan.devname,
                    name, (vid - name)) < 0)
907
        goto error;
908 909 910

    return 0;

911
error:
912 913
    VIR_FREE(ifacedef->data.vlan.tag);
    VIR_FREE(ifacedef->data.vlan.devname);
914 915 916 917

    return -1;
}

918
static virInterfaceDef * ATTRIBUTE_NONNULL(1)
919
udevGetIfaceDef(struct udev *udev, const char *name)
920 921 922 923 924 925
{
    struct udev_device *dev = NULL;
    virInterfaceDef *ifacedef;
    unsigned int mtu;
    const char *mtu_str;
    char *vlan_parent_dev = NULL;
926
    const char *devtype;
927 928 929 930 931 932 933 934 935

    /* Allocate our interface definition structure */
    if (VIR_ALLOC(ifacedef) < 0) {
        virReportOOMError();
        return NULL;
    }

    /* Clear our structure and set safe defaults */
    ifacedef->startmode = VIR_INTERFACE_START_UNSPECIFIED;
936
    if (VIR_STRDUP(ifacedef->name, name) < 0)
937
        goto error;
938 939 940 941 942 943

    /* Lookup the device we've been asked about */
    dev = udev_device_new_from_subsystem_sysname(udev, "net", name);
    if (!dev) {
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("couldn't find interface named '%s'"), name);
944
        goto error;
945 946 947
    }

    /* MAC address */
948 949
    if (VIR_STRDUP(ifacedef->mac,
                   udev_device_get_sysattr_value(dev, "address")) < 0)
950
        goto error;
951 952 953 954 955 956

    /* MTU */
    mtu_str = udev_device_get_sysattr_value(dev, "mtu");
    if (virStrToLong_ui(mtu_str, NULL, 10, &mtu) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                _("Could not parse MTU value '%s'"), mtu_str);
957
        goto error;
958 959 960 961 962 963 964 965
    }
    ifacedef->mtu = mtu;

    /* Number of IP protocols this interface has assigned */
    /* XXX: Do we want a netlink query or a call out to ip or leave it? */
    ifacedef->nprotos = 0;
    ifacedef->protos = NULL;

966 967 968 969 970 971 972 973 974 975 976 977 978
    /* Check the type of device we are working with based on the devtype */
    devtype = udev_device_get_devtype(dev);

    /* Set our type to ethernet as the default case */
    ifacedef->type = VIR_INTERFACE_TYPE_ETHERNET;

    if (STREQ_NULLABLE(devtype, "vlan")) {
        /* This only works on modern kernels (3.7 and newer)
         * e949b09b71d975a82f13ac88ce4ad338fed213da
         */
        ifacedef->type = VIR_INTERFACE_TYPE_VLAN;
    } else if (STREQ_NULLABLE(devtype, "bridge")) {
        ifacedef->type = VIR_INTERFACE_TYPE_BRIDGE;
979 980 981
    } else if (STREQ_NULLABLE(devtype, "bond")) {
        /* This only works on modern kernels (3.9 and newer) */
        ifacedef->type = VIR_INTERFACE_TYPE_BOND;
982 983 984 985 986 987 988 989 990 991 992
    }

    /* Fallback checks if the devtype check didn't work. */
    if (ifacedef->type == VIR_INTERFACE_TYPE_ETHERNET) {
        /* First check if its a VLAN based on the name containing a dot,
         * to prevent false positives
         */
        vlan_parent_dev = strrchr(name, '.');
        if (vlan_parent_dev) {
            ifacedef->type = VIR_INTERFACE_TYPE_VLAN;
        }
993 994 995 996 997

        /* Fallback check to see if this is a bond device */
        if (udev_device_get_sysattr_value(dev, "bonding/mode")) {
            ifacedef->type = VIR_INTERFACE_TYPE_BOND;
        }
998 999 1000 1001
    }

    switch (ifacedef->type) {
    case VIR_INTERFACE_TYPE_VLAN:
1002
        if (udevGetIfaceDefVlan(udev, dev, name, ifacedef) < 0)
1003
            goto error;
1004 1005
        break;
    case VIR_INTERFACE_TYPE_BRIDGE:
1006
        if (udevGetIfaceDefBridge(udev, dev, name, ifacedef) < 0)
1007
            goto error;
1008
        break;
1009
    case VIR_INTERFACE_TYPE_BOND:
1010
        if (udevGetIfaceDefBond(udev, dev, name, ifacedef) < 0)
1011
            goto error;
1012
        break;
1013 1014
    case VIR_INTERFACE_TYPE_ETHERNET:
        break;
1015 1016 1017 1018 1019 1020
    }

    udev_device_unref(dev);

    return ifacedef;

1021
error:
1022 1023
    udev_device_unref(dev);

1024
    virInterfaceDefFree(ifacedef);
1025 1026 1027 1028 1029

    return NULL;
}

static char *
1030 1031
udevInterfaceGetXMLDesc(virInterfacePtr ifinfo,
                        unsigned int flags)
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
{
    struct udev_iface_driver *driverState = ifinfo->conn->interfacePrivateData;
    struct udev *udev = udev_ref(driverState->udev);
    virInterfaceDef *ifacedef;
    char *xmlstr = NULL;

    virCheckFlags(VIR_INTERFACE_XML_INACTIVE, NULL);

    /* Recursively build up the interface XML based on the requested
     * interface name
     */
1043
    ifacedef = udevGetIfaceDef(udev, ifinfo->name);
1044 1045

    if (!ifacedef)
1046
        goto cleanup;
1047 1048 1049

    xmlstr = virInterfaceDefFormat(ifacedef);

1050
    virInterfaceDefFree(ifacedef);
1051

1052
cleanup:
1053 1054 1055 1056 1057 1058
    /* decrement our udev ptr */
    udev_unref(udev);

    return xmlstr;
}

1059
static int
1060
udevInterfaceIsActive(virInterfacePtr ifinfo)
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
{
    struct udev_iface_driver *driverState = ifinfo->conn->interfacePrivateData;
    struct udev *udev = udev_ref(driverState->udev);
    struct udev_device *dev;
    int status;

    dev = udev_device_new_from_subsystem_sysname(udev, "net",
                                                 ifinfo->name);
    if (!dev) {
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("couldn't find interface named '%s'"),
                       ifinfo->name);
        status = -1;
        goto cleanup;
    }

    /* Check if it's active or not */
    status = STREQ(udev_device_get_sysattr_value(dev, "operstate"), "up");

    udev_device_unref(dev);

cleanup:
    udev_unref(udev);

    return status;
}

1088 1089
static virInterfaceDriver udevIfaceDriver = {
    "udev",
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    .interfaceOpen = udevInterfaceOpen, /* 1.0.0 */
    .interfaceClose = udevInterfaceClose, /* 1.0.0 */
    .connectNumOfInterfaces = udevConnectNumOfInterfaces, /* 1.0.0 */
    .connectListInterfaces = udevConnectListInterfaces, /* 1.0.0 */
    .connectNumOfDefinedInterfaces = udevConnectNumOfDefinedInterfaces, /* 1.0.0 */
    .connectListDefinedInterfaces = udevConnectListDefinedInterfaces, /* 1.0.0 */
    .connectListAllInterfaces = udevConnectListAllInterfaces, /* 1.0.0 */
    .interfaceLookupByName = udevInterfaceLookupByName, /* 1.0.0 */
    .interfaceLookupByMACString = udevInterfaceLookupByMACString, /* 1.0.0 */
    .interfaceIsActive = udevInterfaceIsActive, /* 1.0.0 */
    .interfaceGetXMLDesc = udevInterfaceGetXMLDesc, /* 1.0.0 */
1101 1102 1103
};

int
1104
udevIfaceRegister(void) {
1105 1106 1107 1108 1109 1110 1111
    if (virRegisterInterfaceDriver(&udevIfaceDriver) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to register udev interface driver"));
        return -1;
    }
    return 0;
}