virnetlink.c 16.5 KB
Newer Older
1
/*
S
Serge Hallyn 已提交
2
 * Copyright (C) 2010-2012 Red Hat, Inc.
3
 * Copyright (C) 2010-2012 IBM Corporation
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * 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
 *
 * 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 36
 */

#include <config.h>

#include <errno.h>
#include <unistd.h>
#include <sys/types.h>

37
#include "virnetlink.h"
38
#include "logging.h"
39
#include "memory.h"
40 41
#include "threads.h"
#include "virmacaddr.h"
42 43 44 45 46 47 48 49 50 51
#include "virterror_internal.h"

#define VIR_FROM_THIS VIR_FROM_NET

#define netlinkError(code, ...)                                           \
        virReportErrorHelper(VIR_FROM_NET, code, __FILE__,                 \
                             __FUNCTION__, __LINE__, __VA_ARGS__)

#define NETLINK_ACK_TIMEOUT_S  2

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

S
Serge Hallyn 已提交
63 64 65 66 67 68 69 70 71 72
# 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

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

static virNetlinkEventSrvPrivatePtr server = NULL;

/* Function definitions */

104
/**
105
 * virNetlinkCommand:
106 107 108 109 110 111 112 113 114 115
 * @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.
 * @nl_pid: the pid of the process to talk to, i.e., pid = 0 for kernel
 *
 * 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.
 */
116 117 118
int virNetlinkCommand(struct nl_msg *nl_msg,
                      unsigned char **respbuf, unsigned int *respbuflen,
                      int nl_pid)
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
{
    int rc = 0;
    struct sockaddr_nl nladdr = {
            .nl_family = AF_NETLINK,
            .nl_pid    = nl_pid,
            .nl_groups = 0,
    };
    ssize_t nbytes;
    struct timeval tv = {
        .tv_sec = NETLINK_ACK_TIMEOUT_S,
    };
    fd_set readfds;
    int fd;
    int n;
    struct nlmsghdr *nlmsg = nlmsg_hdr(nl_msg);
S
Serge Hallyn 已提交
134
    virNetlinkHandle *nlhandle = virNetlinkAlloc();
135 136 137 138 139 140 141 142 143 144 145

    if (!nlhandle) {
        virReportSystemError(errno,
                             "%s", _("cannot allocate nlhandle for netlink"));
        return -1;
    }

    if (nl_connect(nlhandle, NETLINK_ROUTE) < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot connect to netlink socket"));
        rc = -1;
146
        goto error;
147 148 149 150 151 152 153 154 155 156 157
    }

    nlmsg_set_dst(nl_msg, &nladdr);

    nlmsg->nlmsg_pid = getpid();

    nbytes = nl_send_auto_complete(nlhandle, nl_msg);
    if (nbytes < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot send to netlink socket"));
        rc = -1;
158
        goto error;
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    }

    fd = nl_socket_get_fd(nlhandle);

    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);

    n = select(fd + 1, &readfds, NULL, NULL, &tv);
    if (n <= 0) {
        if (n < 0)
            virReportSystemError(errno, "%s",
                                 _("error in select call"));
        if (n == 0)
            virReportSystemError(ETIMEDOUT, "%s",
                                 _("no valid netlink response was received"));
        rc = -1;
175
        goto error;
176 177 178 179 180 181 182 183
    }

    *respbuflen = nl_recv(nlhandle, &nladdr, respbuf, NULL);
    if (*respbuflen <= 0) {
        virReportSystemError(errno,
                             "%s", _("nl_recv failed"));
        rc = -1;
    }
184
error:
185 186 187 188 189 190
    if (rc == -1) {
        VIR_FREE(*respbuf);
        *respbuf = NULL;
        *respbuflen = 0;
    }

S
Serge Hallyn 已提交
191
    virNetlinkFree(nlhandle);
192 193 194
    return rc;
}

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
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
 *
 * 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.
 */
static void
virNetlinkEventRemoveClientPrimitive(size_t i)
{
    virNetlinkEventRemoveCallback removeCB = server->handles[i].removeCB;

    if (removeCB) {
        (removeCB)(server->handles[i].watch,
                   server->handles[i].macaddr,
                   server->handles[i].opaque);
    }
    server->handles[i].deleted = VIR_NETLINK_HANDLE_DELETED;
}

static void
virNetlinkEventCallback(int watch,
                        int fd ATTRIBUTE_UNUSED,
                        int events ATTRIBUTE_UNUSED,
                        void *opaque)
{
    virNetlinkEventSrvPrivatePtr srv = opaque;
    unsigned char *msg;
    struct sockaddr_nl peer;
    struct ucred *creds = NULL;
    int i, length;
    bool handled = false;

    length = nl_recv(srv->netlinknh, &peer, &msg, &creds);

    if (length == 0)
        return;
    if (length < 0) {
251 252
        virReportSystemError(errno,
                             "%s", _("nl_recv returned with error"));
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        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;

        VIR_DEBUG("dispatching client %d.", i);

        (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.
 *
283
 * Returns -1 if the monitor cannot be unregistered, 0 upon success
284 285 286 287 288 289 290 291 292 293 294 295 296 297
 */
int
virNetlinkEventServiceStop(void)
{
    virNetlinkEventSrvPrivatePtr srv = server;
    int i;

    VIR_INFO("stopping netlink event service");

    if (!server)
        return 0;

    virNetlinkEventServerLock(srv);
    nl_close(srv->netlinknh);
S
Serge Hallyn 已提交
298
    virNetlinkFree(srv->netlinknh);
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    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)
            virNetlinkEventRemoveClientPrimitive(i);
    }

    server = 0;
    virNetlinkEventServerUnlock(srv);

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

/**
 * virNetlinkEventServiceIsRunning:
 *
318
 * Returns if the netlink event service is running.
319
 *
320
 * Returns 'true' if the service is running, 'false' if stopped.
321 322 323 324
 */
bool
virNetlinkEventServiceIsRunning(void)
{
325
    return server != NULL;
326 327 328 329 330 331 332 333
}

/**
 * virNetlinkEventServiceStart:
 *
 * start a monitor to receive netlink messages for libvirtd.
 * This registers a netlink socket with the event interface.
 *
334
 * Returns -1 if the monitor cannot be registered, 0 upon success
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
 */
int
virNetlinkEventServiceStart(void)
{
    virNetlinkEventSrvPrivatePtr srv;
    int fd;
    int ret = -1;

    if (server)
        return 0;

    VIR_INFO("starting netlink event service");

    if (VIR_ALLOC(srv) < 0) {
        virReportOOMError();
350
        return -1;
351 352
    }

353 354 355 356
    if (virMutexInit(&srv->lock) < 0) {
        VIR_FREE(srv);
        return -1;
    }
357 358 359 360

    virNetlinkEventServerLock(srv);

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

    if (!srv->netlinknh) {
364 365
        virReportSystemError(errno,
                             "%s", _("cannot allocate nlhandle for virNetlinkEvent server"));
366 367 368 369
        goto error_locked;
    }

    if (nl_connect(srv->netlinknh, NETLINK_ROUTE) < 0) {
370 371
        virReportSystemError(errno,
                             "%s", _("cannot connect to netlink socket"));
372 373 374 375 376 377
        goto error_server;
    }

    fd = nl_socket_get_fd(srv->netlinknh);

    if (fd < 0) {
378 379
        virReportSystemError(errno,
                             "%s", _("cannot get netlink socket fd"));
380 381 382 383
        goto error_server;
    }

    if (nl_socket_set_nonblocking(srv->netlinknh)) {
384 385
        virReportSystemError(errno, "%s",
                             _("cannot set netlink socket nonblocking"));
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        goto error_server;
    }

    if ((srv->eventwatch = virEventAddHandle(fd,
                                             VIR_EVENT_HANDLE_READABLE,
                                             virNetlinkEventCallback,
                                             srv, NULL)) < 0) {
        netlinkError(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Failed to add netlink event handle watch"));
        goto error_server;
    }

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

    ret = 0;
    server = srv;

error_server:
    if (ret < 0) {
        nl_close(srv->netlinknh);
S
Serge Hallyn 已提交
407
        virNetlinkFree(srv->netlinknh);
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    }
error_locked:
    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
424 425
 * @macaddr: macaddr to store with the data. Used to identify callers.
 *           May be null.
426 427 428 429 430
 *
 * register a callback for handling of netlink messages. The
 * registered function receives the entire netlink message and
 * may choose to act upon it.
 *
431 432
 * Returns -1 if the file handle cannot be registered, number of
 * monitor upon success.
433 434 435 436 437 438 439 440 441
 */
int
virNetlinkEventAddClient(virNetlinkEventHandleCallback handleCB,
                         virNetlinkEventRemoveCallback removeCB,
                         void *opaque, const unsigned char *macaddr)
{
    int i, r, ret = -1;
    virNetlinkEventSrvPrivatePtr srv = server;

442 443 444
    if (handleCB == NULL) {
        netlinkError(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Invalid NULL callback provided"));
445
        return -1;
446
    }
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

    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,
                        srv->handlesCount, NETLINK_EVENT_ALLOC_EXTENT) < 0) {
466
            virReportOOMError();
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
            goto error;
        }
    }
    r = srv->handlesCount++;

addentry:
    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)
        memcpy(srv->handles[r].macaddr, macaddr, VIR_MAC_BUFLEN);
    else
        memset(srv->handles[r].macaddr, 0, VIR_MAC_BUFLEN);

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

    ret = nextWatch++;
error:
    virNetlinkEventServerUnlock(srv);
    return ret;
}

/**
 * virNetlinkEventRemoveClient:
 *
 * @watch: watch whose handle to remove
 * @macaddr: macaddr whose handle to remove
 *
 * 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.
 *
501
 * Returns -1 if the file handle was not registered, 0 upon success
502 503 504 505 506 507 508 509 510 511 512 513 514 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
 */
int
virNetlinkEventRemoveClient(int watch, const unsigned char *macaddr)
{
    int i;
    int ret = -1;
    virNetlinkEventSrvPrivatePtr srv = server;

    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 &&
             memcmp(macaddr, srv->handles[i].macaddr, VIR_MAC_BUFLEN) == 0)) {

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

cleanup:
    virNetlinkEventServerUnlock(srv);
    return ret;
}

541 542
#else

543 544 545 546 547 548
# 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

549
int virNetlinkCommand(struct nl_msg *nl_msg ATTRIBUTE_UNUSED,
550 551 552 553
           unsigned char **respbuf ATTRIBUTE_UNUSED,
           unsigned int *respbuflen ATTRIBUTE_UNUSED,
           int nl_pid ATTRIBUTE_UNUSED)
{
554
    netlinkError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
555 556 557
    return -1;
}

558
/**
559 560
 * stopNetlinkEventServer: stop the monitor to receive netlink
 * messages for libvirtd
561 562 563
 */
int virNetlinkEventServiceStop(void)
{
564
    VIR_DEBUG("%s", _(unsupported));
565 566 567 568
    return 0;
}

/**
569 570
 * startNetlinkEventServer: start a monitor to receive netlink
 * messages for libvirtd
571 572 573
 */
int virNetlinkEventServiceStart(void)
{
574
    VIR_DEBUG("%s", _(unsupported));
575 576 577 578
    return 0;
}

/**
579 580
 * virNetlinkEventServiceIsRunning: returns if the netlink event
 * service is running.
581
 */
J
Jim Fehlig 已提交
582
bool virNetlinkEventServiceIsRunning(void)
583
{
584
    netlinkError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
585 586 587 588
    return 0;
}

/**
589 590
 * virNetlinkEventAddClient: register a callback for handling of
 * netlink messages
591
 */
J
Jim Fehlig 已提交
592 593 594 595
int virNetlinkEventAddClient(virNetlinkEventHandleCallback handleCB ATTRIBUTE_UNUSED,
                             virNetlinkEventRemoveCallback removeCB ATTRIBUTE_UNUSED,
                             void *opaque ATTRIBUTE_UNUSED,
                             const unsigned char *macaddr ATTRIBUTE_UNUSED)
596
{
597
    netlinkError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
598 599 600 601 602 603
    return -1;
}

/**
 * virNetlinkEventRemoveClient: unregister a callback from a netlink monitor
 */
J
Jim Fehlig 已提交
604 605
int virNetlinkEventRemoveClient(int watch ATTRIBUTE_UNUSED,
                                const unsigned char *macaddr ATTRIBUTE_UNUSED)
606
{
607
    netlinkError(VIR_ERR_INTERNAL_ERROR, "%s", _(unsupported));
608 609 610
    return -1;
}

611
#endif /* __linux__ */