remote_driver.c 253.2 KB
Newer Older
1 2 3 4
/*
 * remote_internal.c: driver to provide access to libvirtd running
 *   on a remote machine
 *
5
 * Copyright (C) 2007-2009 Red Hat, Inc.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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
 *
 * Author: Richard Jones <rjones@redhat.com>
 */

24
#include <config.h>
25

26
/* Windows socket compatibility functions. */
27 28
#include <errno.h>
#include <sys/socket.h>
29

30 31 32
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
33
#include <string.h>
34 35 36
#include <assert.h>
#include <signal.h>
#include <sys/types.h>
37 38
#include <sys/stat.h>
#include <fcntl.h>
39

40 41 42 43 44 45 46
#ifndef HAVE_WINSOCK2_H		/* Unix & Cygwin. */
# include <sys/un.h>
# include <net/if.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
#endif

47 48 49 50 51 52 53 54 55
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif

#ifdef HAVE_PWD_H
#include <pwd.h>
#endif

#ifdef HAVE_PATHS_H
56
#include <paths.h>
57 58
#endif

59
#include <rpc/types.h>
60 61 62
#include <rpc/xdr.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
63
#include "gnutls_1_0_compat.h"
64 65 66
#if HAVE_SASL
#include <sasl/sasl.h>
#endif
67 68
#include <libxml/uri.h>

J
Jim Meyering 已提交
69
#include <netdb.h>
70

71 72
#include <poll.h>

73 74 75 76 77
/* AI_ADDRCONFIG is missing on some systems. */
#ifndef AI_ADDRCONFIG
# define AI_ADDRCONFIG 0
#endif

78
#include "virterror_internal.h"
79
#include "logging.h"
80
#include "datatypes.h"
81
#include "domain_event.h"
82
#include "driver.h"
83 84
#include "buf.h"
#include "qparams.h"
85
#include "remote_driver.h"
86
#include "remote_protocol.h"
87
#include "memory.h"
88
#include "util.h"
89
#include "event.h"
90

91 92
#define VIR_FROM_THIS VIR_FROM_REMOTE

93 94 95 96 97
#ifdef WIN32
#define pipe(fds) _pipe(fds,4096, _O_BINARY)
#endif


98 99
static int inside_daemon = 0;

100 101 102 103 104 105 106 107 108 109 110 111 112
struct remote_thread_call;


enum {
    REMOTE_MODE_WAIT_TX,
    REMOTE_MODE_WAIT_RX,
    REMOTE_MODE_COMPLETE,
    REMOTE_MODE_ERROR,
};

struct remote_thread_call {
    int mode;

113 114
    /* Buffer for outgoing data packet
     * 4 byte length, followed by RPC message header+body */
115 116 117 118 119 120 121 122 123
    char buffer[4 + REMOTE_MESSAGE_MAX];
    unsigned int bufferLength;
    unsigned int bufferOffset;

    unsigned int serial;
    unsigned int proc_nr;

    virCond cond;

124
    int want_reply;
125 126 127 128 129 130 131 132
    xdrproc_t ret_filter;
    char *ret;

    remote_error err;

    struct remote_thread_call *next;
};

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
struct private_stream_data {
    unsigned int has_error : 1;
    remote_error err;

    unsigned int serial;
    unsigned int proc_nr;

    /* XXX this is potentially unbounded if the client
     * app has domain events registered, since packets
     * may be read off wire, while app isn't ready to
     * recv them. Figure out how to address this some
     * time....
     */
    char *incoming;
    unsigned int incomingOffset;
    unsigned int incomingLength;

    struct private_stream_data *next;
};

153
struct private_data {
154 155
    virMutex lock;

156
    int sock;                   /* Socket. */
157
    int watch;                  /* File handle watch */
158
    pid_t pid;                  /* PID of tunnel process */
159 160 161 162
    int uses_tls;               /* TLS enabled on socket? */
    gnutls_session_t session;   /* GnuTLS session (if uses_tls != 0). */
    char *type;                 /* Cached return from remoteType. */
    int counter;                /* Generates serial numbers for RPC. */
163
    int localUses;              /* Ref count for private data */
164 165
    char *hostname;             /* Original hostname */
    FILE *debugLog;             /* Debug remote protocol */
166

167 168
#if HAVE_SASL
    sasl_conn_t *saslconn;      /* SASL context */
169

170 171 172
    const char *saslDecoded;
    unsigned int saslDecodedLength;
    unsigned int saslDecodedOffset;
173 174 175 176

    const char *saslEncoded;
    unsigned int saslEncodedLength;
    unsigned int saslEncodedOffset;
177
#endif
178

179 180
    /* Buffer for incoming data packets
     * 4 byte length, followed by RPC message header+body */
181 182 183 184
    char buffer[4 + REMOTE_MESSAGE_MAX];
    unsigned int bufferLength;
    unsigned int bufferOffset;

185 186 187 188 189 190 191
    /* The list of domain event callbacks */
    virDomainEventCallbackListPtr callbackList;
    /* The queue of domain events generated
       during a call / response rpc          */
    virDomainEventQueuePtr domainEvents;
    /* Timer for flushing domainEvents queue */
    int eventFlushTimer;
192 193
    /* Flag if we're in process of dispatching */
    int domainEventDispatching;
194 195 196 197 198 199 200

    /* Self-pipe to wakeup threads waiting in poll() */
    int wakeupSendFD;
    int wakeupReadFD;

    /* List of threads currently waiting for dispatch */
    struct remote_thread_call *waitDispatch;
201 202

    struct private_stream_data *streams;
203 204
};

205 206 207 208 209 210
enum {
    REMOTE_CALL_IN_OPEN = 1,
    REMOTE_CALL_QUIET_MISSING_RPC = 2,
};


211 212 213 214 215 216 217 218 219 220
static void remoteDriverLock(struct private_data *driver)
{
    virMutexLock(&driver->lock);
}

static void remoteDriverUnlock(struct private_data *driver)
{
    virMutexUnlock(&driver->lock);
}

221 222 223 224
static int remoteIO(virConnectPtr conn,
                    struct private_data *priv,
                    int flags,
                    struct remote_thread_call *thiscall);
225 226 227 228
static int call (virConnectPtr conn, struct private_data *priv,
                 int flags, int proc_nr,
                 xdrproc_t args_filter, char *args,
                 xdrproc_t ret_filter, char *ret);
229 230
static int remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
                               virConnectAuthPtr auth, const char *authtype);
231
#if HAVE_SASL
232 233
static int remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                           virConnectAuthPtr auth, const char *mech);
234
#endif
235
#if HAVE_POLKIT
236 237
static int remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                             virConnectAuthPtr auth);
238
#endif /* HAVE_POLKIT */
239 240 241 242 243 244 245
#define error(conn, code, info)                                 \
    virReportErrorHelper(conn, VIR_FROM_QEMU, code, __FILE__,   \
                         __FUNCTION__, __LINE__, "%s", info)
#define errorf(conn, code, fmt...)                              \
    virReportErrorHelper(conn, VIR_FROM_QEMU, code, __FILE__,   \
                         __FUNCTION__, __LINE__, fmt)

246 247
static virDomainPtr get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain);
static virNetworkPtr get_nonnull_network (virConnectPtr conn, remote_nonnull_network network);
248
static virInterfacePtr get_nonnull_interface (virConnectPtr conn, remote_nonnull_interface iface);
249 250
static virStoragePoolPtr get_nonnull_storage_pool (virConnectPtr conn, remote_nonnull_storage_pool pool);
static virStorageVolPtr get_nonnull_storage_vol (virConnectPtr conn, remote_nonnull_storage_vol vol);
251
static virNodeDevicePtr get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev);
252
static virSecretPtr get_nonnull_secret (virConnectPtr conn, remote_nonnull_secret secret);
253 254
static void make_nonnull_domain (remote_nonnull_domain *dom_dst, virDomainPtr dom_src);
static void make_nonnull_network (remote_nonnull_network *net_dst, virNetworkPtr net_src);
D
Daniel Veillard 已提交
255
static void make_nonnull_interface (remote_nonnull_interface *interface_dst, virInterfacePtr interface_src);
256 257
static void make_nonnull_storage_pool (remote_nonnull_storage_pool *pool_dst, virStoragePoolPtr vol_src);
static void make_nonnull_storage_vol (remote_nonnull_storage_vol *vol_dst, virStorageVolPtr vol_src);
258
static void make_nonnull_secret (remote_nonnull_secret *secret_dst, virSecretPtr secret_src);
259
void remoteDomainEventFired(int watch, int fd, int event, void *data);
260 261
static void remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr);
void remoteDomainEventQueueFlush(int timer, void *opaque);
262 263 264 265 266 267 268
/*----------------------------------------------------------------------*/

/* Helper functions for remoteOpen. */
static char *get_transport_from_scheme (char *scheme);

/* GnuTLS functions used by remoteOpen. */
static int initialise_gnutls (virConnectPtr conn);
269
static gnutls_session_t negotiate_gnutls_on_connection (virConnectPtr conn, struct private_data *priv, int no_verify);
270

A
Atsushi SAKAI 已提交
271
#ifdef WITH_LIBVIRTD
272
static int
273
remoteStartup(int privileged ATTRIBUTE_UNUSED)
274 275 276 277 278 279 280
{
    /* Mark that we're inside the daemon so we can avoid
     * re-entering ourselves
     */
    inside_daemon = 1;
    return 0;
}
A
Atsushi SAKAI 已提交
281
#endif
282

283
#ifndef WIN32
284 285 286 287
/**
 * remoteFindServerPath:
 *
 * Tries to find the path to the libvirtd binary.
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 315 316 317 318 319
 * Returns path on success or NULL in case of error.
 */
static const char *
remoteFindDaemonPath(void)
{
    static const char *serverPaths[] = {
        SBINDIR "/libvirtd",
        SBINDIR "/libvirtd_dbg",
        NULL
    };
    int i;
    const char *customDaemon = getenv("LIBVIRTD_PATH");

    if (customDaemon)
        return(customDaemon);

    for (i = 0; serverPaths[i]; i++) {
        if (access(serverPaths[i], X_OK | R_OK) == 0) {
            return serverPaths[i];
        }
    }
    return NULL;
}

/**
 * qemuForkDaemon:
 *
 * Forks and try to launch the libvirtd daemon
 *
 * Returns 0 in case of success or -1 in case of detected error.
 */
320
static int
321 322 323
remoteForkDaemon(virConnectPtr conn)
{
    const char *daemonPath = remoteFindDaemonPath();
324
    const char *const daemonargs[] = { daemonPath, "--timeout=30", NULL };
325
    pid_t pid;
326 327

    if (!daemonPath) {
328
        error(conn, VIR_ERR_INTERNAL_ERROR, _("failed to find libvirtd binary"));
329
        return -1;
330 331
    }

332
    if (virExecDaemonize(NULL, daemonargs, NULL, NULL,
333 334
                         &pid, -1, NULL, NULL,
                         VIR_EXEC_CLEAR_CAPS,
335
                         NULL, NULL, NULL) < 0)
336
        return -1;
337

338
    return 0;
339
}
340
#endif
341

342
enum virDrvOpenRemoteFlags {
343
    VIR_DRV_OPEN_REMOTE_RO = (1 << 0),
344 345
    VIR_DRV_OPEN_REMOTE_USER      = (1 << 1), /* Use the per-user socket path */
    VIR_DRV_OPEN_REMOTE_AUTOSTART = (1 << 2), /* Autostart a per-user daemon */
346
};
347

348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
/*
 * URIs that this driver needs to handle:
 *
 * The easy answer:
 *   - Everything that no one else has yet claimed, but nothing if
 *     we're inside the libvirtd daemon
 *
 * The hard answer:
 *   - Plain paths (///var/lib/xen/xend-socket)  -> UNIX domain socket
 *   - xxx://servername/      -> TLS connection
 *   - xxx+tls://servername/  -> TLS connection
 *   - xxx+tls:///            -> TLS connection to localhost
 *   - xxx+tcp://servername/  -> TCP connection
 *   - xxx+tcp:///            -> TCP connection to localhost
 *   - xxx+unix:///           -> UNIX domain socket
 *   - xxx:///                -> UNIX domain socket
 */
366
static int
367 368 369 370
doRemoteOpen (virConnectPtr conn,
              struct private_data *priv,
              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
              int flags)
371
{
372
    int wakeupFD[2] = { -1, -1 };
373
    char *transport_str = NULL;
374 375 376 377 378 379 380
    enum {
        trans_tls,
        trans_unix,
        trans_ssh,
        trans_ext,
        trans_tcp,
    } transport;
381

382 383
    /* We handle *ALL*  URIs here. The caller has rejected any
     * URIs we don't care about */
384

385 386 387
    if (conn->uri) {
        if (!conn->uri->scheme) {
            /* This is the ///var/lib/xen/xend-socket local path style */
388
            transport = trans_unix;
389 390
        } else {
            transport_str = get_transport_from_scheme (conn->uri->scheme);
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
            if (!transport_str) {
                if (conn->uri->server)
                    transport = trans_tls;
                else
                    transport = trans_unix;
            } else {
                if (STRCASEEQ (transport_str, "tls"))
                    transport = trans_tls;
                else if (STRCASEEQ (transport_str, "unix"))
                    transport = trans_unix;
                else if (STRCASEEQ (transport_str, "ssh"))
                    transport = trans_ssh;
                else if (STRCASEEQ (transport_str, "ext"))
                    transport = trans_ext;
                else if (STRCASEEQ (transport_str, "tcp"))
                    transport = trans_tcp;
                else {
                    error (conn, VIR_ERR_INVALID_ARG,
                           _("remote_open: transport in URL not recognised "
                             "(should be tls|unix|ssh|ext|tcp)"));
                    return VIR_DRV_OPEN_ERROR;
                }
            }
        }
    } else {
        /* No URI, then must be probing so use UNIX socket */
        transport = trans_unix;
419
    }
420

421 422 423
    /* Local variables which we will initialise. These can
     * get freed in the failed: path.
     */
424 425
    char *name = NULL, *command = NULL, *sockname = NULL, *netcat = NULL;
    char *port = NULL, *authtype = NULL, *username = NULL;
426
    int no_verify = 0, no_tty = 0;
427
    char **cmd_argv = NULL;
428

429 430 431
    /* Return code from this function, and the private data. */
    int retcode = VIR_DRV_OPEN_ERROR;

432
    /* Remote server defaults to "localhost" if not specified. */
433
    if (conn->uri && conn->uri->port != 0) {
434
        if (virAsprintf(&port, "%d", conn->uri->port) == -1) goto out_of_memory;
435 436 437 438 439 440 441
    } else if (transport == trans_tls) {
        port = strdup (LIBVIRTD_TLS_PORT);
        if (!port) goto out_of_memory;
    } else if (transport == trans_tcp) {
        port = strdup (LIBVIRTD_TCP_PORT);
        if (!port) goto out_of_memory;
    } else
442
        port = NULL; /* Port not used for unix, ext., default for ssh */
443

444

445 446
    priv->hostname = strdup (conn->uri && conn->uri->server ?
                             conn->uri->server : "localhost");
447 448
    if (!priv->hostname)
        goto out_of_memory;
449 450
    if (conn->uri && conn->uri->user) {
        username = strdup (conn->uri->user);
451 452
        if (!username)
            goto out_of_memory;
453 454
    }

455 456 457 458 459
    /* Get the variables from the query string.
     * Then we need to reconstruct the query string (because
     * feasibly it might contain variables needed by the real driver,
     * although that won't be the case for now).
     */
460 461 462
    struct qparam_set *vars;
    struct qparam *var;
    int i;
463 464
    char *query;

465
    if (conn->uri) {
466
#ifdef HAVE_XMLURI_QUERY_RAW
467
        query = conn->uri->query_raw;
468
#else
469
        query = conn->uri->query;
470
#endif
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 505 506 507 508 509 510 511
        vars = qparam_query_parse (query);
        if (vars == NULL) goto failed;

        for (i = 0; i < vars->n; i++) {
            var = &vars->p[i];
            if (STRCASEEQ (var->name, "name")) {
                name = strdup (var->value);
                if (!name) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "command")) {
                command = strdup (var->value);
                if (!command) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "socket")) {
                sockname = strdup (var->value);
                if (!sockname) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "auth")) {
                authtype = strdup (var->value);
                if (!authtype) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "netcat")) {
                netcat = strdup (var->value);
                if (!netcat) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "no_verify")) {
                no_verify = atoi (var->value);
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "no_tty")) {
                no_tty = atoi (var->value);
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "debug")) {
                if (var->value &&
                    STRCASEEQ (var->value, "stdout"))
                    priv->debugLog = stdout;
                else
                    priv->debugLog = stderr;
            } else
                DEBUG("passing through variable '%s' ('%s') to remote end",
                      var->name, var->value);
        }
512

513 514
        /* Construct the original name. */
        if (!name) {
515 516 517
            if (conn->uri->scheme &&
                (STREQ(conn->uri->scheme, "remote") ||
                 STRPREFIX(conn->uri->scheme, "remote+"))) {
518 519 520 521 522
                /* Allow remote serve to probe */
                name = strdup("");
            } else {
                xmlURI tmpuri = {
                    .scheme = conn->uri->scheme,
523
#ifdef HAVE_XMLURI_QUERY_RAW
524
                    .query_raw = qparam_get_query (vars),
525
#else
526
                    .query = qparam_get_query (vars),
527
#endif
528 529 530 531 532 533 534 535 536
                    .path = conn->uri->path,
                    .fragment = conn->uri->fragment,
                };

                /* Evil, blank out transport scheme temporarily */
                if (transport_str) {
                    assert (transport_str[-1] == '+');
                    transport_str[-1] = '\0';
                }
537

538
                name = (char *) xmlSaveUri (&tmpuri);
539

540 541 542 543 544 545 546 547 548 549
#ifdef HAVE_XMLURI_QUERY_RAW
                VIR_FREE(tmpuri.query_raw);
#else
                VIR_FREE(tmpuri.query);
#endif

                /* Restore transport scheme */
                if (transport_str)
                    transport_str[-1] = '+';
            }
550 551
        }

552 553 554 555 556
        free_qparam_set (vars);
    } else {
        /* Probe URI server side */
        name = strdup("");
    }
557

558
    if (!name) {
559
        virReportOOMError(conn);
560
        goto failed;
561 562
    }

563
    DEBUG("proceeding with name = %s", name);
564

565 566 567 568 569 570 571
    /* For ext transport, command is required. */
    if (transport == trans_ext && !command) {
        error (conn, VIR_ERR_INVALID_ARG,
               _("remote_open: for 'ext' transport, command is required"));
        goto failed;
    }

572 573 574 575
    /* Connect to the remote service. */
    switch (transport) {
    case trans_tls:
        if (initialise_gnutls (conn) == -1) goto failed;
576
        priv->uses_tls = 1;
577 578 579 580 581 582

        /*FALLTHROUGH*/
    case trans_tcp: {
        // http://people.redhat.com/drepper/userapi-ipv6.html
        struct addrinfo *res, *r;
        struct addrinfo hints;
583
        int saved_errno = EINVAL;
584 585 586
        memset (&hints, 0, sizeof hints);
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_ADDRCONFIG;
587
        int e = getaddrinfo (priv->hostname, port, &hints, &res);
588
        if (e != 0) {
589 590 591
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to resolve hostname '%s': %s"),
                    priv->hostname, gai_strerror (e));
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
            goto failed;
        }

        /* Try to connect to each returned address in turn. */
        /* XXX This loop contains a subtle problem.  In the case
         * where a host is accessible over IPv4 and IPv6, it will
         * try the IPv4 and IPv6 addresses in turn.  However it
         * should be able to present different client certificates
         * (because the commonName field in a client cert contains
         * the client IP address, which is different for IPv4 and
         * IPv6).  At the moment we only have a single client
         * certificate, and no way to specify what address family
         * that certificate belongs to.
         */
        for (r = res; r; r = r->ai_next) {
            int no_slow_start = 1;

609 610
            priv->sock = socket (r->ai_family, SOCK_STREAM, 0);
            if (priv->sock == -1) {
J
Jim Meyering 已提交
611
                saved_errno = errno;
612 613 614 615
                continue;
            }

            /* Disable Nagle - Dan Berrange. */
616
            setsockopt (priv->sock,
617 618 619
                        IPPROTO_TCP, TCP_NODELAY, (void *)&no_slow_start,
                        sizeof no_slow_start);

620
            if (connect (priv->sock, r->ai_addr, r->ai_addrlen) == -1) {
J
Jim Meyering 已提交
621
                saved_errno = errno;
622
                close (priv->sock);
623 624 625
                continue;
            }

626 627
            if (priv->uses_tls) {
                priv->session =
628
                    negotiate_gnutls_on_connection
629
                      (conn, priv, no_verify);
630 631 632
                if (!priv->session) {
                    close (priv->sock);
                    priv->sock = -1;
633 634 635 636 637 638 639
                    continue;
                }
            }
            goto tcp_connected;
        }

        freeaddrinfo (res);
640
        virReportSystemError(conn, saved_errno,
641
                             _("unable to connect to libvirtd at '%s'"),
642
                             priv->hostname);
643 644 645 646 647 648 649 650 651 652
        goto failed;

       tcp_connected:
        freeaddrinfo (res);

        // NB. All versioning is done by the RPC headers, so we don't
        // need to worry (at this point anyway) about versioning.
        break;
    }

653
#ifndef WIN32
654 655
    case trans_unix: {
        if (!sockname) {
656
            if (flags & VIR_DRV_OPEN_REMOTE_USER) {
657
                char *userdir = virGetUserDirectory(conn, getuid());
658

659
                if (!userdir)
660
                    goto failed;
661

662 663
                if (virAsprintf(&sockname, "@%s" LIBVIRTD_USER_UNIX_SOCKET, userdir) < 0) {
                    VIR_FREE(userdir);
664
                    goto out_of_memory;
665 666
                }
                VIR_FREE(userdir);
667
            } else {
668
                if (flags & VIR_DRV_OPEN_REMOTE_RO)
669 670 671
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET_RO);
                else
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET);
672 673
                if (sockname == NULL)
                    goto out_of_memory;
674
            }
675 676 677 678 679 680
        }

#ifndef UNIX_PATH_MAX
#define UNIX_PATH_MAX(addr) (sizeof (addr).sun_path)
#endif
        struct sockaddr_un addr;
681 682
        int trials = 0;

683 684
        memset (&addr, 0, sizeof addr);
        addr.sun_family = AF_UNIX;
C
Chris Lalancette 已提交
685 686 687 688 689
        if (virStrcpyStatic(addr.sun_path, sockname) == NULL) {
            errorf(conn, VIR_ERR_INTERNAL_ERROR,
                   _("Socket %s too big for destination"), sockname);
            goto failed;
        }
690 691
        if (addr.sun_path[0] == '@')
            addr.sun_path[0] = '\0';
692

693 694 695
      autostart_retry:
        priv->sock = socket (AF_UNIX, SOCK_STREAM, 0);
        if (priv->sock == -1) {
696 697
            virReportSystemError(conn, errno, "%s",
                                 _("unable to create socket"));
698 699
            goto failed;
        }
700 701 702 703 704 705 706 707 708 709
        if (connect (priv->sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
            /* We might have to autostart the daemon in some cases....
             * It takes a short while for the daemon to startup, hence we
             * have a number of retries, with a small sleep. This will
             * sometimes cause multiple daemons to be started - this is
             * ok because the duplicates will fail to bind to the socket
             * and immediately exit, leaving just one daemon.
             */
            if (errno == ECONNREFUSED &&
                flags & VIR_DRV_OPEN_REMOTE_AUTOSTART &&
710
                trials < 20) {
711 712
                close(priv->sock);
                priv->sock = -1;
713 714
                if (trials > 0 ||
                    remoteForkDaemon(conn) == 0) {
715
                    trials++;
716
                    usleep(1000 * 100 * trials);
717 718 719
                    goto autostart_retry;
                }
            }
720 721 722
            virReportSystemError(conn, errno,
                                 _("unable to connect to '%s'"),
                                 sockname);
723 724 725 726 727 728 729
            goto failed;
        }

        break;
    }

    case trans_ssh: {
730
        int j, nr_args = 6;
731 732 733

        if (username) nr_args += 2; /* For -l username */
        if (no_tty) nr_args += 5;   /* For -T -o BatchMode=yes -e none */
734
        if (port) nr_args += 2;     /* For -p port */
735

736
        command = command ? command : strdup ("ssh");
737 738
        if (command == NULL)
            goto out_of_memory;
739 740

        // Generate the final command argv[] array.
741
        //   ssh [-p $port] [-l $username] $hostname $netcat -U $sockname [NULL]
742 743
        if (VIR_ALLOC_N(cmd_argv, nr_args) < 0)
            goto out_of_memory;
J
Jim Meyering 已提交
744

745 746
        j = 0;
        cmd_argv[j++] = strdup (command);
747 748 749 750
        if (port) {
            cmd_argv[j++] = strdup ("-p");
            cmd_argv[j++] = strdup (port);
        }
751 752 753 754
        if (username) {
            cmd_argv[j++] = strdup ("-l");
            cmd_argv[j++] = strdup (username);
        }
755 756 757 758 759 760 761
        if (no_tty) {
            cmd_argv[j++] = strdup ("-T");
            cmd_argv[j++] = strdup ("-o");
            cmd_argv[j++] = strdup ("BatchMode=yes");
            cmd_argv[j++] = strdup ("-e");
            cmd_argv[j++] = strdup ("none");
        }
762
        cmd_argv[j++] = strdup (priv->hostname);
763 764
        cmd_argv[j++] = strdup (netcat ? netcat : "nc");
        cmd_argv[j++] = strdup ("-U");
765 766 767 768
        cmd_argv[j++] = strdup (sockname ? sockname :
                                (flags & VIR_CONNECT_RO
                                 ? LIBVIRTD_PRIV_UNIX_SOCKET_RO
                                 : LIBVIRTD_PRIV_UNIX_SOCKET));
769 770
        cmd_argv[j++] = 0;
        assert (j == nr_args);
771 772 773
        for (j = 0; j < (nr_args-1); j++)
            if (cmd_argv[j] == NULL)
                goto out_of_memory;
774 775 776 777
    }

        /*FALLTHROUGH*/
    case trans_ext: {
778
        pid_t pid;
779 780 781 782 783 784 785
        int sv[2];

        /* Fork off the external process.  Use socketpair to create a private
         * (unnamed) Unix domain socket to the child process so we don't have
         * to faff around with two file descriptors (a la 'pipe(2)').
         */
        if (socketpair (PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
786 787
            virReportSystemError(conn, errno, "%s",
                                 _("unable to create socket pair"));
788 789 790
            goto failed;
        }

791
        if (virExec(conn, (const char**)cmd_argv, NULL, NULL,
792 793
                    &pid, sv[1], &(sv[1]), NULL,
                    VIR_EXEC_CLEAR_CAPS) < 0)
794 795 796 797
            goto failed;

        /* Parent continues here. */
        close (sv[1]);
798
        priv->sock = sv[0];
799
        priv->pid = pid;
800
    }
801 802 803 804 805 806 807
#else /* WIN32 */

    case trans_unix:
    case trans_ssh:
    case trans_ext:
        error (conn, VIR_ERR_INVALID_ARG,
               _("transport methods unix, ssh and ext are not supported under Windows"));
808
        goto failed;
809 810 811

#endif /* WIN32 */

812 813
    } /* switch (transport) */

814
    if (virSetNonBlock(priv->sock) < 0) {
815 816
        virReportSystemError(conn, errno, "%s",
                             _("unable to make socket non-blocking"));
817 818 819 820
        goto failed;
    }

    if (pipe(wakeupFD) < 0) {
821 822
        virReportSystemError(conn, errno, "%s",
                             _("unable to make pipe"));
823 824 825 826
        goto failed;
    }
    priv->wakeupReadFD = wakeupFD[0];
    priv->wakeupSendFD = wakeupFD[1];
827 828

    /* Try and authenticate with server */
829
    if (remoteAuthenticate(conn, priv, 1, auth, authtype) == -1)
830 831
        goto failed;

832 833 834
    /* Finally we can call the remote side's open function. */
    remote_open_args args = { &name, flags };

835
    if (call (conn, priv, REMOTE_CALL_IN_OPEN, REMOTE_PROC_OPEN,
836 837 838 839
              (xdrproc_t) xdr_remote_open_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto failed;

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    /* Now try and find out what URI the daemon used */
    if (conn->uri == NULL) {
        remote_get_uri_ret uriret;
        int urierr;

        memset (&uriret, 0, sizeof uriret);
        urierr = call (conn, priv,
                       REMOTE_CALL_IN_OPEN | REMOTE_CALL_QUIET_MISSING_RPC,
                       REMOTE_PROC_GET_URI,
                       (xdrproc_t) xdr_void, (char *) NULL,
                       (xdrproc_t) xdr_remote_get_uri_ret, (char *) &uriret);
        if (urierr == -2) {
            /* Should not really happen, since we only probe local libvirtd's,
               & the library should always match the daemon. Only case is post
               RPM upgrade where an old daemon instance is still running with
               new client. Too bad. It is not worth the hassle to fix this */
            error (conn, VIR_ERR_INTERNAL_ERROR, _("unable to auto-detect URI"));
            goto failed;
        }
        if (urierr == -1) {
            goto failed;
        }

        DEBUG("Auto-probed URI is %s", uriret.uri);
        conn->uri = xmlParseURI(uriret.uri);
        VIR_FREE(uriret.uri);
        if (!conn->uri) {
867
            virReportOOMError (conn);
868 869 870 871
            goto failed;
        }
    }

872 873 874 875 876 877 878 879 880 881 882 883
    if(VIR_ALLOC(priv->callbackList)<0) {
        error(conn, VIR_ERR_INVALID_ARG, _("Error allocating callbacks list"));
        goto failed;
    }

    if(VIR_ALLOC(priv->domainEvents)<0) {
        error(conn, VIR_ERR_INVALID_ARG, _("Error allocating domainEvents"));
        goto failed;
    }

    DEBUG0("Adding Handler for remote events");
    /* Set up a callback to listen on the socket data */
884
    if ((priv->watch = virEventAddHandle(priv->sock,
885
                                         VIR_EVENT_HANDLE_READABLE,
886
                                         remoteDomainEventFired,
887
                                         conn, NULL)) < 0) {
888 889 890 891 892 893
        DEBUG0("virEventAddHandle failed: No addHandleImpl defined."
               " continuing without events.");
    } else {

        DEBUG0("Adding Timeout for remote event queue flushing");
        if ( (priv->eventFlushTimer = virEventAddTimeout(-1,
894 895
                                                         remoteDomainEventQueueFlush,
                                                         conn, NULL)) < 0) {
896 897
            DEBUG0("virEventAddTimeout failed: No addTimeoutImpl defined. "
                    "continuing without events.");
898
            virEventRemoveHandle(priv->watch);
899
            priv->watch = -1;
900 901
        }
    }
902 903 904
    /* Successful. */
    retcode = VIR_DRV_OPEN_SUCCESS;

905
 cleanup:
906
    /* Free up the URL and strings. */
907 908 909 910 911 912 913
    VIR_FREE(name);
    VIR_FREE(command);
    VIR_FREE(sockname);
    VIR_FREE(authtype);
    VIR_FREE(netcat);
    VIR_FREE(username);
    VIR_FREE(port);
914 915 916
    if (cmd_argv) {
        char **cmd_argv_ptr = cmd_argv;
        while (*cmd_argv_ptr) {
917
            VIR_FREE(*cmd_argv_ptr);
918 919
            cmd_argv_ptr++;
        }
920
        VIR_FREE(cmd_argv);
921 922 923
    }

    return retcode;
924 925

 out_of_memory:
926
    virReportOOMError (conn);
927 928 929 930 931 932 933 934 935

 failed:
    /* Close the socket if we failed. */
    if (priv->sock >= 0) {
        if (priv->uses_tls && priv->session) {
            gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
            gnutls_deinit (priv->session);
        }
        close (priv->sock);
936
#ifndef WIN32
937 938 939 940 941 942 943 944
        if (priv->pid > 0) {
            pid_t reap;
            do {
                reap = waitpid(priv->pid, NULL, 0);
                if (reap == -1 && errno == EINTR)
                    continue;
            } while (reap != -1 && reap != priv->pid);
        }
945
#endif
946 947
    }

948 949 950 951 952
    if (wakeupFD[0] >= 0) {
        close(wakeupFD[0]);
        close(wakeupFD[1]);
    }

953
    VIR_FREE(priv->hostname);
954
    goto cleanup;
955 956
}

957 958
static struct private_data *
remoteAllocPrivateData(virConnectPtr conn)
959
{
960
    struct private_data *priv;
961
    if (VIR_ALLOC(priv) < 0) {
962 963
        virReportOOMError(conn);
        return NULL;
964 965
    }

966 967 968 969
    if (virMutexInit(&priv->lock) < 0) {
        error(conn, VIR_ERR_INTERNAL_ERROR,
              _("cannot initialize mutex"));
        VIR_FREE(priv);
970
        return NULL;
971 972 973
    }
    remoteDriverLock(priv);
    priv->localUses = 1;
974
    priv->watch = -1;
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    priv->sock = -1;

    return priv;
}

static int
remoteOpenSecondaryDriver(virConnectPtr conn,
                          virConnectAuthPtr auth,
                          int flags,
                          struct private_data **priv)
{
    int ret;
    int rflags = 0;

    if (!((*priv) = remoteAllocPrivateData(conn)))
        return VIR_DRV_OPEN_ERROR;

    if (flags & VIR_CONNECT_RO)
        rflags |= VIR_DRV_OPEN_REMOTE_RO;

    ret = doRemoteOpen(conn, *priv, auth, rflags);
    if (ret != VIR_DRV_OPEN_SUCCESS) {
        remoteDriverUnlock(*priv);
        VIR_FREE(*priv);
    } else {
        (*priv)->localUses = 1;
        remoteDriverUnlock(*priv);
    }

    return ret;
}

static virDrvOpenStatus
remoteOpen (virConnectPtr conn,
            virConnectAuthPtr auth,
            int flags)
{
    struct private_data *priv;
    int ret, rflags = 0;
1014
    const char *autostart = getenv("LIBVIRT_AUTOSTART");
1015

1016
    if (inside_daemon && (!conn->uri || (conn->uri && !conn->uri->server)))
1017 1018 1019 1020
        return VIR_DRV_OPEN_DECLINED;

    if (!(priv = remoteAllocPrivateData(conn)))
        return VIR_DRV_OPEN_ERROR;
1021

1022
    if (flags & VIR_CONNECT_RO)
1023 1024
        rflags |= VIR_DRV_OPEN_REMOTE_RO;

1025 1026 1027 1028 1029 1030 1031 1032 1033
    /*
     * If no servername is given, and no +XXX
     * transport is listed, or transport is unix,
     * and path is /session, and uid is unprivileged
     * then auto-spawn a daemon.
     */
    if (conn->uri &&
        !conn->uri->server &&
        conn->uri->path &&
D
Daniel P. Berrange 已提交
1034
        conn->uri->scheme &&
1035 1036
        ((strchr(conn->uri->scheme, '+') == 0)||
         (strstr(conn->uri->scheme, "+unix") != NULL)) &&
1037 1038
        (STREQ(conn->uri->path, "/session") ||
         STRPREFIX(conn->uri->scheme, "test+")) &&
1039 1040 1041
        getuid() > 0) {
        DEBUG0("Auto-spawn user daemon instance");
        rflags |= VIR_DRV_OPEN_REMOTE_USER;
1042 1043 1044
        if (!autostart ||
            STRNEQ(autostart, "0"))
            rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
1045 1046 1047
    }

    /*
J
John Levon 已提交
1048 1049 1050 1051
     * If URI is NULL, then do a UNIX connection possibly auto-spawning
     * unprivileged server and probe remote server for URI. On Solaris,
     * this isn't supported, but we may be privileged enough to connect
     * to the UNIX socket anyway.
1052 1053 1054
     */
    if (!conn->uri) {
        DEBUG0("Auto-probe remote URI");
J
John Levon 已提交
1055
#ifndef __sun
1056 1057 1058
        if (getuid() > 0) {
            DEBUG0("Auto-spawn user daemon instance");
            rflags |= VIR_DRV_OPEN_REMOTE_USER;
1059 1060 1061
            if (!autostart ||
                STRNEQ(autostart, "0"))
                rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
1062
        }
J
John Levon 已提交
1063
#endif
1064
    }
1065

1066
    ret = doRemoteOpen(conn, priv, auth, rflags);
1067 1068
    if (ret != VIR_DRV_OPEN_SUCCESS) {
        conn->privateData = NULL;
1069
        remoteDriverUnlock(priv);
1070
        VIR_FREE(priv);
1071 1072
    } else {
        conn->privateData = priv;
1073
        remoteDriverUnlock(priv);
1074 1075 1076 1077 1078
    }
    return ret;
}


1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
/* In a string "driver+transport" return a pointer to "transport". */
static char *
get_transport_from_scheme (char *scheme)
{
    char *p = strchr (scheme, '+');
    return p ? p+1 : 0;
}

/* GnuTLS functions used by remoteOpen. */
static gnutls_certificate_credentials_t x509_cred;

1090 1091

static int
1092
check_cert_file (virConnectPtr conn, const char *type, const char *file)
1093 1094 1095
{
    struct stat sb;
    if (stat(file, &sb) < 0) {
1096 1097 1098
        virReportSystemError(conn, errno,
                             _("Cannot access %s '%s'"),
                             type, file);
1099 1100 1101 1102 1103 1104
        return -1;
    }
    return 0;
}


1105
static int
1106
initialise_gnutls (virConnectPtr conn)
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
{
    static int initialised = 0;
    int err;

    if (initialised) return 0;

    gnutls_global_init ();

    /* X509 stuff */
    err = gnutls_certificate_allocate_credentials (&x509_cred);
    if (err) {
1118 1119 1120
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to allocate TLS credentials: %s"),
                gnutls_strerror (err));
1121 1122 1123
        return -1;
    }

1124

1125
    if (check_cert_file(conn, "CA certificate", LIBVIRT_CACERT) < 0)
1126
        return -1;
1127
    if (check_cert_file(conn, "client key", LIBVIRT_CLIENTKEY) < 0)
1128
        return -1;
1129
    if (check_cert_file(conn, "client certificate", LIBVIRT_CLIENTCERT) < 0)
1130 1131
        return -1;

1132
    /* Set the trusted CA cert. */
1133
    DEBUG("loading CA file %s", LIBVIRT_CACERT);
1134 1135 1136 1137
    err =
        gnutls_certificate_set_x509_trust_file (x509_cred, LIBVIRT_CACERT,
                                                GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1138 1139 1140
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load CA certificate: %s"),
                gnutls_strerror (err));
1141 1142 1143 1144
        return -1;
    }

    /* Set the client certificate and private key. */
1145 1146
    DEBUG("loading client cert and key from files %s and %s",
          LIBVIRT_CLIENTCERT, LIBVIRT_CLIENTKEY);
1147 1148 1149 1150 1151 1152
    err =
        gnutls_certificate_set_x509_key_file (x509_cred,
                                              LIBVIRT_CLIENTCERT,
                                              LIBVIRT_CLIENTKEY,
                                              GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1153 1154 1155
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load private key/certificate: %s"),
                gnutls_strerror (err));
1156 1157 1158 1159 1160 1161 1162
        return -1;
    }

    initialised = 1;
    return 0;
}

1163
static int verify_certificate (virConnectPtr conn, struct private_data *priv, gnutls_session_t session);
1164 1165 1166

static gnutls_session_t
negotiate_gnutls_on_connection (virConnectPtr conn,
1167 1168
                                struct private_data *priv,
                                int no_verify)
1169 1170 1171 1172 1173 1174 1175 1176 1177
{
    const int cert_type_priority[3] = {
        GNUTLS_CRT_X509,
        GNUTLS_CRT_OPENPGP,
        0
    };
    int err;
    gnutls_session_t session;

1178
    /* Initialize TLS session
1179 1180 1181
     */
    err = gnutls_init (&session, GNUTLS_CLIENT);
    if (err) {
1182 1183 1184
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to initialize TLS client: %s"),
                gnutls_strerror (err));
1185 1186 1187 1188 1189 1190
        return NULL;
    }

    /* Use default priorities */
    err = gnutls_set_default_priority (session);
    if (err) {
1191 1192 1193
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set TLS algorithm priority: %s"),
                gnutls_strerror (err));
1194 1195 1196 1197 1198 1199
        return NULL;
    }
    err =
        gnutls_certificate_type_set_priority (session,
                                              cert_type_priority);
    if (err) {
1200 1201 1202
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set certificate priority: %s"),
                gnutls_strerror (err));
1203 1204 1205 1206 1207 1208 1209
        return NULL;
    }

    /* put the x509 credentials to the current session
     */
    err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
    if (err) {
1210 1211 1212
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set session credentials: %s"),
                gnutls_strerror (err));
1213 1214 1215 1216
        return NULL;
    }

    gnutls_transport_set_ptr (session,
1217
                              (gnutls_transport_ptr_t) (long) priv->sock);
1218 1219 1220 1221 1222 1223 1224

    /* Perform the TLS handshake. */
 again:
    err = gnutls_handshake (session);
    if (err < 0) {
        if (err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
            goto again;
1225 1226 1227
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS handshake: %s"),
                gnutls_strerror (err));
1228 1229 1230 1231
        return NULL;
    }

    /* Verify certificate. */
1232
    if (verify_certificate (conn, priv, session) == -1) {
1233 1234 1235
        DEBUG0("failed to verify peer's certificate");
        if (!no_verify) return NULL;
    }
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246

    /* At this point, the server is verifying _our_ certificate, IP address,
     * etc.  If we make the grade, it will send us a '\1' byte.
     */
    char buf[1];
    int len;
 again_2:
    len = gnutls_record_recv (session, buf, 1);
    if (len < 0 && len != GNUTLS_E_UNEXPECTED_PACKET_LENGTH) {
        if (len == GNUTLS_E_AGAIN || len == GNUTLS_E_INTERRUPTED)
            goto again_2;
1247 1248 1249
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS initialization: %s"),
                gnutls_strerror (len));
1250 1251 1252
        return NULL;
    }
    if (len != 1 || buf[0] != '\1') {
1253
        error (conn, VIR_ERR_RPC,
1254
               _("server verification (of our certificate or IP address) failed\n"));
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
        return NULL;
    }

#if 0
    /* Print session info. */
    print_info (session);
#endif

    return session;
}

static int
verify_certificate (virConnectPtr conn ATTRIBUTE_UNUSED,
1268 1269
                    struct private_data *priv,
                    gnutls_session_t session)
1270 1271 1272 1273 1274 1275 1276 1277
{
    int ret;
    unsigned int status;
    const gnutls_datum_t *certs;
    unsigned int nCerts, i;
    time_t now;

    if ((ret = gnutls_certificate_verify_peers2 (session, &status)) < 0) {
1278 1279 1280
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to verify server certificate: %s"),
                gnutls_strerror (ret));
1281 1282
        return -1;
    }
1283

1284
    if ((now = time(NULL)) == ((time_t)-1)) {
1285 1286
        virReportSystemError(conn, errno, "%s",
                             _("cannot get current time"));
1287 1288 1289 1290
        return -1;
    }

    if (status != 0) {
1291
        const char *reason = _("Invalid certificate");
1292 1293

        if (status & GNUTLS_CERT_INVALID)
1294
            reason = _("The certificate is not trusted.");
1295

1296
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1297
            reason = _("The certificate hasn't got a known issuer.");
1298

1299
        if (status & GNUTLS_CERT_REVOKED)
1300
            reason = _("The certificate has been revoked.");
1301 1302

#ifndef GNUTLS_1_0_COMPAT
1303
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1304
            reason = _("The certificate uses an insecure algorithm");
1305
#endif
1306

1307 1308 1309
        errorf (conn, VIR_ERR_RPC,
                _("server certificate failed validation: %s"),
                reason);
1310 1311 1312 1313
        return -1;
    }

    if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) {
1314
        error (conn, VIR_ERR_RPC, _("Certificate type is not X.509"));
1315 1316
        return -1;
    }
1317

1318
    if (!(certs = gnutls_certificate_get_peers(session, &nCerts))) {
1319
        error (conn, VIR_ERR_RPC, _("gnutls_certificate_get_peers failed"));
1320 1321
        return -1;
    }
1322

1323 1324 1325 1326 1327
    for (i = 0 ; i < nCerts ; i++) {
        gnutls_x509_crt_t cert;

        ret = gnutls_x509_crt_init (&cert);
        if (ret < 0) {
1328 1329 1330
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to initialize certificate: %s"),
                    gnutls_strerror (ret));
1331 1332
            return -1;
        }
1333

1334 1335
        ret = gnutls_x509_crt_import (cert, &certs[i], GNUTLS_X509_FMT_DER);
        if (ret < 0) {
1336 1337 1338
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to import certificate: %s"),
                    gnutls_strerror (ret));
1339 1340 1341
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1342

1343
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1344
            error (conn, VIR_ERR_RPC, _("The certificate has expired"));
1345 1346 1347
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1348

1349
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1350
            error (conn, VIR_ERR_RPC, _("The certificate is not yet activated"));
1351 1352 1353
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1354

1355
        if (i == 0) {
1356
            if (!gnutls_x509_crt_check_hostname (cert, priv->hostname)) {
1357 1358 1359
                errorf(conn, VIR_ERR_RPC,
                       _("Certificate's owner does not match the hostname (%s)"),
                       priv->hostname);
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
                gnutls_x509_crt_deinit (cert);
                return -1;
            }
        }
    }

    return 0;
}

/*----------------------------------------------------------------------*/

1371

1372
static int
1373
doRemoteClose (virConnectPtr conn, struct private_data *priv)
1374 1375 1376 1377 1378 1379
{
    if (call (conn, priv, 0, REMOTE_PROC_CLOSE,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        return -1;

1380 1381 1382 1383 1384
    if (priv->eventFlushTimer >= 0) {
        /* Remove timeout */
        virEventRemoveTimeout(priv->eventFlushTimer);
        /* Remove handle for remote events */
        virEventRemoveHandle(priv->watch);
1385
        priv->watch = -1;
1386
    }
1387

1388
    /* Close socket. */
1389
    if (priv->uses_tls && priv->session) {
1390
        gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
1391 1392 1393 1394 1395 1396
        gnutls_deinit (priv->session);
    }
#if HAVE_SASL
    if (priv->saslconn)
        sasl_dispose (&priv->saslconn);
#endif
1397 1398
    close (priv->sock);

1399
#ifndef WIN32
1400 1401 1402 1403 1404 1405 1406 1407
    if (priv->pid > 0) {
        pid_t reap;
        do {
            reap = waitpid(priv->pid, NULL, 0);
            if (reap == -1 && errno == EINTR)
                continue;
        } while (reap != -1 && reap != priv->pid);
    }
1408
#endif
1409 1410 1411 1412 1413
    if (priv->wakeupReadFD >= 0) {
        close(priv->wakeupReadFD);
        close(priv->wakeupSendFD);
    }

1414

1415
    /* Free hostname copy */
1416
    free (priv->hostname);
1417

1418
    /* See comment for remoteType. */
1419
    free (priv->type);
1420

1421 1422 1423 1424 1425 1426
    /* Free callback list */
    virDomainEventCallbackListFree(priv->callbackList);

    /* Free queued events */
    virDomainEventQueueFree(priv->domainEvents);

1427 1428 1429
    return 0;
}

1430 1431 1432
static int
remoteClose (virConnectPtr conn)
{
1433
    int ret = 0;
1434
    struct private_data *priv = conn->privateData;
1435

1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        ret = doRemoteClose(conn, priv);
        conn->privateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE (priv);
    }
    if (priv)
        remoteDriverUnlock(priv);
1447 1448 1449 1450

    return ret;
}

1451 1452 1453
static int
remoteSupportsFeature (virConnectPtr conn, int feature)
{
1454
    int rv = -1;
1455 1456
    remote_supports_feature_args args;
    remote_supports_feature_ret ret;
1457
    struct private_data *priv = conn->privateData;
1458

1459 1460
    remoteDriverLock(priv);

1461
    /* VIR_DRV_FEATURE_REMOTE* features are handled directly. */
1462 1463 1464 1465
    if (feature == VIR_DRV_FEATURE_REMOTE) {
        rv = 1;
        goto done;
    }
1466 1467 1468 1469 1470 1471 1472

    args.feature = feature;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_SUPPORTS_FEATURE,
              (xdrproc_t) xdr_remote_supports_feature_args, (char *) &args,
              (xdrproc_t) xdr_remote_supports_feature_ret, (char *) &ret) == -1)
1473 1474 1475
        goto done;

    rv = ret.supported;
1476

1477
done:
1478
    remoteDriverUnlock(priv);
1479
    return rv;
1480 1481
}

1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
/* Unfortunately this function is defined to return a static string.
 * Since the remote end always answers with the same type (for a
 * single connection anyway) we cache the type in the connection's
 * private data, and free it when we close the connection.
 *
 * See also:
 * http://www.redhat.com/archives/libvir-list/2007-February/msg00096.html
 */
static const char *
remoteType (virConnectPtr conn)
{
1493
    char *rv = NULL;
1494
    remote_get_type_ret ret;
1495
    struct private_data *priv = conn->privateData;
1496

1497 1498
    remoteDriverLock(priv);

1499
    /* Cached? */
1500 1501 1502 1503
    if (priv->type) {
        rv = priv->type;
        goto done;
    }
1504 1505 1506 1507 1508

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_GET_TYPE,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_get_type_ret, (char *) &ret) == -1)
1509
        goto done;
1510 1511

    /* Stash. */
1512 1513 1514
    rv = priv->type = ret.type;

done:
1515
    remoteDriverUnlock(priv);
1516
    return rv;
1517 1518 1519
}

static int
1520
remoteGetVersion (virConnectPtr conn, unsigned long *hvVer)
1521
{
1522
    int rv = -1;
1523
    remote_get_version_ret ret;
1524
    struct private_data *priv = conn->privateData;
1525

1526 1527
    remoteDriverLock(priv);

1528 1529 1530 1531
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_GET_VERSION,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_get_version_ret, (char *) &ret) == -1)
1532
        goto done;
1533 1534

    if (hvVer) *hvVer = ret.hv_ver;
1535 1536 1537
    rv = 0;

done:
1538
    remoteDriverUnlock(priv);
1539
    return rv;
1540 1541
}

1542 1543 1544
static char *
remoteGetHostname (virConnectPtr conn)
{
1545
    char *rv = NULL;
1546
    remote_get_hostname_ret ret;
1547
    struct private_data *priv = conn->privateData;
1548

1549 1550
    remoteDriverLock(priv);

1551 1552 1553 1554
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_GET_HOSTNAME,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_get_hostname_ret, (char *) &ret) == -1)
1555
        goto done;
1556 1557

    /* Caller frees this. */
1558 1559 1560
    rv = ret.hostname;

done:
1561
    remoteDriverUnlock(priv);
1562
    return rv;
1563 1564
}

1565 1566 1567
static int
remoteGetMaxVcpus (virConnectPtr conn, const char *type)
{
1568
    int rv = -1;
1569 1570
    remote_get_max_vcpus_args args;
    remote_get_max_vcpus_ret ret;
1571
    struct private_data *priv = conn->privateData;
1572

1573 1574
    remoteDriverLock(priv);

1575
    memset (&ret, 0, sizeof ret);
1576
    args.type = type == NULL ? NULL : (char **) &type;
1577 1578 1579
    if (call (conn, priv, 0, REMOTE_PROC_GET_MAX_VCPUS,
              (xdrproc_t) xdr_remote_get_max_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_remote_get_max_vcpus_ret, (char *) &ret) == -1)
1580 1581 1582
        goto done;

    rv = ret.max_vcpus;
1583

1584
done:
1585
    remoteDriverUnlock(priv);
1586
    return rv;
1587 1588 1589 1590 1591
}

static int
remoteNodeGetInfo (virConnectPtr conn, virNodeInfoPtr info)
{
1592
    int rv = -1;
1593
    remote_node_get_info_ret ret;
1594
    struct private_data *priv = conn->privateData;
1595

1596 1597
    remoteDriverLock(priv);

1598 1599 1600 1601
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_GET_INFO,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_node_get_info_ret, (char *) &ret) == -1)
1602
        goto done;
1603

C
Chris Lalancette 已提交
1604 1605
    if (virStrcpyStatic(info->model, ret.model) == NULL)
        goto done;
1606 1607 1608 1609 1610 1611 1612
    info->memory = ret.memory;
    info->cpus = ret.cpus;
    info->mhz = ret.mhz;
    info->nodes = ret.nodes;
    info->sockets = ret.sockets;
    info->cores = ret.cores;
    info->threads = ret.threads;
1613 1614 1615
    rv = 0;

done:
1616
    remoteDriverUnlock(priv);
1617
    return rv;
1618 1619 1620 1621 1622
}

static char *
remoteGetCapabilities (virConnectPtr conn)
{
1623
    char *rv = NULL;
1624
    remote_get_capabilities_ret ret;
1625
    struct private_data *priv = conn->privateData;
1626

1627 1628
    remoteDriverLock(priv);

1629 1630 1631 1632
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_GET_CAPABILITIES,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_get_capabilities_ret, (char *)&ret) == -1)
1633
        goto done;
1634 1635

    /* Caller frees this. */
1636 1637 1638
    rv = ret.capabilities;

done:
1639
    remoteDriverUnlock(priv);
1640
    return rv;
1641 1642
}

1643 1644 1645 1646 1647 1648
static int
remoteNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
1649
    int rv = -1;
1650 1651 1652
    remote_node_get_cells_free_memory_args args;
    remote_node_get_cells_free_memory_ret ret;
    int i;
1653
    struct private_data *priv = conn->privateData;
1654

1655 1656
    remoteDriverLock(priv);

1657 1658 1659 1660 1661
    if (maxCells > REMOTE_NODE_MAX_CELLS) {
        errorf (conn, VIR_ERR_RPC,
                _("too many NUMA cells: %d > %d"),
                maxCells,
                REMOTE_NODE_MAX_CELLS);
1662
        goto done;
1663 1664 1665 1666 1667 1668 1669 1670 1671
    }

    args.startCell = startCell;
    args.maxCells = maxCells;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_GET_CELLS_FREE_MEMORY,
              (xdrproc_t) xdr_remote_node_get_cells_free_memory_args, (char *)&args,
              (xdrproc_t) xdr_remote_node_get_cells_free_memory_ret, (char *)&ret) == -1)
1672
        goto done;
1673 1674 1675 1676 1677 1678

    for (i = 0 ; i < ret.freeMems.freeMems_len ; i++)
        freeMems[i] = ret.freeMems.freeMems_val[i];

    xdr_free((xdrproc_t) xdr_remote_node_get_cells_free_memory_ret, (char *) &ret);

1679 1680 1681
    rv = ret.freeMems.freeMems_len;

done:
1682
    remoteDriverUnlock(priv);
1683
    return rv;
1684 1685 1686 1687 1688
}

static unsigned long long
remoteNodeGetFreeMemory (virConnectPtr conn)
{
1689
    unsigned long long rv = 0; /* 0 is error value this special function*/
1690
    remote_node_get_free_memory_ret ret;
1691
    struct private_data *priv = conn->privateData;
1692

1693 1694
    remoteDriverLock(priv);

1695 1696 1697 1698
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_GET_FREE_MEMORY,
              (xdrproc_t) xdr_void, NULL,
              (xdrproc_t) xdr_remote_node_get_free_memory_ret, (char *)&ret) == -1)
1699 1700 1701
        goto done;

    rv = ret.freeMem;
1702

1703
done:
1704
    remoteDriverUnlock(priv);
1705
    return rv;
1706 1707 1708
}


1709 1710 1711
static int
remoteListDomains (virConnectPtr conn, int *ids, int maxids)
{
1712
    int rv = -1;
1713 1714 1715
    int i;
    remote_list_domains_args args;
    remote_list_domains_ret ret;
1716
    struct private_data *priv = conn->privateData;
1717

1718 1719
    remoteDriverLock(priv);

1720
    if (maxids > REMOTE_DOMAIN_ID_LIST_MAX) {
1721 1722 1723
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                maxids, REMOTE_DOMAIN_ID_LIST_MAX);
1724
        goto done;
1725 1726 1727 1728 1729 1730 1731
    }
    args.maxids = maxids;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DOMAINS,
              (xdrproc_t) xdr_remote_list_domains_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_domains_ret, (char *) &ret) == -1)
1732
        goto done;
1733 1734

    if (ret.ids.ids_len > maxids) {
1735 1736 1737
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                ret.ids.ids_len, maxids);
1738
        goto cleanup;
1739 1740 1741 1742 1743
    }

    for (i = 0; i < ret.ids.ids_len; ++i)
        ids[i] = ret.ids.ids_val[i];

1744 1745 1746
    rv = ret.ids.ids_len;

cleanup:
1747 1748
    xdr_free ((xdrproc_t) xdr_remote_list_domains_ret, (char *) &ret);

1749
done:
1750
    remoteDriverUnlock(priv);
1751
    return rv;
1752 1753 1754 1755 1756
}

static int
remoteNumOfDomains (virConnectPtr conn)
{
1757
    int rv = -1;
1758
    remote_num_of_domains_ret ret;
1759
    struct private_data *priv = conn->privateData;
1760

1761 1762
    remoteDriverLock(priv);

1763 1764 1765 1766
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DOMAINS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_domains_ret, (char *) &ret) == -1)
1767 1768 1769
        goto done;

    rv = ret.num;
1770

1771
done:
1772
    remoteDriverUnlock(priv);
1773
    return rv;
1774 1775 1776
}

static virDomainPtr
1777
remoteDomainCreateXML (virConnectPtr conn,
1778 1779 1780
                         const char *xmlDesc,
                         unsigned int flags)
{
1781
    virDomainPtr dom = NULL;
1782 1783
    remote_domain_create_xml_args args;
    remote_domain_create_xml_ret ret;
1784
    struct private_data *priv = conn->privateData;
1785

1786 1787
    remoteDriverLock(priv);

1788 1789 1790 1791
    args.xml_desc = (char *) xmlDesc;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
1792 1793 1794
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_CREATE_XML,
              (xdrproc_t) xdr_remote_domain_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_create_xml_ret, (char *) &ret) == -1)
1795
        goto done;
1796 1797

    dom = get_nonnull_domain (conn, ret.dom);
1798
    xdr_free ((xdrproc_t) &xdr_remote_domain_create_xml_ret, (char *) &ret);
1799

1800
done:
1801
    remoteDriverUnlock(priv);
1802 1803 1804 1805 1806 1807
    return dom;
}

static virDomainPtr
remoteDomainLookupByID (virConnectPtr conn, int id)
{
1808
    virDomainPtr dom = NULL;
1809 1810
    remote_domain_lookup_by_id_args args;
    remote_domain_lookup_by_id_ret ret;
1811
    struct private_data *priv = conn->privateData;
1812

1813 1814
    remoteDriverLock(priv);

1815 1816 1817 1818 1819 1820
    args.id = id;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_ID,
              (xdrproc_t) xdr_remote_domain_lookup_by_id_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_lookup_by_id_ret, (char *) &ret) == -1)
1821
        goto done;
1822 1823 1824 1825

    dom = get_nonnull_domain (conn, ret.dom);
    xdr_free ((xdrproc_t) &xdr_remote_domain_lookup_by_id_ret, (char *) &ret);

1826
done:
1827
    remoteDriverUnlock(priv);
1828 1829 1830 1831 1832 1833
    return dom;
}

static virDomainPtr
remoteDomainLookupByUUID (virConnectPtr conn, const unsigned char *uuid)
{
1834
    virDomainPtr dom = NULL;
1835 1836
    remote_domain_lookup_by_uuid_args args;
    remote_domain_lookup_by_uuid_ret ret;
1837
    struct private_data *priv = conn->privateData;
1838

1839 1840
    remoteDriverLock(priv);

1841 1842 1843 1844 1845 1846
    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_ret, (char *) &ret) == -1)
1847
        goto done;
1848 1849 1850

    dom = get_nonnull_domain (conn, ret.dom);
    xdr_free ((xdrproc_t) &xdr_remote_domain_lookup_by_uuid_ret, (char *) &ret);
1851 1852

done:
1853
    remoteDriverUnlock(priv);
1854 1855 1856 1857 1858 1859
    return dom;
}

static virDomainPtr
remoteDomainLookupByName (virConnectPtr conn, const char *name)
{
1860
    virDomainPtr dom = NULL;
1861 1862
    remote_domain_lookup_by_name_args args;
    remote_domain_lookup_by_name_ret ret;
1863
    struct private_data *priv = conn->privateData;
1864

1865 1866
    remoteDriverLock(priv);

1867 1868 1869 1870 1871 1872
    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_domain_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_lookup_by_name_ret, (char *) &ret) == -1)
1873
        goto done;
1874 1875 1876 1877

    dom = get_nonnull_domain (conn, ret.dom);
    xdr_free ((xdrproc_t) &xdr_remote_domain_lookup_by_name_ret, (char *) &ret);

1878
done:
1879
    remoteDriverUnlock(priv);
1880 1881 1882 1883 1884 1885
    return dom;
}

static int
remoteDomainSuspend (virDomainPtr domain)
{
1886
    int rv = -1;
1887
    remote_domain_suspend_args args;
1888
    struct private_data *priv = domain->conn->privateData;
1889

1890 1891
    remoteDriverLock(priv);

1892 1893 1894 1895 1896
    make_nonnull_domain (&args.dom, domain);

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SUSPEND,
              (xdrproc_t) xdr_remote_domain_suspend_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
1897
        goto done;
1898

1899 1900 1901
    rv = 0;

done:
1902
    remoteDriverUnlock(priv);
1903
    return rv;
1904 1905 1906 1907 1908
}

static int
remoteDomainResume (virDomainPtr domain)
{
1909
    int rv = -1;
1910
    remote_domain_resume_args args;
1911
    struct private_data *priv = domain->conn->privateData;
1912

1913 1914
    remoteDriverLock(priv);

1915 1916 1917 1918 1919
    make_nonnull_domain (&args.dom, domain);

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_RESUME,
              (xdrproc_t) xdr_remote_domain_resume_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
1920
        goto done;
1921

1922 1923 1924
    rv = 0;

done:
1925
    remoteDriverUnlock(priv);
1926
    return rv;
1927 1928 1929 1930 1931
}

static int
remoteDomainShutdown (virDomainPtr domain)
{
1932
    int rv = -1;
1933
    remote_domain_shutdown_args args;
1934
    struct private_data *priv = domain->conn->privateData;
1935

1936 1937
    remoteDriverLock(priv);

1938 1939 1940 1941 1942
    make_nonnull_domain (&args.dom, domain);

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SHUTDOWN,
              (xdrproc_t) xdr_remote_domain_shutdown_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
1943
        goto done;
1944

1945 1946 1947
    rv = 0;

done:
1948
    remoteDriverUnlock(priv);
1949
    return rv;
1950 1951 1952 1953 1954
}

static int
remoteDomainReboot (virDomainPtr domain, unsigned int flags)
{
1955
    int rv = -1;
1956
    remote_domain_reboot_args args;
1957
    struct private_data *priv = domain->conn->privateData;
1958

1959 1960
    remoteDriverLock(priv);

1961 1962 1963 1964 1965 1966
    make_nonnull_domain (&args.dom, domain);
    args.flags = flags;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_REBOOT,
              (xdrproc_t) xdr_remote_domain_reboot_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
1967
        goto done;
1968

1969 1970 1971
    rv = 0;

done:
1972
    remoteDriverUnlock(priv);
1973
    return rv;
1974 1975 1976 1977 1978
}

static int
remoteDomainDestroy (virDomainPtr domain)
{
1979
    int rv = -1;
1980
    remote_domain_destroy_args args;
1981
    struct private_data *priv = domain->conn->privateData;
1982

1983 1984
    remoteDriverLock(priv);

1985 1986 1987 1988 1989
    make_nonnull_domain (&args.dom, domain);

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_DESTROY,
              (xdrproc_t) xdr_remote_domain_destroy_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
1990
        goto done;
1991

1992
    rv = 0;
1993
    domain->id = -1;
1994 1995

done:
1996
    remoteDriverUnlock(priv);
1997
    return rv;
1998 1999 2000 2001 2002
}

static char *
remoteDomainGetOSType (virDomainPtr domain)
{
2003
    char *rv = NULL;
2004 2005
    remote_domain_get_os_type_args args;
    remote_domain_get_os_type_ret ret;
2006
    struct private_data *priv = domain->conn->privateData;
2007

2008 2009
    remoteDriverLock(priv);

2010 2011 2012 2013 2014 2015
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_OS_TYPE,
              (xdrproc_t) xdr_remote_domain_get_os_type_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_os_type_ret, (char *) &ret) == -1)
2016
        goto done;
2017 2018

    /* Caller frees. */
2019 2020 2021
    rv = ret.type;

done:
2022
    remoteDriverUnlock(priv);
2023
    return rv;
2024 2025 2026 2027 2028
}

static unsigned long
remoteDomainGetMaxMemory (virDomainPtr domain)
{
2029
    unsigned long rv = 0;
2030 2031
    remote_domain_get_max_memory_args args;
    remote_domain_get_max_memory_ret ret;
2032
    struct private_data *priv = domain->conn->privateData;
2033

2034 2035
    remoteDriverLock(priv);

2036 2037 2038 2039 2040 2041
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_MAX_MEMORY,
              (xdrproc_t) xdr_remote_domain_get_max_memory_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_max_memory_ret, (char *) &ret) == -1)
2042 2043 2044
        goto done;

    rv = ret.memory;
2045

2046
done:
2047
    remoteDriverUnlock(priv);
2048
    return rv;
2049 2050 2051 2052 2053
}

static int
remoteDomainSetMaxMemory (virDomainPtr domain, unsigned long memory)
{
2054
    int rv = -1;
2055
    remote_domain_set_max_memory_args args;
2056
    struct private_data *priv = domain->conn->privateData;
2057

2058 2059
    remoteDriverLock(priv);

2060 2061 2062 2063 2064 2065
    make_nonnull_domain (&args.dom, domain);
    args.memory = memory;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_MAX_MEMORY,
              (xdrproc_t) xdr_remote_domain_set_max_memory_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2066
        goto done;
2067

2068 2069 2070
    rv = 0;

done:
2071
    remoteDriverUnlock(priv);
2072
    return rv;
2073 2074 2075 2076 2077
}

static int
remoteDomainSetMemory (virDomainPtr domain, unsigned long memory)
{
2078
    int rv = -1;
2079
    remote_domain_set_memory_args args;
2080
    struct private_data *priv = domain->conn->privateData;
2081

2082 2083
    remoteDriverLock(priv);

2084 2085 2086 2087 2088 2089
    make_nonnull_domain (&args.dom, domain);
    args.memory = memory;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_MEMORY,
              (xdrproc_t) xdr_remote_domain_set_memory_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2090
        goto done;
2091

2092 2093 2094
    rv = 0;

done:
2095
    remoteDriverUnlock(priv);
2096
    return rv;
2097 2098 2099 2100 2101
}

static int
remoteDomainGetInfo (virDomainPtr domain, virDomainInfoPtr info)
{
2102
    int rv = -1;
2103 2104
    remote_domain_get_info_args args;
    remote_domain_get_info_ret ret;
2105
    struct private_data *priv = domain->conn->privateData;
2106

2107 2108
    remoteDriverLock(priv);

2109 2110 2111 2112 2113 2114
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_INFO,
              (xdrproc_t) xdr_remote_domain_get_info_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_info_ret, (char *) &ret) == -1)
2115
        goto done;
2116 2117 2118 2119 2120 2121

    info->state = ret.state;
    info->maxMem = ret.max_mem;
    info->memory = ret.memory;
    info->nrVirtCpu = ret.nr_virt_cpu;
    info->cpuTime = ret.cpu_time;
2122

2123 2124 2125
    rv = 0;

done:
2126
    remoteDriverUnlock(priv);
2127
    return rv;
2128 2129 2130 2131 2132
}

static int
remoteDomainSave (virDomainPtr domain, const char *to)
{
2133
    int rv = -1;
2134
    remote_domain_save_args args;
2135
    struct private_data *priv = domain->conn->privateData;
2136

2137 2138
    remoteDriverLock(priv);

2139 2140 2141 2142 2143 2144
    make_nonnull_domain (&args.dom, domain);
    args.to = (char *) to;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SAVE,
              (xdrproc_t) xdr_remote_domain_save_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2145
        goto done;
2146

2147 2148 2149
    rv = 0;

done:
2150
    remoteDriverUnlock(priv);
2151
    return rv;
2152 2153 2154 2155 2156
}

static int
remoteDomainRestore (virConnectPtr conn, const char *from)
{
2157
    int rv = -1;
2158
    remote_domain_restore_args args;
2159
    struct private_data *priv = conn->privateData;
2160

2161 2162
    remoteDriverLock(priv);

2163 2164 2165 2166 2167
    args.from = (char *) from;

    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_RESTORE,
              (xdrproc_t) xdr_remote_domain_restore_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2168
        goto done;
2169

2170 2171 2172
    rv = 0;

done:
2173
    remoteDriverUnlock(priv);
2174
    return rv;
2175 2176 2177 2178 2179
}

static int
remoteDomainCoreDump (virDomainPtr domain, const char *to, int flags)
{
2180
    int rv = -1;
2181
    remote_domain_core_dump_args args;
2182
    struct private_data *priv = domain->conn->privateData;
2183

2184 2185
    remoteDriverLock(priv);

2186 2187 2188 2189 2190 2191 2192
    make_nonnull_domain (&args.dom, domain);
    args.to = (char *) to;
    args.flags = flags;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_CORE_DUMP,
              (xdrproc_t) xdr_remote_domain_core_dump_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2193
        goto done;
2194

2195 2196 2197
    rv = 0;

done:
2198
    remoteDriverUnlock(priv);
2199
    return rv;
2200 2201 2202 2203 2204
}

static int
remoteDomainSetVcpus (virDomainPtr domain, unsigned int nvcpus)
{
2205
    int rv = -1;
2206
    remote_domain_set_vcpus_args args;
2207
    struct private_data *priv = domain->conn->privateData;
2208

2209 2210
    remoteDriverLock(priv);

2211 2212 2213 2214 2215 2216
    make_nonnull_domain (&args.dom, domain);
    args.nvcpus = nvcpus;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_VCPUS,
              (xdrproc_t) xdr_remote_domain_set_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2217
        goto done;
2218

2219 2220 2221
    rv = 0;

done:
2222
    remoteDriverUnlock(priv);
2223
    return rv;
2224 2225 2226 2227 2228 2229 2230 2231
}

static int
remoteDomainPinVcpu (virDomainPtr domain,
                     unsigned int vcpu,
                     unsigned char *cpumap,
                     int maplen)
{
2232
    int rv = -1;
2233
    remote_domain_pin_vcpu_args args;
2234
    struct private_data *priv = domain->conn->privateData;
2235

2236 2237
    remoteDriverLock(priv);

2238
    if (maplen > REMOTE_CPUMAP_MAX) {
2239 2240 2241
        errorf (domain->conn, VIR_ERR_RPC,
                _("map length greater than maximum: %d > %d"),
                maplen, REMOTE_CPUMAP_MAX);
2242
        goto done;
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
    }

    make_nonnull_domain (&args.dom, domain);
    args.vcpu = vcpu;
    args.cpumap.cpumap_len = maplen;
    args.cpumap.cpumap_val = (char *) cpumap;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_PIN_VCPU,
              (xdrproc_t) xdr_remote_domain_pin_vcpu_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2253
        goto done;
2254

2255 2256 2257
    rv = 0;

done:
2258
    remoteDriverUnlock(priv);
2259
    return rv;
2260 2261 2262 2263 2264 2265 2266 2267 2268
}

static int
remoteDomainGetVcpus (virDomainPtr domain,
                      virVcpuInfoPtr info,
                      int maxinfo,
                      unsigned char *cpumaps,
                      int maplen)
{
2269
    int rv = -1;
2270 2271 2272
    int i;
    remote_domain_get_vcpus_args args;
    remote_domain_get_vcpus_ret ret;
2273
    struct private_data *priv = domain->conn->privateData;
2274

2275 2276
    remoteDriverLock(priv);

2277
    if (maxinfo > REMOTE_VCPUINFO_MAX) {
2278 2279 2280
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU count exceeds maximum: %d > %d"),
                maxinfo, REMOTE_VCPUINFO_MAX);
2281
        goto done;
2282
    }
2283
    if (maxinfo * maplen > REMOTE_CPUMAPS_MAX) {
2284 2285 2286
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU map buffer length exceeds maximum: %d > %d"),
                maxinfo * maplen, REMOTE_CPUMAPS_MAX);
2287
        goto done;
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
    }

    make_nonnull_domain (&args.dom, domain);
    args.maxinfo = maxinfo;
    args.maplen = maplen;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_VCPUS,
              (xdrproc_t) xdr_remote_domain_get_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret) == -1)
2298
        goto done;
2299 2300

    if (ret.info.info_len > maxinfo) {
2301 2302 2303
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports too many vCPUs: %d > %d"),
                ret.info.info_len, maxinfo);
2304
        goto cleanup;
2305
    }
2306
    if (ret.cpumaps.cpumaps_len > maxinfo * maplen) {
2307 2308 2309
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports map buffer length exceeds maximum: %d > %d"),
                ret.cpumaps.cpumaps_len, maxinfo * maplen);
2310
        goto cleanup;
2311 2312
    }

2313 2314 2315
    memset (info, 0, sizeof (virVcpuInfo) * maxinfo);
    memset (cpumaps, 0, maxinfo * maplen);

2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
    for (i = 0; i < ret.info.info_len; ++i) {
        info[i].number = ret.info.info_val[i].number;
        info[i].state = ret.info.info_val[i].state;
        info[i].cpuTime = ret.info.info_val[i].cpu_time;
        info[i].cpu = ret.info.info_val[i].cpu;
    }

    for (i = 0; i < ret.cpumaps.cpumaps_len; ++i)
        cpumaps[i] = ret.cpumaps.cpumaps_val[i];

2326 2327 2328
    rv = ret.info.info_len;

cleanup:
2329
    xdr_free ((xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret);
2330 2331

done:
2332
    remoteDriverUnlock(priv);
2333
    return rv;
2334 2335 2336 2337 2338
}

static int
remoteDomainGetMaxVcpus (virDomainPtr domain)
{
2339
    int rv = -1;
2340 2341
    remote_domain_get_max_vcpus_args args;
    remote_domain_get_max_vcpus_ret ret;
2342
    struct private_data *priv = domain->conn->privateData;
2343

2344 2345
    remoteDriverLock(priv);

2346 2347 2348
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
2349
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_MAX_VCPUS,
2350 2351
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_ret, (char *) &ret) == -1)
2352
        goto done;
2353

2354 2355 2356
    rv = ret.num;

done:
2357
    remoteDriverUnlock(priv);
2358
    return rv;
2359 2360
}

2361 2362 2363 2364 2365 2366
static int
remoteDomainGetSecurityLabel (virDomainPtr domain, virSecurityLabelPtr seclabel)
{
    remote_domain_get_security_label_args args;
    remote_domain_get_security_label_ret ret;
    struct private_data *priv = domain->conn->privateData;
2367 2368 2369
    int rv = -1;

    remoteDriverLock(priv);
2370 2371 2372

    make_nonnull_domain (&args.dom, domain);
    memset (&ret, 0, sizeof ret);
2373 2374
    memset (seclabel, 0, sizeof (*seclabel));

2375 2376 2377
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_SECURITY_LABEL,
              (xdrproc_t) xdr_remote_domain_get_security_label_args, (char *)&args,
              (xdrproc_t) xdr_remote_domain_get_security_label_ret, (char *)&ret) == -1) {
2378
        goto done;
2379 2380 2381 2382 2383 2384
    }

    if (ret.label.label_val != NULL) {
        if (strlen (ret.label.label_val) >= sizeof seclabel->label) {
            errorf (domain->conn, VIR_ERR_RPC, _("security label exceeds maximum: %zd"),
                    sizeof seclabel->label - 1);
2385
            goto done;
2386 2387 2388 2389 2390
        }
        strcpy (seclabel->label, ret.label.label_val);
        seclabel->enforcing = ret.enforcing;
    }

2391 2392 2393 2394 2395
    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
2396 2397 2398 2399 2400 2401 2402
}

static int
remoteNodeGetSecurityModel (virConnectPtr conn, virSecurityModelPtr secmodel)
{
    remote_node_get_security_model_ret ret;
    struct private_data *priv = conn->privateData;
2403 2404 2405
    int rv = -1;

    remoteDriverLock(priv);
2406 2407

    memset (&ret, 0, sizeof ret);
2408 2409
    memset (secmodel, 0, sizeof (*secmodel));

2410 2411 2412
    if (call (conn, priv, 0, REMOTE_PROC_NODE_GET_SECURITY_MODEL,
              (xdrproc_t) xdr_void, NULL,
              (xdrproc_t) xdr_remote_node_get_security_model_ret, (char *)&ret) == -1) {
2413
        goto done;
2414 2415 2416 2417 2418 2419
    }

    if (ret.model.model_val != NULL) {
        if (strlen (ret.model.model_val) >= sizeof secmodel->model) {
            errorf (conn, VIR_ERR_RPC, _("security model exceeds maximum: %zd"),
                    sizeof secmodel->model - 1);
2420
            goto done;
2421 2422 2423 2424 2425 2426 2427 2428
        }
        strcpy (secmodel->model, ret.model.model_val);
    }

    if (ret.doi.doi_val != NULL) {
        if (strlen (ret.doi.doi_val) >= sizeof secmodel->doi) {
            errorf (conn, VIR_ERR_RPC, _("security doi exceeds maximum: %zd"),
                    sizeof secmodel->doi - 1);
2429
            goto done;
2430 2431 2432
        }
        strcpy (secmodel->doi, ret.doi.doi_val);
    }
2433 2434 2435 2436 2437 2438

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
2439 2440
}

2441 2442 2443
static char *
remoteDomainDumpXML (virDomainPtr domain, int flags)
{
2444
    char *rv = NULL;
2445 2446
    remote_domain_dump_xml_args args;
    remote_domain_dump_xml_ret ret;
2447
    struct private_data *priv = domain->conn->privateData;
2448

2449 2450
    remoteDriverLock(priv);

2451 2452 2453 2454 2455 2456 2457
    make_nonnull_domain (&args.dom, domain);
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_DUMP_XML,
              (xdrproc_t) xdr_remote_domain_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_dump_xml_ret, (char *) &ret) == -1)
2458
        goto done;
2459 2460

    /* Caller frees. */
2461 2462 2463
    rv = ret.xml;

done:
2464
    remoteDriverUnlock(priv);
2465
    return rv;
2466 2467
}

2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
static char *
remoteDomainXMLFromNative (virConnectPtr conn,
                           const char *format,
                           const char *config,
                           unsigned int flags)
{
    char *rv = NULL;
    remote_domain_xml_from_native_args args;
    remote_domain_xml_from_native_ret ret;
    struct private_data *priv = conn->privateData;

    remoteDriverLock(priv);

    args.nativeFormat = (char *)format;
    args.nativeConfig = (char *)config;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_XML_FROM_NATIVE,
              (xdrproc_t) xdr_remote_domain_xml_from_native_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_xml_from_native_ret, (char *) &ret) == -1)
        goto done;

    /* Caller frees. */
    rv = ret.domainXml;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static char *
remoteDomainXMLToNative (virConnectPtr conn,
                         const char *format,
                         const char *xml,
                         unsigned int flags)
{
    char *rv = NULL;
    remote_domain_xml_to_native_args args;
    remote_domain_xml_to_native_ret ret;
    struct private_data *priv = conn->privateData;

    remoteDriverLock(priv);

    args.nativeFormat = (char *)format;
    args.domainXml = (char *)xml;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_XML_TO_NATIVE,
              (xdrproc_t) xdr_remote_domain_xml_to_native_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_xml_to_native_ret, (char *) &ret) == -1)
        goto done;

    /* Caller frees. */
    rv = ret.nativeConfig;

done:
    remoteDriverUnlock(priv);
    return rv;
}

2530 2531 2532 2533 2534 2535 2536
static int
remoteDomainMigratePrepare (virConnectPtr dconn,
                            char **cookie, int *cookielen,
                            const char *uri_in, char **uri_out,
                            unsigned long flags, const char *dname,
                            unsigned long resource)
{
2537
    int rv = -1;
2538 2539
    remote_domain_migrate_prepare_args args;
    remote_domain_migrate_prepare_ret ret;
2540
    struct private_data *priv = dconn->privateData;
2541

2542 2543
    remoteDriverLock(priv);

2544 2545 2546 2547 2548 2549 2550 2551 2552
    args.uri_in = uri_in == NULL ? NULL : (char **) &uri_in;
    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
    args.resource = resource;

    memset (&ret, 0, sizeof ret);
    if (call (dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_PREPARE,
              (xdrproc_t) xdr_remote_domain_migrate_prepare_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_prepare_ret, (char *) &ret) == -1)
2553
        goto done;
2554 2555 2556 2557 2558 2559 2560 2561

    if (ret.cookie.cookie_len > 0) {
        *cookie = ret.cookie.cookie_val; /* Caller frees. */
        *cookielen = ret.cookie.cookie_len;
    }
    if (ret.uri_out)
        *uri_out = *ret.uri_out; /* Caller frees. */

2562 2563 2564
    rv = 0;

done:
2565
    remoteDriverUnlock(priv);
2566
    return rv;
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
}

static int
remoteDomainMigratePerform (virDomainPtr domain,
                            const char *cookie,
                            int cookielen,
                            const char *uri,
                            unsigned long flags,
                            const char *dname,
                            unsigned long resource)
{
2578
    int rv = -1;
2579
    remote_domain_migrate_perform_args args;
2580
    struct private_data *priv = domain->conn->privateData;
2581

2582 2583
    remoteDriverLock(priv);

2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    make_nonnull_domain (&args.dom, domain);
    args.cookie.cookie_len = cookielen;
    args.cookie.cookie_val = (char *) cookie;
    args.uri = (char *) uri;
    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
    args.resource = resource;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_PERFORM,
              (xdrproc_t) xdr_remote_domain_migrate_perform_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2595
        goto done;
2596

2597 2598 2599
    rv = 0;

done:
2600
    remoteDriverUnlock(priv);
2601
    return rv;
2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
}

static virDomainPtr
remoteDomainMigrateFinish (virConnectPtr dconn,
                           const char *dname,
                           const char *cookie,
                           int cookielen,
                           const char *uri,
                           unsigned long flags)
{
2612
    virDomainPtr ddom = NULL;
2613 2614
    remote_domain_migrate_finish_args args;
    remote_domain_migrate_finish_ret ret;
2615
    struct private_data *priv = dconn->privateData;
2616

2617 2618
    remoteDriverLock(priv);

2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
    args.dname = (char *) dname;
    args.cookie.cookie_len = cookielen;
    args.cookie.cookie_val = (char *) cookie;
    args.uri = (char *) uri;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_FINISH,
              (xdrproc_t) xdr_remote_domain_migrate_finish_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_finish_ret, (char *) &ret) == -1)
2629
        goto done;
2630 2631 2632 2633

    ddom = get_nonnull_domain (dconn, ret.ddom);
    xdr_free ((xdrproc_t) &xdr_remote_domain_migrate_finish_ret, (char *) &ret);

2634
done:
2635
    remoteDriverUnlock(priv);
2636 2637 2638
    return ddom;
}

D
Daniel Veillard 已提交
2639 2640 2641 2642 2643 2644 2645 2646
static int
remoteDomainMigratePrepare2 (virConnectPtr dconn,
                             char **cookie, int *cookielen,
                             const char *uri_in, char **uri_out,
                             unsigned long flags, const char *dname,
                             unsigned long resource,
                             const char *dom_xml)
{
2647
    int rv = -1;
D
Daniel Veillard 已提交
2648 2649
    remote_domain_migrate_prepare2_args args;
    remote_domain_migrate_prepare2_ret ret;
2650
    struct private_data *priv = dconn->privateData;
D
Daniel Veillard 已提交
2651

2652 2653
    remoteDriverLock(priv);

D
Daniel Veillard 已提交
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
    args.uri_in = uri_in == NULL ? NULL : (char **) &uri_in;
    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
    args.resource = resource;
    args.dom_xml = (char *) dom_xml;

    memset (&ret, 0, sizeof ret);
    if (call (dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_PREPARE2,
              (xdrproc_t) xdr_remote_domain_migrate_prepare2_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_prepare2_ret, (char *) &ret) == -1)
2664
        goto done;
D
Daniel Veillard 已提交
2665 2666 2667 2668 2669 2670 2671 2672

    if (ret.cookie.cookie_len > 0) {
        *cookie = ret.cookie.cookie_val; /* Caller frees. */
        *cookielen = ret.cookie.cookie_len;
    }
    if (ret.uri_out)
        *uri_out = *ret.uri_out; /* Caller frees. */

2673 2674 2675
    rv = 0;

done:
2676
    remoteDriverUnlock(priv);
2677
    return rv;
D
Daniel Veillard 已提交
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
}

static virDomainPtr
remoteDomainMigrateFinish2 (virConnectPtr dconn,
                            const char *dname,
                            const char *cookie,
                            int cookielen,
                            const char *uri,
                            unsigned long flags,
                            int retcode)
{
2689
    virDomainPtr ddom = NULL;
D
Daniel Veillard 已提交
2690 2691
    remote_domain_migrate_finish2_args args;
    remote_domain_migrate_finish2_ret ret;
2692
    struct private_data *priv = dconn->privateData;
D
Daniel Veillard 已提交
2693

2694 2695
    remoteDriverLock(priv);

D
Daniel Veillard 已提交
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
    args.dname = (char *) dname;
    args.cookie.cookie_len = cookielen;
    args.cookie.cookie_val = (char *) cookie;
    args.uri = (char *) uri;
    args.flags = flags;
    args.retcode = retcode;

    memset (&ret, 0, sizeof ret);
    if (call (dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_FINISH2,
              (xdrproc_t) xdr_remote_domain_migrate_finish2_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_finish2_ret, (char *) &ret) == -1)
2707
        goto done;
D
Daniel Veillard 已提交
2708 2709 2710 2711

    ddom = get_nonnull_domain (dconn, ret.ddom);
    xdr_free ((xdrproc_t) &xdr_remote_domain_migrate_finish2_ret, (char *) &ret);

2712
done:
2713
    remoteDriverUnlock(priv);
D
Daniel Veillard 已提交
2714 2715 2716
    return ddom;
}

2717 2718 2719
static int
remoteListDefinedDomains (virConnectPtr conn, char **const names, int maxnames)
{
2720
    int rv = -1;
2721 2722 2723
    int i;
    remote_list_defined_domains_args args;
    remote_list_defined_domains_ret ret;
2724
    struct private_data *priv = conn->privateData;
2725

2726 2727
    remoteDriverLock(priv);

2728
    if (maxnames > REMOTE_DOMAIN_NAME_LIST_MAX) {
2729 2730 2731
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                maxnames, REMOTE_DOMAIN_NAME_LIST_MAX);
2732
        goto done;
2733 2734 2735 2736 2737 2738 2739
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DEFINED_DOMAINS,
              (xdrproc_t) xdr_remote_list_defined_domains_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_defined_domains_ret, (char *) &ret) == -1)
2740
        goto done;
2741 2742

    if (ret.names.names_len > maxnames) {
2743 2744 2745
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                ret.names.names_len, maxnames);
2746
        goto cleanup;
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

2757 2758 2759
    rv = ret.names.names_len;

cleanup:
2760 2761
    xdr_free ((xdrproc_t) xdr_remote_list_defined_domains_ret, (char *) &ret);

2762
done:
2763
    remoteDriverUnlock(priv);
2764
    return rv;
2765 2766 2767 2768 2769
}

static int
remoteNumOfDefinedDomains (virConnectPtr conn)
{
2770
    int rv = -1;
2771
    remote_num_of_defined_domains_ret ret;
2772
    struct private_data *priv = conn->privateData;
2773

2774 2775
    remoteDriverLock(priv);

2776 2777 2778 2779
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DEFINED_DOMAINS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_defined_domains_ret, (char *) &ret) == -1)
2780
        goto done;
2781

2782 2783 2784
    rv = ret.num;

done:
2785
    remoteDriverUnlock(priv);
2786
    return rv;
2787 2788 2789 2790 2791
}

static int
remoteDomainCreate (virDomainPtr domain)
{
2792
    int rv = -1;
2793
    remote_domain_create_args args;
2794 2795
    remote_domain_lookup_by_uuid_args args2;
    remote_domain_lookup_by_uuid_ret ret2;
2796
    struct private_data *priv = domain->conn->privateData;
2797

2798 2799
    remoteDriverLock(priv);

2800 2801 2802 2803 2804
    make_nonnull_domain (&args.dom, domain);

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_CREATE,
              (xdrproc_t) xdr_remote_domain_create_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2805
        goto done;
2806

2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
    /* Need to do a lookup figure out ID of newly started guest, because
     * bug in design of REMOTE_PROC_DOMAIN_CREATE means we aren't getting
     * it returned.
     */
    memcpy (args2.uuid, domain->uuid, VIR_UUID_BUFLEN);
    memset (&ret2, 0, sizeof ret2);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_args, (char *) &args2,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_ret, (char *) &ret2) == -1)
        goto done;

    domain->id = ret2.dom.id;
    xdr_free ((xdrproc_t) &xdr_remote_domain_lookup_by_uuid_ret, (char *) &ret2);

2821 2822 2823
    rv = 0;

done:
2824
    remoteDriverUnlock(priv);
2825
    return rv;
2826 2827 2828 2829 2830
}

static virDomainPtr
remoteDomainDefineXML (virConnectPtr conn, const char *xml)
{
2831
    virDomainPtr dom = NULL;
2832 2833
    remote_domain_define_xml_args args;
    remote_domain_define_xml_ret ret;
2834
    struct private_data *priv = conn->privateData;
2835

2836 2837
    remoteDriverLock(priv);

2838 2839 2840 2841 2842 2843
    args.xml = (char *) xml;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_DEFINE_XML,
              (xdrproc_t) xdr_remote_domain_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_define_xml_ret, (char *) &ret) == -1)
2844
        goto done;
2845 2846 2847 2848

    dom = get_nonnull_domain (conn, ret.dom);
    xdr_free ((xdrproc_t) xdr_remote_domain_define_xml_ret, (char *) &ret);

2849
done:
2850
    remoteDriverUnlock(priv);
2851 2852 2853 2854 2855 2856
    return dom;
}

static int
remoteDomainUndefine (virDomainPtr domain)
{
2857
    int rv = -1;
2858
    remote_domain_undefine_args args;
2859
    struct private_data *priv = domain->conn->privateData;
2860

2861 2862
    remoteDriverLock(priv);

2863 2864 2865 2866 2867
    make_nonnull_domain (&args.dom, domain);

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_UNDEFINE,
              (xdrproc_t) xdr_remote_domain_undefine_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2868
        goto done;
2869

2870 2871 2872
    rv = 0;

done:
2873
    remoteDriverUnlock(priv);
2874
    return rv;
2875 2876 2877
}

static int
2878
remoteDomainAttachDevice (virDomainPtr domain, const char *xml)
2879
{
2880
    int rv = -1;
2881
    remote_domain_attach_device_args args;
2882
    struct private_data *priv = domain->conn->privateData;
2883

2884 2885
    remoteDriverLock(priv);

2886
    make_nonnull_domain (&args.dom, domain);
2887
    args.xml = (char *) xml;
2888 2889 2890 2891

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_ATTACH_DEVICE,
              (xdrproc_t) xdr_remote_domain_attach_device_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2892
        goto done;
2893

2894 2895 2896
    rv = 0;

done:
2897
    remoteDriverUnlock(priv);
2898
    return rv;
2899 2900 2901
}

static int
2902
remoteDomainDetachDevice (virDomainPtr domain, const char *xml)
2903
{
2904
    int rv = -1;
2905
    remote_domain_detach_device_args args;
2906
    struct private_data *priv = domain->conn->privateData;
2907

2908 2909
    remoteDriverLock(priv);

2910
    make_nonnull_domain (&args.dom, domain);
2911
    args.xml = (char *) xml;
2912 2913 2914 2915

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_DETACH_DEVICE,
              (xdrproc_t) xdr_remote_domain_detach_device_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2916
        goto done;
2917

2918 2919 2920
    rv = 0;

done:
2921
    remoteDriverUnlock(priv);
2922
    return rv;
2923 2924 2925 2926 2927
}

static int
remoteDomainGetAutostart (virDomainPtr domain, int *autostart)
{
2928
    int rv = -1;
2929 2930
    remote_domain_get_autostart_args args;
    remote_domain_get_autostart_ret ret;
2931
    struct private_data *priv = domain->conn->privateData;
2932

2933 2934
    remoteDriverLock(priv);

2935 2936 2937 2938 2939 2940
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_AUTOSTART,
              (xdrproc_t) xdr_remote_domain_get_autostart_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_autostart_ret, (char *) &ret) == -1)
2941
        goto done;
2942 2943

    if (autostart) *autostart = ret.autostart;
2944 2945 2946
    rv = 0;

done:
2947
    remoteDriverUnlock(priv);
2948
    return rv;
2949 2950 2951 2952 2953
}

static int
remoteDomainSetAutostart (virDomainPtr domain, int autostart)
{
2954
    int rv = -1;
2955
    remote_domain_set_autostart_args args;
2956
    struct private_data *priv = domain->conn->privateData;
2957

2958 2959
    remoteDriverLock(priv);

2960 2961 2962 2963 2964 2965
    make_nonnull_domain (&args.dom, domain);
    args.autostart = autostart;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_AUTOSTART,
              (xdrproc_t) xdr_remote_domain_set_autostart_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
2966
        goto done;
2967

2968 2969 2970
    rv = 0;

done:
2971
    remoteDriverUnlock(priv);
2972
    return rv;
2973 2974
}

2975 2976 2977
static char *
remoteDomainGetSchedulerType (virDomainPtr domain, int *nparams)
{
2978
    char *rv = NULL;
2979 2980
    remote_domain_get_scheduler_type_args args;
    remote_domain_get_scheduler_type_ret ret;
2981
    struct private_data *priv = domain->conn->privateData;
2982

2983 2984
    remoteDriverLock(priv);

2985 2986 2987 2988 2989 2990
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_SCHEDULER_TYPE,
              (xdrproc_t) xdr_remote_domain_get_scheduler_type_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_scheduler_type_ret, (char *) &ret) == -1)
2991
        goto done;
2992 2993 2994 2995

    if (nparams) *nparams = ret.nparams;

    /* Caller frees this. */
2996 2997 2998
    rv = ret.type;

done:
2999
    remoteDriverUnlock(priv);
3000
    return rv;
3001 3002 3003 3004 3005 3006
}

static int
remoteDomainGetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int *nparams)
{
3007
    int rv = -1;
3008 3009
    remote_domain_get_scheduler_parameters_args args;
    remote_domain_get_scheduler_parameters_ret ret;
3010
    int i = -1;
3011
    struct private_data *priv = domain->conn->privateData;
3012

3013 3014
    remoteDriverLock(priv);

3015 3016 3017 3018 3019 3020 3021
    make_nonnull_domain (&args.dom, domain);
    args.nparams = *nparams;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_SCHEDULER_PARAMETERS,
              (xdrproc_t) xdr_remote_domain_get_scheduler_parameters_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret) == -1)
3022
        goto done;
3023 3024 3025 3026

    /* Check the length of the returned list carefully. */
    if (ret.params.params_len > REMOTE_DOMAIN_SCHEDULER_PARAMETERS_MAX ||
        ret.params.params_len > *nparams) {
3027 3028 3029
        error (domain->conn, VIR_ERR_RPC,
               _("remoteDomainGetSchedulerParameters: "
                 "returned number of parameters exceeds limit"));
3030
        goto cleanup;
3031 3032 3033 3034 3035
    }
    *nparams = ret.params.params_len;

    /* Deserialise the result. */
    for (i = 0; i < *nparams; ++i) {
C
Chris Lalancette 已提交
3036 3037 3038 3039 3040 3041
        if (virStrcpyStatic(params[i].field, ret.params.params_val[i].field) == NULL) {
            errorf(domain->conn, VIR_ERR_INTERNAL_ERROR,
                   _("Parameter %s too big for destination"),
                   ret.params.params_val[i].field);
            goto cleanup;
        }
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
        params[i].type = ret.params.params_val[i].value.type;
        switch (params[i].type) {
        case VIR_DOMAIN_SCHED_FIELD_INT:
            params[i].value.i = ret.params.params_val[i].value.remote_sched_param_value_u.i; break;
        case VIR_DOMAIN_SCHED_FIELD_UINT:
            params[i].value.ui = ret.params.params_val[i].value.remote_sched_param_value_u.ui; break;
        case VIR_DOMAIN_SCHED_FIELD_LLONG:
            params[i].value.l = ret.params.params_val[i].value.remote_sched_param_value_u.l; break;
        case VIR_DOMAIN_SCHED_FIELD_ULLONG:
            params[i].value.ul = ret.params.params_val[i].value.remote_sched_param_value_u.ul; break;
        case VIR_DOMAIN_SCHED_FIELD_DOUBLE:
            params[i].value.d = ret.params.params_val[i].value.remote_sched_param_value_u.d; break;
        case VIR_DOMAIN_SCHED_FIELD_BOOLEAN:
            params[i].value.b = ret.params.params_val[i].value.remote_sched_param_value_u.b; break;
        default:
3057 3058 3059
            error (domain->conn, VIR_ERR_RPC,
                   _("remoteDomainGetSchedulerParameters: "
                     "unknown parameter type"));
3060
            goto cleanup;
3061 3062 3063
        }
    }

3064 3065 3066
    rv = 0;

cleanup:
3067
    xdr_free ((xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret);
3068
done:
3069
    remoteDriverUnlock(priv);
3070
    return rv;
3071 3072 3073 3074 3075 3076
}

static int
remoteDomainSetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int nparams)
{
3077
    int rv = -1;
3078 3079
    remote_domain_set_scheduler_parameters_args args;
    int i, do_error;
3080
    struct private_data *priv = domain->conn->privateData;
3081

3082 3083
    remoteDriverLock(priv);

3084 3085 3086 3087
    make_nonnull_domain (&args.dom, domain);

    /* Serialise the scheduler parameters. */
    args.params.params_len = nparams;
3088
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
3089
        error (domain->conn, VIR_ERR_RPC, _("out of memory allocating array"));
3090
        goto done;
3091 3092 3093 3094 3095 3096 3097
    }

    do_error = 0;
    for (i = 0; i < nparams; ++i) {
        // call() will free this:
        args.params.params_val[i].field = strdup (params[i].field);
        if (args.params.params_val[i].field == NULL) {
3098
            virReportOOMError (domain->conn);
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
            do_error = 1;
        }
        args.params.params_val[i].value.type = params[i].type;
        switch (params[i].type) {
        case VIR_DOMAIN_SCHED_FIELD_INT:
            args.params.params_val[i].value.remote_sched_param_value_u.i = params[i].value.i; break;
        case VIR_DOMAIN_SCHED_FIELD_UINT:
            args.params.params_val[i].value.remote_sched_param_value_u.ui = params[i].value.ui; break;
        case VIR_DOMAIN_SCHED_FIELD_LLONG:
            args.params.params_val[i].value.remote_sched_param_value_u.l = params[i].value.l; break;
        case VIR_DOMAIN_SCHED_FIELD_ULLONG:
            args.params.params_val[i].value.remote_sched_param_value_u.ul = params[i].value.ul; break;
        case VIR_DOMAIN_SCHED_FIELD_DOUBLE:
            args.params.params_val[i].value.remote_sched_param_value_u.d = params[i].value.d; break;
        case VIR_DOMAIN_SCHED_FIELD_BOOLEAN:
            args.params.params_val[i].value.remote_sched_param_value_u.b = params[i].value.b; break;
        default:
3116
            error (domain->conn, VIR_ERR_RPC, _("unknown parameter type"));
3117 3118 3119 3120 3121 3122
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_scheduler_parameters_args, (char *) &args);
3123
        goto done;
3124 3125 3126 3127 3128
    }

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_SCHEDULER_PARAMETERS,
              (xdrproc_t) xdr_remote_domain_set_scheduler_parameters_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
3129
        goto done;
3130

3131 3132 3133
    rv = 0;

done:
3134
    remoteDriverUnlock(priv);
3135
    return rv;
3136 3137
}

3138 3139 3140 3141
static int
remoteDomainBlockStats (virDomainPtr domain, const char *path,
                        struct _virDomainBlockStats *stats)
{
3142
    int rv = -1;
3143 3144
    remote_domain_block_stats_args args;
    remote_domain_block_stats_ret ret;
3145
    struct private_data *priv = domain->conn->privateData;
3146

3147 3148
    remoteDriverLock(priv);

3149 3150 3151 3152 3153 3154 3155 3156
    make_nonnull_domain (&args.dom, domain);
    args.path = (char *) path;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_BLOCK_STATS,
              (xdrproc_t) xdr_remote_domain_block_stats_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_block_stats_ret, (char *) &ret)
        == -1)
3157
        goto done;
3158 3159 3160 3161 3162 3163 3164

    stats->rd_req = ret.rd_req;
    stats->rd_bytes = ret.rd_bytes;
    stats->wr_req = ret.wr_req;
    stats->wr_bytes = ret.wr_bytes;
    stats->errs = ret.errs;

3165 3166 3167
    rv = 0;

done:
3168
    remoteDriverUnlock(priv);
3169
    return rv;
3170 3171 3172 3173 3174 3175
}

static int
remoteDomainInterfaceStats (virDomainPtr domain, const char *path,
                            struct _virDomainInterfaceStats *stats)
{
3176
    int rv = -1;
3177 3178
    remote_domain_interface_stats_args args;
    remote_domain_interface_stats_ret ret;
3179
    struct private_data *priv = domain->conn->privateData;
3180

3181 3182
    remoteDriverLock(priv);

3183 3184 3185 3186 3187 3188 3189 3190 3191
    make_nonnull_domain (&args.dom, domain);
    args.path = (char *) path;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_INTERFACE_STATS,
              (xdrproc_t) xdr_remote_domain_interface_stats_args,
                (char *) &args,
              (xdrproc_t) xdr_remote_domain_interface_stats_ret,
                (char *) &ret) == -1)
3192
        goto done;
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202

    stats->rx_bytes = ret.rx_bytes;
    stats->rx_packets = ret.rx_packets;
    stats->rx_errs = ret.rx_errs;
    stats->rx_drop = ret.rx_drop;
    stats->tx_bytes = ret.tx_bytes;
    stats->tx_packets = ret.tx_packets;
    stats->tx_errs = ret.tx_errs;
    stats->tx_drop = ret.tx_drop;

3203 3204 3205
    rv = 0;

done:
3206
    remoteDriverUnlock(priv);
3207
    return rv;
3208 3209
}

3210 3211 3212 3213 3214 3215 3216 3217
static int
remoteDomainBlockPeek (virDomainPtr domain,
                       const char *path,
                       unsigned long long offset,
                       size_t size,
                       void *buffer,
                       unsigned int flags)
{
3218
    int rv = -1;
3219 3220
    remote_domain_block_peek_args args;
    remote_domain_block_peek_ret ret;
3221
    struct private_data *priv = domain->conn->privateData;
3222

3223 3224
    remoteDriverLock(priv);

3225 3226 3227 3228
    if (size > REMOTE_DOMAIN_BLOCK_PEEK_BUFFER_MAX) {
        errorf (domain->conn, VIR_ERR_RPC,
                _("block peek request too large for remote protocol, %zi > %d"),
                size, REMOTE_DOMAIN_BLOCK_PEEK_BUFFER_MAX);
3229
        goto done;
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
    }

    make_nonnull_domain (&args.dom, domain);
    args.path = (char *) path;
    args.offset = offset;
    args.size = size;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_BLOCK_PEEK,
              (xdrproc_t) xdr_remote_domain_block_peek_args,
                (char *) &args,
              (xdrproc_t) xdr_remote_domain_block_peek_ret,
                (char *) &ret) == -1)
3244
        goto done;
3245 3246

    if (ret.buffer.buffer_len != size) {
3247 3248 3249
        errorf (domain->conn, VIR_ERR_RPC,
                "%s", _("returned buffer is not same size as requested"));
        goto cleanup;
3250 3251 3252
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
3253 3254 3255
    rv = 0;

cleanup:
3256 3257
    free (ret.buffer.buffer_val);

3258
done:
3259
    remoteDriverUnlock(priv);
3260
    return rv;
3261 3262
}

R
Richard W.M. Jones 已提交
3263 3264 3265 3266 3267 3268 3269
static int
remoteDomainMemoryPeek (virDomainPtr domain,
                        unsigned long long offset,
                        size_t size,
                        void *buffer,
                        unsigned int flags)
{
3270
    int rv = -1;
R
Richard W.M. Jones 已提交
3271 3272
    remote_domain_memory_peek_args args;
    remote_domain_memory_peek_ret ret;
3273
    struct private_data *priv = domain->conn->privateData;
R
Richard W.M. Jones 已提交
3274

3275 3276
    remoteDriverLock(priv);

R
Richard W.M. Jones 已提交
3277 3278 3279 3280
    if (size > REMOTE_DOMAIN_MEMORY_PEEK_BUFFER_MAX) {
        errorf (domain->conn, VIR_ERR_RPC,
                _("memory peek request too large for remote protocol, %zi > %d"),
                size, REMOTE_DOMAIN_MEMORY_PEEK_BUFFER_MAX);
3281
        goto done;
R
Richard W.M. Jones 已提交
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
    }

    make_nonnull_domain (&args.dom, domain);
    args.offset = offset;
    args.size = size;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_MEMORY_PEEK,
              (xdrproc_t) xdr_remote_domain_memory_peek_args,
                (char *) &args,
              (xdrproc_t) xdr_remote_domain_memory_peek_ret,
                (char *) &ret) == -1)
3295
        goto done;
R
Richard W.M. Jones 已提交
3296 3297

    if (ret.buffer.buffer_len != size) {
3298 3299 3300
        errorf (domain->conn, VIR_ERR_RPC,
                "%s", _("returned buffer is not same size as requested"));
        goto cleanup;
R
Richard W.M. Jones 已提交
3301 3302 3303
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
3304 3305 3306
    rv = 0;

cleanup:
R
Richard W.M. Jones 已提交
3307 3308
    free (ret.buffer.buffer_val);

3309
done:
3310
    remoteDriverUnlock(priv);
3311
    return rv;
R
Richard W.M. Jones 已提交
3312 3313
}

3314 3315
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
3316
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
3317
remoteNetworkOpen (virConnectPtr conn,
3318
                   virConnectAuthPtr auth,
3319
                   int flags)
3320
{
3321 3322 3323
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
3324
    if (conn->driver &&
3325
        STREQ (conn->driver->name, "remote")) {
3326 3327 3328
        struct private_data *priv;

       /* If we're here, the remote driver is already
3329 3330 3331
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
3332 3333 3334 3335 3336
        priv = conn->privateData;
        remoteDriverLock(priv);
        priv->localUses++;
        conn->networkPrivateData = priv;
        remoteDriverUnlock(priv);
3337
        return VIR_DRV_OPEN_SUCCESS;
3338 3339 3340
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
3341 3342
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the network APIs.
3343
         */
3344
        struct private_data *priv;
3345 3346 3347 3348 3349 3350
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
3351 3352 3353
            conn->networkPrivateData = priv;
        return ret;
    }
3354 3355 3356
}

static int
3357 3358
remoteNetworkClose (virConnectPtr conn)
{
3359
    int rv = 0;
3360 3361
    struct private_data *priv = conn->networkPrivateData;

3362 3363 3364 3365 3366 3367 3368 3369
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        rv = doRemoteClose(conn, priv);
        conn->networkPrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
3370
    }
3371 3372
    if (priv)
        remoteDriverUnlock(priv);
3373
    return rv;
3374 3375 3376 3377 3378
}

static int
remoteNumOfNetworks (virConnectPtr conn)
{
3379
    int rv = -1;
3380
    remote_num_of_networks_ret ret;
3381
    struct private_data *priv = conn->networkPrivateData;
3382

3383 3384
    remoteDriverLock(priv);

3385 3386 3387 3388
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_NETWORKS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_networks_ret, (char *) &ret) == -1)
3389 3390 3391
        goto done;

    rv = ret.num;
3392

3393
done:
3394
    remoteDriverUnlock(priv);
3395
    return rv;
3396 3397 3398 3399 3400
}

static int
remoteListNetworks (virConnectPtr conn, char **const names, int maxnames)
{
3401
    int rv = -1;
3402 3403 3404
    int i;
    remote_list_networks_args args;
    remote_list_networks_ret ret;
3405
    struct private_data *priv = conn->networkPrivateData;
3406

3407 3408
    remoteDriverLock(priv);

3409
    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
3410 3411 3412
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
3413
        goto done;
3414 3415 3416 3417 3418 3419 3420
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_NETWORKS,
              (xdrproc_t) xdr_remote_list_networks_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_networks_ret, (char *) &ret) == -1)
3421
        goto done;
3422 3423

    if (ret.names.names_len > maxnames) {
3424 3425 3426
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
3427
        goto cleanup;
3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

3438 3439 3440
    rv = ret.names.names_len;

cleanup:
3441 3442
    xdr_free ((xdrproc_t) xdr_remote_list_networks_ret, (char *) &ret);

3443
done:
3444
    remoteDriverUnlock(priv);
3445
    return rv;
3446 3447 3448 3449 3450
}

static int
remoteNumOfDefinedNetworks (virConnectPtr conn)
{
3451
    int rv = -1;
3452
    remote_num_of_defined_networks_ret ret;
3453
    struct private_data *priv = conn->networkPrivateData;
3454

3455 3456
    remoteDriverLock(priv);

3457 3458 3459 3460
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DEFINED_NETWORKS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_defined_networks_ret, (char *) &ret) == -1)
3461 3462 3463
        goto done;

    rv = ret.num;
3464

3465
done:
3466
    remoteDriverUnlock(priv);
3467
    return rv;
3468 3469 3470 3471 3472 3473
}

static int
remoteListDefinedNetworks (virConnectPtr conn,
                           char **const names, int maxnames)
{
3474
    int rv = -1;
3475 3476 3477
    int i;
    remote_list_defined_networks_args args;
    remote_list_defined_networks_ret ret;
3478
    struct private_data *priv = conn->networkPrivateData;
3479

3480 3481
    remoteDriverLock(priv);

3482
    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
3483 3484 3485
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
3486
        goto done;
3487 3488 3489 3490 3491 3492 3493
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DEFINED_NETWORKS,
              (xdrproc_t) xdr_remote_list_defined_networks_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_defined_networks_ret, (char *) &ret) == -1)
3494
        goto done;
3495 3496

    if (ret.names.names_len > maxnames) {
3497 3498 3499
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
3500
        goto cleanup;
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

3511 3512 3513
    rv = ret.names.names_len;

cleanup:
3514 3515
    xdr_free ((xdrproc_t) xdr_remote_list_defined_networks_ret, (char *) &ret);

3516
done:
3517
    remoteDriverUnlock(priv);
3518
    return rv;
3519 3520 3521 3522 3523 3524
}

static virNetworkPtr
remoteNetworkLookupByUUID (virConnectPtr conn,
                           const unsigned char *uuid)
{
3525
    virNetworkPtr net = NULL;
3526 3527
    remote_network_lookup_by_uuid_args args;
    remote_network_lookup_by_uuid_ret ret;
3528
    struct private_data *priv = conn->networkPrivateData;
3529

3530 3531
    remoteDriverLock(priv);

3532 3533 3534 3535 3536 3537
    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_network_lookup_by_uuid_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_lookup_by_uuid_ret, (char *) &ret) == -1)
3538
        goto done;
3539 3540 3541 3542

    net = get_nonnull_network (conn, ret.net);
    xdr_free ((xdrproc_t) &xdr_remote_network_lookup_by_uuid_ret, (char *) &ret);

3543
done:
3544
    remoteDriverUnlock(priv);
3545 3546 3547 3548 3549 3550 3551
    return net;
}

static virNetworkPtr
remoteNetworkLookupByName (virConnectPtr conn,
                           const char *name)
{
3552
    virNetworkPtr net = NULL;
3553 3554
    remote_network_lookup_by_name_args args;
    remote_network_lookup_by_name_ret ret;
3555
    struct private_data *priv = conn->networkPrivateData;
3556

3557 3558
    remoteDriverLock(priv);

3559 3560 3561 3562 3563 3564
    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_network_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_lookup_by_name_ret, (char *) &ret) == -1)
3565
        goto done;
3566 3567 3568 3569

    net = get_nonnull_network (conn, ret.net);
    xdr_free ((xdrproc_t) &xdr_remote_network_lookup_by_name_ret, (char *) &ret);

3570
done:
3571
    remoteDriverUnlock(priv);
3572 3573 3574 3575 3576 3577
    return net;
}

static virNetworkPtr
remoteNetworkCreateXML (virConnectPtr conn, const char *xmlDesc)
{
3578
    virNetworkPtr net = NULL;
3579 3580
    remote_network_create_xml_args args;
    remote_network_create_xml_ret ret;
3581
    struct private_data *priv = conn->networkPrivateData;
3582

3583 3584
    remoteDriverLock(priv);

3585 3586 3587 3588 3589 3590
    args.xml = (char *) xmlDesc;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_CREATE_XML,
              (xdrproc_t) xdr_remote_network_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_create_xml_ret, (char *) &ret) == -1)
3591
        goto done;
3592 3593 3594 3595

    net = get_nonnull_network (conn, ret.net);
    xdr_free ((xdrproc_t) &xdr_remote_network_create_xml_ret, (char *) &ret);

3596
done:
3597
    remoteDriverUnlock(priv);
3598 3599 3600 3601 3602 3603
    return net;
}

static virNetworkPtr
remoteNetworkDefineXML (virConnectPtr conn, const char *xml)
{
3604
    virNetworkPtr net = NULL;
3605 3606
    remote_network_define_xml_args args;
    remote_network_define_xml_ret ret;
3607
    struct private_data *priv = conn->networkPrivateData;
3608

3609 3610
    remoteDriverLock(priv);

3611 3612 3613 3614 3615 3616
    args.xml = (char *) xml;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_DEFINE_XML,
              (xdrproc_t) xdr_remote_network_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_define_xml_ret, (char *) &ret) == -1)
3617
        goto done;
3618 3619 3620 3621

    net = get_nonnull_network (conn, ret.net);
    xdr_free ((xdrproc_t) &xdr_remote_network_define_xml_ret, (char *) &ret);

3622
done:
3623
    remoteDriverUnlock(priv);
3624 3625 3626 3627 3628 3629
    return net;
}

static int
remoteNetworkUndefine (virNetworkPtr network)
{
3630
    int rv = -1;
3631
    remote_network_undefine_args args;
3632
    struct private_data *priv = network->conn->networkPrivateData;
3633

3634 3635
    remoteDriverLock(priv);

3636 3637 3638 3639 3640
    make_nonnull_network (&args.net, network);

    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_UNDEFINE,
              (xdrproc_t) xdr_remote_network_undefine_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
3641
        goto done;
3642

3643 3644 3645
    rv = 0;

done:
3646
    remoteDriverUnlock(priv);
3647
    return rv;
3648 3649 3650 3651 3652
}

static int
remoteNetworkCreate (virNetworkPtr network)
{
3653
    int rv = -1;
3654
    remote_network_create_args args;
3655
    struct private_data *priv = network->conn->networkPrivateData;
3656

3657 3658
    remoteDriverLock(priv);

3659 3660 3661 3662 3663
    make_nonnull_network (&args.net, network);

    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_CREATE,
              (xdrproc_t) xdr_remote_network_create_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
3664
        goto done;
3665

3666 3667 3668
    rv = 0;

done:
3669
    remoteDriverUnlock(priv);
3670
    return rv;
3671 3672 3673 3674 3675
}

static int
remoteNetworkDestroy (virNetworkPtr network)
{
3676
    int rv = -1;
3677
    remote_network_destroy_args args;
3678
    struct private_data *priv = network->conn->networkPrivateData;
3679

3680 3681
    remoteDriverLock(priv);

3682 3683 3684 3685 3686
    make_nonnull_network (&args.net, network);

    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_DESTROY,
              (xdrproc_t) xdr_remote_network_destroy_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
3687
        goto done;
3688

3689 3690 3691
    rv = 0;

done:
3692
    remoteDriverUnlock(priv);
3693
    return rv;
3694 3695 3696 3697 3698
}

static char *
remoteNetworkDumpXML (virNetworkPtr network, int flags)
{
3699
    char *rv = NULL;
3700 3701
    remote_network_dump_xml_args args;
    remote_network_dump_xml_ret ret;
3702
    struct private_data *priv = network->conn->networkPrivateData;
3703

3704 3705
    remoteDriverLock(priv);

3706 3707 3708 3709 3710 3711 3712
    make_nonnull_network (&args.net, network);
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_DUMP_XML,
              (xdrproc_t) xdr_remote_network_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_dump_xml_ret, (char *) &ret) == -1)
3713
        goto done;
3714 3715

    /* Caller frees. */
3716 3717 3718
    rv = ret.xml;

done:
3719
    remoteDriverUnlock(priv);
3720
    return rv;
3721 3722 3723 3724 3725
}

static char *
remoteNetworkGetBridgeName (virNetworkPtr network)
{
3726
    char *rv = NULL;
3727 3728
    remote_network_get_bridge_name_args args;
    remote_network_get_bridge_name_ret ret;
3729
    struct private_data *priv = network->conn->networkPrivateData;
3730

3731 3732
    remoteDriverLock(priv);

3733 3734 3735 3736 3737 3738
    make_nonnull_network (&args.net, network);

    memset (&ret, 0, sizeof ret);
    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_GET_BRIDGE_NAME,
              (xdrproc_t) xdr_remote_network_get_bridge_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_get_bridge_name_ret, (char *) &ret) == -1)
3739
        goto done;
3740 3741

    /* Caller frees. */
3742 3743 3744
    rv = ret.name;

done:
3745
    remoteDriverUnlock(priv);
3746
    return rv;
3747 3748 3749 3750 3751
}

static int
remoteNetworkGetAutostart (virNetworkPtr network, int *autostart)
{
3752
    int rv = -1;
3753 3754
    remote_network_get_autostart_args args;
    remote_network_get_autostart_ret ret;
3755
    struct private_data *priv = network->conn->networkPrivateData;
3756

3757 3758
    remoteDriverLock(priv);

3759 3760 3761 3762 3763 3764
    make_nonnull_network (&args.net, network);

    memset (&ret, 0, sizeof ret);
    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_GET_AUTOSTART,
              (xdrproc_t) xdr_remote_network_get_autostart_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_get_autostart_ret, (char *) &ret) == -1)
3765
        goto done;
3766 3767 3768

    if (autostart) *autostart = ret.autostart;

3769 3770 3771
    rv = 0;

done:
3772
    remoteDriverUnlock(priv);
3773
    return rv;
3774 3775 3776 3777 3778
}

static int
remoteNetworkSetAutostart (virNetworkPtr network, int autostart)
{
3779
    int rv = -1;
3780
    remote_network_set_autostart_args args;
3781
    struct private_data *priv = network->conn->networkPrivateData;
3782

3783 3784
    remoteDriverLock(priv);

3785 3786 3787 3788 3789 3790
    make_nonnull_network (&args.net, network);
    args.autostart = autostart;

    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_SET_AUTOSTART,
              (xdrproc_t) xdr_remote_network_set_autostart_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
3791
        goto done;
3792

3793 3794 3795
    rv = 0;

done:
3796
    remoteDriverUnlock(priv);
3797
    return rv;
3798 3799
}

3800 3801 3802



D
Daniel Veillard 已提交
3803 3804
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
3805
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
D
Daniel Veillard 已提交
3806
remoteInterfaceOpen (virConnectPtr conn,
J
Jim Meyering 已提交
3807 3808
                     virConnectAuthPtr auth,
                     int flags)
D
Daniel Veillard 已提交
3809 3810 3811 3812
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
3813
    if (conn->driver &&
D
Daniel Veillard 已提交
3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
        STREQ (conn->driver->name, "remote")) {
        struct private_data *priv;

       /* If we're here, the remote driver is already
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
        priv = conn->privateData;
        remoteDriverLock(priv);
        priv->localUses++;
        conn->interfacePrivateData = priv;
        remoteDriverUnlock(priv);
        return VIR_DRV_OPEN_SUCCESS;
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for interface APIs, forcing it to
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the interface APIs.
         */
        struct private_data *priv;
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
            conn->interfacePrivateData = priv;
        return ret;
    }
}

static int
remoteInterfaceClose (virConnectPtr conn)
{
    int rv = 0;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        rv = doRemoteClose(conn, priv);
        conn->interfacePrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
    }
    if (priv)
        remoteDriverUnlock(priv);
    return rv;
}

static int
remoteNumOfInterfaces (virConnectPtr conn)
{
    int rv = -1;
    remote_num_of_interfaces_ret ret;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_INTERFACES,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_interfaces_ret, (char *) &ret) == -1)
        goto done;

    rv = ret.num;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteListInterfaces (virConnectPtr conn, char **const names, int maxnames)
{
    int rv = -1;
    int i;
    remote_list_interfaces_args args;
    remote_list_interfaces_ret ret;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);

    if (maxnames > REMOTE_INTERFACE_NAME_LIST_MAX) {
        errorf (conn, VIR_ERR_RPC,
                _("too many remote interfaces: %d > %d"),
                maxnames, REMOTE_INTERFACE_NAME_LIST_MAX);
        goto done;
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_INTERFACES,
              (xdrproc_t) xdr_remote_list_interfaces_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_interfaces_ret, (char *) &ret) == -1)
        goto done;

    if (ret.names.names_len > maxnames) {
        errorf (conn, VIR_ERR_RPC,
                _("too many remote interfaces: %d > %d"),
                ret.names.names_len, maxnames);
        goto cleanup;
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

    rv = ret.names.names_len;

cleanup:
    xdr_free ((xdrproc_t) xdr_remote_list_interfaces_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
    return rv;
}

3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008
static int
remoteNumOfDefinedInterfaces (virConnectPtr conn)
{
    int rv = -1;
    remote_num_of_defined_interfaces_ret ret;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DEFINED_INTERFACES,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_defined_interfaces_ret, (char *) &ret) == -1)
        goto done;

    rv = ret.num;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteListDefinedInterfaces (virConnectPtr conn, char **const names, int maxnames)
{
    int rv = -1;
    int i;
    remote_list_defined_interfaces_args args;
    remote_list_defined_interfaces_ret ret;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);

    if (maxnames > REMOTE_DEFINED_INTERFACE_NAME_LIST_MAX) {
        errorf (conn, VIR_ERR_RPC,
                _("too many remote interfaces: %d > %d"),
                maxnames, REMOTE_DEFINED_INTERFACE_NAME_LIST_MAX);
        goto done;
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DEFINED_INTERFACES,
              (xdrproc_t) xdr_remote_list_defined_interfaces_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_defined_interfaces_ret, (char *) &ret) == -1)
        goto done;

    if (ret.names.names_len > maxnames) {
        errorf (conn, VIR_ERR_RPC,
                _("too many remote interfaces: %d > %d"),
                ret.names.names_len, maxnames);
        goto cleanup;
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

    rv = ret.names.names_len;

cleanup:
    xdr_free ((xdrproc_t) xdr_remote_list_defined_interfaces_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
    return rv;
}

D
Daniel Veillard 已提交
4009 4010 4011 4012
static virInterfacePtr
remoteInterfaceLookupByName (virConnectPtr conn,
                             const char *name)
{
4013
    virInterfacePtr iface = NULL;
D
Daniel Veillard 已提交
4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027
    remote_interface_lookup_by_name_args args;
    remote_interface_lookup_by_name_ret ret;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);

    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_INTERFACE_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_interface_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_interface_lookup_by_name_ret, (char *) &ret) == -1)
        goto done;

4028
    iface = get_nonnull_interface (conn, ret.iface);
D
Daniel Veillard 已提交
4029 4030 4031 4032
    xdr_free ((xdrproc_t) &xdr_remote_interface_lookup_by_name_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
4033
    return iface;
D
Daniel Veillard 已提交
4034 4035 4036 4037 4038 4039
}

static virInterfacePtr
remoteInterfaceLookupByMACString (virConnectPtr conn,
                                  const char *mac)
{
4040
    virInterfacePtr iface = NULL;
D
Daniel Veillard 已提交
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054
    remote_interface_lookup_by_mac_string_args args;
    remote_interface_lookup_by_mac_string_ret ret;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);

    args.mac = (char *) mac;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_INTERFACE_LOOKUP_BY_MAC_STRING,
              (xdrproc_t) xdr_remote_interface_lookup_by_mac_string_args, (char *) &args,
              (xdrproc_t) xdr_remote_interface_lookup_by_mac_string_ret, (char *) &ret) == -1)
        goto done;

4055
    iface = get_nonnull_interface (conn, ret.iface);
D
Daniel Veillard 已提交
4056 4057 4058 4059
    xdr_free ((xdrproc_t) &xdr_remote_interface_lookup_by_mac_string_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
4060
    return iface;
D
Daniel Veillard 已提交
4061 4062 4063
}

static char *
4064
remoteInterfaceGetXMLDesc (virInterfacePtr iface,
D
Daniel Veillard 已提交
4065 4066 4067 4068 4069
                           unsigned int flags)
{
    char *rv = NULL;
    remote_interface_get_xml_desc_args args;
    remote_interface_get_xml_desc_ret ret;
4070
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4071 4072 4073

    remoteDriverLock(priv);

4074
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4075 4076 4077
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
4078
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_GET_XML_DESC,
D
Daniel Veillard 已提交
4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
              (xdrproc_t) xdr_remote_interface_get_xml_desc_args, (char *) &args,
              (xdrproc_t) xdr_remote_interface_get_xml_desc_ret, (char *) &ret) == -1)
        goto done;

    /* Caller frees. */
    rv = ret.xml;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static virInterfacePtr
remoteInterfaceDefineXML (virConnectPtr conn,
                          const char *xmlDesc,
                          unsigned int flags)
{
4096
    virInterfacePtr iface = NULL;
D
Daniel Veillard 已提交
4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
    remote_interface_define_xml_args args;
    remote_interface_define_xml_ret ret;
    struct private_data *priv = conn->interfacePrivateData;

    remoteDriverLock(priv);

    args.xml = (char *) xmlDesc;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_INTERFACE_DEFINE_XML,
              (xdrproc_t) xdr_remote_interface_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_interface_define_xml_ret, (char *) &ret) == -1)
        goto done;

4112
    iface = get_nonnull_interface (conn, ret.iface);
D
Daniel Veillard 已提交
4113 4114 4115 4116
    xdr_free ((xdrproc_t) &xdr_remote_interface_define_xml_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
4117
    return iface;
D
Daniel Veillard 已提交
4118 4119 4120
}

static int
4121
remoteInterfaceUndefine (virInterfacePtr iface)
D
Daniel Veillard 已提交
4122 4123 4124
{
    int rv = -1;
    remote_interface_undefine_args args;
4125
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4126 4127 4128

    remoteDriverLock(priv);

4129
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4130

4131
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_UNDEFINE,
D
Daniel Veillard 已提交
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143
              (xdrproc_t) xdr_remote_interface_undefine_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
4144
remoteInterfaceCreate (virInterfacePtr iface,
D
Daniel Veillard 已提交
4145 4146 4147 4148
                       unsigned int flags)
{
    int rv = -1;
    remote_interface_create_args args;
4149
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4150 4151 4152

    remoteDriverLock(priv);

4153
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4154 4155
    args.flags = flags;

4156
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_CREATE,
D
Daniel Veillard 已提交
4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
              (xdrproc_t) xdr_remote_interface_create_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
4169
remoteInterfaceDestroy (virInterfacePtr iface,
D
Daniel Veillard 已提交
4170 4171 4172 4173
                        unsigned int flags)
{
    int rv = -1;
    remote_interface_destroy_args args;
4174
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4175 4176 4177

    remoteDriverLock(priv);

4178
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4179 4180
    args.flags = flags;

4181
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_DESTROY,
D
Daniel Veillard 已提交
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192
              (xdrproc_t) xdr_remote_interface_destroy_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

4193 4194
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
4195
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
4196 4197 4198 4199 4200 4201 4202
remoteStorageOpen (virConnectPtr conn,
                   virConnectAuthPtr auth,
                   int flags)
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
4203
    if (conn->driver &&
4204
        STREQ (conn->driver->name, "remote")) {
4205
        struct private_data *priv = conn->privateData;
4206 4207 4208 4209
        /* If we're here, the remote driver is already
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
4210 4211 4212 4213
        remoteDriverLock(priv);
        priv->localUses++;
        conn->storagePrivateData = priv;
        remoteDriverUnlock(priv);
4214 4215 4216
        return VIR_DRV_OPEN_SUCCESS;
    } else if (conn->networkDriver &&
               STREQ (conn->networkDriver->name, "remote")) {
4217 4218 4219 4220 4221
        struct private_data *priv = conn->networkPrivateData;
        remoteDriverLock(priv);
        conn->storagePrivateData = priv;
        priv->localUses++;
        remoteDriverUnlock(priv);
4222 4223 4224 4225 4226 4227 4228
        return VIR_DRV_OPEN_SUCCESS;
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the network APIs.
         */
4229
        struct private_data *priv;
4230 4231 4232 4233 4234 4235
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
4236 4237 4238 4239 4240 4241 4242 4243 4244
            conn->storagePrivateData = priv;
        return ret;
    }
}

static int
remoteStorageClose (virConnectPtr conn)
{
    int ret = 0;
4245 4246
    struct private_data *priv = conn->storagePrivateData;

4247 4248 4249 4250 4251 4252 4253 4254
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        ret = doRemoteClose(conn, priv);
        conn->storagePrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
4255
    }
4256 4257
    if (priv)
        remoteDriverUnlock(priv);
4258

4259 4260 4261 4262 4263 4264
    return ret;
}

static int
remoteNumOfStoragePools (virConnectPtr conn)
{
4265
    int rv = -1;
4266
    remote_num_of_storage_pools_ret ret;
4267
    struct private_data *priv = conn->storagePrivateData;
4268

4269 4270
    remoteDriverLock(priv);

4271 4272 4273 4274
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_STORAGE_POOLS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_storage_pools_ret, (char *) &ret) == -1)
4275 4276 4277
        goto done;

    rv = ret.num;
4278

4279
done:
4280
    remoteDriverUnlock(priv);
4281
    return rv;
4282 4283 4284 4285 4286
}

static int
remoteListStoragePools (virConnectPtr conn, char **const names, int maxnames)
{
4287
    int rv = -1;
4288 4289 4290
    int i;
    remote_list_storage_pools_args args;
    remote_list_storage_pools_ret ret;
4291
    struct private_data *priv = conn->storagePrivateData;
4292

4293 4294
    remoteDriverLock(priv);

4295 4296
    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
4297
        goto done;
4298 4299 4300 4301 4302 4303 4304
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_STORAGE_POOLS,
              (xdrproc_t) xdr_remote_list_storage_pools_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_storage_pools_ret, (char *) &ret) == -1)
4305
        goto done;
4306 4307 4308

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
4309
        goto cleanup;
4310 4311 4312 4313 4314 4315 4316 4317 4318 4319
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

4320 4321 4322
    rv = ret.names.names_len;

cleanup:
4323 4324
    xdr_free ((xdrproc_t) xdr_remote_list_storage_pools_ret, (char *) &ret);

4325
done:
4326
    remoteDriverUnlock(priv);
4327
    return rv;
4328 4329 4330 4331 4332
}

static int
remoteNumOfDefinedStoragePools (virConnectPtr conn)
{
4333
    int rv = -1;
4334
    remote_num_of_defined_storage_pools_ret ret;
4335
    struct private_data *priv = conn->storagePrivateData;
4336

4337 4338
    remoteDriverLock(priv);

4339 4340 4341 4342
    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DEFINED_STORAGE_POOLS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_defined_storage_pools_ret, (char *) &ret) == -1)
4343
        goto done;
4344

4345 4346 4347
    rv = ret.num;

done:
4348
    remoteDriverUnlock(priv);
4349
    return rv;
4350 4351 4352 4353 4354 4355
}

static int
remoteListDefinedStoragePools (virConnectPtr conn,
                               char **const names, int maxnames)
{
4356
    int rv = -1;
4357 4358 4359
    int i;
    remote_list_defined_storage_pools_args args;
    remote_list_defined_storage_pools_ret ret;
4360
    struct private_data *priv = conn->storagePrivateData;
4361

4362 4363
    remoteDriverLock(priv);

4364 4365
    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
4366
        goto done;
4367 4368 4369 4370 4371 4372 4373
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DEFINED_STORAGE_POOLS,
              (xdrproc_t) xdr_remote_list_defined_storage_pools_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_defined_storage_pools_ret, (char *) &ret) == -1)
4374
        goto done;
4375 4376 4377

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
4378
        goto cleanup;
4379 4380 4381 4382 4383 4384 4385 4386 4387 4388
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

4389 4390 4391
    rv = ret.names.names_len;

cleanup:
4392 4393
    xdr_free ((xdrproc_t) xdr_remote_list_defined_storage_pools_ret, (char *) &ret);

4394
done:
4395
    remoteDriverUnlock(priv);
4396
    return rv;
4397 4398
}

4399 4400 4401 4402 4403 4404
static char *
remoteFindStoragePoolSources (virConnectPtr conn,
                              const char *type,
                              const char *srcSpec,
                              unsigned int flags)
{
4405
    char *rv = NULL;
4406 4407
    remote_find_storage_pool_sources_args args;
    remote_find_storage_pool_sources_ret ret;
4408
    struct private_data *priv = conn->storagePrivateData;
4409 4410
    const char *emptyString = "";

4411 4412
    remoteDriverLock(priv);

4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431
    args.type = (char*)type;
    /*
     * I'd think the following would work here:
     *    args.srcSpec = (char**)&srcSpec;
     * since srcSpec is a remote_string (not a remote_nonnull_string).
     *
     * But when srcSpec is NULL, this yields:
     *    libvir: Remote error : marshalling args
     *
     * So for now I'm working around this by turning NULL srcSpecs
     * into empty strings.
     */
    args.srcSpec = srcSpec ? (char **)&srcSpec : (char **)&emptyString;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_FIND_STORAGE_POOL_SOURCES,
              (xdrproc_t) xdr_remote_find_storage_pool_sources_args, (char *) &args,
              (xdrproc_t) xdr_remote_find_storage_pool_sources_ret, (char *) &ret) == -1)
4432
        goto done;
4433

4434
    rv = ret.xml;
4435 4436 4437 4438
    ret.xml = NULL; /* To stop xdr_free free'ing it */

    xdr_free ((xdrproc_t) xdr_remote_find_storage_pool_sources_ret, (char *) &ret);

4439
done:
4440
    remoteDriverUnlock(priv);
4441
    return rv;
4442 4443
}

4444 4445 4446 4447
static virStoragePoolPtr
remoteStoragePoolLookupByUUID (virConnectPtr conn,
                               const unsigned char *uuid)
{
4448
    virStoragePoolPtr pool = NULL;
4449 4450
    remote_storage_pool_lookup_by_uuid_args args;
    remote_storage_pool_lookup_by_uuid_ret ret;
4451
    struct private_data *priv = conn->storagePrivateData;
4452

4453 4454
    remoteDriverLock(priv);

4455 4456 4457 4458 4459 4460
    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_uuid_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_uuid_ret, (char *) &ret) == -1)
4461
        goto done;
4462 4463 4464 4465

    pool = get_nonnull_storage_pool (conn, ret.pool);
    xdr_free ((xdrproc_t) &xdr_remote_storage_pool_lookup_by_uuid_ret, (char *) &ret);

4466
done:
4467
    remoteDriverUnlock(priv);
4468 4469 4470 4471 4472 4473 4474
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByName (virConnectPtr conn,
                               const char *name)
{
4475
    virStoragePoolPtr pool = NULL;
4476 4477
    remote_storage_pool_lookup_by_name_args args;
    remote_storage_pool_lookup_by_name_ret ret;
4478
    struct private_data *priv = conn->storagePrivateData;
4479

4480 4481
    remoteDriverLock(priv);

4482 4483 4484 4485 4486 4487
    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_name_ret, (char *) &ret) == -1)
4488
        goto done;
4489 4490 4491 4492

    pool = get_nonnull_storage_pool (conn, ret.pool);
    xdr_free ((xdrproc_t) &xdr_remote_storage_pool_lookup_by_name_ret, (char *) &ret);

4493
done:
4494
    remoteDriverUnlock(priv);
4495 4496 4497 4498 4499 4500
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByVolume (virStorageVolPtr vol)
{
4501
    virStoragePoolPtr pool = NULL;
4502 4503
    remote_storage_pool_lookup_by_volume_args args;
    remote_storage_pool_lookup_by_volume_ret ret;
4504
    struct private_data *priv = vol->conn->storagePrivateData;
4505

4506 4507
    remoteDriverLock(priv);

4508 4509 4510 4511 4512 4513
    make_nonnull_storage_vol (&args.vol, vol);

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LOOKUP_BY_VOLUME,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_volume_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_volume_ret, (char *) &ret) == -1)
4514
        goto done;
4515 4516 4517 4518

    pool = get_nonnull_storage_pool (vol->conn, ret.pool);
    xdr_free ((xdrproc_t) &xdr_remote_storage_pool_lookup_by_volume_ret, (char *) &ret);

4519
done:
4520
    remoteDriverUnlock(priv);
4521 4522 4523 4524 4525 4526 4527
    return pool;
}


static virStoragePoolPtr
remoteStoragePoolCreateXML (virConnectPtr conn, const char *xmlDesc, unsigned int flags)
{
4528
    virStoragePoolPtr pool = NULL;
4529 4530
    remote_storage_pool_create_xml_args args;
    remote_storage_pool_create_xml_ret ret;
4531
    struct private_data *priv = conn->storagePrivateData;
4532

4533 4534
    remoteDriverLock(priv);

4535 4536 4537 4538 4539 4540 4541
    args.xml = (char *) xmlDesc;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_CREATE_XML,
              (xdrproc_t) xdr_remote_storage_pool_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_create_xml_ret, (char *) &ret) == -1)
4542
        goto done;
4543 4544 4545 4546

    pool = get_nonnull_storage_pool (conn, ret.pool);
    xdr_free ((xdrproc_t) &xdr_remote_storage_pool_create_xml_ret, (char *) &ret);

4547
done:
4548
    remoteDriverUnlock(priv);
4549 4550 4551 4552 4553 4554
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolDefineXML (virConnectPtr conn, const char *xml, unsigned int flags)
{
4555
    virStoragePoolPtr pool = NULL;
4556 4557
    remote_storage_pool_define_xml_args args;
    remote_storage_pool_define_xml_ret ret;
4558
    struct private_data *priv = conn->storagePrivateData;
4559

4560 4561
    remoteDriverLock(priv);

4562 4563 4564 4565 4566 4567 4568
    args.xml = (char *) xml;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_DEFINE_XML,
              (xdrproc_t) xdr_remote_storage_pool_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_define_xml_ret, (char *) &ret) == -1)
4569
        goto done;
4570 4571 4572 4573

    pool = get_nonnull_storage_pool (conn, ret.pool);
    xdr_free ((xdrproc_t) &xdr_remote_storage_pool_define_xml_ret, (char *) &ret);

4574
done:
4575
    remoteDriverUnlock(priv);
4576 4577 4578 4579 4580 4581
    return pool;
}

static int
remoteStoragePoolUndefine (virStoragePoolPtr pool)
{
4582
    int rv = -1;
4583
    remote_storage_pool_undefine_args args;
4584
    struct private_data *priv = pool->conn->storagePrivateData;
4585

4586 4587
    remoteDriverLock(priv);

4588 4589 4590 4591 4592
    make_nonnull_storage_pool (&args.pool, pool);

    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_UNDEFINE,
              (xdrproc_t) xdr_remote_storage_pool_undefine_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
4593
        goto done;
4594

4595 4596 4597
    rv = 0;

done:
4598
    remoteDriverUnlock(priv);
4599
    return rv;
4600 4601 4602 4603 4604
}

static int
remoteStoragePoolCreate (virStoragePoolPtr pool, unsigned int flags)
{
4605
    int rv = -1;
4606
    remote_storage_pool_create_args args;
4607
    struct private_data *priv = pool->conn->storagePrivateData;
4608

4609 4610
    remoteDriverLock(priv);

4611 4612 4613 4614 4615 4616
    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_CREATE,
              (xdrproc_t) xdr_remote_storage_pool_create_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
4617
        goto done;
4618

4619 4620 4621
    rv = 0;

done:
4622
    remoteDriverUnlock(priv);
4623
    return rv;
4624 4625 4626 4627 4628 4629
}

static int
remoteStoragePoolBuild (virStoragePoolPtr pool,
                        unsigned int flags)
{
4630
    int rv = -1;
4631
    remote_storage_pool_build_args args;
4632
    struct private_data *priv = pool->conn->storagePrivateData;
4633

4634 4635
    remoteDriverLock(priv);

4636 4637 4638 4639 4640 4641
    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_BUILD,
              (xdrproc_t) xdr_remote_storage_pool_build_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
4642
        goto done;
4643

4644 4645 4646
    rv = 0;

done:
4647
    remoteDriverUnlock(priv);
4648
    return rv;
4649 4650 4651 4652 4653
}

static int
remoteStoragePoolDestroy (virStoragePoolPtr pool)
{
4654
    int rv = -1;
4655
    remote_storage_pool_destroy_args args;
4656
    struct private_data *priv = pool->conn->storagePrivateData;
4657

4658 4659
    remoteDriverLock(priv);

4660 4661 4662 4663 4664
    make_nonnull_storage_pool (&args.pool, pool);

    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_DESTROY,
              (xdrproc_t) xdr_remote_storage_pool_destroy_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
4665
        goto done;
4666

4667 4668 4669
    rv = 0;

done:
4670
    remoteDriverUnlock(priv);
4671
    return rv;
4672 4673 4674 4675 4676 4677
}

static int
remoteStoragePoolDelete (virStoragePoolPtr pool,
                         unsigned int flags)
{
4678
    int rv = -1;
4679
    remote_storage_pool_delete_args args;
4680
    struct private_data *priv = pool->conn->storagePrivateData;
4681

4682 4683
    remoteDriverLock(priv);

4684 4685 4686 4687 4688 4689
    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_DELETE,
              (xdrproc_t) xdr_remote_storage_pool_delete_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
4690
        goto done;
4691

4692 4693 4694
    rv = 0;

done:
4695
    remoteDriverUnlock(priv);
4696
    return rv;
4697 4698 4699 4700 4701 4702
}

static int
remoteStoragePoolRefresh (virStoragePoolPtr pool,
                          unsigned int flags)
{
4703
    int rv = -1;
4704
    remote_storage_pool_refresh_args args;
4705
    struct private_data *priv = pool->conn->storagePrivateData;
4706

4707 4708
    remoteDriverLock(priv);

4709 4710 4711 4712 4713 4714
    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_REFRESH,
              (xdrproc_t) xdr_remote_storage_pool_refresh_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
4715
        goto done;
4716

4717 4718 4719
    rv = 0;

done:
4720
    remoteDriverUnlock(priv);
4721
    return rv;
4722 4723 4724 4725 4726
}

static int
remoteStoragePoolGetInfo (virStoragePoolPtr pool, virStoragePoolInfoPtr info)
{
4727
    int rv = -1;
4728 4729
    remote_storage_pool_get_info_args args;
    remote_storage_pool_get_info_ret ret;
4730
    struct private_data *priv = pool->conn->storagePrivateData;
4731

4732 4733
    remoteDriverLock(priv);

4734 4735 4736 4737 4738 4739
    make_nonnull_storage_pool (&args.pool, pool);

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_GET_INFO,
              (xdrproc_t) xdr_remote_storage_pool_get_info_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_get_info_ret, (char *) &ret) == -1)
4740
        goto done;
4741 4742 4743 4744 4745 4746

    info->state = ret.state;
    info->capacity = ret.capacity;
    info->allocation = ret.allocation;
    info->available = ret.available;

4747 4748 4749
    rv = 0;

done:
4750
    remoteDriverUnlock(priv);
4751
    return rv;
4752 4753 4754 4755 4756 4757
}

static char *
remoteStoragePoolDumpXML (virStoragePoolPtr pool,
                          unsigned int flags)
{
4758
    char *rv = NULL;
4759 4760
    remote_storage_pool_dump_xml_args args;
    remote_storage_pool_dump_xml_ret ret;
4761
    struct private_data *priv = pool->conn->storagePrivateData;
4762

4763 4764
    remoteDriverLock(priv);

4765 4766 4767 4768 4769 4770 4771
    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_DUMP_XML,
              (xdrproc_t) xdr_remote_storage_pool_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_dump_xml_ret, (char *) &ret) == -1)
4772
        goto done;
4773 4774

    /* Caller frees. */
4775 4776 4777
    rv = ret.xml;

done:
4778
    remoteDriverUnlock(priv);
4779
    return rv;
4780 4781 4782 4783 4784
}

static int
remoteStoragePoolGetAutostart (virStoragePoolPtr pool, int *autostart)
{
4785
    int rv = -1;
4786 4787
    remote_storage_pool_get_autostart_args args;
    remote_storage_pool_get_autostart_ret ret;
4788
    struct private_data *priv = pool->conn->storagePrivateData;
4789

4790 4791
    remoteDriverLock(priv);

4792 4793 4794 4795 4796 4797
    make_nonnull_storage_pool (&args.pool, pool);

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_GET_AUTOSTART,
              (xdrproc_t) xdr_remote_storage_pool_get_autostart_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_get_autostart_ret, (char *) &ret) == -1)
4798
        goto done;
4799 4800 4801

    if (autostart) *autostart = ret.autostart;

4802 4803 4804
    rv = 0;

done:
4805
    remoteDriverUnlock(priv);
4806
    return rv;
4807 4808 4809 4810 4811
}

static int
remoteStoragePoolSetAutostart (virStoragePoolPtr pool, int autostart)
{
4812
    int rv = -1;
4813
    remote_storage_pool_set_autostart_args args;
4814
    struct private_data *priv = pool->conn->storagePrivateData;
4815

4816 4817
    remoteDriverLock(priv);

4818 4819 4820 4821 4822 4823
    make_nonnull_storage_pool (&args.pool, pool);
    args.autostart = autostart;

    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_SET_AUTOSTART,
              (xdrproc_t) xdr_remote_storage_pool_set_autostart_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
4824
        goto done;
4825

4826 4827 4828
    rv = 0;

done:
4829
    remoteDriverUnlock(priv);
4830
    return rv;
4831 4832 4833 4834 4835 4836
}


static int
remoteStoragePoolNumOfVolumes (virStoragePoolPtr pool)
{
4837
    int rv = -1;
4838 4839
    remote_storage_pool_num_of_volumes_args args;
    remote_storage_pool_num_of_volumes_ret ret;
4840
    struct private_data *priv = pool->conn->storagePrivateData;
4841

4842 4843
    remoteDriverLock(priv);

4844 4845 4846 4847 4848 4849
    make_nonnull_storage_pool(&args.pool, pool);

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_NUM_OF_VOLUMES,
              (xdrproc_t) xdr_remote_storage_pool_num_of_volumes_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_num_of_volumes_ret, (char *) &ret) == -1)
4850 4851 4852
        goto done;

    rv = ret.num;
4853

4854
done:
4855
    remoteDriverUnlock(priv);
4856
    return rv;
4857 4858 4859 4860 4861
}

static int
remoteStoragePoolListVolumes (virStoragePoolPtr pool, char **const names, int maxnames)
{
4862
    int rv = -1;
4863 4864 4865
    int i;
    remote_storage_pool_list_volumes_args args;
    remote_storage_pool_list_volumes_ret ret;
4866
    struct private_data *priv = pool->conn->storagePrivateData;
4867

4868 4869
    remoteDriverLock(priv);

4870 4871
    if (maxnames > REMOTE_STORAGE_VOL_NAME_LIST_MAX) {
        error (pool->conn, VIR_ERR_RPC, _("too many storage volumes requested"));
4872
        goto done;
4873 4874 4875 4876 4877 4878 4879 4880
    }
    args.maxnames = maxnames;
    make_nonnull_storage_pool(&args.pool, pool);

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LIST_VOLUMES,
              (xdrproc_t) xdr_remote_storage_pool_list_volumes_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_list_volumes_ret, (char *) &ret) == -1)
4881
        goto done;
4882 4883 4884

    if (ret.names.names_len > maxnames) {
        error (pool->conn, VIR_ERR_RPC, _("too many storage volumes received"));
4885
        goto cleanup;
4886 4887 4888 4889 4890 4891 4892 4893 4894 4895
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

4896 4897 4898
    rv = ret.names.names_len;

cleanup:
4899 4900
    xdr_free ((xdrproc_t) xdr_remote_storage_pool_list_volumes_ret, (char *) &ret);

4901
done:
4902
    remoteDriverUnlock(priv);
4903
    return rv;
4904 4905 4906 4907 4908 4909 4910 4911
}



static virStorageVolPtr
remoteStorageVolLookupByName (virStoragePoolPtr pool,
                              const char *name)
{
4912
    virStorageVolPtr vol = NULL;
4913 4914
    remote_storage_vol_lookup_by_name_args args;
    remote_storage_vol_lookup_by_name_ret ret;
4915
    struct private_data *priv = pool->conn->storagePrivateData;
4916

4917 4918
    remoteDriverLock(priv);

4919 4920 4921 4922 4923 4924 4925
    make_nonnull_storage_pool(&args.pool, pool);
    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_name_ret, (char *) &ret) == -1)
4926
        goto done;
4927 4928 4929 4930

    vol = get_nonnull_storage_vol (pool->conn, ret.vol);
    xdr_free ((xdrproc_t) &xdr_remote_storage_vol_lookup_by_name_ret, (char *) &ret);

4931
done:
4932
    remoteDriverUnlock(priv);
4933 4934 4935 4936 4937 4938 4939
    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByKey (virConnectPtr conn,
                             const char *key)
{
4940
    virStorageVolPtr  vol = NULL;
4941 4942
    remote_storage_vol_lookup_by_key_args args;
    remote_storage_vol_lookup_by_key_ret ret;
4943
    struct private_data *priv = conn->storagePrivateData;
4944

4945 4946
    remoteDriverLock(priv);

4947 4948 4949 4950 4951 4952
    args.key = (char *) key;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_VOL_LOOKUP_BY_KEY,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_key_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_key_ret, (char *) &ret) == -1)
4953
        goto done;
4954 4955 4956 4957

    vol = get_nonnull_storage_vol (conn, ret.vol);
    xdr_free ((xdrproc_t) &xdr_remote_storage_vol_lookup_by_key_ret, (char *) &ret);

4958
done:
4959
    remoteDriverUnlock(priv);
4960 4961 4962 4963 4964 4965 4966
    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByPath (virConnectPtr conn,
                              const char *path)
{
4967
    virStorageVolPtr vol = NULL;
4968 4969
    remote_storage_vol_lookup_by_path_args args;
    remote_storage_vol_lookup_by_path_ret ret;
4970
    struct private_data *priv = conn->storagePrivateData;
4971

4972 4973
    remoteDriverLock(priv);

4974 4975 4976 4977 4978 4979
    args.path = (char *) path;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_VOL_LOOKUP_BY_PATH,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_path_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_path_ret, (char *) &ret) == -1)
4980
        goto done;
4981 4982 4983 4984

    vol = get_nonnull_storage_vol (conn, ret.vol);
    xdr_free ((xdrproc_t) &xdr_remote_storage_vol_lookup_by_path_ret, (char *) &ret);

4985
done:
4986
    remoteDriverUnlock(priv);
4987 4988 4989 4990 4991 4992 4993
    return vol;
}

static virStorageVolPtr
remoteStorageVolCreateXML (virStoragePoolPtr pool, const char *xmlDesc,
                           unsigned int flags)
{
4994
    virStorageVolPtr vol = NULL;
4995 4996
    remote_storage_vol_create_xml_args args;
    remote_storage_vol_create_xml_ret ret;
4997
    struct private_data *priv = pool->conn->storagePrivateData;
4998

4999 5000
    remoteDriverLock(priv);

5001 5002 5003 5004 5005 5006 5007 5008
    make_nonnull_storage_pool (&args.pool, pool);
    args.xml = (char *) xmlDesc;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_CREATE_XML,
              (xdrproc_t) xdr_remote_storage_vol_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_create_xml_ret, (char *) &ret) == -1)
5009
        goto done;
5010 5011 5012 5013

    vol = get_nonnull_storage_vol (pool->conn, ret.vol);
    xdr_free ((xdrproc_t) &xdr_remote_storage_vol_create_xml_ret, (char *) &ret);

5014
done:
5015
    remoteDriverUnlock(priv);
5016 5017 5018
    return vol;
}

5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
static virStorageVolPtr
remoteStorageVolCreateXMLFrom (virStoragePoolPtr pool,
                               const char *xmlDesc,
                               virStorageVolPtr clonevol,
                               unsigned int flags)
{
    virStorageVolPtr newvol = NULL;
    remote_storage_vol_create_xml_from_args args;
    remote_storage_vol_create_xml_from_ret ret;
    struct private_data *priv = pool->conn->storagePrivateData;

    remoteDriverLock(priv);

    make_nonnull_storage_pool (&args.pool, pool);
    make_nonnull_storage_vol (&args.clonevol, clonevol);
    args.xml = (char *) xmlDesc;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_CREATE_XML_FROM,
              (xdrproc_t) xdr_remote_storage_vol_create_xml_from_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_create_xml_from_ret, (char *) &ret) == -1)
        goto done;

    newvol = get_nonnull_storage_vol (pool->conn, ret.vol);
    xdr_free ((xdrproc_t) &xdr_remote_storage_vol_create_xml_from_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
    return newvol;
}

5051 5052 5053 5054
static int
remoteStorageVolDelete (virStorageVolPtr vol,
                        unsigned int flags)
{
5055
    int rv = -1;
5056
    remote_storage_vol_delete_args args;
5057
    struct private_data *priv = vol->conn->storagePrivateData;
5058

5059 5060
    remoteDriverLock(priv);

5061 5062 5063 5064 5065 5066
    make_nonnull_storage_vol (&args.vol, vol);
    args.flags = flags;

    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_DELETE,
              (xdrproc_t) xdr_remote_storage_vol_delete_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
5067
        goto done;
5068

5069 5070 5071
    rv = 0;

done:
5072
    remoteDriverUnlock(priv);
5073
    return rv;
5074 5075 5076 5077 5078
}

static int
remoteStorageVolGetInfo (virStorageVolPtr vol, virStorageVolInfoPtr info)
{
5079
    int rv = -1;
5080 5081
    remote_storage_vol_get_info_args args;
    remote_storage_vol_get_info_ret ret;
5082
    struct private_data *priv = vol->conn->storagePrivateData;
5083

5084 5085
    remoteDriverLock(priv);

5086 5087 5088 5089 5090 5091
    make_nonnull_storage_vol (&args.vol, vol);

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_GET_INFO,
              (xdrproc_t) xdr_remote_storage_vol_get_info_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_get_info_ret, (char *) &ret) == -1)
5092
        goto done;
5093 5094 5095 5096 5097

    info->type = ret.type;
    info->capacity = ret.capacity;
    info->allocation = ret.allocation;

5098 5099 5100
    rv = 0;

done:
5101
    remoteDriverUnlock(priv);
5102
    return rv;
5103 5104 5105 5106 5107 5108
}

static char *
remoteStorageVolDumpXML (virStorageVolPtr vol,
                         unsigned int flags)
{
5109
    char *rv = NULL;
5110 5111
    remote_storage_vol_dump_xml_args args;
    remote_storage_vol_dump_xml_ret ret;
5112
    struct private_data *priv = vol->conn->storagePrivateData;
5113

5114 5115
    remoteDriverLock(priv);

5116 5117 5118 5119 5120 5121 5122
    make_nonnull_storage_vol (&args.vol, vol);
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_DUMP_XML,
              (xdrproc_t) xdr_remote_storage_vol_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_dump_xml_ret, (char *) &ret) == -1)
5123
        goto done;
5124 5125

    /* Caller frees. */
5126 5127 5128
    rv = ret.xml;

done:
5129
    remoteDriverUnlock(priv);
5130
    return rv;
5131 5132 5133 5134 5135
}

static char *
remoteStorageVolGetPath (virStorageVolPtr vol)
{
5136
    char *rv = NULL;
5137 5138
    remote_storage_vol_get_path_args args;
    remote_storage_vol_get_path_ret ret;
5139
    struct private_data *priv = vol->conn->storagePrivateData;
5140

5141 5142
    remoteDriverLock(priv);

5143 5144 5145 5146 5147 5148
    make_nonnull_storage_vol (&args.vol, vol);

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_GET_PATH,
              (xdrproc_t) xdr_remote_storage_vol_get_path_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_get_path_ret, (char *) &ret) == -1)
5149
        goto done;
5150 5151

    /* Caller frees. */
5152 5153 5154
    rv = ret.name;

done:
5155
    remoteDriverUnlock(priv);
5156
    return rv;
5157 5158 5159
}


5160 5161
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
5162
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
5163 5164 5165 5166
remoteDevMonOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 int flags ATTRIBUTE_UNUSED)
{
5167 5168 5169
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
5170
    if (conn->driver &&
5171
        STREQ (conn->driver->name, "remote")) {
5172
        struct private_data *priv = conn->privateData;
5173 5174 5175 5176
        /* If we're here, the remote driver is already
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
5177 5178 5179 5180
        remoteDriverLock(priv);
        priv->localUses++;
        conn->devMonPrivateData = priv;
        remoteDriverUnlock(priv);
5181
        return VIR_DRV_OPEN_SUCCESS;
5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196
    } else if (conn->networkDriver &&
               STREQ (conn->networkDriver->name, "remote")) {
        struct private_data *priv = conn->networkPrivateData;
        remoteDriverLock(priv);
        conn->devMonPrivateData = priv;
        priv->localUses++;
        remoteDriverUnlock(priv);
        return VIR_DRV_OPEN_SUCCESS;
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the network APIs.
         */
        struct private_data *priv;
5197 5198 5199 5200 5201 5202
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
5203 5204 5205
            conn->devMonPrivateData = priv;
        return ret;
    }
5206 5207 5208 5209 5210
}

static int remoteDevMonClose(virConnectPtr conn)
{
    int ret = 0;
5211 5212
    struct private_data *priv = conn->devMonPrivateData;

5213 5214 5215 5216 5217 5218 5219 5220
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        ret = doRemoteClose(conn, priv);
        conn->devMonPrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
5221
    }
5222 5223
    if (priv)
        remoteDriverUnlock(priv);
5224 5225 5226 5227 5228 5229 5230
    return ret;
}

static int remoteNodeNumOfDevices(virConnectPtr conn,
                                  const char *cap,
                                  unsigned int flags)
{
5231
    int rv = -1;
5232 5233
    remote_node_num_of_devices_args args;
    remote_node_num_of_devices_ret ret;
5234
    struct private_data *priv = conn->devMonPrivateData;
5235

5236 5237
    remoteDriverLock(priv);

5238 5239 5240 5241 5242 5243 5244
    args.cap = cap ? (char **)&cap : NULL;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_NUM_OF_DEVICES,
              (xdrproc_t) xdr_remote_node_num_of_devices_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_num_of_devices_ret, (char *) &ret) == -1)
5245 5246 5247
        goto done;

    rv = ret.num;
5248

5249
done:
5250
    remoteDriverUnlock(priv);
5251
    return rv;
5252 5253 5254 5255 5256 5257 5258 5259 5260
}


static int remoteNodeListDevices(virConnectPtr conn,
                                 const char *cap,
                                 char **const names,
                                 int maxnames,
                                 unsigned int flags)
{
5261
    int rv = -1;
5262 5263 5264
    int i;
    remote_node_list_devices_args args;
    remote_node_list_devices_ret ret;
5265
    struct private_data *priv = conn->devMonPrivateData;
5266

5267 5268
    remoteDriverLock(priv);

5269 5270
    if (maxnames > REMOTE_NODE_DEVICE_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many device names requested"));
5271
        goto done;
5272 5273 5274 5275 5276 5277 5278 5279 5280
    }
    args.cap = cap ? (char **)&cap : NULL;
    args.maxnames = maxnames;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_LIST_DEVICES,
              (xdrproc_t) xdr_remote_node_list_devices_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_list_devices_ret, (char *) &ret) == -1)
5281
        goto done;
5282 5283 5284

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many device names received"));
5285
        goto cleanup;
5286 5287 5288 5289 5290 5291 5292 5293 5294 5295
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

5296 5297 5298
    rv = ret.names.names_len;

cleanup:
5299 5300
    xdr_free ((xdrproc_t) xdr_remote_node_list_devices_ret, (char *) &ret);

5301
done:
5302
    remoteDriverUnlock(priv);
5303
    return rv;
5304 5305 5306 5307 5308 5309 5310 5311
}


static virNodeDevicePtr remoteNodeDeviceLookupByName(virConnectPtr conn,
                                                     const char *name)
{
    remote_node_device_lookup_by_name_args args;
    remote_node_device_lookup_by_name_ret ret;
5312
    virNodeDevicePtr dev = NULL;
5313
    struct private_data *priv = conn->devMonPrivateData;
5314

5315 5316
    remoteDriverLock(priv);

5317 5318 5319 5320 5321 5322
    args.name = (char *)name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_DEVICE_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_node_device_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_lookup_by_name_ret, (char *) &ret) == -1)
5323
        goto done;
5324 5325 5326 5327 5328

    dev = get_nonnull_node_device(conn, ret.dev);

    xdr_free ((xdrproc_t) xdr_remote_node_device_lookup_by_name_ret, (char *) &ret);

5329
done:
5330
    remoteDriverUnlock(priv);
5331 5332 5333 5334 5335 5336
    return dev;
}

static char *remoteNodeDeviceDumpXML(virNodeDevicePtr dev,
                                     unsigned int flags)
{
5337
    char *rv = NULL;
5338 5339
    remote_node_device_dump_xml_args args;
    remote_node_device_dump_xml_ret ret;
5340
    struct private_data *priv = dev->conn->devMonPrivateData;
5341

5342 5343
    remoteDriverLock(priv);

5344 5345 5346 5347 5348 5349 5350
    args.name = dev->name;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_DUMP_XML,
              (xdrproc_t) xdr_remote_node_device_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_dump_xml_ret, (char *) &ret) == -1)
5351
        goto done;
5352 5353

    /* Caller frees. */
5354 5355 5356
    rv = ret.xml;

done:
5357
    remoteDriverUnlock(priv);
5358
    return rv;
5359 5360 5361 5362
}

static char *remoteNodeDeviceGetParent(virNodeDevicePtr dev)
{
5363
    char *rv = NULL;
5364 5365
    remote_node_device_get_parent_args args;
    remote_node_device_get_parent_ret ret;
5366
    struct private_data *priv = dev->conn->devMonPrivateData;
5367

5368 5369
    remoteDriverLock(priv);

5370 5371 5372 5373 5374 5375
    args.name = dev->name;

    memset (&ret, 0, sizeof ret);
    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_GET_PARENT,
              (xdrproc_t) xdr_remote_node_device_get_parent_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_get_parent_ret, (char *) &ret) == -1)
5376
        goto done;
5377 5378

    /* Caller frees. */
5379
    rv = ret.parent ? *ret.parent : NULL;
5380
    VIR_FREE(ret.parent);
5381 5382

done:
5383
    remoteDriverUnlock(priv);
5384
    return rv;
5385 5386 5387 5388
}

static int remoteNodeDeviceNumOfCaps(virNodeDevicePtr dev)
{
5389
    int rv = -1;
5390 5391
    remote_node_device_num_of_caps_args args;
    remote_node_device_num_of_caps_ret ret;
5392
    struct private_data *priv = dev->conn->devMonPrivateData;
5393

5394 5395
    remoteDriverLock(priv);

5396 5397 5398 5399 5400 5401
    args.name = dev->name;

    memset (&ret, 0, sizeof ret);
    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_NUM_OF_CAPS,
              (xdrproc_t) xdr_remote_node_device_num_of_caps_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_num_of_caps_ret, (char *) &ret) == -1)
5402 5403 5404
        goto done;

    rv = ret.num;
5405

5406
done:
5407
    remoteDriverUnlock(priv);
5408
    return rv;
5409 5410 5411 5412 5413 5414
}

static int remoteNodeDeviceListCaps(virNodeDevicePtr dev,
                                    char **const names,
                                    int maxnames)
{
5415
    int rv = -1;
5416 5417 5418
    int i;
    remote_node_device_list_caps_args args;
    remote_node_device_list_caps_ret ret;
5419
    struct private_data *priv = dev->conn->devMonPrivateData;
5420

5421 5422
    remoteDriverLock(priv);

5423 5424
    if (maxnames > REMOTE_NODE_DEVICE_CAPS_LIST_MAX) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names requested"));
5425
        goto done;
5426 5427 5428 5429 5430 5431 5432 5433
    }
    args.maxnames = maxnames;
    args.name = dev->name;

    memset (&ret, 0, sizeof ret);
    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_LIST_CAPS,
              (xdrproc_t) xdr_remote_node_device_list_caps_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_list_caps_ret, (char *) &ret) == -1)
5434
        goto done;
5435 5436 5437

    if (ret.names.names_len > maxnames) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names received"));
5438
        goto cleanup;
5439 5440 5441 5442 5443 5444 5445 5446 5447 5448
    }

    /* This call is caller-frees (although that isn't clear from
     * the documentation).  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.names.names_len; ++i)
        names[i] = strdup (ret.names.names_val[i]);

5449 5450 5451
    rv = ret.names.names_len;

cleanup:
5452 5453
    xdr_free ((xdrproc_t) xdr_remote_node_device_list_caps_ret, (char *) &ret);

5454
done:
5455
    remoteDriverUnlock(priv);
5456
    return rv;
5457 5458
}

5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527
static int
remoteNodeDeviceDettach (virNodeDevicePtr dev)
{
    int rv = -1;
    remote_node_device_dettach_args args;
    struct private_data *priv = dev->conn->privateData;

    remoteDriverLock(priv);

    args.name = dev->name;

    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_DETTACH,
              (xdrproc_t) xdr_remote_node_device_dettach_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteNodeDeviceReAttach (virNodeDevicePtr dev)
{
    int rv = -1;
    remote_node_device_re_attach_args args;
    struct private_data *priv = dev->conn->privateData;

    remoteDriverLock(priv);

    args.name = dev->name;

    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_RE_ATTACH,
              (xdrproc_t) xdr_remote_node_device_re_attach_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteNodeDeviceReset (virNodeDevicePtr dev)
{
    int rv = -1;
    remote_node_device_reset_args args;
    struct private_data *priv = dev->conn->privateData;

    remoteDriverLock(priv);

    args.name = dev->name;

    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_RESET,
              (xdrproc_t) xdr_remote_node_device_reset_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

5528

5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568
static virNodeDevicePtr
remoteNodeDeviceCreateXML(virConnectPtr conn,
                          const char *xmlDesc,
                          unsigned int flags)
{
    remote_node_device_create_xml_args args;
    remote_node_device_create_xml_ret ret;
    virNodeDevicePtr dev = NULL;
    struct private_data *priv = conn->privateData;

    remoteDriverLock(priv);

    memset(&ret, 0, sizeof ret);
    args.xml_desc = (char *)xmlDesc;
    args.flags = flags;

    if (call(conn, priv, 0, REMOTE_PROC_NODE_DEVICE_CREATE_XML,
             (xdrproc_t) xdr_remote_node_device_create_xml_args, (char *) &args,
             (xdrproc_t) xdr_remote_node_device_create_xml_ret, (char *) &ret) == -1)
        goto done;

    dev = get_nonnull_node_device(conn, ret.dev);
    xdr_free ((xdrproc_t) xdr_remote_node_device_create_xml_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
    return dev;
}

static int
remoteNodeDeviceDestroy(virNodeDevicePtr dev)
{
    int rv = -1;
    remote_node_device_destroy_args args;
    struct private_data *priv = dev->conn->privateData;

    remoteDriverLock(priv);

    args.name = dev->name;

5569
    if (call(dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_DESTROY,
5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581
             (xdrproc_t) xdr_remote_node_device_destroy_args, (char *) &args,
             (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}


5582 5583
/*----------------------------------------------------------------------*/

5584
static int
5585
remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
5586 5587 5588 5589 5590 5591
                    virConnectAuthPtr auth
#if !HAVE_SASL && !HAVE_POLKIT
                    ATTRIBUTE_UNUSED
#endif
                    ,
                    const char *authtype)
5592 5593
{
    struct remote_auth_list_ret ret;
5594
    int err, type = REMOTE_AUTH_NONE;
5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610

    memset(&ret, 0, sizeof ret);
    err = call (conn, priv,
                REMOTE_CALL_IN_OPEN | REMOTE_CALL_QUIET_MISSING_RPC,
                REMOTE_PROC_AUTH_LIST,
                (xdrproc_t) xdr_void, (char *) NULL,
                (xdrproc_t) xdr_remote_auth_list_ret, (char *) &ret);
    if (err == -2) /* Missing RPC - old server - ignore */
        return 0;

    if (err < 0)
        return -1;

    if (ret.types.types_len == 0)
        return 0;

5611 5612 5613 5614 5615 5616 5617 5618
    if (authtype) {
        int want, i;
        if (STRCASEEQ(authtype, "sasl") ||
            STRCASEEQLEN(authtype, "sasl.", 5)) {
            want = REMOTE_AUTH_SASL;
        } else if (STRCASEEQ(authtype, "polkit")) {
            want = REMOTE_AUTH_POLKIT;
        } else {
5619
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5620 5621 5622
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("unknown authentication type %s"), authtype);
5623 5624 5625 5626 5627 5628 5629
            return -1;
        }
        for (i = 0 ; i < ret.types.types_len ; i++) {
            if (ret.types.types_val[i] == want)
                type = want;
        }
        if (type == REMOTE_AUTH_NONE) {
5630
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5631
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5632 5633
                             _("requested authentication type %s rejected"),
                             authtype);
5634 5635 5636 5637 5638 5639 5640
            return -1;
        }
    } else {
        type = ret.types.types_val[0];
    }

    switch (type) {
5641
#if HAVE_SASL
5642 5643 5644 5645 5646 5647 5648
    case REMOTE_AUTH_SASL: {
        const char *mech = NULL;
        if (authtype &&
            STRCASEEQLEN(authtype, "sasl.", 5))
            mech = authtype + 5;

        if (remoteAuthSASL(conn, priv, in_open, auth, mech) < 0) {
5649
            VIR_FREE(ret.types.types_val);
5650 5651 5652
            return -1;
        }
        break;
5653
    }
5654 5655
#endif

5656 5657
#if HAVE_POLKIT
    case REMOTE_AUTH_POLKIT:
5658
        if (remoteAuthPolkit(conn, priv, in_open, auth) < 0) {
5659
            VIR_FREE(ret.types.types_val);
5660 5661 5662 5663 5664
            return -1;
        }
        break;
#endif

5665 5666 5667 5668 5669
    case REMOTE_AUTH_NONE:
        /* Nothing todo, hurrah ! */
        break;

    default:
5670
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5671 5672 5673 5674
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
                         _("unsupported authentication type %d"),
                         ret.types.types_val[0]);
5675
        VIR_FREE(ret.types.types_val);
5676 5677 5678
        return -1;
    }

5679
    VIR_FREE(ret.types.types_val);
5680 5681 5682 5683 5684 5685 5686 5687

    return 0;
}



#if HAVE_SASL
/*
5688
 * NB, keep in sync with similar method in remote/remote.c
5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699
 */
static char *addrToString(struct sockaddr_storage *sa, socklen_t salen)
{
    char host[NI_MAXHOST], port[NI_MAXSERV];
    char *addr;
    int err;

    if ((err = getnameinfo((struct sockaddr *)sa, salen,
                           host, sizeof(host),
                           port, sizeof(port),
                           NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
5700
        virRaiseError (NULL, NULL, NULL, VIR_FROM_REMOTE,
5701 5702 5703 5704
                       VIR_ERR_UNKNOWN_HOST, VIR_ERR_ERROR,
                       NULL, NULL, NULL, 0, 0,
                       _("Cannot resolve address %d: %s"),
                       err, gai_strerror(err));
5705 5706 5707
        return NULL;
    }

5708 5709
    if (virAsprintf(&addr, "%s;%s", host, port) == -1) {
        virReportOOMError(NULL);
5710 5711 5712 5713 5714 5715 5716
        return NULL;
    }

    return addr;
}


5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794
static int remoteAuthCredVir2SASL(int vircred)
{
    switch (vircred) {
    case VIR_CRED_USERNAME:
        return SASL_CB_USER;

    case VIR_CRED_AUTHNAME:
        return SASL_CB_AUTHNAME;

    case VIR_CRED_LANGUAGE:
        return SASL_CB_LANGUAGE;

    case VIR_CRED_CNONCE:
        return SASL_CB_CNONCE;

    case VIR_CRED_PASSPHRASE:
        return SASL_CB_PASS;

    case VIR_CRED_ECHOPROMPT:
        return SASL_CB_ECHOPROMPT;

    case VIR_CRED_NOECHOPROMPT:
        return SASL_CB_NOECHOPROMPT;

    case VIR_CRED_REALM:
        return SASL_CB_GETREALM;
    }

    return 0;
}

static int remoteAuthCredSASL2Vir(int vircred)
{
    switch (vircred) {
    case SASL_CB_USER:
        return VIR_CRED_USERNAME;

    case SASL_CB_AUTHNAME:
        return VIR_CRED_AUTHNAME;

    case SASL_CB_LANGUAGE:
        return VIR_CRED_LANGUAGE;

    case SASL_CB_CNONCE:
        return VIR_CRED_CNONCE;

    case SASL_CB_PASS:
        return VIR_CRED_PASSPHRASE;

    case SASL_CB_ECHOPROMPT:
        return VIR_CRED_ECHOPROMPT;

    case SASL_CB_NOECHOPROMPT:
        return VIR_CRED_NOECHOPROMPT;

    case SASL_CB_GETREALM:
        return VIR_CRED_REALM;
    }

    return 0;
}

/*
 * @param credtype array of credential types client supports
 * @param ncredtype size of credtype array
 * @return the SASL callback structure, or NULL on error
 *
 * Build up the SASL callback structure. We register one callback for
 * each credential type that the libvirt client indicated they support.
 * We explicitly leav the callback function pointer at NULL though,
 * because we don't actually want to get SASL callbacks triggered.
 * Instead, we want the start/step functions to return SASL_INTERACT.
 * This lets us give the libvirt client a list of all required
 * credentials in one go, rather than triggering the callback one
 * credential at a time,
 */
static sasl_callback_t *remoteAuthMakeCallbacks(int *credtype, int ncredtype)
{
5795
    sasl_callback_t *cbs;
5796
    int i, n;
5797
    if (VIR_ALLOC_N(cbs, ncredtype+1) < 0) {
5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816
        return NULL;
    }

    for (i = 0, n = 0 ; i < ncredtype ; i++) {
        int id = remoteAuthCredVir2SASL(credtype[i]);
        if (id != 0)
            cbs[n++].id = id;
        /* Don't fill proc or context fields of sasl_callback_t
         * because we want to use interactions instead */
    }
    cbs[n].id = 0;
    return cbs;
}


/*
 * @param interact SASL interactions required
 * @param cred populated with libvirt credential metadata
 * @return the size of the cred array returned
5817
 *
5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831
 * Builds up an array of libvirt credential structs, populating
 * with data from the SASL interaction struct. These two structs
 * are basically a 1-to-1 copy of each other.
 */
static int remoteAuthMakeCredentials(sasl_interact_t *interact,
                                     virConnectCredentialPtr *cred)
{
    int ninteract;
    if (!cred)
        return -1;

    for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++)
        ; /* empty */

5832
    if (VIR_ALLOC_N(*cred, ninteract) < 0)
5833 5834 5835 5836 5837
        return -1;

    for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
        (*cred)[ninteract].type = remoteAuthCredSASL2Vir(interact[ninteract].id);
        if (!(*cred)[ninteract].type) {
5838
            VIR_FREE(*cred);
5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856
            return -1;
        }
        if (interact[ninteract].challenge)
            (*cred)[ninteract].challenge = interact[ninteract].challenge;
        (*cred)[ninteract].prompt = interact[ninteract].prompt;
        if (interact[ninteract].defresult)
            (*cred)[ninteract].defresult = interact[ninteract].defresult;
        (*cred)[ninteract].result = NULL;
    }

    return ninteract;
}

static void remoteAuthFreeCredentials(virConnectCredentialPtr cred,
                                      int ncred)
{
    int i;
    for (i = 0 ; i < ncred ; i++)
5857 5858
        VIR_FREE(cred[i].result);
    VIR_FREE(cred);
5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879
}


/*
 * @param cred the populated libvirt credentials
 * @param interact the SASL interactions to fill in results for
 *
 * Fills the SASL interactions with the result from the libvirt
 * callbacks
 */
static void remoteAuthFillInteract(virConnectCredentialPtr cred,
                                   sasl_interact_t *interact)
{
    int ninteract;
    for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
        interact[ninteract].result = cred[ninteract].result;
        interact[ninteract].len = cred[ninteract].resultlen;
    }
}

/* Perform the SASL authentication process
5880 5881
 */
static int
5882 5883
remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                virConnectAuthPtr auth, const char *wantmech)
5884 5885
{
    sasl_conn_t *saslconn = NULL;
5886
    sasl_security_properties_t secprops;
5887 5888 5889 5890 5891 5892
    remote_auth_sasl_init_ret iret;
    remote_auth_sasl_start_args sargs;
    remote_auth_sasl_start_ret sret;
    remote_auth_sasl_step_args pargs;
    remote_auth_sasl_step_ret pret;
    const char *clientout;
5893
    char *serverin = NULL;
5894 5895 5896 5897 5898
    unsigned int clientoutlen, serverinlen;
    const char *mech;
    int err, complete;
    struct sockaddr_storage sa;
    socklen_t salen;
5899
    char *localAddr = NULL, *remoteAddr = NULL;
5900 5901
    const void *val;
    sasl_ssf_t ssf;
5902 5903 5904 5905 5906 5907
    sasl_callback_t *saslcb = NULL;
    sasl_interact_t *interact = NULL;
    virConnectCredentialPtr cred = NULL;
    int ncred = 0;
    int ret = -1;
    const char *mechlist;
5908

5909
    DEBUG0("Client initialize SASL authentication");
5910 5911 5912
    /* Sets up the SASL library as a whole */
    err = sasl_client_init(NULL);
    if (err != SASL_OK) {
5913
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5914
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5915
                         _("failed to initialize SASL library: %d (%s)"),
5916
                         err, sasl_errstring(err, NULL, NULL));
5917
        goto cleanup;
5918 5919 5920 5921 5922
    }

    /* Get local address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getsockname(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
5923 5924
        virReportSystemError(in_open ? NULL : conn, errno, "%s",
                             _("failed to get sock address"));
5925
        goto cleanup;
5926
    }
5927 5928
    if ((localAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;
5929 5930 5931 5932

    /* Get remote address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getpeername(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
5933 5934
        virReportSystemError(in_open ? NULL : conn, errno, "%s",
                             _("failed to get peer address"));
5935
        goto cleanup;
5936
    }
5937 5938 5939
    if ((remoteAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;

5940 5941 5942 5943 5944 5945
    if (auth) {
        if ((saslcb = remoteAuthMakeCallbacks(auth->credtype, auth->ncredtype)) == NULL)
            goto cleanup;
    } else {
        saslcb = NULL;
    }
5946 5947 5948 5949 5950 5951

    /* Setup a handle for being a client */
    err = sasl_client_new("libvirt",
                          priv->hostname,
                          localAddr,
                          remoteAddr,
5952
                          saslcb,
5953 5954
                          SASL_SUCCESS_DATA,
                          &saslconn);
5955

5956
    if (err != SASL_OK) {
5957
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5958
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5959
                         _("Failed to create SASL client context: %d (%s)"),
5960
                         err, sasl_errstring(err, NULL, NULL));
5961
        goto cleanup;
5962 5963
    }

5964 5965 5966 5967 5968 5969
    /* Initialize some connection props we care about */
    if (priv->uses_tls) {
        gnutls_cipher_algorithm_t cipher;

        cipher = gnutls_cipher_get(priv->session);
        if (!(ssf = (sasl_ssf_t)gnutls_cipher_get_key_size(cipher))) {
5970
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5971
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5972
                             "%s", _("invalid cipher size for TLS session"));
5973
            goto cleanup;
5974 5975 5976
        }
        ssf *= 8; /* key size is bytes, sasl wants bits */

5977
        DEBUG("Setting external SSF %d", ssf);
5978 5979
        err = sasl_setprop(saslconn, SASL_SSF_EXTERNAL, &ssf);
        if (err != SASL_OK) {
5980
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5981
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5982
                             _("cannot set external SSF %d (%s)"),
5983
                             err, sasl_errstring(err, NULL, NULL));
5984
            goto cleanup;
5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998
        }
    }

    memset (&secprops, 0, sizeof secprops);
    /* If we've got TLS, we don't care about SSF */
    secprops.min_ssf = priv->uses_tls ? 0 : 56; /* Equiv to DES supported by all Kerberos */
    secprops.max_ssf = priv->uses_tls ? 0 : 100000; /* Very strong ! AES == 256 */
    secprops.maxbufsize = 100000;
    /* If we're not TLS, then forbid any anonymous or trivially crackable auth */
    secprops.security_flags = priv->uses_tls ? 0 :
        SASL_SEC_NOANONYMOUS | SASL_SEC_NOPLAINTEXT;

    err = sasl_setprop(saslconn, SASL_SEC_PROPS, &secprops);
    if (err != SASL_OK) {
5999
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6000
                         VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6001
                         _("cannot set security props %d (%s)"),
6002
                         err, sasl_errstring(err, NULL, NULL));
6003
        goto cleanup;
6004 6005
    }

6006 6007 6008 6009
    /* First call is to inquire about supported mechanisms in the server */
    memset (&iret, 0, sizeof iret);
    if (call (conn, priv, in_open, REMOTE_PROC_AUTH_SASL_INIT,
              (xdrproc_t) xdr_void, (char *)NULL,
6010 6011
              (xdrproc_t) xdr_remote_auth_sasl_init_ret, (char *) &iret) != 0)
        goto cleanup;
6012 6013


6014 6015 6016
    mechlist = iret.mechlist;
    if (wantmech) {
        if (strstr(mechlist, wantmech) == NULL) {
6017
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6018 6019 6020 6021
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("SASL mechanism %s not supported by server"),
                             wantmech);
6022
            VIR_FREE(iret.mechlist);
6023 6024 6025 6026 6027
            goto cleanup;
        }
        mechlist = wantmech;
    }
 restart:
6028
    /* Start the auth negotiation on the client end first */
6029
    DEBUG("Client start negotiation mechlist '%s'", mechlist);
6030
    err = sasl_client_start(saslconn,
6031 6032
                            mechlist,
                            &interact,
6033 6034 6035
                            &clientout,
                            &clientoutlen,
                            &mech);
6036
    if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
6037
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6038
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6039
                         _("Failed to start SASL negotiation: %d (%s)"),
6040
                         err, sasl_errdetail(saslconn));
6041
        VIR_FREE(iret.mechlist);
6042 6043 6044 6045 6046
        goto cleanup;
    }

    /* Need to gather some credentials from the client */
    if (err == SASL_INTERACT) {
6047
        const char *msg;
6048 6049 6050 6051 6052 6053
        if (cred) {
            remoteAuthFreeCredentials(cred, ncred);
            cred = NULL;
        }
        if ((ncred =
             remoteAuthMakeCredentials(interact, &cred)) < 0) {
6054
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6055 6056 6057
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             "%s", _("Failed to make auth credentials"));
6058
            VIR_FREE(iret.mechlist);
6059 6060 6061
            goto cleanup;
        }
        /* Run the authentication callback */
6062
        if (auth && auth->cb) {
6063 6064 6065
            if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                remoteAuthFillInteract(cred, interact);
                goto restart;
6066
            }
6067
            msg = "Failed to collect auth credentials";
6068
        } else {
6069
            msg = "No authentication callback available";
6070
        }
6071
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6072
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
6073
                         0, 0, "%s", msg);
6074
        goto cleanup;
6075
    }
6076
    VIR_FREE(iret.mechlist);
6077 6078

    if (clientoutlen > REMOTE_AUTH_SASL_DATA_MAX) {
6079
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6080
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6081 6082
                         _("SASL negotiation data too long: %d bytes"),
                         clientoutlen);
6083
        goto cleanup;
6084 6085 6086 6087 6088 6089 6090
    }
    /* NB, distinction of NULL vs "" is *critical* in SASL */
    memset(&sargs, 0, sizeof sargs);
    sargs.nil = clientout ? 0 : 1;
    sargs.data.data_val = (char*)clientout;
    sargs.data.data_len = clientoutlen;
    sargs.mech = (char*)mech;
6091
    DEBUG("Server start negotiation with mech %s. Data %d bytes %p", mech, clientoutlen, clientout);
6092 6093 6094 6095 6096

    /* Now send the initial auth data to the server */
    memset (&sret, 0, sizeof sret);
    if (call (conn, priv, in_open, REMOTE_PROC_AUTH_SASL_START,
              (xdrproc_t) xdr_remote_auth_sasl_start_args, (char *) &sargs,
6097 6098
              (xdrproc_t) xdr_remote_auth_sasl_start_ret, (char *) &sret) != 0)
        goto cleanup;
6099 6100 6101 6102 6103

    complete = sret.complete;
    /* NB, distinction of NULL vs "" is *critical* in SASL */
    serverin = sret.nil ? NULL : sret.data.data_val;
    serverinlen = sret.data.data_len;
6104 6105
    DEBUG("Client step result complete: %d. Data %d bytes %p",
          complete, serverinlen, serverin);
6106 6107 6108

    /* Loop-the-loop...
     * Even if the server has completed, the client must *always* do at least one step
D
Daniel Veillard 已提交
6109
     * in this loop to verify the server isn't lying about something. Mutual auth */
6110
    for (;;) {
6111
    restep:
6112 6113 6114
        err = sasl_client_step(saslconn,
                               serverin,
                               serverinlen,
6115
                               &interact,
6116 6117
                               &clientout,
                               &clientoutlen);
6118
        if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
6119
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6120
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6121
                             _("Failed SASL step: %d (%s)"),
6122
                             err, sasl_errdetail(saslconn));
6123 6124 6125 6126
            goto cleanup;
        }
        /* Need to gather some credentials from the client */
        if (err == SASL_INTERACT) {
6127
            const char *msg;
6128 6129 6130 6131 6132
            if (cred) {
                remoteAuthFreeCredentials(cred, ncred);
                cred = NULL;
            }
            if ((ncred = remoteAuthMakeCredentials(interact, &cred)) < 0) {
6133
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6134
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6135
                                 "%s", _("Failed to make auth credentials"));
6136 6137 6138
                goto cleanup;
            }
            /* Run the authentication callback */
6139
            if (auth && auth->cb) {
6140 6141 6142
                if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                    remoteAuthFillInteract(cred, interact);
                    goto restep;
6143
                }
6144
                msg = "Failed to collect auth credentials";
6145
            } else {
6146
                msg = "No authentication callback available";
6147
            }
6148
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6149
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
6150
                             0, 0, "%s", msg);
6151
            goto cleanup;
6152 6153
        }

6154
        VIR_FREE(serverin);
6155
        DEBUG("Client step result %d. Data %d bytes %p", err, clientoutlen, clientout);
6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166

        /* Previous server call showed completion & we're now locally complete too */
        if (complete && err == SASL_OK)
            break;

        /* Not done, prepare to talk with the server for another iteration */
        /* NB, distinction of NULL vs "" is *critical* in SASL */
        memset(&pargs, 0, sizeof pargs);
        pargs.nil = clientout ? 0 : 1;
        pargs.data.data_val = (char*)clientout;
        pargs.data.data_len = clientoutlen;
6167
        DEBUG("Server step with %d bytes %p", clientoutlen, clientout);
6168 6169 6170 6171

        memset (&pret, 0, sizeof pret);
        if (call (conn, priv, in_open, REMOTE_PROC_AUTH_SASL_STEP,
                  (xdrproc_t) xdr_remote_auth_sasl_step_args, (char *) &pargs,
6172 6173
                  (xdrproc_t) xdr_remote_auth_sasl_step_ret, (char *) &pret) != 0)
            goto cleanup;
6174 6175 6176 6177 6178 6179

        complete = pret.complete;
        /* NB, distinction of NULL vs "" is *critical* in SASL */
        serverin = pret.nil ? NULL : pret.data.data_val;
        serverinlen = pret.data.data_len;

6180 6181
        DEBUG("Client step result complete: %d. Data %d bytes %p",
              complete, serverinlen, serverin);
6182 6183 6184

        /* This server call shows complete, and earlier client step was OK */
        if (complete && err == SASL_OK) {
6185
            VIR_FREE(serverin);
6186 6187 6188 6189
            break;
        }
    }

6190 6191 6192 6193
    /* Check for suitable SSF if non-TLS */
    if (!priv->uses_tls) {
        err = sasl_getprop(saslconn, SASL_SSF, &val);
        if (err != SASL_OK) {
6194
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6195
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6196
                             _("cannot query SASL ssf on connection %d (%s)"),
6197
                             err, sasl_errstring(err, NULL, NULL));
6198
            goto cleanup;
6199 6200
        }
        ssf = *(const int *)val;
6201
        DEBUG("SASL SSF value %d", ssf);
6202
        if (ssf < 56) { /* 56 == DES level, good for Kerberos */
6203
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6204
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6205
                             _("negotiation SSF %d was not strong enough"), ssf);
6206
            goto cleanup;
6207 6208 6209
        }
    }

6210
    DEBUG0("SASL authentication complete");
6211
    priv->saslconn = saslconn;
6212 6213 6214
    ret = 0;

 cleanup:
6215 6216 6217
    VIR_FREE(localAddr);
    VIR_FREE(remoteAddr);
    VIR_FREE(serverin);
6218

6219
    VIR_FREE(saslcb);
6220 6221 6222
    remoteAuthFreeCredentials(cred, ncred);
    if (ret != 0 && saslconn)
        sasl_dispose(&saslconn);
6223

6224
    return ret;
6225 6226 6227
}
#endif /* HAVE_SASL */

6228 6229

#if HAVE_POLKIT
6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248
#if HAVE_POLKIT1
static int
remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                  virConnectAuthPtr auth ATTRIBUTE_UNUSED)
{
    remote_auth_polkit_ret ret;
    DEBUG0("Client initialize PolicyKit-1 authentication");

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, in_open, REMOTE_PROC_AUTH_POLKIT,
              (xdrproc_t) xdr_void, (char *)NULL,
              (xdrproc_t) xdr_remote_auth_polkit_ret, (char *) &ret) != 0) {
        return -1; /* virError already set by call */
    }

    DEBUG0("PolicyKit-1 authentication complete");
    return 0;
}
#elif HAVE_POLKIT0
6249 6250 6251 6252 6253 6254 6255
/* Perform the PolicyKit authentication process
 */
static int
remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                  virConnectAuthPtr auth)
{
    remote_auth_polkit_ret ret;
6256
    int i, allowcb = 0;
6257 6258 6259 6260 6261 6262 6263 6264
    virConnectCredential cred = {
        VIR_CRED_EXTERNAL,
        conn->flags & VIR_CONNECT_RO ? "org.libvirt.unix.monitor" : "org.libvirt.unix.manage",
        "PolicyKit",
        NULL,
        NULL,
        0,
    };
6265
    DEBUG0("Client initialize PolicyKit-0 authentication");
6266

6267
    if (auth && auth->cb) {
6268
        /* Check if the necessary credential type for PolicyKit is supported */
6269 6270 6271 6272
        for (i = 0 ; i < auth->ncredtype ; i++) {
            if (auth->credtype[i] == VIR_CRED_EXTERNAL)
                allowcb = 1;
        }
6273

6274
        if (allowcb) {
6275
            DEBUG0("Client run callback for PolicyKit authentication");
6276 6277
            /* Run the authentication callback */
            if ((*(auth->cb))(&cred, 1, auth->cbdata) < 0) {
6278
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6279
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
J
Jim Meyering 已提交
6280
                                 "%s", _("Failed to collect auth credentials"));
6281 6282
                return -1;
            }
6283
        } else {
6284
            DEBUG0("Client auth callback does not support PolicyKit");
6285 6286
        }
    } else {
6287
        DEBUG0("No auth callback provided");
6288 6289 6290 6291 6292 6293 6294 6295 6296
    }

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, in_open, REMOTE_PROC_AUTH_POLKIT,
              (xdrproc_t) xdr_void, (char *)NULL,
              (xdrproc_t) xdr_remote_auth_polkit_ret, (char *) &ret) != 0) {
        return -1; /* virError already set by call */
    }

6297
    DEBUG0("PolicyKit-0 authentication complete");
6298 6299
    return 0;
}
6300
#endif /* HAVE_POLKIT0 */
6301
#endif /* HAVE_POLKIT */
6302 6303 6304
/*----------------------------------------------------------------------*/

static int remoteDomainEventRegister (virConnectPtr conn,
6305 6306
                                      virConnectDomainEventCallback callback,
                                      void *opaque,
6307
                                      virFreeCallback freecb)
6308
{
6309
    int rv = -1;
6310 6311
    struct private_data *priv = conn->privateData;

6312 6313
    remoteDriverLock(priv);

6314 6315
    if (priv->eventFlushTimer < 0) {
         error (conn, VIR_ERR_NO_SUPPORT, _("no event support"));
6316
         goto done;
6317
    }
6318
    if (virDomainEventCallbackListAdd(conn, priv->callbackList,
6319
                                      callback, opaque, freecb) < 0) {
6320
         error (conn, VIR_ERR_RPC, _("adding cb to list"));
6321
         goto done;
6322 6323 6324 6325 6326 6327 6328
    }

    if ( priv->callbackList->count == 1 ) {
        /* Tell the server when we are the first callback deregistering */
        if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_REGISTER,
                (xdrproc_t) xdr_void, (char *) NULL,
                (xdrproc_t) xdr_void, (char *) NULL) == -1)
6329
            goto done;
6330 6331
    }

6332 6333 6334
    rv = 0;

done:
6335
    remoteDriverUnlock(priv);
6336
    return rv;
6337 6338 6339
}

static int remoteDomainEventDeregister (virConnectPtr conn,
6340
                                        virConnectDomainEventCallback callback)
6341 6342
{
    struct private_data *priv = conn->privateData;
6343
    int rv = -1;
6344

6345 6346
    remoteDriverLock(priv);

6347 6348 6349 6350
    if (priv->domainEventDispatching) {
        if (virDomainEventCallbackListMarkDelete(conn, priv->callbackList,
                                                 callback) < 0) {
            error (conn, VIR_ERR_RPC, _("marking cb for deletion"));
6351
            goto done;
6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366
        }
    } else {
        if (virDomainEventCallbackListRemove(conn, priv->callbackList,
                                             callback) < 0) {
            error (conn, VIR_ERR_RPC, _("removing cb from list"));
            goto done;
        }

        if ( priv->callbackList->count == 0 ) {
            /* Tell the server when we are the last callback deregistering */
            if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_DEREGISTER,
                      (xdrproc_t) xdr_void, (char *) NULL,
                      (xdrproc_t) xdr_void, (char *) NULL) == -1)
                goto done;
        }
6367 6368
    }

6369 6370 6371
    rv = 0;

done:
6372
    remoteDriverUnlock(priv);
6373
    return rv;
6374
}
6375

J
Jim Meyering 已提交
6376
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
6377 6378 6379 6380 6381 6382 6383
remoteSecretOpen (virConnectPtr conn,
                  virConnectAuthPtr auth,
                  int flags)
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
6384
    if (conn->driver &&
6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512
        STREQ (conn->driver->name, "remote")) {
        struct private_data *priv;

        /* If we're here, the remote driver is already
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
        priv = conn->privateData;
        remoteDriverLock(priv);
        priv->localUses++;
        conn->secretPrivateData = priv;
        remoteDriverUnlock(priv);
        return VIR_DRV_OPEN_SUCCESS;
    } else if (conn->networkDriver &&
               STREQ (conn->networkDriver->name, "remote")) {
        struct private_data *priv = conn->networkPrivateData;
        remoteDriverLock(priv);
        conn->secretPrivateData = priv;
        priv->localUses++;
        remoteDriverUnlock(priv);
        return VIR_DRV_OPEN_SUCCESS;
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for secret APIs, forcing it to
         * use the UNIX transport.
         */
        struct private_data *priv;
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
            conn->secretPrivateData = priv;
        return ret;
    }
}

static int
remoteSecretClose (virConnectPtr conn)
{
    int rv = 0;
    struct private_data *priv = conn->secretPrivateData;

    conn->secretPrivateData = NULL;
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        rv = doRemoteClose(conn, priv);
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
    }
    if (priv)
        remoteDriverUnlock(priv);
    return rv;
}

static int
remoteSecretNumOfSecrets (virConnectPtr conn)
{
    int rv = -1;
    remote_num_of_secrets_ret ret;
    struct private_data *priv = conn->secretPrivateData;

    remoteDriverLock (priv);

    memset (&ret, 0, sizeof (ret));
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_SECRETS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_secrets_ret, (char *) &ret) == -1)
        goto done;

    rv = ret.num;

done:
    remoteDriverUnlock (priv);
    return rv;
}

static int
remoteSecretListSecrets (virConnectPtr conn, char **uuids, int maxuuids)
{
    int rv = -1;
    int i;
    remote_list_secrets_args args;
    remote_list_secrets_ret ret;
    struct private_data *priv = conn->secretPrivateData;

    remoteDriverLock(priv);

    if (maxuuids > REMOTE_SECRET_UUID_LIST_MAX) {
        errorf (conn, VIR_ERR_RPC, _("too many remote secret UUIDs: %d > %d"),
                maxuuids, REMOTE_SECRET_UUID_LIST_MAX);
        goto done;
    }
    args.maxuuids = maxuuids;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_SECRETS,
              (xdrproc_t) xdr_remote_list_secrets_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_secrets_ret, (char *) &ret) == -1)
        goto done;

    if (ret.uuids.uuids_len > maxuuids) {
        errorf (conn, VIR_ERR_RPC, _("too many remote secret UUIDs: %d > %d"),
                ret.uuids.uuids_len, maxuuids);
        goto cleanup;
    }

    /* This call is caller-frees.  However xdr_free will free up both the
     * names and the list of pointers, so we have to strdup the
     * names here.
     */
    for (i = 0; i < ret.uuids.uuids_len; ++i)
        uuids[i] = strdup (ret.uuids.uuids_val[i]);

    rv = ret.uuids.uuids_len;

cleanup:
    xdr_free ((xdrproc_t) xdr_remote_list_secrets_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
    return rv;
}

static virSecretPtr
6513
remoteSecretLookupByUUID (virConnectPtr conn, const unsigned char *uuid)
6514 6515
{
    virSecretPtr rv = NULL;
6516 6517
    remote_secret_lookup_by_uuid_args args;
    remote_secret_lookup_by_uuid_ret ret;
6518 6519 6520 6521
    struct private_data *priv = conn->secretPrivateData;

    remoteDriverLock (priv);

6522
    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);
6523 6524

    memset (&ret, 0, sizeof (ret));
6525 6526 6527
    if (call (conn, priv, 0, REMOTE_PROC_SECRET_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_secret_lookup_by_uuid_args, (char *) &args,
              (xdrproc_t) xdr_remote_secret_lookup_by_uuid_ret, (char *) &ret) == -1)
6528 6529 6530
        goto done;

    rv = get_nonnull_secret (conn, ret.secret);
6531
    xdr_free ((xdrproc_t) xdr_remote_secret_lookup_by_uuid_ret,
6532 6533 6534 6535 6536 6537 6538
              (char *) &ret);

done:
    remoteDriverUnlock (priv);
    return rv;
}

6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566
static virSecretPtr
remoteSecretLookupByUsage (virConnectPtr conn, int usageType, const char *usageID)
{
    virSecretPtr rv = NULL;
    remote_secret_lookup_by_usage_args args;
    remote_secret_lookup_by_usage_ret ret;
    struct private_data *priv = conn->secretPrivateData;

    remoteDriverLock (priv);

    args.usageType = usageType;
    args.usageID = (char *)usageID;

    memset (&ret, 0, sizeof (ret));
    if (call (conn, priv, 0, REMOTE_PROC_SECRET_LOOKUP_BY_USAGE,
              (xdrproc_t) xdr_remote_secret_lookup_by_usage_args, (char *) &args,
              (xdrproc_t) xdr_remote_secret_lookup_by_usage_ret, (char *) &ret) == -1)
        goto done;

    rv = get_nonnull_secret (conn, ret.secret);
    xdr_free ((xdrproc_t) xdr_remote_secret_lookup_by_usage_ret,
              (char *) &ret);

done:
    remoteDriverUnlock (priv);
    return rv;
}

6567 6568 6569 6570 6571
static virSecretPtr
remoteSecretDefineXML (virConnectPtr conn, const char *xml, unsigned int flags)
{
    virSecretPtr rv = NULL;
    remote_secret_define_xml_args args;
6572
    remote_secret_define_xml_ret ret;
6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586
    struct private_data *priv = conn->secretPrivateData;

    remoteDriverLock (priv);

    args.xml = (char *) xml;
    args.flags = flags;

    memset (&ret, 0, sizeof (ret));
    if (call (conn, priv, 0, REMOTE_PROC_SECRET_DEFINE_XML,
              (xdrproc_t) xdr_remote_secret_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_secret_define_xml_ret, (char *) &ret) == -1)
        goto done;

    rv = get_nonnull_secret (conn, ret.secret);
6587
    xdr_free ((xdrproc_t) xdr_remote_secret_define_xml_ret,
6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699
              (char *) &ret);

done:
    remoteDriverUnlock (priv);
    return rv;
}

static char *
remoteSecretGetXMLDesc (virSecretPtr secret, unsigned int flags)
{
    char *rv = NULL;
    remote_secret_get_xml_desc_args args;
    remote_secret_get_xml_desc_ret ret;
    struct private_data *priv = secret->conn->secretPrivateData;

    remoteDriverLock (priv);

    make_nonnull_secret (&args.secret, secret);
    args.flags = flags;

    memset (&ret, 0, sizeof (ret));
    if (call (secret->conn, priv, 0, REMOTE_PROC_SECRET_GET_XML_DESC,
              (xdrproc_t) xdr_remote_secret_get_xml_desc_args, (char *) &args,
              (xdrproc_t) xdr_remote_secret_get_xml_desc_ret, (char *) &ret) == -1)
        goto done;

    /* Caller frees. */
    rv = ret.xml;

done:
    remoteDriverUnlock (priv);
    return rv;
}

static int
remoteSecretSetValue (virSecretPtr secret, const unsigned char *value,
                      size_t value_size, unsigned int flags)
{
    int rv = -1;
    remote_secret_set_value_args args;
    struct private_data *priv = secret->conn->secretPrivateData;

    remoteDriverLock (priv);

    make_nonnull_secret (&args.secret, secret);
    args.value.value_len = value_size;
    args.value.value_val = (char *) value;
    args.flags = flags;

    if (call (secret->conn, priv, 0, REMOTE_PROC_SECRET_SET_VALUE,
              (xdrproc_t) xdr_remote_secret_set_value_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock (priv);
    return rv;
}

static unsigned char *
remoteSecretGetValue (virSecretPtr secret, size_t *value_size,
                      unsigned int flags)
{
    unsigned char *rv = NULL;
    remote_secret_get_value_args args;
    remote_secret_get_value_ret ret;
    struct private_data *priv = secret->conn->secretPrivateData;

    remoteDriverLock (priv);

    make_nonnull_secret (&args.secret, secret);
    args.flags = flags;

    memset (&ret, 0, sizeof (ret));
    if (call (secret->conn, priv, 0, REMOTE_PROC_SECRET_GET_VALUE,
              (xdrproc_t) xdr_remote_secret_get_value_args, (char *) &args,
              (xdrproc_t) xdr_remote_secret_get_value_ret, (char *) &ret) == -1)
        goto done;

    *value_size = ret.value.value_len;
    rv = (unsigned char *) ret.value.value_val; /* Caller frees. */

done:
    remoteDriverUnlock (priv);
    return rv;
}

static int
remoteSecretUndefine (virSecretPtr secret)
{
    int rv = -1;
    remote_secret_undefine_args args;
    struct private_data *priv = secret->conn->secretPrivateData;

    remoteDriverLock (priv);

    make_nonnull_secret (&args.secret, secret);

    if (call (secret->conn, priv, 0, REMOTE_PROC_SECRET_UNDEFINE,
              (xdrproc_t) xdr_remote_secret_undefine_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock (priv);
    return rv;
}

6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054

#if 0
static struct private_stream_data *
remoteStreamOpen(virStreamPtr st,
                 int output ATTRIBUTE_UNUSED,
                 unsigned int proc_nr,
                 unsigned int serial)
{
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *stpriv;

    if (VIR_ALLOC(stpriv) < 0)
        return NULL;

    /* Initialize call object used to receive replies */
    stpriv->proc_nr = proc_nr;
    stpriv->serial = serial;

    stpriv->next = priv->streams;
    priv->streams = stpriv;

    return stpriv;
}


static int
remoteStreamPacket(virStreamPtr st,
                   int status,
                   const char *data,
                   size_t nbytes)
{
    DEBUG("st=%p status=%d data=%p nbytes=%d", st, status, data, nbytes);
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
    XDR xdr;
    struct remote_thread_call *thiscall;
    remote_message_header hdr;

    memset(&hdr, 0, sizeof hdr);

    if (VIR_ALLOC(thiscall) < 0) {
        virReportOOMError(st->conn);
        return -1;
    }

    thiscall->mode = REMOTE_MODE_WAIT_TX;
    thiscall->serial = privst->serial;
    thiscall->proc_nr = privst->proc_nr;
    if (status == REMOTE_OK ||
        status == REMOTE_ERROR)
        thiscall->want_reply = 1;

    if (virCondInit(&thiscall->cond) < 0) {
        VIR_FREE(thiscall);
        error (st->conn, VIR_ERR_INTERNAL_ERROR,
               _("cannot initialize mutex"));
        return -1;
    }

    /* Don't fill in any other fields in 'thiscall' since
     * we're not expecting a reply for this */

    hdr.prog = REMOTE_PROGRAM;
    hdr.vers = REMOTE_PROTOCOL_VERSION;
    hdr.proc = privst->proc_nr;
    hdr.type = REMOTE_STREAM;
    hdr.serial = privst->serial;
    hdr.status = status;


    /* Length must include the length word itself (always encoded in
     * 4 bytes as per RFC 4506), so offset start length. We write this
     * later.
     */
    thiscall->bufferLength = REMOTE_MESSAGE_HEADER_XDR_LEN;

    /* Serialise header followed by args. */
    xdrmem_create (&xdr, thiscall->buffer + thiscall->bufferLength,
                   REMOTE_MESSAGE_MAX, XDR_ENCODE);
    if (!xdr_remote_message_header (&xdr, &hdr)) {
        error (st->conn,
               VIR_ERR_RPC, _("xdr_remote_message_header failed"));
        goto error;
    }

    thiscall->bufferLength += xdr_getpos (&xdr);
    xdr_destroy (&xdr);

    if (status == REMOTE_CONTINUE) {
        if (((4 + REMOTE_MESSAGE_MAX) - thiscall->bufferLength) < nbytes) {
            errorf(st->conn,
                   VIR_ERR_RPC, _("data size %d too large for payload %d"),
                   nbytes, ((4 + REMOTE_MESSAGE_MAX) - thiscall->bufferLength));
            goto error;
        }

        memcpy(thiscall->buffer + thiscall->bufferLength, data, nbytes);
        thiscall->bufferLength += nbytes;
    }

    /* Go back to packet start and encode the length word. */
    xdrmem_create (&xdr, thiscall->buffer, REMOTE_MESSAGE_HEADER_XDR_LEN, XDR_ENCODE);
    if (!xdr_u_int (&xdr, &thiscall->bufferLength)) {
        error(st->conn, VIR_ERR_RPC,
               _("xdr_u_int (length word)"));
        goto error;
    }
    xdr_destroy (&xdr);

    /* remoteIO frees 'thiscall' for us (XXX that's dubious semantics) */
    if (remoteIO(st->conn, priv, 0, thiscall) < 0)
        return -1;

    return nbytes;

error:
    xdr_destroy (&xdr);
    VIR_FREE(thiscall);
    return -1;
}

static int
remoteStreamHasError(virStreamPtr st) {
    struct private_stream_data *privst = st->privateData;
    if (!privst->has_error) {
        return 0;
    }

    VIR_WARN0("Raising async error");
    virRaiseErrorFull(st->conn,
                      __FILE__, __FUNCTION__, __LINE__,
                      privst->err.domain,
                      privst->err.code,
                      privst->err.level,
                      privst->err.str1 ? *privst->err.str1 : NULL,
                      privst->err.str2 ? *privst->err.str2 : NULL,
                      privst->err.str3 ? *privst->err.str3 : NULL,
                      privst->err.int1,
                      privst->err.int2,
                      "%s", privst->err.message ? *privst->err.message : NULL);

    return 1;
}

static void
remoteStreamRelease(virStreamPtr st)
{
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;

    if (priv->streams == privst)
        priv->streams = privst->next;
    else {
        struct private_stream_data *tmp = priv->streams;
        while (tmp && tmp->next) {
            if (tmp->next == privst) {
                tmp->next = privst->next;
                break;
            }
        }
    }

    if (privst->has_error)
        xdr_free((xdrproc_t)xdr_remote_error,  (char *)&privst->err);

    VIR_FREE(privst);

    st->driver = NULL;
    st->privateData = NULL;
}


static int
remoteStreamSend(virStreamPtr st,
                 const char *data,
                 size_t nbytes)
{
    DEBUG("st=%p data=%p nbytes=%d", st, data, nbytes);
    struct private_data *priv = st->conn->privateData;
    int rv = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    rv = remoteStreamPacket(st,
                            REMOTE_CONTINUE,
                            data,
                            nbytes);

cleanup:
    if (rv == -1)
        remoteStreamRelease(st);

    remoteDriverUnlock(priv);

    return rv;
}


static int
remoteStreamRecv(virStreamPtr st,
                 char *data,
                 size_t nbytes)
{
    DEBUG("st=%p data=%p nbytes=%d", st, data, nbytes);
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
    int rv = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    if (!privst->incomingOffset) {
        struct remote_thread_call *thiscall;

        if (VIR_ALLOC(thiscall) < 0) {
            virReportOOMError(st->conn);
            goto cleanup;
        }

        /* We're not really doing an RPC calls, so we're
         * skipping straight to RX part */
        thiscall->mode = REMOTE_MODE_WAIT_RX;
        thiscall->serial = privst->serial;
        thiscall->proc_nr = privst->proc_nr;
        thiscall->want_reply = 1;

        if (virCondInit(&thiscall->cond) < 0) {
            VIR_FREE(thiscall);
            error (st->conn, VIR_ERR_INTERNAL_ERROR,
                   _("cannot initialize mutex"));
            goto cleanup;
        }

        /* remoteIO frees 'thiscall' for us (XXX that's dubious semantics) */
        if (remoteIO(st->conn, priv, 0, thiscall) < 0)
            goto cleanup;
    }

    DEBUG("After IO %d", privst->incomingOffset);
    if (privst->incomingOffset) {
        int want = privst->incomingOffset;
        if (want > nbytes)
            want = nbytes;
        memcpy(data, privst->incoming, want);
        if (want < privst->incomingOffset) {
            memmove(privst->incoming, privst->incoming + want, privst->incomingOffset - want);
            privst->incomingOffset -= want;
        } else {
            VIR_FREE(privst->incoming);
            privst->incomingOffset = privst->incomingLength = 0;
        }
        rv = want;
    } else {
        rv = 0;
    }

    DEBUG("Done %d", rv);

cleanup:
    if (rv == -1)
        remoteStreamRelease(st);
    remoteDriverUnlock(priv);

    return rv;
}

static int
remoteStreamEventAddCallback(virStreamPtr stream ATTRIBUTE_UNUSED,
                             int events ATTRIBUTE_UNUSED,
                             virStreamEventCallback cb ATTRIBUTE_UNUSED,
                             void *opaque ATTRIBUTE_UNUSED,
                             virFreeCallback ff ATTRIBUTE_UNUSED)
{
    return -1;
}

static int
remoteStreamEventUpdateCallback(virStreamPtr stream ATTRIBUTE_UNUSED,
                                int events ATTRIBUTE_UNUSED)
{
    return -1;
}


static int
remoteStreamEventRemoveCallback(virStreamPtr stream ATTRIBUTE_UNUSED)
{
    return -1;
}

static int
remoteStreamFinish(virStreamPtr st)
{
    struct private_data *priv = st->conn->privateData;
    int ret = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    ret = remoteStreamPacket(st,
                             REMOTE_OK,
                             NULL,
                             0);

cleanup:
    remoteStreamRelease(st);

    remoteDriverUnlock(priv);
    return ret;
}

static int
remoteStreamAbort(virStreamPtr st)
{
    struct private_data *priv = st->conn->privateData;
    int ret = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    ret = remoteStreamPacket(st,
                             REMOTE_ERROR,
                             NULL,
                             0);

cleanup:
    remoteStreamRelease(st);

    remoteDriverUnlock(priv);
    return ret;
}



static virStreamDriver remoteStreamDrv = {
    .streamRecv = remoteStreamRecv,
    .streamSend = remoteStreamSend,
    .streamFinish = remoteStreamFinish,
    .streamAbort = remoteStreamAbort,
    .streamAddCallback = remoteStreamEventAddCallback,
    .streamUpdateCallback = remoteStreamEventUpdateCallback,
    .streamRemoveCallback = remoteStreamEventRemoveCallback,
};
#endif


7055 7056
/*----------------------------------------------------------------------*/

7057

7058 7059 7060 7061 7062 7063 7064 7065
static struct remote_thread_call *
prepareCall(virConnectPtr conn,
            struct private_data *priv,
            int flags,
            int proc_nr,
            xdrproc_t args_filter, char *args,
            xdrproc_t ret_filter, char *ret)
{
7066
    XDR xdr;
7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079
    struct remote_message_header hdr;
    struct remote_thread_call *rv;

    if (VIR_ALLOC(rv) < 0)
        return NULL;

    if (virCondInit(&rv->cond) < 0) {
        VIR_FREE(rv);
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
               VIR_ERR_INTERNAL_ERROR,
               _("cannot initialize mutex"));
        return NULL;
    }
7080 7081

    /* Get a unique serial number for this message. */
7082 7083 7084 7085
    rv->serial = priv->counter++;
    rv->proc_nr = proc_nr;
    rv->ret_filter = ret_filter;
    rv->ret = ret;
7086
    rv->want_reply = 1;
7087 7088 7089 7090

    hdr.prog = REMOTE_PROGRAM;
    hdr.vers = REMOTE_PROTOCOL_VERSION;
    hdr.proc = proc_nr;
7091
    hdr.type = REMOTE_CALL;
7092
    hdr.serial = rv->serial;
7093 7094 7095
    hdr.status = REMOTE_OK;

    /* Serialise header followed by args. */
7096
    xdrmem_create (&xdr, rv->buffer+4, REMOTE_MESSAGE_MAX, XDR_ENCODE);
7097
    if (!xdr_remote_message_header (&xdr, &hdr)) {
7098
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
7099
               VIR_ERR_RPC, _("xdr_remote_message_header failed"));
7100
        goto error;
7101 7102 7103
    }

    if (!(*args_filter) (&xdr, args)) {
7104 7105
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
               _("marshalling args"));
7106
        goto error;
7107 7108 7109
    }

    /* Get the length stored in buffer. */
7110
    rv->bufferLength = xdr_getpos (&xdr);
7111 7112 7113 7114 7115
    xdr_destroy (&xdr);

    /* Length must include the length word itself (always encoded in
     * 4 bytes as per RFC 4506).
     */
7116
    rv->bufferLength += REMOTE_MESSAGE_HEADER_XDR_LEN;
7117 7118

    /* Encode the length word. */
7119 7120
    xdrmem_create (&xdr, rv->buffer, REMOTE_MESSAGE_HEADER_XDR_LEN, XDR_ENCODE);
    if (!xdr_u_int (&xdr, &rv->bufferLength)) {
7121
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
7122
               _("xdr_u_int (length word)"));
7123
        goto error;
7124 7125 7126
    }
    xdr_destroy (&xdr);

7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137
    return rv;

error:
    xdr_destroy (&xdr);
    VIR_FREE(rv);
    return NULL;
}



static int
7138 7139 7140 7141
remoteIOWriteBuffer(virConnectPtr conn,
                    struct private_data *priv,
                    int in_open /* if we are in virConnectOpen */,
                    const char *bytes, int len)
7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166
{
    int ret;

    if (priv->uses_tls) {
    tls_resend:
        ret = gnutls_record_send (priv->session, bytes, len);
        if (ret < 0) {
            if (ret == GNUTLS_E_INTERRUPTED)
                goto tls_resend;
            if (ret == GNUTLS_E_AGAIN)
                return 0;

            error (in_open ? NULL : conn,
                   VIR_ERR_GNUTLS_ERROR, gnutls_strerror (ret));
            return -1;
        }
    } else {
    resend:
        ret = send (priv->sock, bytes, len, 0);
        if (ret == -1) {
            if (errno == EINTR)
                goto resend;
            if (errno == EWOULDBLOCK)
                return 0;

7167 7168
            virReportSystemError(in_open ? NULL : conn, errno,
                                 "%s", _("cannot send data"));
7169 7170 7171 7172 7173 7174 7175 7176 7177 7178
            return -1;

        }
    }

    return ret;
}


static int
7179 7180 7181 7182
remoteIOReadBuffer(virConnectPtr conn,
                   struct private_data *priv,
                   int in_open /* if we are in virConnectOpen */,
                   char *bytes, int len)
7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216
{
    int ret;

    if (priv->uses_tls) {
    tls_resend:
        ret = gnutls_record_recv (priv->session, bytes, len);
        if (ret == GNUTLS_E_INTERRUPTED)
            goto tls_resend;
        if (ret == GNUTLS_E_AGAIN)
            return 0;

        /* Treat 0 == EOF as an error */
        if (ret <= 0) {
            if (ret < 0)
                errorf (in_open ? NULL : conn,
                        VIR_ERR_GNUTLS_ERROR,
                        _("failed to read from TLS socket %s"),
                        gnutls_strerror (ret));
            else
                errorf (in_open ? NULL : conn,
                        VIR_ERR_SYSTEM_ERROR,
                        "%s", _("server closed connection"));
            return -1;
        }
    } else {
    resend:
        ret = recv (priv->sock, bytes, len, 0);
        if (ret <= 0) {
            if (ret == -1) {
                if (errno == EINTR)
                    goto resend;
                if (errno == EWOULDBLOCK)
                    return 0;

7217 7218
                virReportSystemError(in_open ? NULL : conn, errno,
                                     "%s", _("cannot recv data"));
7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232
            } else {
                errorf (in_open ? NULL : conn,
                        VIR_ERR_SYSTEM_ERROR,
                        "%s", _("server closed connection"));
            }
            return -1;
        }
    }

    return ret;
}


static int
7233 7234 7235 7236
remoteIOWriteMessage(virConnectPtr conn,
                     struct private_data *priv,
                     int in_open,
                     struct remote_thread_call *thecall)
7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261
{
#if HAVE_SASL
    if (priv->saslconn) {
        const char *output;
        unsigned int outputlen;
        int err, ret;

        if (!priv->saslEncoded) {
            err = sasl_encode(priv->saslconn,
                              thecall->buffer + thecall->bufferOffset,
                              thecall->bufferLength - thecall->bufferOffset,
                              &output, &outputlen);
            if (err != SASL_OK) {
                errorf (in_open ? NULL : conn, VIR_ERR_INTERNAL_ERROR,
                        _("failed to encode SASL data: %s"),
                        sasl_errstring(err, NULL, NULL));
                return -1;
            }
            priv->saslEncoded = output;
            priv->saslEncodedLength = outputlen;
            priv->saslEncodedOffset = 0;

            thecall->bufferOffset = thecall->bufferLength;
        }

7262 7263 7264
        ret = remoteIOWriteBuffer(conn, priv, in_open,
                                  priv->saslEncoded + priv->saslEncodedOffset,
                                  priv->saslEncodedLength - priv->saslEncodedOffset);
7265 7266 7267 7268 7269 7270 7271
        if (ret < 0)
            return ret;
        priv->saslEncodedOffset += ret;

        if (priv->saslEncodedOffset == priv->saslEncodedLength) {
            priv->saslEncoded = NULL;
            priv->saslEncodedOffset = priv->saslEncodedLength = 0;
7272 7273 7274 7275
            if (thecall->want_reply)
                thecall->mode = REMOTE_MODE_WAIT_RX;
            else
                thecall->mode = REMOTE_MODE_COMPLETE;
7276 7277 7278 7279
        }
    } else {
#endif
        int ret;
7280 7281 7282
        ret = remoteIOWriteBuffer(conn, priv, in_open,
                                  thecall->buffer + thecall->bufferOffset,
                                  thecall->bufferLength - thecall->bufferOffset);
7283 7284 7285 7286 7287 7288
        if (ret < 0)
            return ret;
        thecall->bufferOffset += ret;

        if (thecall->bufferOffset == thecall->bufferLength) {
            thecall->bufferOffset = thecall->bufferLength = 0;
7289 7290 7291 7292
            if (thecall->want_reply)
                thecall->mode = REMOTE_MODE_WAIT_RX;
            else
                thecall->mode = REMOTE_MODE_COMPLETE;
7293 7294 7295 7296 7297 7298 7299 7300 7301
        }
#if HAVE_SASL
    }
#endif
    return 0;
}


static int
7302 7303
remoteIOHandleOutput(virConnectPtr conn, struct private_data *priv,
                     int in_open) {
7304 7305 7306 7307 7308 7309 7310 7311 7312 7313
    struct remote_thread_call *thecall = priv->waitDispatch;

    while (thecall &&
           thecall->mode != REMOTE_MODE_WAIT_TX)
        thecall = thecall->next;

    if (!thecall)
        return -1; /* Shouldn't happen, but you never know... */

    while (thecall) {
7314
        int ret = remoteIOWriteMessage(conn, priv, in_open, thecall);
7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327
        if (ret < 0)
            return ret;

        if (thecall->mode == REMOTE_MODE_WAIT_TX)
            return 0; /* Blocking write, to back to event loop */

        thecall = thecall->next;
    }

    return 0; /* No more calls to send, all done */
}

static int
7328
remoteIOReadMessage(virConnectPtr conn, struct private_data *priv,
7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342
                    int in_open) {
    unsigned int wantData;

    /* Start by reading length word */
    if (priv->bufferLength == 0)
        priv->bufferLength = 4;

    wantData = priv->bufferLength - priv->bufferOffset;

#if HAVE_SASL
    if (priv->saslconn) {
        if (priv->saslDecoded == NULL) {
            char encoded[8192];
            int ret, err;
7343
            ret = remoteIOReadBuffer(conn, priv, in_open,
7344
                                     encoded, sizeof(encoded));
7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378
            if (ret < 0)
                return -1;
            if (ret == 0)
                return 0;

            err = sasl_decode(priv->saslconn, encoded, ret,
                              &priv->saslDecoded, &priv->saslDecodedLength);
            if (err != SASL_OK) {
                errorf (in_open ? NULL : conn, VIR_ERR_INTERNAL_ERROR,
                        _("failed to decode SASL data: %s"),
                        sasl_errstring(err, NULL, NULL));
                return -1;
            }
            priv->saslDecodedOffset = 0;
        }

        if ((priv->saslDecodedLength - priv->saslDecodedOffset) < wantData)
            wantData = (priv->saslDecodedLength - priv->saslDecodedOffset);

        memcpy(priv->buffer + priv->bufferOffset,
               priv->saslDecoded + priv->saslDecodedOffset,
               wantData);
        priv->saslDecodedOffset += wantData;
        priv->bufferOffset += wantData;
        if (priv->saslDecodedOffset == priv->saslDecodedLength) {
            priv->saslDecodedLength = priv->saslDecodedLength = 0;
            priv->saslDecoded = NULL;
        }

        return wantData;
    } else {
#endif
        int ret;

7379 7380 7381
        ret = remoteIOReadBuffer(conn, priv, in_open,
                                 priv->buffer + priv->bufferOffset,
                                 wantData);
7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;

        priv->bufferOffset += ret;

        return ret;
#if HAVE_SASL
    }
#endif
}
7394 7395


7396
static int
7397 7398
remoteIODecodeMessageLength(virConnectPtr conn, struct private_data *priv,
                            int in_open) {
7399
    XDR xdr;
7400
    unsigned int len;
7401 7402

    xdrmem_create (&xdr, priv->buffer, priv->bufferLength, XDR_DECODE);
7403
    if (!xdr_u_int (&xdr, &len)) {
7404
        error (in_open ? NULL : conn,
7405
               VIR_ERR_RPC, _("xdr_u_int (length word, reply)"));
7406 7407 7408 7409
        return -1;
    }
    xdr_destroy (&xdr);

7410 7411 7412 7413 7414 7415
    if (len < REMOTE_MESSAGE_HEADER_XDR_LEN) {
        error (in_open ? NULL : conn,
               VIR_ERR_RPC, _("packet received from server too small"));
        return -1;
    }

7416
    /* Length includes length word - adjust to real length to read. */
7417
    len -= REMOTE_MESSAGE_HEADER_XDR_LEN;
7418

7419
    if (len > REMOTE_MESSAGE_MAX) {
7420
        error (in_open ? NULL : conn,
7421
               VIR_ERR_RPC, _("packet received from server too large"));
7422 7423 7424
        return -1;
    }

7425 7426 7427 7428 7429 7430 7431 7432 7433
    /* Extend our declared buffer length and carry
       on reading the header + payload */
    priv->bufferLength += len;
    DEBUG("Got length, now need %d total (%d more)", priv->bufferLength, len);
    return 0;
}


static int
7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444
processCallDispatchReply(virConnectPtr conn, struct private_data *priv,
                         int in_open,
                         remote_message_header *hdr,
                         XDR *xdr);

static int
processCallDispatchMessage(virConnectPtr conn, struct private_data *priv,
                           int in_open,
                           remote_message_header *hdr,
                           XDR *xdr);

7445 7446 7447 7448 7449 7450
static int
processCallDispatchStream(virConnectPtr conn, struct private_data *priv,
                          int in_open,
                          remote_message_header *hdr,
                          XDR *xdr);

7451 7452 7453 7454

static int
processCallDispatch(virConnectPtr conn, struct private_data *priv,
                    int in_open) {
7455 7456 7457
    XDR xdr;
    struct remote_message_header hdr;
    int len = priv->bufferLength - 4;
7458
    int rv = -1;
7459

7460 7461 7462
    /* Length word has already been read */
    priv->bufferOffset = 4;

7463
    /* Deserialise reply header. */
7464
    xdrmem_create (&xdr, priv->buffer + priv->bufferOffset, len, XDR_DECODE);
7465
    if (!xdr_remote_message_header (&xdr, &hdr)) {
7466
        error (in_open ? NULL : conn,
7467
               VIR_ERR_RPC, _("invalid header in reply"));
7468 7469 7470
        return -1;
    }

7471 7472
    priv->bufferOffset += xdr_getpos(&xdr);

7473 7474
    /* Check program, version, etc. are what we expect. */
    if (hdr.prog != REMOTE_PROGRAM) {
7475 7476 7477 7478 7479
        virRaiseError (in_open ? NULL : conn,
                       NULL, NULL, VIR_FROM_REMOTE,
                       VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
                       _("unknown program (received %x, expected %x)"),
                       hdr.prog, REMOTE_PROGRAM);
7480 7481 7482
        return -1;
    }
    if (hdr.vers != REMOTE_PROTOCOL_VERSION) {
7483 7484 7485 7486 7487
        virRaiseError (in_open ? NULL : conn,
                       NULL, NULL, VIR_FROM_REMOTE,
                       VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
                       _("unknown protocol version (received %x, expected %x)"),
                       hdr.vers, REMOTE_PROTOCOL_VERSION);
7488 7489 7490
        return -1;
    }

7491

7492 7493 7494 7495 7496
    switch (hdr.type) {
    case REMOTE_REPLY: /* Normal RPC replies */
        rv = processCallDispatchReply(conn, priv, in_open,
                                      &hdr, &xdr);
        break;
7497

7498 7499 7500 7501 7502
    case REMOTE_MESSAGE: /* Async notifications */
        rv = processCallDispatchMessage(conn, priv, in_open,
                                        &hdr, &xdr);
        break;

7503 7504 7505 7506 7507
    case REMOTE_STREAM: /* Stream protocol */
        rv = processCallDispatchStream(conn, priv, in_open,
                                       &hdr, &xdr);
        break;

7508 7509 7510 7511 7512 7513 7514 7515
    default:
         virRaiseError (in_open ? NULL : conn,
                        NULL, NULL, VIR_FROM_REMOTE,
                        VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
                        _("got unexpected RPC call %d from server"),
                        hdr.proc);
        rv = -1;
        break;
7516
    }
7517

7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529
    xdr_destroy(&xdr);
    return rv;
}


static int
processCallDispatchReply(virConnectPtr conn, struct private_data *priv,
                         int in_open,
                         remote_message_header *hdr,
                         XDR *xdr) {
    struct remote_thread_call *thecall;

7530 7531 7532 7533
    /* Ok, definitely got an RPC reply now find
       out who's been waiting for it */
    thecall = priv->waitDispatch;
    while (thecall &&
7534
           thecall->serial != hdr->serial)
7535 7536 7537 7538 7539 7540 7541
        thecall = thecall->next;

    if (!thecall) {
        virRaiseError (in_open ? NULL : conn,
                       NULL, NULL, VIR_FROM_REMOTE,
                       VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
                       _("no call waiting for reply with serial %d"),
7542
                       hdr->serial);
7543 7544
        return -1;
    }
7545

7546
    if (hdr->proc != thecall->proc_nr) {
7547 7548 7549 7550
        virRaiseError (in_open ? NULL : conn,
                       NULL, NULL, VIR_FROM_REMOTE,
                       VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
                       _("unknown procedure (received %x, expected %x)"),
7551
                       hdr->proc, thecall->proc_nr);
7552 7553 7554 7555 7556 7557 7558
        return -1;
    }

    /* Status is either REMOTE_OK (meaning that what follows is a ret
     * structure), or REMOTE_ERROR (and what follows is a remote_error
     * structure).
     */
7559
    switch (hdr->status) {
7560
    case REMOTE_OK:
7561
        if (!(*thecall->ret_filter) (xdr, thecall->ret)) {
7562
            error (in_open ? NULL : conn, VIR_ERR_RPC,
7563
                   _("unmarshalling ret"));
7564 7565
            return -1;
        }
7566
        thecall->mode = REMOTE_MODE_COMPLETE;
7567 7568 7569
        return 0;

    case REMOTE_ERROR:
7570
        VIR_WARN0("Method call error");
7571
        memset (&thecall->err, 0, sizeof thecall->err);
7572
        if (!xdr_remote_error (xdr, &thecall->err)) {
7573
            error (in_open ? NULL : conn,
7574
                   VIR_ERR_RPC, _("unmarshalling remote_error"));
7575 7576
            return -1;
        }
7577 7578
        thecall->mode = REMOTE_MODE_ERROR;
        return 0;
7579 7580

    default:
7581 7582 7583
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
                       VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
                       _("unknown status (received %x)"),
7584
                       hdr->status);
7585 7586 7587 7588
        return -1;
    }
}

7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613
static int
processCallDispatchMessage(virConnectPtr conn, struct private_data *priv,
                           int in_open,
                           remote_message_header *hdr,
                           XDR *xdr) {
    /* An async message has come in while we were waiting for the
     * response. Process it to pull it off the wire, and try again
     */
    DEBUG0("Encountered an event while waiting for a response");

    if (in_open) {
        DEBUG("Ignoring bogus event %d received while in open", hdr->proc);
        return -1;
    }

    if (hdr->proc == REMOTE_PROC_DOMAIN_EVENT) {
        remoteDomainQueueEvent(conn, xdr);
        virEventUpdateTimeout(priv->eventFlushTimer, 0);
    } else {
        return -1;
        DEBUG("Unexpected event proc %d", hdr->proc);
    }
    return 0;
}

7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720
static int
processCallDispatchStream(virConnectPtr conn ATTRIBUTE_UNUSED,
                          struct private_data *priv,
                          int in_open ATTRIBUTE_UNUSED,
                          remote_message_header *hdr,
                          XDR *xdr) {
    struct private_stream_data *privst;
    struct remote_thread_call *thecall;

    /* Try and find a matching stream */
    privst = priv->streams;
    while (privst &&
           privst->serial != hdr->serial &&
           privst->proc_nr != hdr->proc)
        privst = privst->next;

    if (!privst) {
        VIR_WARN("No registered stream matching serial=%d, proc=%d",
                 hdr->serial, hdr->proc);
        return -1;
    }

    /* See if there's also a (optional) call waiting for this reply */
    thecall = priv->waitDispatch;
    while (thecall &&
           thecall->serial != hdr->serial)
        thecall = thecall->next;


    /* Status is either REMOTE_OK (meaning that what follows is a ret
     * structure), or REMOTE_ERROR (and what follows is a remote_error
     * structure).
     */
    switch (hdr->status) {
    case REMOTE_CONTINUE: {
        int avail = privst->incomingLength - privst->incomingOffset;
        int need = priv->bufferLength - priv->bufferOffset;
        VIR_WARN0("Got a stream data packet");

        /* XXX flag stream as complete somwhere if need==0 */

        if (need > avail) {
            int extra = need - avail;
            if (VIR_REALLOC_N(privst->incoming,
                              privst->incomingLength + extra) < 0) {
                VIR_WARN0("Out of memory");
                return -1;
            }
            privst->incomingLength += extra;
        }

        memcpy(privst->incoming + privst->incomingOffset,
               priv->buffer + priv->bufferOffset,
               priv->bufferLength - priv->bufferOffset);
        privst->incomingOffset += (priv->bufferLength - priv->bufferOffset);

        if (thecall && thecall->want_reply) {
            VIR_WARN("Got sync data packet offset=%d", privst->incomingOffset);
            thecall->mode = REMOTE_MODE_COMPLETE;
        } else {
            VIR_WARN("Got aysnc data packet offset=%d", privst->incomingOffset);
        }
        return 0;
    }

    case REMOTE_OK:
        VIR_WARN0("Got a synchronous confirm");
        if (!thecall) {
            VIR_WARN0("Got unexpected stream finish confirmation");
            return -1;
        }
        thecall->mode = REMOTE_MODE_COMPLETE;
        return 0;

    case REMOTE_ERROR:
        if (thecall && thecall->want_reply) {
            VIR_WARN0("Got a synchronous error");
            /* Give the error straight to this call */
            memset (&thecall->err, 0, sizeof thecall->err);
            if (!xdr_remote_error (xdr, &thecall->err)) {
                error (in_open ? NULL : conn,
                       VIR_ERR_RPC, _("unmarshalling remote_error"));
                return -1;
            }
            thecall->mode = REMOTE_MODE_ERROR;
        } else {
            VIR_WARN0("Got a asynchronous error");
            /* No call, so queue the error against the stream */
            if (privst->has_error) {
                VIR_WARN0("Got unexpected duplicate stream error");
                return -1;
            }
            privst->has_error = 1;
            memset (&privst->err, 0, sizeof privst->err);
            if (!xdr_remote_error (xdr, &privst->err)) {
                VIR_WARN0("Failed to unmarshall error");
                return -1;
            }
        }
        return 0;

    default:
        VIR_WARN("Stream with unexpected serial=%d, proc=%d, status=%d",
                 hdr->serial, hdr->proc, hdr->status);
        return -1;
    }
}
7721 7722

static int
7723 7724
remoteIOHandleInput(virConnectPtr conn, struct private_data *priv,
                    int in_open)
7725
{
7726
    /* Read as much data as is available, until we get
7727
     * EAGAIN
7728
     */
7729
    for (;;) {
7730
        int ret = remoteIOReadMessage(conn, priv, in_open);
7731

7732 7733 7734 7735
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;  /* Blocking on read */
7736

7737 7738 7739
        /* Check for completion of our goal */
        if (priv->bufferOffset == priv->bufferLength) {
            if (priv->bufferOffset == 4) {
7740
                ret = remoteIODecodeMessageLength(conn, priv, in_open);
7741 7742 7743 7744 7745 7746 7747 7748 7749
                if (ret < 0)
                    return -1;

                /*
                 * We'll carry on around the loop to immediately
                 * process the message body, because it has probably
                 * already arrived. Worst case, we'll get EAGAIN on
                 * next iteration.
                 */
7750
            } else {
7751
                ret = processCallDispatch(conn, priv, in_open);
7752
                priv->bufferOffset = priv->bufferLength = 0;
7753 7754 7755 7756 7757 7758 7759 7760
                /*
                 * We've completed one call, so return even
                 * though there might still be more data on
                 * the wire. We need to actually let the caller
                 * deal with this arrived message to keep good
                 * response, and also to correctly handle EOF.
                 */
                return ret;
7761 7762 7763
            }
        }
    }
7764 7765
}

7766 7767 7768 7769 7770
/*
 * Process all calls pending dispatch/receive until we
 * get a reply to our own call. Then quit and pass the buck
 * to someone else.
 */
7771
static int
7772 7773 7774 7775
remoteIOEventLoop(virConnectPtr conn,
                  struct private_data *priv,
                  int in_open,
                  struct remote_thread_call *thiscall)
7776
{
7777 7778
    struct pollfd fds[2];
    int ret;
7779

7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800
    fds[0].fd = priv->sock;
    fds[1].fd = priv->wakeupReadFD;

    for (;;) {
        struct remote_thread_call *tmp = priv->waitDispatch;
        struct remote_thread_call *prev;
        char ignore;

        fds[0].events = fds[0].revents = 0;
        fds[1].events = fds[1].revents = 0;

        fds[1].events = POLLIN;
        while (tmp) {
            if (tmp->mode == REMOTE_MODE_WAIT_RX)
                fds[0].events |= POLLIN;
            if (tmp->mode == REMOTE_MODE_WAIT_TX)
                fds[0].events |= POLLOUT;

            tmp = tmp->next;
        }

7801 7802 7803
        if (priv->streams)
            fds[0].events |= POLLIN;

7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821
        /* Release lock while poll'ing so other threads
         * can stuff themselves on the queue */
        remoteDriverUnlock(priv);

    repoll:
        ret = poll(fds, ARRAY_CARDINALITY(fds), -1);
        if (ret < 0 && errno == EINTR)
            goto repoll;
        remoteDriverLock(priv);

        if (fds[1].revents) {
            DEBUG0("Woken up from poll by other thread");
            saferead(priv->wakeupReadFD, &ignore, sizeof(ignore));
        }

        if (ret < 0) {
            if (errno == EWOULDBLOCK)
                continue;
7822 7823
            virReportSystemError(in_open ? NULL : conn, errno,
                                 "%s", _("poll on socket failed"));
7824
            goto error;
7825 7826 7827
        }

        if (fds[0].revents & POLLOUT) {
7828
            if (remoteIOHandleOutput(conn, priv, in_open) < 0)
7829
                goto error;
7830
        }
7831 7832

        if (fds[0].revents & POLLIN) {
7833
            if (remoteIOHandleInput(conn, priv, in_open) < 0)
7834
                goto error;
7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858
        }

        /* Iterate through waiting threads and if
         * any are complete then tell 'em to wakeup
         */
        tmp = priv->waitDispatch;
        prev = NULL;
        while (tmp) {
            if (tmp != thiscall &&
                (tmp->mode == REMOTE_MODE_COMPLETE ||
                 tmp->mode == REMOTE_MODE_ERROR)) {
                /* Take them out of the list */
                if (prev)
                    prev->next = tmp->next;
                else
                    priv->waitDispatch = tmp->next;

                /* And wake them up....
                 * ...they won't actually wakeup until
                 * we release our mutex a short while
                 * later...
                 */
                DEBUG("Waking up sleep %d %p %p", tmp->proc_nr, tmp, priv->waitDispatch);
                virCondSignal(&tmp->cond);
7859
            }
7860 7861
            prev = tmp;
            tmp = tmp->next;
7862 7863
        }

7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879
        /* Now see if *we* are done */
        if (thiscall->mode == REMOTE_MODE_COMPLETE ||
            thiscall->mode == REMOTE_MODE_ERROR) {
            /* We're at head of the list already, so
             * remove us
             */
            priv->waitDispatch = thiscall->next;
            DEBUG("Giving up the buck %d %p %p", thiscall->proc_nr, thiscall, priv->waitDispatch);
            /* See if someone else is still waiting
             * and if so, then pass the buck ! */
            if (priv->waitDispatch) {
                DEBUG("Passing the buck to %d %p", priv->waitDispatch->proc_nr, priv->waitDispatch);
                virCondSignal(&priv->waitDispatch->cond);
            }
            return 0;
        }
7880

7881 7882 7883 7884

        if (fds[0].revents & (POLLHUP | POLLERR)) {
            errorf(in_open ? NULL : conn, VIR_ERR_INTERNAL_ERROR,
                   "%s", _("received hangup / error event on socket"));
7885
            goto error;
7886 7887
        }
    }
7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899


error:
    priv->waitDispatch = thiscall->next;
    DEBUG("Giving up the buck due to I/O error %d %p %p", thiscall->proc_nr, thiscall, priv->waitDispatch);
    /* See if someone else is still waiting
     * and if so, then pass the buck ! */
    if (priv->waitDispatch) {
        DEBUG("Passing the buck to %d %p", priv->waitDispatch->proc_nr, priv->waitDispatch);
        virCondSignal(&priv->waitDispatch->cond);
    }
    return -1;
7900 7901
}

7902
/*
7903
 * This function sends a message to remote server and awaits a reply
7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934
 *
 * NB. This does not free the args structure (not desirable, since you
 * often want this allocated on the stack or else it contains strings
 * which come from the user).  It does however free any intermediate
 * results, eg. the error structure if there is one.
 *
 * NB(2). Make sure to memset (&ret, 0, sizeof ret) before calling,
 * else Bad Things will happen in the XDR code.
 *
 * NB(3) You must have the private_data lock before calling this
 *
 * NB(4) This is very complicated. Due to connection cloning, multiple
 * threads can want to use the socket at once. Obviously only one of
 * them can. So if someone's using the socket, other threads are put
 * to sleep on condition variables. THe existing thread may completely
 * send & receive their RPC call/reply while they're asleep. Or it
 * may only get around to dealing with sending the call. Or it may
 * get around to neither. So upon waking up from slumber, the other
 * thread may or may not have more work todo.
 *
 * We call this dance  'passing the buck'
 *
 *      http://en.wikipedia.org/wiki/Passing_the_buck
 *
 *   "Buck passing or passing the buck is the action of transferring
 *    responsibility or blame unto another person. It is also used as
 *    a strategy in power politics when the actions of one country/
 *    nation are blamed on another, providing an opportunity for war."
 *
 * NB(5) Don't Panic!
 */
7935
static int
7936 7937 7938 7939
remoteIO(virConnectPtr conn,
         struct private_data *priv,
         int flags,
         struct remote_thread_call *thiscall)
7940
{
7941 7942
    int rv;

7943 7944 7945
    DEBUG("Do proc=%d serial=%d length=%d wait=%p",
          thiscall->proc_nr, thiscall->serial,
          thiscall->bufferLength, priv->waitDispatch);
7946

7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957
    /* Check to see if another thread is dispatching */
    if (priv->waitDispatch) {
        /* Stick ourselves on the end of the wait queue */
        struct remote_thread_call *tmp = priv->waitDispatch;
        char ignore = 1;
        while (tmp && tmp->next)
            tmp = tmp->next;
        if (tmp)
            tmp->next = thiscall;
        else
            priv->waitDispatch = thiscall;
7958

7959 7960
        /* Force other thread to wakup from poll */
        safewrite(priv->wakeupSendFD, &ignore, sizeof(ignore));
7961

7962
        DEBUG("Going to sleep %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979
        /* Go to sleep while other thread is working... */
        if (virCondWait(&thiscall->cond, &priv->lock) < 0) {
            if (priv->waitDispatch == thiscall) {
                priv->waitDispatch = thiscall->next;
            } else {
                tmp = priv->waitDispatch;
                while (tmp && tmp->next &&
                       tmp->next != thiscall) {
                    tmp = tmp->next;
                }
                if (tmp && tmp->next == thiscall)
                    tmp->next = thiscall->next;
            }
            errorf(flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
                   VIR_ERR_INTERNAL_ERROR, "%s",
                   _("failed to wait on condition"));
            VIR_FREE(thiscall);
7980
            return -1;
7981
        }
7982

7983
        DEBUG("Wokeup from sleep %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997
        /* Two reasons we can be woken up
         *  1. Other thread has got our reply ready for us
         *  2. Other thread is all done, and it is our turn to
         *     be the dispatcher to finish waiting for
         *     our reply
         */
        if (thiscall->mode == REMOTE_MODE_COMPLETE ||
            thiscall->mode == REMOTE_MODE_ERROR) {
            /*
             * We avoided catching the buck and our reply is ready !
             * We've already had 'thiscall' removed from the list
             * so just need to (maybe) handle errors & free it
             */
            goto cleanup;
7998
        }
7999 8000 8001

        /* Grr, someone passed the buck onto us ... */

8002
    } else {
8003 8004 8005 8006
        /* We're first to catch the buck */
        priv->waitDispatch = thiscall;
    }

8007
    DEBUG("We have the buck %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024
    /*
     * The buck stops here!
     *
     * At this point we're about to own the dispatch
     * process...
     */

    /*
     * Avoid needless wake-ups of the event loop in the
     * case where this call is being made from a different
     * thread than the event loop. These wake-ups would
     * cause the event loop thread to be blocked on the
     * mutex for the duration of the call
     */
    if (priv->watch >= 0)
        virEventUpdateHandle(priv->watch, 0);

8025 8026 8027
    rv = remoteIOEventLoop(conn, priv,
                           flags & REMOTE_CALL_IN_OPEN ? 1 : 0,
                           thiscall);
8028 8029 8030 8031 8032 8033 8034 8035 8036 8037

    if (priv->watch >= 0)
        virEventUpdateHandle(priv->watch, VIR_EVENT_HANDLE_READABLE);

    if (rv < 0) {
        VIR_FREE(thiscall);
        return -1;
    }

cleanup:
8038
    DEBUG("All done with our call %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
8039 8040 8041 8042 8043 8044 8045
    if (thiscall->mode == REMOTE_MODE_ERROR) {
        /* See if caller asked us to keep quiet about missing RPCs
         * eg for interop with older servers */
        if (flags & REMOTE_CALL_QUIET_MISSING_RPC &&
            thiscall->err.domain == VIR_FROM_REMOTE &&
            thiscall->err.code == VIR_ERR_RPC &&
            thiscall->err.level == VIR_ERR_ERROR &&
8046
            thiscall->err.message &&
8047 8048 8049
            STRPREFIX(*thiscall->err.message, "unknown procedure")) {
            rv = -2;
        } else {
8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060
            virRaiseErrorFull(flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
                              __FILE__, __FUNCTION__, __LINE__,
                              thiscall->err.domain,
                              thiscall->err.code,
                              thiscall->err.level,
                              thiscall->err.str1 ? *thiscall->err.str1 : NULL,
                              thiscall->err.str2 ? *thiscall->err.str2 : NULL,
                              thiscall->err.str3 ? *thiscall->err.str3 : NULL,
                              thiscall->err.int1,
                              thiscall->err.int2,
                              "%s", thiscall->err.message ? *thiscall->err.message : NULL);
8061
            rv = -1;
8062
        }
8063
        xdr_free((xdrproc_t)xdr_remote_error,  (char *)&thiscall->err);
8064 8065
    } else {
        rv = 0;
8066
    }
8067 8068 8069
    VIR_FREE(thiscall);
    return rv;
}
8070

8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098

/*
 * Serial a set of arguments into a method call message,
 * send that to the server and wait for reply
 */
static int
call (virConnectPtr conn, struct private_data *priv,
      int flags /* if we are in virConnectOpen */,
      int proc_nr,
      xdrproc_t args_filter, char *args,
      xdrproc_t ret_filter, char *ret)
{
    struct remote_thread_call *thiscall;

    thiscall = prepareCall(conn, priv, flags, proc_nr,
                           args_filter, args,
                           ret_filter, ret);

    if (!thiscall) {
        virReportOOMError (flags & REMOTE_CALL_IN_OPEN ? NULL : conn);
        return -1;
    }

    return remoteIO(conn, priv, flags, thiscall);
}



8099 8100 8101 8102 8103 8104 8105 8106
/**
 * remoteDomainReadEvent
 *
 * Read the event data off the wire
 */
static virDomainEventPtr
remoteDomainReadEvent(virConnectPtr conn, XDR *xdr)
{
8107
    remote_domain_event_msg msg;
8108 8109
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
8110
    memset (&msg, 0, sizeof msg);
8111 8112

    /* unmarshall parameters, and process it*/
8113
    if (! xdr_remote_domain_event_msg(xdr, &msg) ) {
8114
        error (conn, VIR_ERR_RPC,
8115
               _("remoteDomainProcessEvent: unmarshalling msg"));
8116 8117 8118
        return NULL;
    }

8119
    dom = get_nonnull_domain(conn,msg.dom);
8120 8121 8122
    if (!dom)
        return NULL;

8123
    event = virDomainEventNewFromDom(dom, msg.event, msg.detail);
8124 8125 8126

    virDomainFree(dom);
    return event;
8127 8128
}

8129 8130
static void
remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr)
8131
{
8132 8133
    struct private_data *priv = conn->privateData;
    virDomainEventPtr event;
8134

8135 8136 8137
    event = remoteDomainReadEvent(conn, xdr);
    if (!event)
        return;
8138

8139 8140 8141 8142 8143
    if (virDomainEventQueuePush(priv->domainEvents,
                                event) < 0) {
        DEBUG0("Error adding event to queue");
        virDomainEventFree(event);
    }
8144 8145
}

8146 8147 8148 8149 8150 8151 8152 8153 8154 8155
/** remoteDomainEventFired:
 *
 * The callback for monitoring the remote socket
 * for event data
 */
void
remoteDomainEventFired(int watch,
                       int fd,
                       int event,
                       void *opaque)
8156
{
8157 8158
    virConnectPtr        conn = opaque;
    struct private_data *priv = conn->privateData;
8159

8160
    remoteDriverLock(priv);
8161

8162 8163 8164
    /* This should be impossible, but it doesn't hurt to check */
    if (priv->waitDispatch)
        goto done;
8165

8166
    DEBUG("Event fired %d %d %d %X", watch, fd, event, event);
8167

8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181
    if (event & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR)) {
         DEBUG("%s : VIR_EVENT_HANDLE_HANGUP or "
               "VIR_EVENT_HANDLE_ERROR encountered", __FUNCTION__);
         virEventRemoveHandle(watch);
         priv->watch = -1;
         goto done;
    }

    if (fd != priv->sock) {
        virEventRemoveHandle(watch);
        priv->watch = -1;
        goto done;
    }

8182
    if (remoteIOHandleInput(conn, priv, 0) < 0)
8183 8184 8185 8186
        DEBUG0("Something went wrong during async message processing");

done:
    remoteDriverUnlock(priv);
8187 8188
}

8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202
static void remoteDomainEventDispatchFunc(virConnectPtr conn,
                                          virDomainEventPtr event,
                                          virConnectDomainEventCallback cb,
                                          void *cbopaque,
                                          void *opaque)
{
    struct private_data *priv = opaque;

    /* Drop the lock whle dispatching, for sake of re-entrancy */
    remoteDriverUnlock(priv);
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    remoteDriverLock(priv);
}

8203 8204
void
remoteDomainEventQueueFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
8205
{
8206 8207
    virConnectPtr conn = opaque;
    struct private_data *priv = conn->privateData;
8208
    virDomainEventQueue tempQueue;
8209 8210 8211

    remoteDriverLock(priv);

8212 8213 8214 8215 8216 8217 8218 8219 8220 8221
    priv->domainEventDispatching = 1;

    /* Copy the queue, so we're reentrant safe */
    tempQueue.count = priv->domainEvents->count;
    tempQueue.events = priv->domainEvents->events;
    priv->domainEvents->count = 0;
    priv->domainEvents->events = NULL;

    virDomainEventQueueDispatch(&tempQueue, priv->callbackList,
                                remoteDomainEventDispatchFunc, priv);
8222 8223
    virEventUpdateTimeout(priv->eventFlushTimer, -1);

8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236
    /* Purge any deleted callbacks */
    virDomainEventCallbackListPurgeMarked(priv->callbackList);

    if ( priv->callbackList->count == 0 ) {
        /* Tell the server when we are the last callback deregistering */
        if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_DEREGISTER,
                  (xdrproc_t) xdr_void, (char *) NULL,
                  (xdrproc_t) xdr_void, (char *) NULL) == -1)
            VIR_WARN0("Failed to de-register events");
    }

    priv->domainEventDispatching = 0;

8237
    remoteDriverUnlock(priv);
8238 8239
}

8240

8241 8242
/* get_nonnull_domain and get_nonnull_network turn an on-wire
 * (name, uuid) pair into virDomainPtr or virNetworkPtr object.
8243
 * These can return NULL if underlying memory allocations fail,
8244
 * but if they do then virterror_internal.has been set.
8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260
 */
static virDomainPtr
get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain)
{
    virDomainPtr dom;
    dom = virGetDomain (conn, domain.name, BAD_CAST domain.uuid);
    if (dom) dom->id = domain.id;
    return dom;
}

static virNetworkPtr
get_nonnull_network (virConnectPtr conn, remote_nonnull_network network)
{
    return virGetNetwork (conn, network.name, BAD_CAST network.uuid);
}

D
Daniel Veillard 已提交
8261
static virInterfacePtr
8262
get_nonnull_interface (virConnectPtr conn, remote_nonnull_interface iface)
D
Daniel Veillard 已提交
8263
{
8264
    return virGetInterface (conn, iface.name, iface.mac);
D
Daniel Veillard 已提交
8265 8266
}

8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278
static virStoragePoolPtr
get_nonnull_storage_pool (virConnectPtr conn, remote_nonnull_storage_pool pool)
{
    return virGetStoragePool (conn, pool.name, BAD_CAST pool.uuid);
}

static virStorageVolPtr
get_nonnull_storage_vol (virConnectPtr conn, remote_nonnull_storage_vol vol)
{
    return virGetStorageVol (conn, vol.pool, vol.name, vol.key);
}

8279 8280 8281 8282 8283 8284
static virNodeDevicePtr
get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev)
{
    return virGetNodeDevice(conn, dev.name);
}

8285 8286 8287
static virSecretPtr
get_nonnull_secret (virConnectPtr conn, remote_nonnull_secret secret)
{
8288
    return virGetSecret(conn, BAD_CAST secret.uuid, secret.usageType, secret.usageID);
8289 8290
}

8291 8292 8293 8294
/* Make remote_nonnull_domain and remote_nonnull_network. */
static void
make_nonnull_domain (remote_nonnull_domain *dom_dst, virDomainPtr dom_src)
{
8295
    dom_dst->id = dom_src->id;
8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306
    dom_dst->name = dom_src->name;
    memcpy (dom_dst->uuid, dom_src->uuid, VIR_UUID_BUFLEN);
}

static void
make_nonnull_network (remote_nonnull_network *net_dst, virNetworkPtr net_src)
{
    net_dst->name = net_src->name;
    memcpy (net_dst->uuid, net_src->uuid, VIR_UUID_BUFLEN);
}

D
Daniel Veillard 已提交
8307 8308 8309 8310 8311 8312 8313 8314
static void
make_nonnull_interface (remote_nonnull_interface *interface_dst,
                        virInterfacePtr interface_src)
{
    interface_dst->name = interface_src->name;
    interface_dst->mac = interface_src->mac;
}

8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329
static void
make_nonnull_storage_pool (remote_nonnull_storage_pool *pool_dst, virStoragePoolPtr pool_src)
{
    pool_dst->name = pool_src->name;
    memcpy (pool_dst->uuid, pool_src->uuid, VIR_UUID_BUFLEN);
}

static void
make_nonnull_storage_vol (remote_nonnull_storage_vol *vol_dst, virStorageVolPtr vol_src)
{
    vol_dst->pool = vol_src->pool;
    vol_dst->name = vol_src->name;
    vol_dst->key = vol_src->key;
}

8330 8331 8332
static void
make_nonnull_secret (remote_nonnull_secret *secret_dst, virSecretPtr secret_src)
{
8333
    memcpy (secret_dst->uuid, secret_src->uuid, VIR_UUID_BUFLEN);
8334 8335
    secret_dst->usageType = secret_src->usageType;
    secret_dst->usageID = secret_src->usageID;
8336 8337
}

8338 8339
/*----------------------------------------------------------------------*/

8340 8341 8342 8343 8344
unsigned long remoteVersion(void)
{
    return REMOTE_PROTOCOL_VERSION;
}

8345
static virDriver remote_driver = {
8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382
    VIR_DRV_REMOTE,
    "remote",
    remoteOpen, /* open */
    remoteClose, /* close */
    remoteSupportsFeature, /* supports_feature */
    remoteType, /* type */
    remoteGetVersion, /* version */
    remoteGetHostname, /* getHostname */
    remoteGetMaxVcpus, /* getMaxVcpus */
    remoteNodeGetInfo, /* nodeGetInfo */
    remoteGetCapabilities, /* getCapabilities */
    remoteListDomains, /* listDomains */
    remoteNumOfDomains, /* numOfDomains */
    remoteDomainCreateXML, /* domainCreateXML */
    remoteDomainLookupByID, /* domainLookupByID */
    remoteDomainLookupByUUID, /* domainLookupByUUID */
    remoteDomainLookupByName, /* domainLookupByName */
    remoteDomainSuspend, /* domainSuspend */
    remoteDomainResume, /* domainResume */
    remoteDomainShutdown, /* domainShutdown */
    remoteDomainReboot, /* domainReboot */
    remoteDomainDestroy, /* domainDestroy */
    remoteDomainGetOSType, /* domainGetOSType */
    remoteDomainGetMaxMemory, /* domainGetMaxMemory */
    remoteDomainSetMaxMemory, /* domainSetMaxMemory */
    remoteDomainSetMemory, /* domainSetMemory */
    remoteDomainGetInfo, /* domainGetInfo */
    remoteDomainSave, /* domainSave */
    remoteDomainRestore, /* domainRestore */
    remoteDomainCoreDump, /* domainCoreDump */
    remoteDomainSetVcpus, /* domainSetVcpus */
    remoteDomainPinVcpu, /* domainPinVcpu */
    remoteDomainGetVcpus, /* domainGetVcpus */
    remoteDomainGetMaxVcpus, /* domainGetMaxVcpus */
    remoteDomainGetSecurityLabel, /* domainGetSecurityLabel */
    remoteNodeGetSecurityModel, /* nodeGetSecurityModel */
    remoteDomainDumpXML, /* domainDumpXML */
8383 8384
    remoteDomainXMLFromNative, /* domainXMLFromNative */
    remoteDomainXMLToNative, /* domainXMLToNative */
8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412
    remoteListDefinedDomains, /* listDefinedDomains */
    remoteNumOfDefinedDomains, /* numOfDefinedDomains */
    remoteDomainCreate, /* domainCreate */
    remoteDomainDefineXML, /* domainDefineXML */
    remoteDomainUndefine, /* domainUndefine */
    remoteDomainAttachDevice, /* domainAttachDevice */
    remoteDomainDetachDevice, /* domainDetachDevice */
    remoteDomainGetAutostart, /* domainGetAutostart */
    remoteDomainSetAutostart, /* domainSetAutostart */
    remoteDomainGetSchedulerType, /* domainGetSchedulerType */
    remoteDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    remoteDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    remoteDomainMigratePrepare, /* domainMigratePrepare */
    remoteDomainMigratePerform, /* domainMigratePerform */
    remoteDomainMigrateFinish, /* domainMigrateFinish */
    remoteDomainBlockStats, /* domainBlockStats */
    remoteDomainInterfaceStats, /* domainInterfaceStats */
    remoteDomainBlockPeek, /* domainBlockPeek */
    remoteDomainMemoryPeek, /* domainMemoryPeek */
    remoteNodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    remoteNodeGetFreeMemory, /* getFreeMemory */
    remoteDomainEventRegister, /* domainEventRegister */
    remoteDomainEventDeregister, /* domainEventDeregister */
    remoteDomainMigratePrepare2, /* domainMigratePrepare2 */
    remoteDomainMigrateFinish2, /* domainMigrateFinish2 */
    remoteNodeDeviceDettach, /* nodeDeviceDettach */
    remoteNodeDeviceReAttach, /* nodeDeviceReAttach */
    remoteNodeDeviceReset, /* nodeDeviceReset */
8413 8414 8415
};

static virNetworkDriver network_driver = {
8416
    .name = "remote",
8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435
    .open = remoteNetworkOpen,
    .close = remoteNetworkClose,
    .numOfNetworks = remoteNumOfNetworks,
    .listNetworks = remoteListNetworks,
    .numOfDefinedNetworks = remoteNumOfDefinedNetworks,
    .listDefinedNetworks = remoteListDefinedNetworks,
    .networkLookupByUUID = remoteNetworkLookupByUUID,
    .networkLookupByName = remoteNetworkLookupByName,
    .networkCreateXML = remoteNetworkCreateXML,
    .networkDefineXML = remoteNetworkDefineXML,
    .networkUndefine = remoteNetworkUndefine,
    .networkCreate = remoteNetworkCreate,
    .networkDestroy = remoteNetworkDestroy,
    .networkDumpXML = remoteNetworkDumpXML,
    .networkGetBridgeName = remoteNetworkGetBridgeName,
    .networkGetAutostart = remoteNetworkGetAutostart,
    .networkSetAutostart = remoteNetworkSetAutostart,
};

D
Daniel Veillard 已提交
8436 8437 8438 8439 8440 8441
static virInterfaceDriver interface_driver = {
    .name = "remote",
    .open = remoteInterfaceOpen,
    .close = remoteInterfaceClose,
    .numOfInterfaces = remoteNumOfInterfaces,
    .listInterfaces = remoteListInterfaces,
8442 8443
    .numOfDefinedInterfaces = remoteNumOfDefinedInterfaces,
    .listDefinedInterfaces = remoteListDefinedInterfaces,
D
Daniel Veillard 已提交
8444 8445 8446 8447 8448 8449 8450 8451 8452
    .interfaceLookupByName = remoteInterfaceLookupByName,
    .interfaceLookupByMACString = remoteInterfaceLookupByMACString,
    .interfaceGetXMLDesc = remoteInterfaceGetXMLDesc,
    .interfaceDefineXML = remoteInterfaceDefineXML,
    .interfaceUndefine = remoteInterfaceUndefine,
    .interfaceCreate = remoteInterfaceCreate,
    .interfaceDestroy = remoteInterfaceDestroy,
};

8453 8454 8455 8456 8457 8458 8459 8460
static virStorageDriver storage_driver = {
    .name = "remote",
    .open = remoteStorageOpen,
    .close = remoteStorageClose,
    .numOfPools = remoteNumOfStoragePools,
    .listPools = remoteListStoragePools,
    .numOfDefinedPools = remoteNumOfDefinedStoragePools,
    .listDefinedPools = remoteListDefinedStoragePools,
8461
    .findPoolSources = remoteFindStoragePoolSources,
8462
    .poolLookupByName = remoteStoragePoolLookupByName,
8463
    .poolLookupByUUID = remoteStoragePoolLookupByUUID,
8464 8465 8466
    .poolLookupByVolume = remoteStoragePoolLookupByVolume,
    .poolCreateXML = remoteStoragePoolCreateXML,
    .poolDefineXML = remoteStoragePoolDefineXML,
8467
    .poolBuild = remoteStoragePoolBuild,
8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483
    .poolUndefine = remoteStoragePoolUndefine,
    .poolCreate = remoteStoragePoolCreate,
    .poolDestroy = remoteStoragePoolDestroy,
    .poolDelete = remoteStoragePoolDelete,
    .poolRefresh = remoteStoragePoolRefresh,
    .poolGetInfo = remoteStoragePoolGetInfo,
    .poolGetXMLDesc = remoteStoragePoolDumpXML,
    .poolGetAutostart = remoteStoragePoolGetAutostart,
    .poolSetAutostart = remoteStoragePoolSetAutostart,
    .poolNumOfVolumes = remoteStoragePoolNumOfVolumes,
    .poolListVolumes = remoteStoragePoolListVolumes,

    .volLookupByName = remoteStorageVolLookupByName,
    .volLookupByKey = remoteStorageVolLookupByKey,
    .volLookupByPath = remoteStorageVolLookupByPath,
    .volCreateXML = remoteStorageVolCreateXML,
8484
    .volCreateXMLFrom = remoteStorageVolCreateXMLFrom,
8485 8486 8487 8488 8489 8490
    .volDelete = remoteStorageVolDelete,
    .volGetInfo = remoteStorageVolGetInfo,
    .volGetXMLDesc = remoteStorageVolDumpXML,
    .volGetPath = remoteStorageVolGetPath,
};

8491 8492 8493 8494 8495 8496
static virSecretDriver secret_driver = {
    .name = "remote",
    .open = remoteSecretOpen,
    .close = remoteSecretClose,
    .numOfSecrets = remoteSecretNumOfSecrets,
    .listSecrets = remoteSecretListSecrets,
8497
    .lookupByUUID = remoteSecretLookupByUUID,
8498
    .lookupByUsage = remoteSecretLookupByUsage,
8499 8500 8501 8502 8503 8504 8505
    .defineXML = remoteSecretDefineXML,
    .getXMLDesc = remoteSecretGetXMLDesc,
    .setValue = remoteSecretSetValue,
    .getValue = remoteSecretGetValue,
    .undefine = remoteSecretUndefine
};

8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516
static virDeviceMonitor dev_monitor = {
    .name = "remote",
    .open = remoteDevMonOpen,
    .close = remoteDevMonClose,
    .numOfDevices = remoteNodeNumOfDevices,
    .listDevices = remoteNodeListDevices,
    .deviceLookupByName = remoteNodeDeviceLookupByName,
    .deviceDumpXML = remoteNodeDeviceDumpXML,
    .deviceGetParent = remoteNodeDeviceGetParent,
    .deviceNumOfCaps = remoteNodeDeviceNumOfCaps,
    .deviceListCaps = remoteNodeDeviceListCaps,
8517 8518
    .deviceCreateXML = remoteNodeDeviceCreateXML,
    .deviceDestroy = remoteNodeDeviceDestroy
8519 8520 8521
};


A
Atsushi SAKAI 已提交
8522
#ifdef WITH_LIBVIRTD
8523
static virStateDriver state_driver = {
8524
    .initialize = remoteStartup,
8525
};
A
Atsushi SAKAI 已提交
8526
#endif
8527 8528


8529
/** remoteRegister:
8530 8531
 *
 * Register driver with libvirt driver system.
8532 8533
 *
 * Returns -1 on error.
8534 8535 8536 8537
 */
int
remoteRegister (void)
{
8538
    if (virRegisterDriver (&remote_driver) == -1) return -1;
8539
    if (virRegisterNetworkDriver (&network_driver) == -1) return -1;
D
Daniel Veillard 已提交
8540
    if (virRegisterInterfaceDriver (&interface_driver) == -1) return -1;
8541
    if (virRegisterStorageDriver (&storage_driver) == -1) return -1;
8542
    if (virRegisterDeviceMonitor (&dev_monitor) == -1) return -1;
8543
    if (virRegisterSecretDriver (&secret_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
8544
#ifdef WITH_LIBVIRTD
8545
    if (virRegisterStateDriver (&state_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
8546
#endif
8547 8548 8549

    return 0;
}