virnetlink.c 23.1 KB
Newer Older
1
/*
2
 * Copyright (C) 2010-2014 Red Hat, Inc.
3
 * Copyright (C) 2010-2012 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 "virlog.h"
40
#include "viralloc.h"
41
#include "virthread.h"
42
#include "virmacaddr.h"
43
#include "virerror.h"
44

45 46 47 48
#ifndef SOL_NETLINK
# define SOL_NETLINK 270
#endif

49 50
#define VIR_FROM_THIS VIR_FROM_NET

51 52
VIR_LOG_INIT("util.netlink");

53
#define NETLINK_ACK_TIMEOUT_S  (2*1000)
54

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

S
Serge Hallyn 已提交
66 67 68 69 70 71 72 73 74 75
# ifdef HAVE_LIBNL1
#  define virNetlinkAlloc nl_handle_alloc
#  define virNetlinkFree nl_handle_destroy
typedef struct nl_handle virNetlinkHandle;
# else
#  define virNetlinkAlloc nl_socket_alloc
#  define virNetlinkFree nl_socket_free
typedef struct nl_sock virNetlinkHandle;
# endif

76 77 78 79 80 81 82
typedef struct _virNetlinkEventSrvPrivate virNetlinkEventSrvPrivate;
typedef virNetlinkEventSrvPrivate *virNetlinkEventSrvPrivatePtr;
struct _virNetlinkEventSrvPrivate {
    /*Server*/
    virMutex lock;
    int eventwatch;
    int netlinkfd;
S
Serge Hallyn 已提交
83
    virNetlinkHandle *netlinknh;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    /*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

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

/* Function definitions */

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 137
/**
 * 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;
138
    VIR_DEBUG("Running global netlink initialization");
J
Jiri Denemark 已提交
139
    placeholder_nlhandle = virNetlinkAlloc();
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    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 已提交
158
        virNetlinkFree(placeholder_nlhandle);
159 160 161 162
        placeholder_nlhandle = NULL;
    }
}

163
/**
164
 * virNetlinkCommand:
165 166 167 168
 * @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.
169 170 171 172
 * @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
173 174 175 176 177
 *
 * 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.
 */
178
int virNetlinkCommand(struct nl_msg *nl_msg,
179
                      struct nlmsghdr **resp, unsigned int *respbuflen,
180 181
                      uint32_t src_pid, uint32_t dst_pid,
                      unsigned int protocol, unsigned int groups)
182
{
183
    int ret = -1;
184 185
    struct sockaddr_nl nladdr = {
            .nl_family = AF_NETLINK,
186
            .nl_pid    = dst_pid,
187 188 189
            .nl_groups = 0,
    };
    ssize_t nbytes;
190
    struct pollfd fds[1];
191 192 193
    int fd;
    int n;
    struct nlmsghdr *nlmsg = nlmsg_hdr(nl_msg);
194
    virNetlinkHandle *nlhandle = NULL;
195
    int len = 0;
196 197 198 199

    if (protocol >= MAX_LINKS) {
        virReportSystemError(EINVAL,
                             _("invalid protocol argument: %d"), protocol);
200
        goto cleanup;
201
    }
202

203
    nlhandle = virNetlinkAlloc();
204 205 206
    if (!nlhandle) {
        virReportSystemError(errno,
                             "%s", _("cannot allocate nlhandle for netlink"));
207
        goto cleanup;
208 209
    }

210 211 212 213
    if (nl_connect(nlhandle, protocol) < 0) {
        virReportSystemError(errno,
                        _("cannot connect to netlink socket with protocol %d"),
                             protocol);
214
        goto cleanup;
215 216 217 218 219 220
    }

    fd = nl_socket_get_fd(nlhandle);
    if (fd < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot get netlink socket fd"));
221
        goto cleanup;
222 223 224
    }

    if (groups && nl_socket_add_membership(nlhandle, groups) < 0) {
225
        virReportSystemError(errno,
226
                             "%s", _("cannot add netlink membership"));
227
        goto cleanup;
228 229 230 231
    }

    nlmsg_set_dst(nl_msg, &nladdr);

232
    nlmsg->nlmsg_pid = src_pid ? src_pid : getpid();
233 234 235 236 237

    nbytes = nl_send_auto_complete(nlhandle, nl_msg);
    if (nbytes < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot send to netlink socket"));
238
        goto cleanup;
239 240
    }

241 242 243
    memset(fds, 0, sizeof(fds));
    fds[0].fd = fd;
    fds[0].events = POLLIN;
244

245
    n = poll(fds, ARRAY_CARDINALITY(fds), NETLINK_ACK_TIMEOUT_S);
246 247 248
    if (n <= 0) {
        if (n < 0)
            virReportSystemError(errno, "%s",
249
                                 _("error in poll call"));
250 251 252
        if (n == 0)
            virReportSystemError(ETIMEDOUT, "%s",
                                 _("no valid netlink response was received"));
253
        goto cleanup;
254 255
    }

256 257 258 259 260
    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;
261
    }
262 263 264 265 266 267 268 269 270
    if (len < 0) {
        virReportSystemError(errno, "%s", _("nl_recv failed"));
        goto cleanup;
    }

    ret = 0;
    *respbuflen = len;
 cleanup:
    if (ret < 0) {
271
        *resp = NULL;
272 273 274
        *respbuflen = 0;
    }

S
Serge Hallyn 已提交
275
    virNetlinkFree(nlhandle);
276
    return ret;
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
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
295
 * @protocol: netlink protocol
296 297 298 299 300 301 302 303 304
 *
 * 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.
 */
305 306
static int
virNetlinkEventRemoveClientPrimitive(size_t i, unsigned int protocol)
307
{
308 309 310 311
    if (protocol >= MAX_LINKS)
        return -EINVAL;

    virNetlinkEventRemoveCallback removeCB = server[protocol]->handles[i].removeCB;
312 313

    if (removeCB) {
314 315 316
        (removeCB)(server[protocol]->handles[i].watch,
                   &server[protocol]->handles[i].macaddr,
                   server[protocol]->handles[i].opaque);
317
    }
318 319
    server[protocol]->handles[i].deleted = VIR_NETLINK_HANDLE_DELETED;
    return 0;
320 321 322 323 324 325 326 327 328
}

static void
virNetlinkEventCallback(int watch,
                        int fd ATTRIBUTE_UNUSED,
                        int events ATTRIBUTE_UNUSED,
                        void *opaque)
{
    virNetlinkEventSrvPrivatePtr srv = opaque;
329
    struct nlmsghdr *msg;
330 331
    struct sockaddr_nl peer;
    struct ucred *creds = NULL;
332 333
    size_t i;
    int length;
334 335
    bool handled = false;

336 337
    length = nl_recv(srv->netlinknh, &peer,
                     (unsigned char **)&msg, &creds);
338 339 340 341

    if (length == 0)
        return;
    if (length < 0) {
342 343
        virReportSystemError(errno,
                             "%s", _("nl_recv returned with error"));
344 345 346 347 348 349 350 351 352 353 354 355
        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;

356
        VIR_DEBUG("dispatching client %zu.", i);
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

        (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.
 *
374 375
 * @protocol: netlink protocol
 *
376
 * Returns -1 if the monitor cannot be unregistered, 0 upon success
377 378
 */
int
379
virNetlinkEventServiceStop(unsigned int protocol)
380
{
381 382 383 384
    if (protocol >= MAX_LINKS)
        return -EINVAL;

    virNetlinkEventSrvPrivatePtr srv = server[protocol];
385
    size_t i;
386 387 388

    VIR_INFO("stopping netlink event service");

389
    if (!server[protocol])
390 391 392 393
        return 0;

    virNetlinkEventServerLock(srv);
    nl_close(srv->netlinknh);
S
Serge Hallyn 已提交
394
    virNetlinkFree(srv->netlinknh);
395 396 397 398 399
    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)
400
            virNetlinkEventRemoveClientPrimitive(i, protocol);
401 402
    }

403
    server[protocol] = NULL;
404 405 406 407 408 409 410
    virNetlinkEventServerUnlock(srv);

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

411 412 413 414 415 416 417 418 419 420
/**
 * 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)
{
421
    size_t i, j;
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
    virNetlinkEventSrvPrivatePtr srv = NULL;

    VIR_INFO("stopping all netlink event services");

    for (i = 0; i < MAX_LINKS; i++) {
        srv = server[i];
        if (!srv)
            continue;

        virNetlinkEventServerLock(srv);
        nl_close(srv->netlinknh);
        virNetlinkFree(srv->netlinknh);
        virEventRemoveHandle(srv->eventwatch);

        for (j = 0; j < srv->handlesCount; j++) {
            if (srv->handles[j].deleted == VIR_NETLINK_HANDLE_VALID)
                virNetlinkEventRemoveClientPrimitive(j, i);
        }

        server[i] = NULL;
        virNetlinkEventServerUnlock(srv);

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

    return 0;
}

451 452 453
/**
 * virNetlinkEventServiceIsRunning:
 *
454
 * Returns if the netlink event service is running.
455
 *
456 457
 * @protocol: netlink protocol
 *
458
 * Returns 'true' if the service is running, 'false' if stopped.
459 460
 */
bool
461
virNetlinkEventServiceIsRunning(unsigned int protocol)
462
{
463 464 465 466 467 468 469
    if (protocol >= MAX_LINKS) {
        virReportSystemError(EINVAL,
                             _("invalid protocol argument: %d"), protocol);
        return false;
    }

    return server[protocol] != NULL;
470 471
}

472 473 474
/**
 * virNetlinkEventServiceLocalPid:
 *
475 476
 * @protocol: netlink protocol
 *
477 478 479 480
 * 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).
 */
481
int virNetlinkEventServiceLocalPid(unsigned int protocol)
482
{
483 484 485 486
    if (protocol >= MAX_LINKS)
        return -EINVAL;

    if (!(server[protocol] && server[protocol]->netlinknh)) {
487 488
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("netlink event service not running"));
489 490
        return -1;
    }
491
    return (int)nl_socket_get_local_port(server[protocol]->netlinknh);
492 493 494
}


495 496 497 498 499 500
/**
 * virNetlinkEventServiceStart:
 *
 * start a monitor to receive netlink messages for libvirtd.
 * This registers a netlink socket with the event interface.
 *
501 502
 * @protocol: netlink protocol
 * @groups: broadcast groups to join in
503
 * Returns -1 if the monitor cannot be registered, 0 upon success
504 505
 */
int
506
virNetlinkEventServiceStart(unsigned int protocol, unsigned int groups)
507 508 509 510 511
{
    virNetlinkEventSrvPrivatePtr srv;
    int fd;
    int ret = -1;

512 513 514 515 516 517 518
    if (protocol >= MAX_LINKS) {
        virReportSystemError(EINVAL,
                             _("invalid protocol argument: %d"), protocol);
        return -EINVAL;
    }

    if (server[protocol])
519 520
        return 0;

521
    VIR_INFO("starting netlink event service with protocol %d", protocol);
522

523
    if (VIR_ALLOC(srv) < 0)
524
        return -1;
525

526 527 528 529
    if (virMutexInit(&srv->lock) < 0) {
        VIR_FREE(srv);
        return -1;
    }
530 531 532 533

    virNetlinkEventServerLock(srv);

    /* Allocate a new socket and get fd */
S
Serge Hallyn 已提交
534
    srv->netlinknh = virNetlinkAlloc();
535 536

    if (!srv->netlinknh) {
537 538
        virReportSystemError(errno,
                             "%s", _("cannot allocate nlhandle for virNetlinkEvent server"));
539 540 541
        goto error_locked;
    }

542
    if (nl_connect(srv->netlinknh, protocol) < 0) {
543
        virReportSystemError(errno,
544
                             _("cannot connect to netlink socket with protocol %d"), protocol);
545 546 547 548 549
        goto error_server;
    }

    fd = nl_socket_get_fd(srv->netlinknh);
    if (fd < 0) {
550 551
        virReportSystemError(errno,
                             "%s", _("cannot get netlink socket fd"));
552 553 554
        goto error_server;
    }

555 556 557 558 559 560
    if (groups && nl_socket_add_membership(srv->netlinknh, groups) < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot add netlink membership"));
        goto error_server;
    }

561
    if (nl_socket_set_nonblocking(srv->netlinknh)) {
562 563
        virReportSystemError(errno, "%s",
                             _("cannot set netlink socket nonblocking"));
564 565 566 567 568 569 570
        goto error_server;
    }

    if ((srv->eventwatch = virEventAddHandle(fd,
                                             VIR_EVENT_HANDLE_READABLE,
                                             virNetlinkEventCallback,
                                             srv, NULL)) < 0) {
571 572
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to add netlink event handle watch"));
573 574 575 576 577 578 579
        goto error_server;
    }

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

    ret = 0;
580
    server[protocol] = srv;
581

582
 error_server:
583 584
    if (ret < 0) {
        nl_close(srv->netlinknh);
S
Serge Hallyn 已提交
585
        virNetlinkFree(srv->netlinknh);
586
    }
587
 error_locked:
588 589 590 591 592 593 594 595 596 597 598 599 600 601
    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
602 603
 * @macaddr: macaddr to store with the data. Used to identify callers.
 *           May be null.
604
 * @protocol: netlink protocol
605 606 607 608 609
 *
 * register a callback for handling of netlink messages. The
 * registered function receives the entire netlink message and
 * may choose to act upon it.
 *
610 611
 * Returns -1 if the file handle cannot be registered, number of
 * monitor upon success.
612 613 614 615
 */
int
virNetlinkEventAddClient(virNetlinkEventHandleCallback handleCB,
                         virNetlinkEventRemoveCallback removeCB,
616
                         void *opaque, const virMacAddr *macaddr,
617
                         unsigned int protocol)
618
{
619 620
    size_t i;
    int r, ret = -1;
621 622 623 624 625 626
    virNetlinkEventSrvPrivatePtr srv = NULL;

    if (protocol >= MAX_LINKS)
        return -EINVAL;

    srv = server[protocol];
627

628
    if (handleCB == NULL) {
629 630
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Invalid NULL callback provided"));
631
        return -1;
632
    }
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650

    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,
651
                        srv->handlesCount, NETLINK_EVENT_ALLOC_EXTENT) < 0)
652 653 654 655
            goto error;
    }
    r = srv->handlesCount++;

656
 addentry:
657 658 659 660 661 662
    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)
663
        virMacAddrSet(&srv->handles[r].macaddr, macaddr);
664
    else
665
        virMacAddrSetRaw(&srv->handles[r].macaddr,
E
Eric Blake 已提交
666
                         (unsigned char[VIR_MAC_BUFLEN]){0, 0, 0, 0, 0, 0});
667 668 669 670

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

    ret = nextWatch++;
671
 error:
672 673 674 675 676 677 678 679 680
    virNetlinkEventServerUnlock(srv);
    return ret;
}

/**
 * virNetlinkEventRemoveClient:
 *
 * @watch: watch whose handle to remove
 * @macaddr: macaddr whose handle to remove
681
 * @protocol: netlink protocol
682 683 684 685 686
 *
 * 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.
 *
687
 * Returns -1 if the file handle was not registered, 0 upon success
688 689
 */
int
690
virNetlinkEventRemoveClient(int watch, const virMacAddr *macaddr,
691
                            unsigned int protocol)
692
{
693
    size_t i;
694
    int ret = -1;
695 696 697 698 699 700
    virNetlinkEventSrvPrivatePtr srv = NULL;

    if (protocol >= MAX_LINKS)
        return -EINVAL;

    srv = server[protocol];
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716

    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 &&
717
             virMacAddrCmp(macaddr, &srv->handles[i].macaddr) == 0)) {
718 719 720

            VIR_DEBUG("removed client: %d by %s.",
                      srv->handles[i].watch, watch ? "index" : "mac");
721
            virNetlinkEventRemoveClientPrimitive(i, protocol);
722 723 724 725 726 727
            ret = 0;
            goto cleanup;
        }
    }
    VIR_DEBUG("no client found to remove.");

728
 cleanup:
729 730 731 732
    virNetlinkEventServerUnlock(srv);
    return ret;
}

733 734
#else

735 736 737 738 739 740
# 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

741 742 743 744 745 746 747 748 749 750 751 752
int
virNetlinkStartup(void)
{
    return 0;
}

void
virNetlinkShutdown(void)
{
    return;
}

753
int virNetlinkCommand(struct nl_msg *nl_msg ATTRIBUTE_UNUSED,
754
                      struct nlmsghdr **resp ATTRIBUTE_UNUSED,
755 756
                      unsigned int *respbuflen ATTRIBUTE_UNUSED,
                      uint32_t src_pid ATTRIBUTE_UNUSED,
757 758 759
                      uint32_t dst_pid ATTRIBUTE_UNUSED,
                      unsigned int protocol ATTRIBUTE_UNUSED,
                      unsigned int groups ATTRIBUTE_UNUSED)
760
{
761
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
762 763 764
    return -1;
}

765
/**
766 767
 * stopNetlinkEventServer: stop the monitor to receive netlink
 * messages for libvirtd
768
 */
769
int virNetlinkEventServiceStop(unsigned int protocol ATTRIBUTE_UNUSED)
770
{
771
    VIR_DEBUG("%s", _(unsupported));
772 773 774
    return 0;
}

775 776 777 778 779 780 781 782 783 784
/**
 * stopNetlinkEventServerAll: stop all the monitors to receive netlink
 * messages for libvirtd
 */
int virNetlinkEventServiceStopAll(void)
{
    VIR_DEBUG("%s", _(unsupported));
    return 0;
}

785
/**
786 787
 * startNetlinkEventServer: start a monitor to receive netlink
 * messages for libvirtd
788
 */
789 790
int virNetlinkEventServiceStart(unsigned int protocol ATTRIBUTE_UNUSED,
                                unsigned int groups ATTRIBUTE_UNUSED)
791
{
792
    VIR_DEBUG("%s", _(unsupported));
793 794 795 796
    return 0;
}

/**
797 798
 * virNetlinkEventServiceIsRunning: returns if the netlink event
 * service is running.
799
 */
800
bool virNetlinkEventServiceIsRunning(unsigned int protocol ATTRIBUTE_UNUSED)
801
{
802
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
803 804 805
    return 0;
}

806
int virNetlinkEventServiceLocalPid(unsigned int protocol ATTRIBUTE_UNUSED)
807
{
808
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
809 810 811
    return -1;
}

812
/**
813 814
 * virNetlinkEventAddClient: register a callback for handling of
 * netlink messages
815
 */
J
Jim Fehlig 已提交
816 817 818
int virNetlinkEventAddClient(virNetlinkEventHandleCallback handleCB ATTRIBUTE_UNUSED,
                             virNetlinkEventRemoveCallback removeCB ATTRIBUTE_UNUSED,
                             void *opaque ATTRIBUTE_UNUSED,
819
                             const virMacAddr *macaddr ATTRIBUTE_UNUSED,
820
                             unsigned int protocol ATTRIBUTE_UNUSED)
821
{
822
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
823 824 825 826 827 828
    return -1;
}

/**
 * virNetlinkEventRemoveClient: unregister a callback from a netlink monitor
 */
J
Jim Fehlig 已提交
829
int virNetlinkEventRemoveClient(int watch ATTRIBUTE_UNUSED,
830
                                const virMacAddr *macaddr ATTRIBUTE_UNUSED,
831
                                unsigned int protocol ATTRIBUTE_UNUSED)
832
{
833
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
834 835 836
    return -1;
}

837
#endif /* __linux__ */