virnetlink.c 33.0 KB
Newer Older
1
/*
L
Leno Hou 已提交
2 3
 * Copyright (C) 2010-2016 Red Hat, Inc.
 * Copyright (C) 2010-2012, 2016 IBM Corporation
4 5 6 7 8 9 10 11 12 13 14 15
 *
 * 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
16
 * License along with this library.  If not, see
O
Osier Yang 已提交
17
 * <http://www.gnu.org/licenses/>.
18 19 20
 *
 * Authors:
 *     Stefan Berger <stefanb@us.ibm.com>
21
 *     Dirk Herrendoerfer <herrend[at]de[dot]ibm[dot]com>
22 23 24 25 26
 *
 * Notes:
 * netlink: http://lovezutto.googlepages.com/netlink.pdf
 *          iproute2 package
 *
27 28
 * 2012/02: Renamed from netlink.[ch] to virnetlink.[ch]
 *
29 30 31 32 33 34 35
 */

#include <config.h>

#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
36
#include <sys/socket.h>
37

38
#include "virnetlink.h"
39
#include "virnetdev.h"
40
#include "virlog.h"
41
#include "viralloc.h"
42
#include "virthread.h"
43
#include "virmacaddr.h"
44
#include "virerror.h"
45 46 47

#define VIR_FROM_THIS VIR_FROM_NET

48 49
VIR_LOG_INIT("util.netlink");

50
#define NETLINK_ACK_TIMEOUT_S  (2*1000)
51

52 53 54 55 56 57 58
#if defined(__linux__) && defined(HAVE_LIBNL)
/* State for a single netlink event handle */
struct virNetlinkEventHandle {
    int watch;
    virNetlinkEventHandleCallback handleCB;
    virNetlinkEventRemoveCallback removeCB;
    void *opaque;
59
    virMacAddr macaddr;
60 61 62
    int deleted;
};

S
Serge Hallyn 已提交
63 64
# ifdef HAVE_LIBNL1
#  define virNetlinkAlloc nl_handle_alloc
L
Leno Hou 已提交
65
#  define virNetlinkSetBufferSize nl_set_buffer_size
S
Serge Hallyn 已提交
66 67 68 69
#  define virNetlinkFree nl_handle_destroy
typedef struct nl_handle virNetlinkHandle;
# else
#  define virNetlinkAlloc nl_socket_alloc
L
Leno Hou 已提交
70
#  define virNetlinkSetBufferSize nl_socket_set_buffer_size
S
Serge Hallyn 已提交
71 72 73 74
#  define virNetlinkFree nl_socket_free
typedef struct nl_sock virNetlinkHandle;
# endif

75 76 77 78 79 80 81
typedef struct _virNetlinkEventSrvPrivate virNetlinkEventSrvPrivate;
typedef virNetlinkEventSrvPrivate *virNetlinkEventSrvPrivatePtr;
struct _virNetlinkEventSrvPrivate {
    /*Server*/
    virMutex lock;
    int eventwatch;
    int netlinkfd;
S
Serge Hallyn 已提交
82
    virNetlinkHandle *netlinknh;
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    /*Events*/
    int handled;
    size_t handlesCount;
    size_t handlesAlloc;
    struct virNetlinkEventHandle *handles;
};

enum virNetlinkDeleteMode {
    VIR_NETLINK_HANDLE_VALID,
    VIR_NETLINK_HANDLE_DELETED,
};

/* Unique ID for the next netlink watch to be registered */
static int nextWatch = 1;

/* Allocate extra slots for virEventPollHandle/virEventPollTimeout
 records in this multiple */
# define NETLINK_EVENT_ALLOC_EXTENT 10

102 103 104
/* Linux kernel supports up to MAX_LINKS (32 at the time) individual
 * netlink protocols. */
static virNetlinkEventSrvPrivatePtr server[MAX_LINKS] = {NULL};
105
static virNetlinkHandle *placeholder_nlhandle;
106 107 108

/* Function definitions */

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
/**
 * virNetlinkStartup:
 *
 * Perform any initialization that needs to take place before the
 * program starts up worker threads. This is currently used to assure
 * that an nl_handle is allocated prior to any attempts to bind a
 * netlink socket. For a discussion of why this is necessary, please
 * see the following email message:
 *
 *   https://www.redhat.com/archives/libvir-list/2012-May/msg00202.html
 *
 * The short version is that, without this placeholder allocation of
 * an nl_handle that is never used, it is possible for nl_connect() in
 * one thread to collide with a direct bind() of a netlink socket in
 * another thread, leading to failure of the operation (which could
 * lead to failure of libvirtd to start). Since getaddrinfo() (used by
 * libvirtd in virSocketAddrParse, which is called quite frequently
 * during startup) directly calls bind() on a netlink socket, this is
 * actually a very common occurrence (15-20% failure rate on some
 * hardware).
 *
 * Returns 0 on success, -1 on failure.
 */
int
virNetlinkStartup(void)
{
    if (placeholder_nlhandle)
        return 0;
137
    VIR_DEBUG("Running global netlink initialization");
J
Jiri Denemark 已提交
138
    placeholder_nlhandle = virNetlinkAlloc();
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    if (!placeholder_nlhandle) {
        virReportSystemError(errno, "%s",
                             _("cannot allocate placeholder nlhandle for netlink"));
        return -1;
    }
    return 0;
}

/**
 * virNetlinkShutdown:
 *
 * Undo any initialization done by virNetlinkStartup. This currently
 * destroys the placeholder nl_handle.
 */
void
virNetlinkShutdown(void)
{
    if (placeholder_nlhandle) {
J
Jiri Denemark 已提交
157
        virNetlinkFree(placeholder_nlhandle);
158 159 160 161
        placeholder_nlhandle = NULL;
    }
}

L
Leno Hou 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

/**
 * virNetLinkCreateSocket:
 *
 * @protocol: which protocol to connect to (e.g. NETLINK_ROUTE,
 *
 * Create a netlink socket, set its buffer size, and turn on message
 * peeking (so the buffer size can be dynamically increased if
 * needed).
 *
 * Returns a handle to the new netlink socket, or 0 if there was a failure.
 *
 */
static virNetlinkHandle *
virNetlinkCreateSocket(int protocol)
{
    virNetlinkHandle *nlhandle = NULL;

    if (!(nlhandle = virNetlinkAlloc())) {
        virReportSystemError(errno, "%s",
                             _("cannot allocate nlhandle for netlink"));
        goto error;
    }
    if (nl_connect(nlhandle, protocol) < 0) {
        virReportSystemError(errno,
                             _("cannot connect to netlink socket "
                               "with protocol %d"), protocol);
        goto error;
    }

    if (virNetlinkSetBufferSize(nlhandle, 131702, 0) < 0) {
        virReportSystemError(errno, "%s",
                             _("cannot set netlink socket buffer "
                               "size to 128k"));
        goto error;
    }
    nl_socket_enable_msg_peek(nlhandle);

 cleanup:
    return nlhandle;

 error:
    if (nlhandle) {
        nl_close(nlhandle);
        virNetlinkFree(nlhandle);
        nlhandle = NULL;
    }
    goto cleanup;
}

212 213 214
static virNetlinkHandle *
virNetlinkSendRequest(struct nl_msg *nl_msg, uint32_t src_pid,
                      struct sockaddr_nl nladdr,
215
                      unsigned int protocol, unsigned int groups)
216 217 218 219
{
    ssize_t nbytes;
    int fd;
    int n;
220
    virNetlinkHandle *nlhandle = NULL;
221 222
    struct pollfd fds[1];
    struct nlmsghdr *nlmsg = nlmsg_hdr(nl_msg);
223 224 225 226

    if (protocol >= MAX_LINKS) {
        virReportSystemError(EINVAL,
                             _("invalid protocol argument: %d"), protocol);
227
        goto error;
228
    }
229

L
Leno Hou 已提交
230
    if (!(nlhandle = virNetlinkCreateSocket(protocol)))
231
        goto error;
232 233 234 235 236

    fd = nl_socket_get_fd(nlhandle);
    if (fd < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot get netlink socket fd"));
237
        goto error;
238 239 240
    }

    if (groups && nl_socket_add_membership(nlhandle, groups) < 0) {
241
        virReportSystemError(errno,
242
                             "%s", _("cannot add netlink membership"));
243
        goto error;
244 245 246 247
    }

    nlmsg_set_dst(nl_msg, &nladdr);

248
    nlmsg->nlmsg_pid = src_pid ? src_pid : getpid();
249 250 251 252 253

    nbytes = nl_send_auto_complete(nlhandle, nl_msg);
    if (nbytes < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot send to netlink socket"));
254
        goto error;
255 256
    }

257
    memset(fds, 0, sizeof(fds));
258

259 260
    fds[0].fd = fd;
    fds[0].events = POLLIN;
261

262
    n = poll(fds, ARRAY_CARDINALITY(fds), NETLINK_ACK_TIMEOUT_S);
263 264 265
    if (n <= 0) {
        if (n < 0)
            virReportSystemError(errno, "%s",
266
                                 _("error in poll call"));
267 268 269 270 271
        if (n == 0)
            virReportSystemError(ETIMEDOUT, "%s",
                                 _("no valid netlink response was received"));
    }

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
    return nlhandle;

 error:
    virNetlinkFree(nlhandle);
    return NULL;
}

/**
 * virNetlinkCommand:
 * @nlmsg: pointer to netlink message
 * @respbuf: pointer to pointer where response buffer will be allocated
 * @respbuflen: pointer to integer holding the size of the response buffer
 *      on return of the function.
 * @src_pid: the pid of the process to send a message
 * @dst_pid: the pid of the process to talk to, i.e., pid = 0 for kernel
 * @protocol: netlink protocol
 * @groups: the group identifier
 *
 * Send the given message to the netlink layer and receive response.
 * Returns 0 on success, -1 on error. In case of error, no response
 * buffer will be returned.
 */
int virNetlinkCommand(struct nl_msg *nl_msg,
                      struct nlmsghdr **resp, unsigned int *respbuflen,
                      uint32_t src_pid, uint32_t dst_pid,
                      unsigned int protocol, unsigned int groups)
{
    int ret = -1;
    struct sockaddr_nl nladdr = {
            .nl_family = AF_NETLINK,
            .nl_pid    = dst_pid,
            .nl_groups = 0,
    };
    struct pollfd fds[1];
    virNetlinkHandle *nlhandle = NULL;
    int len = 0;

    memset(fds, 0, sizeof(fds));

    if (!(nlhandle = virNetlinkSendRequest(nl_msg, src_pid, nladdr,
                                           protocol, groups)))
        goto cleanup;

315 316 317 318 319
    len = nl_recv(nlhandle, &nladdr, (unsigned char **)resp, NULL);
    if (len == 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("nl_recv failed - returned 0 bytes"));
        goto cleanup;
320
    }
321 322 323 324 325 326 327 328 329
    if (len < 0) {
        virReportSystemError(errno, "%s", _("nl_recv failed"));
        goto cleanup;
    }

    ret = 0;
    *respbuflen = len;
 cleanup:
    if (ret < 0) {
330
        *resp = NULL;
331 332 333
        *respbuflen = 0;
    }

S
Serge Hallyn 已提交
334
    virNetlinkFree(nlhandle);
335
    return ret;
336 337
}

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
int
virNetlinkDumpCommand(struct nl_msg *nl_msg,
                      virNetlinkDumpCallback callback,
                      uint32_t src_pid, uint32_t dst_pid,
                      unsigned int protocol, unsigned int groups,
                      void *opaque)
{
    int ret = -1;
    bool end = false;
    int len = 0;
    struct nlmsghdr *resp = NULL;
    struct nlmsghdr *msg = NULL;

    struct sockaddr_nl nladdr = {
            .nl_family = AF_NETLINK,
            .nl_pid    = dst_pid,
            .nl_groups = 0,
    };
    virNetlinkHandle *nlhandle = NULL;

    if (!(nlhandle = virNetlinkSendRequest(nl_msg, src_pid, nladdr,
                                           protocol, groups)))
        goto cleanup;

    while (!end) {
        len = nl_recv(nlhandle, &nladdr, (unsigned char **)&resp, NULL);
364
        VIR_WARNINGS_NO_CAST_ALIGN
365
        for (msg = resp; NLMSG_OK(msg, len); msg = NLMSG_NEXT(msg, len)) {
366
            VIR_WARNINGS_RESET
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
            if (msg->nlmsg_type == NLMSG_DONE)
                end = true;

            if (virNetlinkGetErrorCode(msg, len) < 0)
                goto cleanup;

            if (callback(msg, opaque) < 0)
                goto cleanup;
        }
    }

    ret = 0;

 cleanup:
    virNetlinkFree(nlhandle);
    return ret;
}

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 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
/**
 * virNetlinkDumpLink:
 *
 * @ifname:  The name of the interface; only use if ifindex <= 0
 * @ifindex: The interface index; may be <= 0 if ifname is given
 * @data:    Gets a pointer to the raw data from netlink.
             MUST BE FREED BY CALLER!
 * @nlattr:  Pointer to a pointer of netlink attributes that will contain
 *           the results
 * @src_pid: pid used for nl_pid of the local end of the netlink message
 *           (0 == "use getpid()")
 * @dst_pid: pid of destination nl_pid if the kernel
 *           is not the target of the netlink message but it is to be
 *           sent to another process (0 if sending to the kernel)
 *
 * Get information from netlink about an interface given its name or index.
 *
 * Returns 0 on success, -1 on fatal error.
 */
int
virNetlinkDumpLink(const char *ifname, int ifindex,
                   void **nlData, struct nlattr **tb,
                   uint32_t src_pid, uint32_t dst_pid)
{
    int rc = -1;
    struct nlmsghdr *resp = NULL;
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = {
        .ifi_family = AF_UNSPEC,
        .ifi_index  = ifindex
    };
    unsigned int recvbuflen;
    struct nl_msg *nl_msg;

    if (ifname && ifindex <= 0 && virNetDevGetIndex(ifname, &ifindex) < 0)
        return -1;

    ifinfo.ifi_index = ifindex;

    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 (ifname) {
        if (nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
            goto buffer_too_small;
    }

# ifdef RTEXT_FILTER_VF
    /* if this filter exists in the kernel's netlink implementation,
     * we need to set it, otherwise the response message will not
     * contain the IFLA_VFINFO_LIST that we're looking for.
     */
    {
        uint32_t ifla_ext_mask = RTEXT_FILTER_VF;

        if (nla_put(nl_msg, IFLA_EXT_MASK,
                    sizeof(ifla_ext_mask), &ifla_ext_mask) < 0) {
            goto buffer_too_small;
        }
    }
# endif

    if (virNetlinkCommand(nl_msg, &resp, &recvbuflen,
                          src_pid, dst_pid, NETLINK_ROUTE, 0) < 0)
        goto cleanup;

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

    case GENL_ID_CTRL:
    case NLMSG_DONE:
        rc = nlmsg_parse(resp, sizeof(struct ifinfomsg),
                         tb, IFLA_MAX, NULL);
        if (rc < 0)
            goto malformed_resp;
        break;

    default:
        goto malformed_resp;
    }
    rc = 0;
 cleanup:
    nlmsg_free(nl_msg);
    if (rc < 0)
       VIR_FREE(resp);
    *nlData = resp;
    return rc;

 malformed_resp:
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("malformed netlink response message"));
    goto cleanup;

 buffer_too_small:
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("allocated netlink buffer is too small"));
    goto cleanup;
}


505 506 507 508
/**
 * virNetlinkDelLink:
 *
 * @ifname: Name of the link
509 510 511 512
 * @fallback: pointer to an alternate function that will
 *            be called to perform the delete if RTM_DELLINK fails
 *            with EOPNOTSUPP (any other error will simply be treated
 *            as an error).
513 514 515 516 517 518 519 520
 *
 * delete a network "link" (aka interface aka device) with the given
 * name. This works for many different types of network devices,
 * including macvtap and bridges.
 *
 * Returns 0 on success, -1 on fatal error.
 */
int
521
virNetlinkDelLink(const char *ifname, virNetlinkDelLinkFallback fallback)
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
{
    int rc = -1;
    struct nlmsghdr *resp = NULL;
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = { .ifi_family = AF_UNSPEC };
    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 (virNetlinkCommand(nl_msg, &resp, &recvbuflen, 0, 0,
                          NETLINK_ROUTE, 0) < 0) {
        goto cleanup;
    }

    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;

557 558 559 560
        if (-err->error == EOPNOTSUPP && fallback) {
            rc = fallback(ifname);
            goto cleanup;
        }
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
        if (err->error) {
            virReportSystemError(-err->error,
                                 _("error destroying network device %s"),
                                 ifname);
            goto cleanup;
        }
        break;

    case NLMSG_DONE:
        break;

    default:
        goto malformed_resp;
    }

    rc = 0;
 cleanup:
    nlmsg_free(nl_msg);
    VIR_FREE(resp);
    return rc;

 malformed_resp:
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("malformed netlink response message"));
    goto cleanup;

 buffer_too_small:
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("allocated netlink buffer is too small"));
    goto cleanup;
}


E
Eric Blake 已提交
594 595
int
virNetlinkGetErrorCode(struct nlmsghdr *resp, unsigned int recvbuflen)
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
{
    struct nlmsgerr *err;
    int result = 0;

    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;

        switch (err->error) {
        case 0: /* ACK */
            break;

        default:
            result = err->error;
        }
        break;

    case NLMSG_DONE:
        break;

    default:
622 623 624
        /* We allow multipart messages. */
        if (!(resp->nlmsg_flags & NLM_F_MULTI))
            goto malformed_resp;
625 626 627 628 629 630 631 632 633 634
    }

    return result;

 malformed_resp:
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("malformed netlink response message"));
    return -EINVAL;
}

E
Eric Blake 已提交
635

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
static void
virNetlinkEventServerLock(virNetlinkEventSrvPrivatePtr driver)
{
    virMutexLock(&driver->lock);
}

static void
virNetlinkEventServerUnlock(virNetlinkEventSrvPrivatePtr driver)
{
    virMutexUnlock(&driver->lock);
}

/**
 * virNetlinkEventRemoveClientPrimitive:
 *
 * @i: index of the client to remove from the table
652
 * @protocol: netlink protocol
653 654 655 656 657 658 659 660 661
 *
 * This static function does the low level removal of a client from
 * the table once its index is known, including calling the remove
 * callback (which usually will free resources required by the
 * handler). The event server lock *must* be locked before calling
 * this function.
 *
 * assumes success, returns nothing.
 */
662 663
static int
virNetlinkEventRemoveClientPrimitive(size_t i, unsigned int protocol)
664
{
665 666 667 668
    if (protocol >= MAX_LINKS)
        return -EINVAL;

    virNetlinkEventRemoveCallback removeCB = server[protocol]->handles[i].removeCB;
669 670

    if (removeCB) {
671 672 673
        (removeCB)(server[protocol]->handles[i].watch,
                   &server[protocol]->handles[i].macaddr,
                   server[protocol]->handles[i].opaque);
674
    }
675 676
    server[protocol]->handles[i].deleted = VIR_NETLINK_HANDLE_DELETED;
    return 0;
677 678 679 680 681 682 683 684 685
}

static void
virNetlinkEventCallback(int watch,
                        int fd ATTRIBUTE_UNUSED,
                        int events ATTRIBUTE_UNUSED,
                        void *opaque)
{
    virNetlinkEventSrvPrivatePtr srv = opaque;
686
    struct nlmsghdr *msg;
687 688
    struct sockaddr_nl peer;
    struct ucred *creds = NULL;
689 690
    size_t i;
    int length;
691 692
    bool handled = false;

693 694
    length = nl_recv(srv->netlinknh, &peer,
                     (unsigned char **)&msg, &creds);
695 696 697 698

    if (length == 0)
        return;
    if (length < 0) {
699 700
        virReportSystemError(errno,
                             "%s", _("nl_recv returned with error"));
701 702 703 704 705 706 707 708 709 710 711 712
        return;
    }

    virNetlinkEventServerLock(srv);

    VIR_DEBUG("dispatching to max %d clients, called from event watch %d",
            (int)srv->handlesCount, watch);

    for (i = 0; i < srv->handlesCount; i++) {
        if (srv->handles[i].deleted != VIR_NETLINK_HANDLE_VALID)
            continue;

713
        VIR_DEBUG("dispatching client %zu.", i);
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

        (srv->handles[i].handleCB)(msg, length, &peer, &handled,
                                   srv->handles[i].opaque);
    }

    if (!handled)
        VIR_DEBUG("event not handled.");
    VIR_FREE(msg);
    virNetlinkEventServerUnlock(srv);
}

/**
 * virNetlinkEventServiceStop:
 *
 * stop the monitor to receive netlink messages for libvirtd.
 * This removes the netlink socket fd from the event handler.
 *
731 732
 * @protocol: netlink protocol
 *
733
 * Returns -1 if the monitor cannot be unregistered, 0 upon success
734 735
 */
int
736
virNetlinkEventServiceStop(unsigned int protocol)
737
{
738 739 740 741
    if (protocol >= MAX_LINKS)
        return -EINVAL;

    virNetlinkEventSrvPrivatePtr srv = server[protocol];
742
    size_t i;
743 744 745

    VIR_INFO("stopping netlink event service");

746
    if (!server[protocol])
747 748 749 750
        return 0;

    virNetlinkEventServerLock(srv);
    nl_close(srv->netlinknh);
S
Serge Hallyn 已提交
751
    virNetlinkFree(srv->netlinknh);
752 753 754 755 756
    virEventRemoveHandle(srv->eventwatch);

    /* free any remaining clients on the list */
    for (i = 0; i < srv->handlesCount; i++) {
        if (srv->handles[i].deleted == VIR_NETLINK_HANDLE_VALID)
757
            virNetlinkEventRemoveClientPrimitive(i, protocol);
758 759
    }

760
    server[protocol] = NULL;
761 762 763 764 765 766 767
    virNetlinkEventServerUnlock(srv);

    virMutexDestroy(&srv->lock);
    VIR_FREE(srv);
    return 0;
}

768 769 770 771 772 773 774 775 776 777
/**
 * virNetlinkEventServiceStopAll:
 *
 * Stop all the monitors to receive netlink messages for libvirtd.
 *
 * Returns -1 if any monitor cannot be unregistered, 0 upon success
 */
int
virNetlinkEventServiceStopAll(void)
{
778
    size_t i;
779 780 781

    VIR_INFO("stopping all netlink event services");

782 783
    for (i = 0; i < MAX_LINKS; i++)
        virNetlinkEventServiceStop(i);
784 785 786 787

    return 0;
}

788 789 790
/**
 * virNetlinkEventServiceIsRunning:
 *
791
 * Returns if the netlink event service is running.
792
 *
793 794
 * @protocol: netlink protocol
 *
795
 * Returns 'true' if the service is running, 'false' if stopped.
796 797
 */
bool
798
virNetlinkEventServiceIsRunning(unsigned int protocol)
799
{
800 801 802 803 804 805 806
    if (protocol >= MAX_LINKS) {
        virReportSystemError(EINVAL,
                             _("invalid protocol argument: %d"), protocol);
        return false;
    }

    return server[protocol] != NULL;
807 808
}

809 810 811
/**
 * virNetlinkEventServiceLocalPid:
 *
812 813
 * @protocol: netlink protocol
 *
814 815 816 817
 * Returns the nl_pid value that was used to bind() the netlink socket
 * used by the netlink event service, or -1 on error (netlink
 * guarantees that this value will always be > 0).
 */
818
int virNetlinkEventServiceLocalPid(unsigned int protocol)
819
{
820 821 822 823
    if (protocol >= MAX_LINKS)
        return -EINVAL;

    if (!(server[protocol] && server[protocol]->netlinknh)) {
824 825
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("netlink event service not running"));
826 827
        return -1;
    }
828
    return (int)nl_socket_get_local_port(server[protocol]->netlinknh);
829 830 831
}


832 833 834 835 836 837
/**
 * virNetlinkEventServiceStart:
 *
 * start a monitor to receive netlink messages for libvirtd.
 * This registers a netlink socket with the event interface.
 *
838 839
 * @protocol: netlink protocol
 * @groups: broadcast groups to join in
840
 * Returns -1 if the monitor cannot be registered, 0 upon success
841 842
 */
int
843
virNetlinkEventServiceStart(unsigned int protocol, unsigned int groups)
844 845 846 847 848
{
    virNetlinkEventSrvPrivatePtr srv;
    int fd;
    int ret = -1;

849 850 851 852 853 854 855
    if (protocol >= MAX_LINKS) {
        virReportSystemError(EINVAL,
                             _("invalid protocol argument: %d"), protocol);
        return -EINVAL;
    }

    if (server[protocol])
856 857
        return 0;

858
    VIR_INFO("starting netlink event service with protocol %d", protocol);
859

860
    if (VIR_ALLOC(srv) < 0)
861
        return -1;
862

863 864 865 866
    if (virMutexInit(&srv->lock) < 0) {
        VIR_FREE(srv);
        return -1;
    }
867 868 869 870

    virNetlinkEventServerLock(srv);

    /* Allocate a new socket and get fd */
L
Leno Hou 已提交
871
    if (!(srv->netlinknh = virNetlinkCreateSocket(protocol)))
872 873 874 875
        goto error_locked;

    fd = nl_socket_get_fd(srv->netlinknh);
    if (fd < 0) {
876 877
        virReportSystemError(errno,
                             "%s", _("cannot get netlink socket fd"));
878 879 880
        goto error_server;
    }

881 882 883 884 885 886
    if (groups && nl_socket_add_membership(srv->netlinknh, groups) < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot add netlink membership"));
        goto error_server;
    }

887
    if (nl_socket_set_nonblocking(srv->netlinknh)) {
888 889
        virReportSystemError(errno, "%s",
                             _("cannot set netlink socket nonblocking"));
890 891 892 893 894 895 896
        goto error_server;
    }

    if ((srv->eventwatch = virEventAddHandle(fd,
                                             VIR_EVENT_HANDLE_READABLE,
                                             virNetlinkEventCallback,
                                             srv, NULL)) < 0) {
897 898
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to add netlink event handle watch"));
899 900 901 902 903 904 905
        goto error_server;
    }

    srv->netlinkfd = fd;
    VIR_DEBUG("netlink event listener on fd: %i running", fd);

    ret = 0;
906
    server[protocol] = srv;
907

908
 error_server:
909 910
    if (ret < 0) {
        nl_close(srv->netlinknh);
S
Serge Hallyn 已提交
911
        virNetlinkFree(srv->netlinknh);
912
    }
913
 error_locked:
914 915 916 917 918 919 920 921 922 923 924 925 926 927
    virNetlinkEventServerUnlock(srv);
    if (ret < 0) {
        virMutexDestroy(&srv->lock);
        VIR_FREE(srv);
    }
    return ret;
}

/**
 * virNetlinkEventAddClient:
 *
 * @handleCB: callback to invoke when an event occurs
 * @removeCB: callback to invoke when removing a client
 * @opaque: user data to pass to callback
928 929
 * @macaddr: macaddr to store with the data. Used to identify callers.
 *           May be null.
930
 * @protocol: netlink protocol
931 932 933 934 935
 *
 * register a callback for handling of netlink messages. The
 * registered function receives the entire netlink message and
 * may choose to act upon it.
 *
936 937
 * Returns -1 if the file handle cannot be registered, number of
 * monitor upon success.
938 939 940 941
 */
int
virNetlinkEventAddClient(virNetlinkEventHandleCallback handleCB,
                         virNetlinkEventRemoveCallback removeCB,
942
                         void *opaque, const virMacAddr *macaddr,
943
                         unsigned int protocol)
944
{
945 946
    size_t i;
    int r, ret = -1;
947 948 949 950 951 952
    virNetlinkEventSrvPrivatePtr srv = NULL;

    if (protocol >= MAX_LINKS)
        return -EINVAL;

    srv = server[protocol];
953

954
    if (handleCB == NULL) {
955 956
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Invalid NULL callback provided"));
957
        return -1;
958
    }
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976

    virNetlinkEventServerLock(srv);

    VIR_DEBUG("adding client: %d.", nextWatch);

    r = 0;
    /* first try to re-use deleted free slots */
    for (i = 0; i < srv->handlesCount; i++) {
        if (srv->handles[i].deleted == VIR_NETLINK_HANDLE_DELETED) {
            r = i;
            goto addentry;
        }
    }
    /* Resize the eventLoop array if needed */
    if (srv->handlesCount == srv->handlesAlloc) {
        VIR_DEBUG("Used %zu handle slots, adding at least %d more",
                  srv->handlesAlloc, NETLINK_EVENT_ALLOC_EXTENT);
        if (VIR_RESIZE_N(srv->handles, srv->handlesAlloc,
977
                        srv->handlesCount, NETLINK_EVENT_ALLOC_EXTENT) < 0)
978 979 980 981
            goto error;
    }
    r = srv->handlesCount++;

982
 addentry:
983 984 985 986 987 988
    srv->handles[r].watch    = nextWatch;
    srv->handles[r].handleCB = handleCB;
    srv->handles[r].removeCB = removeCB;
    srv->handles[r].opaque   = opaque;
    srv->handles[r].deleted  = VIR_NETLINK_HANDLE_VALID;
    if (macaddr)
989
        virMacAddrSet(&srv->handles[r].macaddr, macaddr);
990
    else
991
        virMacAddrSetRaw(&srv->handles[r].macaddr,
E
Eric Blake 已提交
992
                         (unsigned char[VIR_MAC_BUFLEN]){0, 0, 0, 0, 0, 0});
993 994 995 996

    VIR_DEBUG("added client to loop slot: %d. with macaddr ptr=%p", r, macaddr);

    ret = nextWatch++;
997
 error:
998 999 1000 1001 1002 1003 1004 1005 1006
    virNetlinkEventServerUnlock(srv);
    return ret;
}

/**
 * virNetlinkEventRemoveClient:
 *
 * @watch: watch whose handle to remove
 * @macaddr: macaddr whose handle to remove
1007
 * @protocol: netlink protocol
1008 1009 1010 1011 1012
 *
 * Unregister a callback from a netlink monitor.
 * The handler function referenced will no longer receive netlink messages.
 * Either watch or macaddr may be used, the other should be null.
 *
1013
 * Returns -1 if the file handle was not registered, 0 upon success
1014 1015
 */
int
1016
virNetlinkEventRemoveClient(int watch, const virMacAddr *macaddr,
1017
                            unsigned int protocol)
1018
{
1019
    size_t i;
1020
    int ret = -1;
1021 1022 1023 1024 1025 1026
    virNetlinkEventSrvPrivatePtr srv = NULL;

    if (protocol >= MAX_LINKS)
        return -EINVAL;

    srv = server[protocol];
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

    VIR_DEBUG("removing client watch=%d, mac=%p.", watch, macaddr);

    if (watch <= 0 && !macaddr) {
        VIR_WARN("Ignoring invalid netlink client id: %d", watch);
        return -1;
    }

    virNetlinkEventServerLock(srv);

    for (i = 0; i < srv->handlesCount; i++) {
        if (srv->handles[i].deleted != VIR_NETLINK_HANDLE_VALID)
            continue;

        if ((watch && srv->handles[i].watch == watch) ||
            (!watch &&
1043
             virMacAddrCmp(macaddr, &srv->handles[i].macaddr) == 0)) {
1044 1045 1046

            VIR_DEBUG("removed client: %d by %s.",
                      srv->handles[i].watch, watch ? "index" : "mac");
1047
            virNetlinkEventRemoveClientPrimitive(i, protocol);
1048 1049 1050 1051 1052 1053
            ret = 0;
            goto cleanup;
        }
    }
    VIR_DEBUG("no client found to remove.");

1054
 cleanup:
1055 1056 1057 1058
    virNetlinkEventServerUnlock(srv);
    return ret;
}

1059 1060
#else

1061 1062 1063 1064 1065 1066
# if defined(__linux)
static const char *unsupported = N_("libnl was not available at build time");
# else
static const char *unsupported = N_("not supported on non-linux platforms");
# endif

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
int
virNetlinkStartup(void)
{
    return 0;
}

void
virNetlinkShutdown(void)
{
    return;
}

1079
int virNetlinkCommand(struct nl_msg *nl_msg ATTRIBUTE_UNUSED,
1080
                      struct nlmsghdr **resp ATTRIBUTE_UNUSED,
1081 1082
                      unsigned int *respbuflen ATTRIBUTE_UNUSED,
                      uint32_t src_pid ATTRIBUTE_UNUSED,
1083 1084 1085
                      uint32_t dst_pid ATTRIBUTE_UNUSED,
                      unsigned int protocol ATTRIBUTE_UNUSED,
                      unsigned int groups ATTRIBUTE_UNUSED)
1086
{
1087
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
1088 1089 1090
    return -1;
}

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
int
virNetlinkDumpCommand(struct nl_msg *nl_msg ATTRIBUTE_UNUSED,
                      virNetlinkDumpCallback callback ATTRIBUTE_UNUSED,
                      uint32_t src_pid ATTRIBUTE_UNUSED,
                      uint32_t dst_pid ATTRIBUTE_UNUSED,
                      unsigned int protocol ATTRIBUTE_UNUSED,
                      unsigned int groups ATTRIBUTE_UNUSED,
                      void *opaque ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
    return -1;
}
1103

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
int
virNetlinkDumpLink(const char *ifname ATTRIBUTE_UNUSED,
                   int ifindex ATTRIBUTE_UNUSED,
                   void **nlData ATTRIBUTE_UNUSED,
                   struct nlattr **tb ATTRIBUTE_UNUSED,
                   uint32_t src_pid ATTRIBUTE_UNUSED,
                   uint32_t dst_pid ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to dump link info on this platform"));
    return -1;
}


1118
int
1119 1120
virNetlinkDelLink(const char *ifname ATTRIBUTE_UNUSED,
                  virNetlinkDelLinkFallback fallback ATTRIBUTE_UNUSED)
1121 1122 1123 1124 1125
{
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
    return -1;
}

1126
/**
1127 1128
 * stopNetlinkEventServer: stop the monitor to receive netlink
 * messages for libvirtd
1129
 */
1130
int virNetlinkEventServiceStop(unsigned int protocol ATTRIBUTE_UNUSED)
1131
{
1132
    VIR_DEBUG("%s", _(unsupported));
1133 1134 1135
    return 0;
}

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
/**
 * stopNetlinkEventServerAll: stop all the monitors to receive netlink
 * messages for libvirtd
 */
int virNetlinkEventServiceStopAll(void)
{
    VIR_DEBUG("%s", _(unsupported));
    return 0;
}

1146
/**
1147 1148
 * startNetlinkEventServer: start a monitor to receive netlink
 * messages for libvirtd
1149
 */
1150 1151
int virNetlinkEventServiceStart(unsigned int protocol ATTRIBUTE_UNUSED,
                                unsigned int groups ATTRIBUTE_UNUSED)
1152
{
1153
    VIR_DEBUG("%s", _(unsupported));
1154 1155 1156 1157
    return 0;
}

/**
1158 1159
 * virNetlinkEventServiceIsRunning: returns if the netlink event
 * service is running.
1160
 */
1161
bool virNetlinkEventServiceIsRunning(unsigned int protocol ATTRIBUTE_UNUSED)
1162
{
1163
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
1164 1165 1166
    return 0;
}

1167
int virNetlinkEventServiceLocalPid(unsigned int protocol ATTRIBUTE_UNUSED)
1168
{
1169
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
1170 1171 1172
    return -1;
}

1173
/**
1174 1175
 * virNetlinkEventAddClient: register a callback for handling of
 * netlink messages
1176
 */
J
Jim Fehlig 已提交
1177 1178 1179
int virNetlinkEventAddClient(virNetlinkEventHandleCallback handleCB ATTRIBUTE_UNUSED,
                             virNetlinkEventRemoveCallback removeCB ATTRIBUTE_UNUSED,
                             void *opaque ATTRIBUTE_UNUSED,
1180
                             const virMacAddr *macaddr ATTRIBUTE_UNUSED,
1181
                             unsigned int protocol ATTRIBUTE_UNUSED)
1182
{
1183
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
1184 1185 1186 1187 1188 1189
    return -1;
}

/**
 * virNetlinkEventRemoveClient: unregister a callback from a netlink monitor
 */
J
Jim Fehlig 已提交
1190
int virNetlinkEventRemoveClient(int watch ATTRIBUTE_UNUSED,
1191
                                const virMacAddr *macaddr ATTRIBUTE_UNUSED,
1192
                                unsigned int protocol ATTRIBUTE_UNUSED)
1193
{
1194
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
1195 1196 1197
    return -1;
}

E
Eric Blake 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206

int
virNetlinkGetErrorCode(struct nlmsghdr *resp ATTRIBUTE_UNUSED,
                       unsigned int recvbuflen ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
    return -EINVAL;
}

1207
#endif /* __linux__ */