interface.c 32.7 KB
Newer Older
1 2 3
/*
 * interface.c: interface support functions
 *
4
 * Copyright (C) 2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 * Copyright (C) 2010 IBM Corp.
 * Copyright (C) 2010 Stefan Berger
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * chgIfaceFlags originated from bridge.c
 *
 * Author: Stefan Berger <stefanb@us.ibm.com>
 */

#include <config.h>

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

#ifdef __linux__
# include <linux/if.h>
36 37
# include <linux/sockios.h>
# include <linux/if_vlan.h>
38
#endif
39 40 41 42 43 44

#include "internal.h"

#include "util.h"
#include "interface.h"
#include "virterror_internal.h"
E
Eric Blake 已提交
45
#include "virfile.h"
46 47
#include "memory.h"
#include "netlink.h"
48 49
#include "pci.h"
#include "logging.h"
50 51

#define VIR_FROM_THIS VIR_FROM_NET
52 53

#define ifaceError(code, ...) \
54
        virReportErrorHelper(VIR_FROM_NET, code, __FILE__, \
55 56
                             __FUNCTION__, __LINE__, __VA_ARGS__)

57 58 59 60 61 62 63 64
#if __linux__
static int
getFlags(int fd, const char *ifname, struct ifreq *ifr) {

    memset(ifr, 0, sizeof(*ifr));

    if (virStrncpy(ifr->ifr_name,
                   ifname, strlen(ifname), sizeof(ifr->ifr_name)) == NULL)
65
        return -ENODEV;
66 67

    if (ioctl(fd, SIOCGIFFLAGS, ifr) < 0)
68
        return -errno;
69 70 71 72 73 74 75 76 77 78 79

    return 0;
}


/**
 * ifaceGetFlags
 *
 * @ifname : name of the interface
 * @flags : pointer to short holding the flags on success
 *
80
 * Get the flags of the interface. Returns 0 on success, -errno on failure.
81 82 83 84 85 86 87 88
 */
int
ifaceGetFlags(const char *ifname, short *flags) {
    struct ifreq ifr;
    int rc;
    int fd = socket(PF_PACKET, SOCK_DGRAM, 0);

    if (fd < 0)
89
        return -errno;
90 91 92 93 94

    rc = getFlags(fd, ifname, &ifr);

    *flags = ifr.ifr_flags;

95
    VIR_FORCE_CLOSE(fd);
96 97 98 99 100 101 102

    return rc;
}


int
ifaceIsUp(const char *ifname, bool *up) {
103
    short flags = 0;
104 105
    int rc = ifaceGetFlags(ifname, &flags);

106
    if (rc < 0)
107 108 109 110 111 112 113 114 115 116 117
        return rc;

    *up = ((flags & IFF_UP) == IFF_UP);

    return 0;
}
#else

/* Note: Showstopper on cygwin is only missing PF_PACKET */

int
118

119 120 121 122
ifaceGetFlags(const char *ifname ATTRIBUTE_UNUSED,
              short *flags ATTRIBUTE_UNUSED) {
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("ifaceGetFlags is not supported on non-linux platforms"));
123
    return -ENOSYS;
124 125 126 127 128 129 130 131
}

int
ifaceIsUp(const char *ifname ATTRIBUTE_UNUSED,
          bool *up ATTRIBUTE_UNUSED) {

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("ifaceIsUp is not supported on non-linux platforms"));
132
    return -ENOSYS;
133 134 135 136
}

#endif /* __linux__ */

137
/*
138
 * chgIfaceFlags: Change flags on an interface
139 140 141 142 143 144 145 146 147
 *
 * @ifname : name of the interface
 * @flagclear : the flags to clear
 * @flagset : the flags to set
 *
 * The new flags of the interface will be calculated as
 * flagmask = (~0 ^ flagclear)
 * newflags = (curflags & flagmask) | flagset;
 *
148
 * Returns 0 on success, -errno on failure.
149
 */
150
#ifdef __linux__
151 152 153
static int chgIfaceFlags(const char *ifname, short flagclear, short flagset) {
    struct ifreq ifr;
    int rc = 0;
154
    short flags;
155 156 157 158
    short flagmask = (~0 ^ flagclear);
    int fd = socket(PF_PACKET, SOCK_DGRAM, 0);

    if (fd < 0)
159
        return -errno;
160

161
    rc = getFlags(fd, ifname, &ifr);
162
    if (rc < 0)
163
        goto cleanup;
164 165 166 167 168 169 170

    flags = (ifr.ifr_flags & flagmask) | flagset;

    if (ifr.ifr_flags != flags) {
        ifr.ifr_flags = flags;

        if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0)
171
            rc = -errno;
172 173
    }

174
cleanup:
175
    VIR_FORCE_CLOSE(fd);
176 177 178 179 180 181 182 183 184 185 186
    return rc;
}


/*
 * ifaceCtrl
 * @name: name of the interface
 * @up: true (1) for up, false (0) for down
 *
 * Function to control if an interface is activated (up, 1) or not (down, 0)
 *
187
 * Returns 0 on success, -errno on failure.
188 189 190 191 192 193 194 195 196
 */
int
ifaceCtrl(const char *name, bool up)
{
    return chgIfaceFlags(name,
                         (up) ? 0      : IFF_UP,
                         (up) ? IFF_UP : 0);
}

197 198 199 200 201
#else

int
ifaceCtrl(const char *name ATTRIBUTE_UNUSED, bool up ATTRIBUTE_UNUSED)
{
202
    return -ENOSYS;
203 204 205
}

#endif /* __linux__ */
206 207 208 209 210 211 212 213 214 215 216 217 218

/**
 * ifaceCheck
 *
 * @reportError: whether to report errors or keep silent
 * @ifname: Name of the interface
 * @macaddr: expected MAC address of the interface; not checked if NULL
 * @ifindex: expected index of the interface; not checked if '-1'
 *
 * Determine whether a given interface is still available. If so,
 * it must have the given MAC address and if an interface index is
 * passed, it must also match the interface index.
 *
219 220 221 222
 * Returns 0 on success, -errno on failure.
 *   -ENODEV : if interface with given name does not exist or its interface
 *             index is different than the one passed
 *   -EINVAL : if interface name is invalid (too long)
223
 */
224
#ifdef __linux__
225 226 227 228 229 230 231 232 233 234 235 236
int
ifaceCheck(bool reportError, const char *ifname,
           const unsigned char *macaddr, int ifindex)
{
    struct ifreq ifr;
    int fd = -1;
    int rc = 0;
    int idx;

    if (macaddr != NULL) {
        fd = socket(PF_PACKET, SOCK_DGRAM, 0);
        if (fd < 0)
237
            return -errno;
238

239 240
        memset(&ifr, 0, sizeof(ifr));

241 242 243 244 245 246
        if (virStrncpy(ifr.ifr_name,
                       ifname, strlen(ifname), sizeof(ifr.ifr_name)) == NULL) {
            if (reportError)
                ifaceError(VIR_ERR_INTERNAL_ERROR,
                           _("invalid interface name %s"),
                           ifname);
247
            rc = -EINVAL;
248
            goto cleanup;
249 250 251 252 253 254 255
        }

        if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
            if (reportError)
                ifaceError(VIR_ERR_INTERNAL_ERROR,
                           _("coud not get MAC address of interface %s"),
                           ifname);
256
            rc = -errno;
257
            goto cleanup;
258 259 260
        }

        if (memcmp(&ifr.ifr_hwaddr.sa_data, macaddr, VIR_MAC_BUFLEN) != 0) {
261
            rc = -ENODEV;
262
            goto cleanup;
263 264 265 266 267 268
        }
    }

    if (ifindex != -1) {
        rc = ifaceGetIndex(reportError, ifname, &idx);
        if (rc == 0 && idx != ifindex)
269
            rc = -ENODEV;
270 271
    }

272
 cleanup:
273
    VIR_FORCE_CLOSE(fd);
274 275 276 277

    return rc;
}

278 279 280 281 282 283 284 285
#else

int
ifaceCheck(bool reportError ATTRIBUTE_UNUSED,
           const char *ifname ATTRIBUTE_UNUSED,
           const unsigned char *macaddr ATTRIBUTE_UNUSED,
           int ifindex ATTRIBUTE_UNUSED)
{
286
    return -ENOSYS;
287 288 289 290
}

#endif /* __linux__ */

291 292 293 294 295 296 297 298 299 300

/**
 * ifaceGetIndex
 *
 * @reportError: whether to report errors or keep silent
 * @ifname : Name of the interface whose index is to be found
 * @ifindex: Pointer to int where the index will be written into
 *
 * Get the index of an interface given its name.
 *
301 302 303
 * Returns 0 on success, -errno on failure.
 *   -ENODEV : if interface with given name does not exist
 *   -EINVAL : if interface name is invalid (too long)
304
 */
305
#ifdef __linux__
306 307 308 309 310 311 312 313
int
ifaceGetIndex(bool reportError, const char *ifname, int *ifindex)
{
    int rc = 0;
    struct ifreq ifreq;
    int fd = socket(PF_PACKET, SOCK_DGRAM, 0);

    if (fd < 0)
314
        return -errno;
315

316 317
    memset(&ifreq, 0, sizeof(ifreq));

318 319 320 321 322 323
    if (virStrncpy(ifreq.ifr_name, ifname, strlen(ifname),
                   sizeof(ifreq.ifr_name)) == NULL) {
        if (reportError)
            ifaceError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid interface name %s"),
                       ifname);
324
        rc = -EINVAL;
325
        goto cleanup;
326 327 328 329 330 331 332 333 334
    }

    if (ioctl(fd, SIOCGIFINDEX, &ifreq) >= 0)
        *ifindex = ifreq.ifr_ifindex;
    else {
        if (reportError)
            ifaceError(VIR_ERR_INTERNAL_ERROR,
                       _("interface %s does not exist"),
                       ifname);
335
        rc = -ENODEV;
336 337
    }

338
cleanup:
339
    VIR_FORCE_CLOSE(fd);
340 341 342

    return rc;
}
343 344 345 346 347 348 349 350 351 352 353 354 355

#else

int
ifaceGetIndex(bool reportError,
              const char *ifname ATTRIBUTE_UNUSED,
              int *ifindex ATTRIBUTE_UNUSED)
{
    if (reportError) {
        ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("ifaceGetIndex is not supported on non-linux platforms"));
    }

356
    return -ENOSYS;
357 358 359
}

#endif /* __linux__ */
360 361 362 363 364 365 366 367 368 369 370

#ifdef __linux__
int
ifaceGetVlanID(const char *vlanifname, int *vlanid) {
    struct vlan_ioctl_args vlanargs = {
      .cmd = GET_VLAN_VID_CMD,
    };
    int rc = 0;
    int fd = socket(PF_PACKET, SOCK_DGRAM, 0);

    if (fd < 0)
371
        return -errno;
372 373

    if (virStrcpyStatic(vlanargs.device1, vlanifname) == NULL) {
374
        rc = -EINVAL;
375
        goto cleanup;
376 377 378
    }

    if (ioctl(fd, SIOCGIFVLAN, &vlanargs) != 0) {
379
        rc = -errno;
380
        goto cleanup;
381 382 383 384
    }

    *vlanid = vlanargs.u.VID;

385
 cleanup:
386
    VIR_FORCE_CLOSE(fd);
387 388 389 390 391 392 393 394 395 396 397 398 399

    return rc;
}

#else

int
ifaceGetVlanID(const char *vlanifname ATTRIBUTE_UNUSED,
               int *vlanid ATTRIBUTE_UNUSED) {

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("ifaceGetVlanID is not supported on non-linux platforms"));

400
    return -ENOSYS;
401 402
}
#endif /* __linux__ */
403 404

/**
405
 * ifaceGetMacAddress:
406 407 408 409 410
 * @ifname: interface name to set MTU for
 * @macaddr: MAC address (VIR_MAC_BUFLEN in size)
 *
 * This function gets the @macaddr for a given interface @ifname.
 *
411
 * Returns 0 on success, -errno on failure.
412 413 414
 */
#ifdef __linux__
int
415 416
ifaceGetMacAddress(const char *ifname,
                   unsigned char *macaddr)
417 418 419
{
    struct ifreq ifr;
    int fd;
420
    int rc = 0;
421 422

    if (!ifname)
423
        return -EINVAL;
424 425 426

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
427
        return -errno;
428 429

    memset(&ifr, 0, sizeof(struct ifreq));
430
    if (virStrcpyStatic(ifr.ifr_name, ifname) == NULL) {
431
        rc = -EINVAL;
432 433
        goto cleanup;
    }
434

435
    if (ioctl(fd, SIOCGIFHWADDR, (char *)&ifr) != 0) {
436
        rc = -errno;
437 438
        goto cleanup;
    }
439 440 441

    memcpy(macaddr, ifr.ifr_ifru.ifru_hwaddr.sa_data, VIR_MAC_BUFLEN);

442 443 444
cleanup:
    VIR_FORCE_CLOSE(fd);
    return rc;
445 446 447 448 449
}

#else

int
450 451
ifaceGetMacAddress(const char *ifname ATTRIBUTE_UNUSED,
                   unsigned char *macaddr ATTRIBUTE_UNUSED)
452
{
453
    return -ENOSYS;
454 455 456 457 458
}

#endif /* __linux__ */

/**
459
 * ifaceSetMacAddress:
460 461 462 463 464 465
 * @ifname: interface name to set MTU for
 * @macaddr: MAC address (VIR_MAC_BUFLEN in size)
 *
 * This function sets the @macaddr for a given interface @ifname. This
 * gets rid of the kernel's automatically assigned random MAC.
 *
466
 * Returns 0 on success, -errno on failure.
467 468 469
 */
#ifdef __linux__
int
470 471
ifaceSetMacAddress(const char *ifname,
                   const unsigned char *macaddr)
472 473 474
{
    struct ifreq ifr;
    int fd;
475
    int rc = 0;
476 477

    if (!ifname)
478
        return -EINVAL;
479 480 481

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
482
        return -errno;
483 484

    memset(&ifr, 0, sizeof(struct ifreq));
485
    if (virStrcpyStatic(ifr.ifr_name, ifname) == NULL) {
486
        rc = -EINVAL;
487 488
        goto cleanup;
    }
489 490

    /* To fill ifr.ifr_hdaddr.sa_family field */
491
    if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0) {
492
        rc = -errno;
493 494
        goto cleanup;
    }
495 496 497

    memcpy(ifr.ifr_hwaddr.sa_data, macaddr, VIR_MAC_BUFLEN);

498
    rc = ioctl(fd, SIOCSIFHWADDR, &ifr) == 0 ? 0 : -errno;
499 500 501 502

cleanup:
    VIR_FORCE_CLOSE(fd);
    return rc;
503 504 505 506 507
}

#else

int
508 509
ifaceSetMacAddress(const char *ifname ATTRIBUTE_UNUSED,
                   const unsigned char *macaddr ATTRIBUTE_UNUSED)
510
{
511
    return -ENOSYS;
512 513 514
}

#endif /* __linux__ */
515 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 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
/**
 * ifaceGetIPAddress:
 * @ifname: name of the interface whose IP address we want
 * @macaddr: MAC address (VIR_MAC_BUFLEN in size)
 *
 * This function gets the @macaddr for a given interface @ifname.
 *
 * Returns 0 on success, -errno on failure.
 */
#ifdef __linux__
int
ifaceGetIPAddress(const char *ifname,
                  virSocketAddrPtr addr)
{
    struct ifreq ifr;
    int fd;
    int rc = 0;

    if (!ifname || !addr)
        return -EINVAL;

    memset (addr, 0, sizeof(*addr));
    addr->data.stor.ss_family = AF_UNSPEC;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
        return -errno;

    memset(&ifr, 0, sizeof(struct ifreq));
    if (virStrcpyStatic(ifr.ifr_name, ifname) == NULL) {
        rc = -EINVAL;
        goto err_exit;
    }

    if (ioctl(fd, SIOCGIFADDR, (char *)&ifr) != 0) {
        rc = -errno;
        goto err_exit;
    }

    addr->data.stor.ss_family = AF_INET;
    addr->len = sizeof(addr->data.inet4);
    memcpy(&addr->data.inet4, &ifr.ifr_addr, addr->len);

err_exit:
    VIR_FORCE_CLOSE(fd);
    return rc;
}

#else

int
ifaceGetIPAddress(const char *ifname ATTRIBUTE_UNUSED,
                  virSocketAddrPtr addr ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}

#endif /* __linux__ */

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
/**
 * ifaceLinkAdd
 *
 * @type: The type of device, i.e., "macvtap"
 * @macaddress: The MAC address of the device
 * @macaddrsize: The size of the MAC address, typically '6'
 * @ifname: The name the interface is supposed to have; optional parameter
 * @srcdev: The name of the 'link' device
 * @macvlan_mode: The macvlan mode to use
 * @retry: Pointer to integer that will be '1' upon return if an interface
 *         with the same name already exists and it is worth to try
 *         again with a different name
 *
 * Create a macvtap device with the given properties.
 *
 * Returns 0 on success, -1 on fatal error.
 */
593
#if defined(__linux__) && WITH_MACVTAP
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
int
ifaceMacvtapLinkAdd(const char *type,
                    const unsigned char *macaddress, int macaddrsize,
                    const char *ifname,
                    const char *srcdev,
                    uint32_t macvlan_mode,
                    int *retry)
{
    int rc = 0;
    struct nlmsghdr *resp;
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = { .ifi_family = AF_UNSPEC };
    int ifindex;
    unsigned char *recvbuf = NULL;
    unsigned int recvbuflen;
    struct nl_msg *nl_msg;
    struct nlattr *linkinfo, *info_data;

612
    if (ifaceGetIndex(true, srcdev, &ifindex) < 0)
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        return -1;

    *retry = 0;

    nl_msg = nlmsg_alloc_simple(RTM_NEWLINK,
                                NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }

    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
        goto buffer_too_small;

    if (nla_put_u32(nl_msg, IFLA_LINK, ifindex) < 0)
        goto buffer_too_small;

    if (nla_put(nl_msg, IFLA_ADDRESS, macaddrsize, macaddress) < 0)
        goto buffer_too_small;

    if (ifname &&
        nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
        goto buffer_too_small;

    if (!(linkinfo = nla_nest_start(nl_msg, IFLA_LINKINFO)))
        goto buffer_too_small;

    if (nla_put(nl_msg, IFLA_INFO_KIND, strlen(type), type) < 0)
        goto buffer_too_small;

    if (macvlan_mode > 0) {
        if (!(info_data = nla_nest_start(nl_msg, IFLA_INFO_DATA)))
            goto buffer_too_small;

        if (nla_put(nl_msg, IFLA_MACVLAN_MODE, sizeof(macvlan_mode),
                    &macvlan_mode) < 0)
            goto buffer_too_small;

        nla_nest_end(nl_msg, info_data);
    }

    nla_nest_end(nl_msg, linkinfo);

    if (nlComm(nl_msg, &recvbuf, &recvbuflen, 0) < 0) {
        rc = -1;
658
        goto cleanup;
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    }

    if (recvbuflen < NLMSG_LENGTH(0) || recvbuf == NULL)
        goto malformed_resp;

    resp = (struct nlmsghdr *)recvbuf;

    switch (resp->nlmsg_type) {
    case NLMSG_ERROR:
        err = (struct nlmsgerr *)NLMSG_DATA(resp);
        if (resp->nlmsg_len < NLMSG_LENGTH(sizeof(*err)))
            goto malformed_resp;

        switch (err->error) {

        case 0:
            break;

        case -EEXIST:
            *retry = 1;
            rc = -1;
            break;

        default:
            virReportSystemError(-err->error,
                                 _("error creating %s type of interface"),
                                 type);
            rc = -1;
        }
        break;

    case NLMSG_DONE:
        break;

    default:
        goto malformed_resp;
    }

697
cleanup:
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    nlmsg_free(nl_msg);

    VIR_FREE(recvbuf);

    return rc;

malformed_resp:
    nlmsg_free(nl_msg);

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("malformed netlink response message"));
    VIR_FREE(recvbuf);
    return -1;

buffer_too_small:
    nlmsg_free(nl_msg);

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("allocated netlink buffer is too small"));
    return -1;
}

#else

int
ifaceMacvtapLinkAdd(const char *type ATTRIBUTE_UNUSED,
                    const unsigned char *macaddress ATTRIBUTE_UNUSED,
                    int macaddrsize ATTRIBUTE_UNUSED,
                    const char *ifname ATTRIBUTE_UNUSED,
                    const char *srcdev ATTRIBUTE_UNUSED,
                    uint32_t macvlan_mode ATTRIBUTE_UNUSED,
                    int *retry ATTRIBUTE_UNUSED)
{
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
732 733 734 735
# if defined(__linux__) && !WITH_MACVTAP
               _("ifaceMacvtapLinkAdd is not supported since the include "
                 "files were too old"));
# else
736 737
               _("ifaceMacvtapLinkAdd is not supported on non-linux "
                 "platforms"));
738 739
# endif

740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    return -1;
}

#endif


/**
 * ifaceLinkDel
 *
 * @ifname: Name of the interface
 *
 * Tear down an interface with the given name.
 *
 * Returns 0 on success, -1 on fatal error.
 */
755
#if defined( __linux__) && WITH_MACVTAP
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
int
ifaceLinkDel(const char *ifname)
{
    int rc = 0;
    struct nlmsghdr *resp;
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = { .ifi_family = AF_UNSPEC };
    unsigned char *recvbuf = NULL;
    unsigned int recvbuflen;
    struct nl_msg *nl_msg;

    nl_msg = nlmsg_alloc_simple(RTM_DELLINK,
                                NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }

    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
        goto buffer_too_small;

    if (nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
        goto buffer_too_small;

    if (nlComm(nl_msg, &recvbuf, &recvbuflen, 0) < 0) {
        rc = -1;
782
        goto cleanup;
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    }

    if (recvbuflen < NLMSG_LENGTH(0) || recvbuf == NULL)
        goto malformed_resp;

    resp = (struct nlmsghdr *)recvbuf;

    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 destroying %s interface"),
                                 ifname);
            rc = -1;
        }
        break;

    case NLMSG_DONE:
        break;

    default:
        goto malformed_resp;
    }

811
cleanup:
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    nlmsg_free(nl_msg);

    VIR_FREE(recvbuf);

    return rc;

malformed_resp:
    nlmsg_free(nl_msg);

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("malformed netlink response message"));
    VIR_FREE(recvbuf);
    return -1;

buffer_too_small:
    nlmsg_free(nl_msg);

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("allocated netlink buffer is too small"));
    return -1;
}

#else

int
ifaceLinkDel(const char *ifname ATTRIBUTE_UNUSED)
{
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
840 841 842 843
# if defined(__linux__) && !WITH_MACVTAP
               _("ifaceLinkDel is not supported since the include files "
                 "were too old"));
# else
844
               _("ifaceLinkDel is not supported on non-linux platforms"));
845
# endif
846 847 848 849 850 851
    return -1;
}

#endif


852 853
#if defined(__linux__) && defined(IFLA_PORT_MAX)

854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
static struct nla_policy ifla_policy[IFLA_MAX + 1] =
{
  [IFLA_VF_PORTS] = { .type = NLA_NESTED },
};

/**
 * ifaceMacvtapLinkDump
 *
 * @nltarget_kernel: whether to send the message to the kernel or another
 *                   process
 * @ifname: The name of the interface; only use if ifindex < 0
 * @ifindex: The interface index; may be < 0 if ifname is given
 * @nlattr: pointer to a pointer of netlink attributes that will contain
 *          the results
 * @recvbuf: Pointer to the buffer holding the returned netlink response
 *           message; free it, once not needed anymore
 * @getPidFunc: Pointer to a function that will be invoked if the kernel
 *              is not the target of the netlink message but it is to be
 *              sent to another process.
 *
 * Get information about an interface given its name or index.
 *
 * Returns 0 on success, -1 on fatal error.
 */
int
ifaceMacvtapLinkDump(bool nltarget_kernel, const char *ifname, int ifindex,
                     struct nlattr **tb, unsigned char **recvbuf,
                     uint32_t (*getPidFunc)(void))
{
    int rc = 0;
    struct nlmsghdr *resp;
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = {
        .ifi_family = AF_UNSPEC,
        .ifi_index  = ifindex
    };
    unsigned int recvbuflen;
    uint32_t pid = 0;
    struct nl_msg *nl_msg;

    *recvbuf = NULL;

    nl_msg = nlmsg_alloc_simple(RTM_GETLINK, NLM_F_REQUEST);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }

    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
        goto buffer_too_small;

    if (ifindex < 0 && ifname) {
        if (nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
            goto buffer_too_small;
    }

    if (!nltarget_kernel) {
        pid = getPidFunc();
        if (pid == 0) {
            rc = -1;
914
            goto cleanup;
915 916 917 918 919
        }
    }

    if (nlComm(nl_msg, recvbuf, &recvbuflen, pid) < 0) {
        rc = -1;
920
        goto cleanup;
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    }

    if (recvbuflen < NLMSG_LENGTH(0) || *recvbuf == NULL)
        goto malformed_resp;

    resp = (struct nlmsghdr *)*recvbuf;

    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 dumping %s (%d) interface"),
                                 ifname, ifindex);
            rc = -1;
        }
        break;

    case GENL_ID_CTRL:
    case NLMSG_DONE:
        if (nlmsg_parse(resp, sizeof(struct ifinfomsg),
                        tb, IFLA_MAX, ifla_policy)) {
            goto malformed_resp;
        }
        break;

    default:
        goto malformed_resp;
    }

    if (rc != 0)
        VIR_FREE(*recvbuf);

957
cleanup:
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 983 984 985 986 987 988
    nlmsg_free(nl_msg);

    return rc;

malformed_resp:
    nlmsg_free(nl_msg);

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("malformed netlink response message"));
    VIR_FREE(*recvbuf);
    return -1;

buffer_too_small:
    nlmsg_free(nl_msg);

    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("allocated netlink buffer is too small"));
    return -1;
}

#else

int
ifaceMacvtapLinkDump(bool nltarget_kernel ATTRIBUTE_UNUSED,
                     const char *ifname ATTRIBUTE_UNUSED,
                     int ifindex ATTRIBUTE_UNUSED,
                     struct nlattr **tb ATTRIBUTE_UNUSED,
                     unsigned char **recvbuf ATTRIBUTE_UNUSED,
                     uint32_t (*getPidFunc)(void) ATTRIBUTE_UNUSED)
{
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
989 990 991 992
# if defined(__linux__) && !defined(IFLA_PORT_MAX)
               _("ifaceMacvtapLinkDump is not supported since the include "
                 "files were too old"));
# else
993 994
               _("ifaceMacvtapLinkDump is not supported on non-linux "
                 "platforms"));
995 996
# endif

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    return -1;
}

#endif


/**
 * ifaceGetNthParent
 *
 * @ifindex : the index of the interface or -1 if ifname is given
 * @ifname : the name of the interface; ignored if ifindex is valid
 * @nthParent : the nth parent interface to get
 * @parent_ifindex : pointer to int
 * @parent_ifname : pointer to buffer of size IFNAMSIZ
 * @nth : the nth parent that is actually returned; if for example eth0.100
 *        was given and the 100th parent is to be returned, then eth0 will
 *        most likely be returned with nth set to 1 since the chain does
 *        not have more interfaces
 *
 * Get the nth parent interface of the given interface. 0 is the interface
 * itself.
 *
 * Return 0 on success, != 0 otherwise
 */
1021
#if defined(__linux__) && WITH_MACVTAP
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
int
ifaceGetNthParent(int ifindex, const char *ifname, unsigned int nthParent,
                  int *parent_ifindex, char *parent_ifname,
                  unsigned int *nth)
{
    int rc;
    struct nlattr *tb[IFLA_MAX + 1] = { NULL, };
    unsigned char *recvbuf = NULL;
    bool end = false;
    unsigned int i = 0;

    *nth = 0;

1035 1036
    if (ifindex <= 0 && ifaceGetIndex(true, ifname, &ifindex) < 0)
        return -1;
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

    while (!end && i <= nthParent) {
        rc = ifaceMacvtapLinkDump(true, ifname, ifindex, tb, &recvbuf, NULL);
        if (rc)
            break;

        if (tb[IFLA_IFNAME]) {
            if (!virStrcpy(parent_ifname, (char*)RTA_DATA(tb[IFLA_IFNAME]),
                           IFNAMSIZ)) {
                ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("buffer for root interface name is too small"));
                VIR_FREE(recvbuf);
1049
                return -1;
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
            }
            *parent_ifindex = ifindex;
        }

        if (tb[IFLA_LINK]) {
            ifindex = *(int *)RTA_DATA(tb[IFLA_LINK]);
            ifname = NULL;
        } else
            end = true;

        VIR_FREE(recvbuf);

        i++;
    }

E
Eric Blake 已提交
1065
    *nth = i - 1;
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

    return rc;
}

#else

int
ifaceGetNthParent(int ifindex ATTRIBUTE_UNUSED,
                  const char *ifname ATTRIBUTE_UNUSED,
                  unsigned int nthParent ATTRIBUTE_UNUSED,
                  int *parent_ifindex ATTRIBUTE_UNUSED,
                  char *parent_ifname ATTRIBUTE_UNUSED,
                  unsigned int *nth ATTRIBUTE_UNUSED)
{
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
1081 1082 1083 1084
# if defined(__linux__) && !WITH_MACVTAP
               _("ifaceGetNthParent is not supported since the include files "
                 "were too old"));
# else
1085
               _("ifaceGetNthParent is not supported on non-linux platforms"));
1086
# endif
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    return -1;
}

#endif

/**
 * ifaceReplaceMacAddress:
 * @macaddress: new MAC address for interface
 * @linkdev: name of interface
 * @stateDir: directory to store old MAC address
 *
1098
 * Returns 0 on success, -errno on failure.
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
 *
 */
int
ifaceReplaceMacAddress(const unsigned char *macaddress,
                       const char *linkdev,
                       const char *stateDir)
{
    unsigned char oldmac[6];
    int rc;

1109
    rc = ifaceGetMacAddress(linkdev, oldmac);
1110

1111
    if (rc < 0) {
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
        virReportSystemError(rc,
                             _("Getting MAC address from '%s' "
                               "to '%02x:%02x:%02x:%02x:%02x:%02x' failed."),
                             linkdev,
                             oldmac[0], oldmac[1], oldmac[2],
                             oldmac[3], oldmac[4], oldmac[5]);
    } else {
        char *path = NULL;
        char macstr[VIR_MAC_STRING_BUFLEN];

        if (virAsprintf(&path, "%s/%s",
                        stateDir,
                        linkdev) < 0) {
            virReportOOMError();
1126
            return -errno;
1127 1128 1129 1130 1131
        }
        virFormatMacAddr(oldmac, macstr);
        if (virFileWriteStr(path, macstr, O_CREAT|O_TRUNC|O_WRONLY) < 0) {
            virReportSystemError(errno, _("Unable to preserve mac for %s"),
                                 linkdev);
1132
            return -errno;
1133 1134 1135
        }
    }

1136
    rc = ifaceSetMacAddress(linkdev, macaddress);
1137
    if (rc < 0) {
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        virReportSystemError(rc,
                             _("Setting MAC address on  '%s' to "
                               "'%02x:%02x:%02x:%02x:%02x:%02x' failed."),
                             linkdev,
                             macaddress[0], macaddress[1], macaddress[2],
                             macaddress[3], macaddress[4], macaddress[5]);
    }

    return rc;
}

/**
 * ifaceRestoreMacAddress:
 * @linkdev: name of interface
 * @stateDir: directory containing old MAC address
 *
1154
 * Returns 0 on success, -errno on failure.
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
 *
 */
int
ifaceRestoreMacAddress(const char *linkdev,
                       const char *stateDir)
{
    int rc;
    char *oldmacname = NULL;
    char *macstr = NULL;
    char *path = NULL;
    unsigned char oldmac[6];

    if (virAsprintf(&path, "%s/%s",
                    stateDir,
                    linkdev) < 0) {
        virReportOOMError();
1171
        return -errno;
1172 1173 1174
    }

    if (virFileReadAll(path, VIR_MAC_STRING_BUFLEN, &macstr) < 0) {
1175
        return -errno;
1176 1177 1178 1179 1180 1181
    }

    if (virParseMacAddr(macstr, &oldmac[0]) != 0) {
        ifaceError(VIR_ERR_INTERNAL_ERROR,
                   _("Cannot parse MAC address from '%s'"),
                   oldmacname);
1182
        VIR_FREE(macstr);
1183
        return -EINVAL;
1184 1185 1186
    }

    /*reset mac and remove file-ignore results*/
1187
    rc = ifaceSetMacAddress(linkdev, oldmac);
1188
    if (rc < 0) {
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
        virReportSystemError(rc,
                             _("Setting MAC address on  '%s' to "
                               "'%02x:%02x:%02x:%02x:%02x:%02x' failed."),
                             linkdev,
                             oldmac[0], oldmac[1], oldmac[2],
                             oldmac[3], oldmac[4], oldmac[5]);
    }
    ignore_value(unlink(path));
    VIR_FREE(macstr);

    return rc;
}
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

#ifdef __linux__
static int
ifaceSysfsFile(char **pf_sysfs_device_link, const char *ifname,
               const char *file)
{

    if (virAsprintf(pf_sysfs_device_link, NET_SYSFS "%s/%s",
        ifname, file) < 0) {
        virReportOOMError();
        return -1;
    }

    return 0;
}

static int
ifaceSysfsDeviceFile(char **pf_sysfs_device_link, const char *ifname,
                     const char *file)
{

    if (virAsprintf(pf_sysfs_device_link, NET_SYSFS "%s/device/%s",
        ifname, file) < 0) {
        virReportOOMError();
        return -1;
    }

    return 0;
}

/**
 * ifaceIsVirtualFunction
 *
 * @ifname : name of the interface
 *
 * Checks if an interface is a SRIOV virtual function.
 *
 * Returns 1 if interface is SRIOV virtual function, 0 if not and -1 if error
 *
 */
int
ifaceIsVirtualFunction(const char *ifname)
{
    char *if_sysfs_device_link = NULL;
    int ret = -1;

    if (ifaceSysfsFile(&if_sysfs_device_link, ifname, "device"))
        return ret;

    ret = pciDeviceIsVirtualFunction(if_sysfs_device_link);

    VIR_FREE(if_sysfs_device_link);

    return ret;
}

/**
 * ifaceGetVirtualFunctionIndex
 *
 * @pfname : name of the physical function interface name
 * @vfname : name of the virtual function interface name
 * @vf_index : Pointer to int. Contains vf index of interface upon successful
 *             return
 *
 * Returns 0 on success, -1 on failure
 *
 */
int
ifaceGetVirtualFunctionIndex(const char *pfname, const char *vfname,
                             int *vf_index)
{
    char *pf_sysfs_device_link = NULL, *vf_sysfs_device_link = NULL;
    int ret = -1;

    if (ifaceSysfsFile(&pf_sysfs_device_link, pfname, "device"))
        return ret;

    if (ifaceSysfsFile(&vf_sysfs_device_link, vfname, "device")) {
        VIR_FREE(pf_sysfs_device_link);
        return ret;
    }

    ret = pciGetVirtualFunctionIndex(pf_sysfs_device_link,
                                     vf_sysfs_device_link,
                                     vf_index);

    VIR_FREE(pf_sysfs_device_link);
    VIR_FREE(vf_sysfs_device_link);

    return ret;
}

/**
 * ifaceGetPhysicalFunction
 *
 * @ifname : name of the physical function interface name
 * @pfname : Contains sriov physical function for interface ifname
 *           upon successful return
 *
 * Returns 0 on success, -1 on failure
 *
 */
int
ifaceGetPhysicalFunction(const char *ifname, char **pfname)
{
    char *physfn_sysfs_path = NULL;
    int ret = -1;

    if (ifaceSysfsDeviceFile(&physfn_sysfs_path, ifname, "physfn"))
        return ret;

    ret = pciDeviceNetName(physfn_sysfs_path, pfname);

    VIR_FREE(physfn_sysfs_path);

    return ret;
}
#else
int
1320
ifaceIsVirtualFunction(const char *ifname ATTRIBUTE_UNUSED)
1321 1322 1323 1324 1325 1326 1327 1328
{
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("ifaceIsVirtualFunction is not supported on non-linux "
               "platforms"));
    return -1;
}

int
1329 1330 1331
ifaceGetVirtualFunctionIndex(const char *pfname ATTRIBUTE_UNUSED,
                             const char *vfname ATTRIBUTE_UNUSED,
                             int *vf_index ATTRIBUTE_UNUSED)
1332 1333 1334 1335 1336 1337 1338 1339
{
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("ifaceGetVirtualFunctionIndex is not supported on non-linux "
               "platforms"));
    return -1;
}

int
1340 1341
ifaceGetPhysicalFunction(const char *ifname ATTRIBUTE_UNUSED,
                         char **pfname ATTRIBUTE_UNUSED)
1342 1343 1344 1345 1346 1347 1348
{
    ifaceError(VIR_ERR_INTERNAL_ERROR, "%s",
               _("ifaceGetPhysicalFunction is not supported on non-linux "
               "platforms"));
    return -1;
}
#endif /* __linux__ */