remote_driver.c 238.6 KB
Newer Older
D
Daniel Veillard 已提交
1

2 3 4 5
/*
 * remote_internal.c: driver to provide access to libvirtd running
 *   on a remote machine
 *
6
 * Copyright (C) 2007-2009 Red Hat, Inc.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * 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>
 */

25
#include <config.h>
26

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

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

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

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

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

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

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

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

72 73
#include <poll.h>

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

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

92 93
#define VIR_FROM_THIS VIR_FROM_REMOTE

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


99 100
static int inside_daemon = 0;

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
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;

    /* 4 byte length, followed by RPC message header+body */
    char buffer[4 + REMOTE_MESSAGE_MAX];
    unsigned int bufferLength;
    unsigned int bufferOffset;

    unsigned int serial;
    unsigned int proc_nr;

    virCond cond;

    xdrproc_t ret_filter;
    char *ret;

    remote_error err;

    struct remote_thread_call *next;
};

132
struct private_data {
133 134
    virMutex lock;

135
    int sock;                   /* Socket. */
136
    int watch;                  /* File handle watch */
137
    pid_t pid;                  /* PID of tunnel process */
138 139 140 141
    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. */
142
    int localUses;              /* Ref count for private data */
143 144
    char *hostname;             /* Original hostname */
    FILE *debugLog;             /* Debug remote protocol */
145

146 147
#if HAVE_SASL
    sasl_conn_t *saslconn;      /* SASL context */
148

149 150 151
    const char *saslDecoded;
    unsigned int saslDecodedLength;
    unsigned int saslDecodedOffset;
152 153 154 155

    const char *saslEncoded;
    unsigned int saslEncodedLength;
    unsigned int saslEncodedOffset;
156
#endif
157 158 159 160 161 162

    /* 4 byte length, followed by RPC message header+body */
    char buffer[4 + REMOTE_MESSAGE_MAX];
    unsigned int bufferLength;
    unsigned int bufferOffset;

163 164 165 166 167 168 169
    /* 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;
170 171
    /* Flag if we're in process of dispatching */
    int domainEventDispatching;
172 173 174 175 176 177 178

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

    /* List of threads currently waiting for dispatch */
    struct remote_thread_call *waitDispatch;
179 180
};

181 182 183 184 185 186
enum {
    REMOTE_CALL_IN_OPEN = 1,
    REMOTE_CALL_QUIET_MISSING_RPC = 2,
};


187 188 189 190 191 192 193 194 195 196
static void remoteDriverLock(struct private_data *driver)
{
    virMutexLock(&driver->lock);
}

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

197 198 199 200
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);
201 202
static int remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
                               virConnectAuthPtr auth, const char *authtype);
203
#if HAVE_SASL
204 205
static int remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                           virConnectAuthPtr auth, const char *mech);
206
#endif
207
#if HAVE_POLKIT
208 209
static int remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                             virConnectAuthPtr auth);
210
#endif /* HAVE_POLKIT */
211 212 213 214 215 216 217
#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)

218 219
static virDomainPtr get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain);
static virNetworkPtr get_nonnull_network (virConnectPtr conn, remote_nonnull_network network);
220
static virInterfacePtr get_nonnull_interface (virConnectPtr conn, remote_nonnull_interface iface);
221 222
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);
223
static virNodeDevicePtr get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev);
224
static virSecretPtr get_nonnull_secret (virConnectPtr conn, remote_nonnull_secret secret);
225 226
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 已提交
227
static void make_nonnull_interface (remote_nonnull_interface *interface_dst, virInterfacePtr interface_src);
228 229
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);
230
static void make_nonnull_secret (remote_nonnull_secret *secret_dst, virSecretPtr secret_src);
231
void remoteDomainEventFired(int watch, int fd, int event, void *data);
232 233
static void remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr);
void remoteDomainEventQueueFlush(int timer, void *opaque);
234 235 236 237 238 239 240
/*----------------------------------------------------------------------*/

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

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

A
Atsushi SAKAI 已提交
243
#ifdef WITH_LIBVIRTD
244
static int
245
remoteStartup(int privileged ATTRIBUTE_UNUSED)
246 247 248 249 250 251 252
{
    /* Mark that we're inside the daemon so we can avoid
     * re-entering ourselves
     */
    inside_daemon = 1;
    return 0;
}
A
Atsushi SAKAI 已提交
253
#endif
254

255
#ifndef WIN32
256 257 258 259
/**
 * remoteFindServerPath:
 *
 * Tries to find the path to the libvirtd binary.
260
 *
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
 * 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.
 */
292
static int
293 294 295
remoteForkDaemon(virConnectPtr conn)
{
    const char *daemonPath = remoteFindDaemonPath();
296
    const char *const daemonargs[] = { daemonPath, "--timeout=30", NULL };
297
    pid_t pid;
298 299

    if (!daemonPath) {
300
        error(conn, VIR_ERR_INTERNAL_ERROR, _("failed to find libvirtd binary"));
301
        return -1;
302 303
    }

304
    if (virExecDaemonize(NULL, daemonargs, NULL, NULL,
305 306
                         &pid, -1, NULL, NULL,
                         VIR_EXEC_CLEAR_CAPS,
307
                         NULL, NULL, NULL) < 0)
308
        return -1;
309

310
    return 0;
311
}
312
#endif
313

314
enum virDrvOpenRemoteFlags {
315
    VIR_DRV_OPEN_REMOTE_RO = (1 << 0),
316 317
    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 */
318
};
319

320

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
/*
 * 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
 */
338
static int
339 340 341 342
doRemoteOpen (virConnectPtr conn,
              struct private_data *priv,
              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
              int flags)
343
{
344
    int wakeupFD[2] = { -1, -1 };
345
    char *transport_str = NULL;
346 347 348 349 350 351 352
    enum {
        trans_tls,
        trans_unix,
        trans_ssh,
        trans_ext,
        trans_tcp,
    } transport;
353

354 355
    /* We handle *ALL*  URIs here. The caller has rejected any
     * URIs we don't care about */
356

357 358 359
    if (conn->uri) {
        if (!conn->uri->scheme) {
            /* This is the ///var/lib/xen/xend-socket local path style */
360
            transport = trans_unix;
361 362
        } else {
            transport_str = get_transport_from_scheme (conn->uri->scheme);
363

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
            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;
391
    }
392

393 394 395
    /* Local variables which we will initialise. These can
     * get freed in the failed: path.
     */
396 397
    char *name = NULL, *command = NULL, *sockname = NULL, *netcat = NULL;
    char *port = NULL, *authtype = NULL, *username = NULL;
398
    int no_verify = 0, no_tty = 0;
399
    char **cmd_argv = NULL;
400

401 402 403
    /* Return code from this function, and the private data. */
    int retcode = VIR_DRV_OPEN_ERROR;

404
    /* Remote server defaults to "localhost" if not specified. */
405
    if (conn->uri && conn->uri->port != 0) {
406
        if (virAsprintf(&port, "%d", conn->uri->port) == -1) goto out_of_memory;
407 408 409 410 411 412 413
    } 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
414
        port = NULL; /* Port not used for unix, ext., default for ssh */
415

416

417 418
    priv->hostname = strdup (conn->uri && conn->uri->server ?
                             conn->uri->server : "localhost");
419 420
    if (!priv->hostname)
        goto out_of_memory;
421 422
    if (conn->uri && conn->uri->user) {
        username = strdup (conn->uri->user);
423 424
        if (!username)
            goto out_of_memory;
425 426
    }

427 428 429 430 431
    /* 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).
     */
432 433 434
    struct qparam_set *vars;
    struct qparam *var;
    int i;
435 436
    char *query;

437
    if (conn->uri) {
438
#ifdef HAVE_XMLURI_QUERY_RAW
439
        query = conn->uri->query_raw;
440
#else
441
        query = conn->uri->query;
442
#endif
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
        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);
        }
484

485 486
        /* Construct the original name. */
        if (!name) {
487 488 489
            if (conn->uri->scheme &&
                (STREQ(conn->uri->scheme, "remote") ||
                 STRPREFIX(conn->uri->scheme, "remote+"))) {
490 491 492 493 494
                /* Allow remote serve to probe */
                name = strdup("");
            } else {
                xmlURI tmpuri = {
                    .scheme = conn->uri->scheme,
495
#ifdef HAVE_XMLURI_QUERY_RAW
496
                    .query_raw = qparam_get_query (vars),
497
#else
498
                    .query = qparam_get_query (vars),
499
#endif
500 501 502 503 504 505 506 507 508
                    .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';
                }
509

510
                name = (char *) xmlSaveUri (&tmpuri);
511

512 513 514 515 516 517 518 519 520 521
#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] = '+';
            }
522 523
        }

524 525 526 527 528
        free_qparam_set (vars);
    } else {
        /* Probe URI server side */
        name = strdup("");
    }
529

530
    if (!name) {
531
        virReportOOMError(conn);
532
        goto failed;
533 534
    }

535
    DEBUG("proceeding with name = %s", name);
536

537 538 539 540 541 542 543
    /* 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;
    }

544 545 546 547
    /* Connect to the remote service. */
    switch (transport) {
    case trans_tls:
        if (initialise_gnutls (conn) == -1) goto failed;
548
        priv->uses_tls = 1;
549 550 551 552 553 554

        /*FALLTHROUGH*/
    case trans_tcp: {
        // http://people.redhat.com/drepper/userapi-ipv6.html
        struct addrinfo *res, *r;
        struct addrinfo hints;
555
        int saved_errno = EINVAL;
556 557 558
        memset (&hints, 0, sizeof hints);
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_ADDRCONFIG;
559
        int e = getaddrinfo (priv->hostname, port, &hints, &res);
560
        if (e != 0) {
561 562 563
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to resolve hostname '%s': %s"),
                    priv->hostname, gai_strerror (e));
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
            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;

581 582
            priv->sock = socket (r->ai_family, SOCK_STREAM, 0);
            if (priv->sock == -1) {
J
Jim Meyering 已提交
583
                saved_errno = errno;
584 585 586 587
                continue;
            }

            /* Disable Nagle - Dan Berrange. */
588
            setsockopt (priv->sock,
589 590 591
                        IPPROTO_TCP, TCP_NODELAY, (void *)&no_slow_start,
                        sizeof no_slow_start);

592
            if (connect (priv->sock, r->ai_addr, r->ai_addrlen) == -1) {
J
Jim Meyering 已提交
593
                saved_errno = errno;
594
                close (priv->sock);
595 596 597
                continue;
            }

598 599
            if (priv->uses_tls) {
                priv->session =
600
                    negotiate_gnutls_on_connection
601
                      (conn, priv, no_verify);
602 603 604
                if (!priv->session) {
                    close (priv->sock);
                    priv->sock = -1;
605 606 607 608 609 610 611
                    continue;
                }
            }
            goto tcp_connected;
        }

        freeaddrinfo (res);
612
        virReportSystemError(conn, saved_errno,
613
                             _("unable to connect to libvirtd at '%s'"),
614
                             priv->hostname);
615 616 617 618 619 620 621 622 623 624
        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;
    }

625
#ifndef WIN32
626 627
    case trans_unix: {
        if (!sockname) {
628
            if (flags & VIR_DRV_OPEN_REMOTE_USER) {
629
                char *userdir = virGetUserDirectory(conn, getuid());
630

631
                if (!userdir)
632
                    goto failed;
633

634 635
                if (virAsprintf(&sockname, "@%s" LIBVIRTD_USER_UNIX_SOCKET, userdir) < 0) {
                    VIR_FREE(userdir);
636
                    goto out_of_memory;
637 638
                }
                VIR_FREE(userdir);
639
            } else {
640
                if (flags & VIR_DRV_OPEN_REMOTE_RO)
641 642 643
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET_RO);
                else
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET);
644 645
                if (sockname == NULL)
                    goto out_of_memory;
646
            }
647 648 649 650 651 652
        }

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

655 656 657
        memset (&addr, 0, sizeof addr);
        addr.sun_family = AF_UNIX;
        strncpy (addr.sun_path, sockname, UNIX_PATH_MAX (addr));
658 659
        if (addr.sun_path[0] == '@')
            addr.sun_path[0] = '\0';
660

661 662 663
      autostart_retry:
        priv->sock = socket (AF_UNIX, SOCK_STREAM, 0);
        if (priv->sock == -1) {
664 665
            virReportSystemError(conn, errno, "%s",
                                 _("unable to create socket"));
666 667
            goto failed;
        }
668 669 670 671 672 673 674 675 676 677
        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 &&
678
                trials < 20) {
679 680
                close(priv->sock);
                priv->sock = -1;
681 682
                if (trials > 0 ||
                    remoteForkDaemon(conn) == 0) {
683
                    trials++;
684
                    usleep(1000 * 100 * trials);
685 686 687
                    goto autostart_retry;
                }
            }
688 689 690
            virReportSystemError(conn, errno,
                                 _("unable to connect to '%s'"),
                                 sockname);
691 692 693 694 695 696 697
            goto failed;
        }

        break;
    }

    case trans_ssh: {
698
        int j, nr_args = 6;
699 700 701

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

704
        command = command ? command : strdup ("ssh");
705 706
        if (command == NULL)
            goto out_of_memory;
707 708

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

713 714
        j = 0;
        cmd_argv[j++] = strdup (command);
715 716 717 718
        if (port) {
            cmd_argv[j++] = strdup ("-p");
            cmd_argv[j++] = strdup (port);
        }
719 720 721 722
        if (username) {
            cmd_argv[j++] = strdup ("-l");
            cmd_argv[j++] = strdup (username);
        }
723 724 725 726 727 728 729
        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");
        }
730
        cmd_argv[j++] = strdup (priv->hostname);
731 732
        cmd_argv[j++] = strdup (netcat ? netcat : "nc");
        cmd_argv[j++] = strdup ("-U");
733 734 735 736
        cmd_argv[j++] = strdup (sockname ? sockname :
                                (flags & VIR_CONNECT_RO
                                 ? LIBVIRTD_PRIV_UNIX_SOCKET_RO
                                 : LIBVIRTD_PRIV_UNIX_SOCKET));
737 738
        cmd_argv[j++] = 0;
        assert (j == nr_args);
739 740 741
        for (j = 0; j < (nr_args-1); j++)
            if (cmd_argv[j] == NULL)
                goto out_of_memory;
742 743 744 745
    }

        /*FALLTHROUGH*/
    case trans_ext: {
746
        pid_t pid;
747 748 749 750 751 752 753
        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) {
754 755
            virReportSystemError(conn, errno, "%s",
                                 _("unable to create socket pair"));
756 757 758
            goto failed;
        }

759
        if (virExec(conn, (const char**)cmd_argv, NULL, NULL,
760 761
                    &pid, sv[1], &(sv[1]), NULL,
                    VIR_EXEC_CLEAR_CAPS) < 0)
762 763 764 765
            goto failed;

        /* Parent continues here. */
        close (sv[1]);
766
        priv->sock = sv[0];
767
        priv->pid = pid;
768
    }
769 770 771 772 773 774 775
#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"));
776
        goto failed;
777 778 779

#endif /* WIN32 */

780 781
    } /* switch (transport) */

782
    if (virSetNonBlock(priv->sock) < 0) {
783 784
        virReportSystemError(conn, errno, "%s",
                             _("unable to make socket non-blocking"));
785 786 787 788
        goto failed;
    }

    if (pipe(wakeupFD) < 0) {
789 790
        virReportSystemError(conn, errno, "%s",
                             _("unable to make pipe"));
791 792 793 794
        goto failed;
    }
    priv->wakeupReadFD = wakeupFD[0];
    priv->wakeupSendFD = wakeupFD[1];
795 796

    /* Try and authenticate with server */
797
    if (remoteAuthenticate(conn, priv, 1, auth, authtype) == -1)
798 799
        goto failed;

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

803
    if (call (conn, priv, REMOTE_CALL_IN_OPEN, REMOTE_PROC_OPEN,
804 805 806 807
              (xdrproc_t) xdr_remote_open_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto failed;

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    /* 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) {
835
            virReportOOMError (conn);
836 837 838 839
            goto failed;
        }
    }

840 841 842 843 844 845 846 847 848 849 850 851
    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 */
852
    if ((priv->watch = virEventAddHandle(priv->sock,
853
                                         VIR_EVENT_HANDLE_READABLE,
854
                                         remoteDomainEventFired,
855
                                         conn, NULL)) < 0) {
856 857 858 859 860 861
        DEBUG0("virEventAddHandle failed: No addHandleImpl defined."
               " continuing without events.");
    } else {

        DEBUG0("Adding Timeout for remote event queue flushing");
        if ( (priv->eventFlushTimer = virEventAddTimeout(-1,
862 863
                                                         remoteDomainEventQueueFlush,
                                                         conn, NULL)) < 0) {
864 865
            DEBUG0("virEventAddTimeout failed: No addTimeoutImpl defined. "
                    "continuing without events.");
866
            virEventRemoveHandle(priv->watch);
867
            priv->watch = -1;
868 869
        }
    }
870 871 872
    /* Successful. */
    retcode = VIR_DRV_OPEN_SUCCESS;

873
 cleanup:
874
    /* Free up the URL and strings. */
875 876 877 878 879 880 881
    VIR_FREE(name);
    VIR_FREE(command);
    VIR_FREE(sockname);
    VIR_FREE(authtype);
    VIR_FREE(netcat);
    VIR_FREE(username);
    VIR_FREE(port);
882 883 884
    if (cmd_argv) {
        char **cmd_argv_ptr = cmd_argv;
        while (*cmd_argv_ptr) {
885
            VIR_FREE(*cmd_argv_ptr);
886 887
            cmd_argv_ptr++;
        }
888
        VIR_FREE(cmd_argv);
889 890 891
    }

    return retcode;
892 893

 out_of_memory:
894
    virReportOOMError (conn);
895 896 897 898 899 900 901 902 903

 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);
904
#ifndef WIN32
905 906 907 908 909 910 911 912
        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);
        }
913
#endif
914 915
    }

916 917 918 919 920
    if (wakeupFD[0] >= 0) {
        close(wakeupFD[0]);
        close(wakeupFD[1]);
    }

921
    VIR_FREE(priv->hostname);
922
    goto cleanup;
923 924
}

925 926
static struct private_data *
remoteAllocPrivateData(virConnectPtr conn)
927
{
928
    struct private_data *priv;
929
    if (VIR_ALLOC(priv) < 0) {
930 931
        virReportOOMError(conn);
        return NULL;
932 933
    }

934 935 936 937
    if (virMutexInit(&priv->lock) < 0) {
        error(conn, VIR_ERR_INTERNAL_ERROR,
              _("cannot initialize mutex"));
        VIR_FREE(priv);
938
        return NULL;
939 940 941
    }
    remoteDriverLock(priv);
    priv->localUses = 1;
942
    priv->watch = -1;
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    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;
982
    const char *autostart = getenv("LIBVIRT_AUTOSTART");
983

984
    if (inside_daemon && (!conn->uri || (conn->uri && !conn->uri->server)))
985 986 987 988
        return VIR_DRV_OPEN_DECLINED;

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

990
    if (flags & VIR_CONNECT_RO)
991 992
        rflags |= VIR_DRV_OPEN_REMOTE_RO;

993 994 995 996 997 998 999 1000 1001
    /*
     * 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 已提交
1002
        conn->uri->scheme &&
1003 1004
        ((strchr(conn->uri->scheme, '+') == 0)||
         (strstr(conn->uri->scheme, "+unix") != NULL)) &&
1005 1006
        (STREQ(conn->uri->path, "/session") ||
         STRPREFIX(conn->uri->scheme, "test+")) &&
1007 1008 1009
        getuid() > 0) {
        DEBUG0("Auto-spawn user daemon instance");
        rflags |= VIR_DRV_OPEN_REMOTE_USER;
1010 1011 1012
        if (!autostart ||
            STRNEQ(autostart, "0"))
            rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
1013 1014 1015
    }

    /*
J
John Levon 已提交
1016 1017 1018 1019
     * 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.
1020 1021 1022
     */
    if (!conn->uri) {
        DEBUG0("Auto-probe remote URI");
J
John Levon 已提交
1023
#ifndef __sun
1024 1025 1026
        if (getuid() > 0) {
            DEBUG0("Auto-spawn user daemon instance");
            rflags |= VIR_DRV_OPEN_REMOTE_USER;
1027 1028 1029
            if (!autostart ||
                STRNEQ(autostart, "0"))
                rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
1030
        }
J
John Levon 已提交
1031
#endif
1032
    }
1033

1034
    ret = doRemoteOpen(conn, priv, auth, rflags);
1035 1036
    if (ret != VIR_DRV_OPEN_SUCCESS) {
        conn->privateData = NULL;
1037
        remoteDriverUnlock(priv);
1038
        VIR_FREE(priv);
1039 1040
    } else {
        conn->privateData = priv;
1041
        remoteDriverUnlock(priv);
1042 1043 1044 1045 1046
    }
    return ret;
}


1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
/* 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;

1058 1059

static int
1060
check_cert_file (virConnectPtr conn, const char *type, const char *file)
1061 1062 1063
{
    struct stat sb;
    if (stat(file, &sb) < 0) {
1064 1065 1066
        virReportSystemError(conn, errno,
                             _("Cannot access %s '%s'"),
                             type, file);
1067 1068 1069 1070 1071 1072
        return -1;
    }
    return 0;
}


1073
static int
1074
initialise_gnutls (virConnectPtr conn)
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
{
    static int initialised = 0;
    int err;

    if (initialised) return 0;

    gnutls_global_init ();

    /* X509 stuff */
    err = gnutls_certificate_allocate_credentials (&x509_cred);
    if (err) {
1086 1087 1088
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to allocate TLS credentials: %s"),
                gnutls_strerror (err));
1089 1090 1091
        return -1;
    }

1092

1093
    if (check_cert_file(conn, "CA certificate", LIBVIRT_CACERT) < 0)
1094
        return -1;
1095
    if (check_cert_file(conn, "client key", LIBVIRT_CLIENTKEY) < 0)
1096
        return -1;
1097
    if (check_cert_file(conn, "client certificate", LIBVIRT_CLIENTCERT) < 0)
1098 1099
        return -1;

1100
    /* Set the trusted CA cert. */
1101
    DEBUG("loading CA file %s", LIBVIRT_CACERT);
1102 1103 1104 1105
    err =
        gnutls_certificate_set_x509_trust_file (x509_cred, LIBVIRT_CACERT,
                                                GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1106 1107 1108
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load CA certificate: %s"),
                gnutls_strerror (err));
1109 1110 1111 1112
        return -1;
    }

    /* Set the client certificate and private key. */
1113 1114
    DEBUG("loading client cert and key from files %s and %s",
          LIBVIRT_CLIENTCERT, LIBVIRT_CLIENTKEY);
1115 1116 1117 1118 1119 1120
    err =
        gnutls_certificate_set_x509_key_file (x509_cred,
                                              LIBVIRT_CLIENTCERT,
                                              LIBVIRT_CLIENTKEY,
                                              GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1121 1122 1123
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load private key/certificate: %s"),
                gnutls_strerror (err));
1124 1125 1126 1127 1128 1129 1130
        return -1;
    }

    initialised = 1;
    return 0;
}

1131
static int verify_certificate (virConnectPtr conn, struct private_data *priv, gnutls_session_t session);
1132 1133 1134

static gnutls_session_t
negotiate_gnutls_on_connection (virConnectPtr conn,
1135 1136
                                struct private_data *priv,
                                int no_verify)
1137 1138 1139 1140 1141 1142 1143 1144 1145
{
    const int cert_type_priority[3] = {
        GNUTLS_CRT_X509,
        GNUTLS_CRT_OPENPGP,
        0
    };
    int err;
    gnutls_session_t session;

1146
    /* Initialize TLS session
1147 1148 1149
     */
    err = gnutls_init (&session, GNUTLS_CLIENT);
    if (err) {
1150 1151 1152
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to initialize TLS client: %s"),
                gnutls_strerror (err));
1153 1154 1155 1156 1157 1158
        return NULL;
    }

    /* Use default priorities */
    err = gnutls_set_default_priority (session);
    if (err) {
1159 1160 1161
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set TLS algorithm priority: %s"),
                gnutls_strerror (err));
1162 1163 1164 1165 1166 1167
        return NULL;
    }
    err =
        gnutls_certificate_type_set_priority (session,
                                              cert_type_priority);
    if (err) {
1168 1169 1170
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set certificate priority: %s"),
                gnutls_strerror (err));
1171 1172 1173 1174 1175 1176 1177
        return NULL;
    }

    /* put the x509 credentials to the current session
     */
    err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
    if (err) {
1178 1179 1180
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set session credentials: %s"),
                gnutls_strerror (err));
1181 1182 1183 1184
        return NULL;
    }

    gnutls_transport_set_ptr (session,
1185
                              (gnutls_transport_ptr_t) (long) priv->sock);
1186 1187 1188 1189 1190 1191 1192

    /* Perform the TLS handshake. */
 again:
    err = gnutls_handshake (session);
    if (err < 0) {
        if (err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
            goto again;
1193 1194 1195
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS handshake: %s"),
                gnutls_strerror (err));
1196 1197 1198 1199
        return NULL;
    }

    /* Verify certificate. */
1200
    if (verify_certificate (conn, priv, session) == -1) {
1201 1202 1203
        DEBUG0("failed to verify peer's certificate");
        if (!no_verify) return NULL;
    }
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

    /* 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;
1215 1216 1217
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS initialization: %s"),
                gnutls_strerror (len));
1218 1219 1220
        return NULL;
    }
    if (len != 1 || buf[0] != '\1') {
1221
        error (conn, VIR_ERR_RPC,
1222
               _("server verification (of our certificate or IP address) failed\n"));
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
        return NULL;
    }

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

    return session;
}

static int
verify_certificate (virConnectPtr conn ATTRIBUTE_UNUSED,
1236 1237
                    struct private_data *priv,
                    gnutls_session_t session)
1238 1239 1240 1241 1242 1243 1244 1245
{
    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) {
1246 1247 1248
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to verify server certificate: %s"),
                gnutls_strerror (ret));
1249 1250
        return -1;
    }
1251

1252
    if ((now = time(NULL)) == ((time_t)-1)) {
1253 1254
        virReportSystemError(conn, errno, "%s",
                             _("cannot get current time"));
1255 1256 1257 1258
        return -1;
    }

    if (status != 0) {
1259
        const char *reason = _("Invalid certificate");
1260 1261

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

1264
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1265
            reason = _("The certificate hasn't got a known issuer.");
1266

1267
        if (status & GNUTLS_CERT_REVOKED)
1268
            reason = _("The certificate has been revoked.");
1269 1270

#ifndef GNUTLS_1_0_COMPAT
1271
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1272
            reason = _("The certificate uses an insecure algorithm");
1273
#endif
1274

1275 1276 1277
        errorf (conn, VIR_ERR_RPC,
                _("server certificate failed validation: %s"),
                reason);
1278 1279 1280 1281
        return -1;
    }

    if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) {
1282
        error (conn, VIR_ERR_RPC, _("Certificate type is not X.509"));
1283 1284
        return -1;
    }
1285

1286
    if (!(certs = gnutls_certificate_get_peers(session, &nCerts))) {
1287
        error (conn, VIR_ERR_RPC, _("gnutls_certificate_get_peers failed"));
1288 1289
        return -1;
    }
1290

1291 1292 1293 1294 1295
    for (i = 0 ; i < nCerts ; i++) {
        gnutls_x509_crt_t cert;

        ret = gnutls_x509_crt_init (&cert);
        if (ret < 0) {
1296 1297 1298
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to initialize certificate: %s"),
                    gnutls_strerror (ret));
1299 1300
            return -1;
        }
1301

1302 1303
        ret = gnutls_x509_crt_import (cert, &certs[i], GNUTLS_X509_FMT_DER);
        if (ret < 0) {
1304 1305 1306
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to import certificate: %s"),
                    gnutls_strerror (ret));
1307 1308 1309
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1310

1311
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1312
            error (conn, VIR_ERR_RPC, _("The certificate has expired"));
1313 1314 1315
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1316

1317
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1318
            error (conn, VIR_ERR_RPC, _("The certificate is not yet activated"));
1319 1320 1321
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1322

1323
        if (i == 0) {
1324
            if (!gnutls_x509_crt_check_hostname (cert, priv->hostname)) {
1325 1326 1327
                errorf(conn, VIR_ERR_RPC,
                       _("Certificate's owner does not match the hostname (%s)"),
                       priv->hostname);
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
                gnutls_x509_crt_deinit (cert);
                return -1;
            }
        }
    }

    return 0;
}

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

1339

1340
static int
1341
doRemoteClose (virConnectPtr conn, struct private_data *priv)
1342 1343 1344 1345 1346 1347
{
    if (call (conn, priv, 0, REMOTE_PROC_CLOSE,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        return -1;

1348 1349 1350 1351 1352
    if (priv->eventFlushTimer >= 0) {
        /* Remove timeout */
        virEventRemoveTimeout(priv->eventFlushTimer);
        /* Remove handle for remote events */
        virEventRemoveHandle(priv->watch);
1353
        priv->watch = -1;
1354
    }
1355

1356
    /* Close socket. */
1357
    if (priv->uses_tls && priv->session) {
1358
        gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
1359 1360 1361 1362 1363 1364
        gnutls_deinit (priv->session);
    }
#if HAVE_SASL
    if (priv->saslconn)
        sasl_dispose (&priv->saslconn);
#endif
1365 1366
    close (priv->sock);

1367
#ifndef WIN32
1368 1369 1370 1371 1372 1373 1374 1375
    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);
    }
1376
#endif
1377 1378 1379 1380 1381
    if (priv->wakeupReadFD >= 0) {
        close(priv->wakeupReadFD);
        close(priv->wakeupSendFD);
    }

1382

1383
    /* Free hostname copy */
1384
    free (priv->hostname);
1385

1386
    /* See comment for remoteType. */
1387
    free (priv->type);
1388

1389 1390 1391 1392 1393 1394
    /* Free callback list */
    virDomainEventCallbackListFree(priv->callbackList);

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

1395 1396 1397
    return 0;
}

1398 1399 1400
static int
remoteClose (virConnectPtr conn)
{
1401
    int ret = 0;
1402
    struct private_data *priv = conn->privateData;
1403

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
    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);
1415 1416 1417 1418

    return ret;
}

1419 1420 1421
static int
remoteSupportsFeature (virConnectPtr conn, int feature)
{
1422
    int rv = -1;
1423 1424
    remote_supports_feature_args args;
    remote_supports_feature_ret ret;
1425
    struct private_data *priv = conn->privateData;
1426

1427 1428
    remoteDriverLock(priv);

1429
    /* VIR_DRV_FEATURE_REMOTE* features are handled directly. */
1430 1431 1432 1433
    if (feature == VIR_DRV_FEATURE_REMOTE) {
        rv = 1;
        goto done;
    }
1434 1435 1436 1437 1438 1439 1440

    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)
1441 1442 1443
        goto done;

    rv = ret.supported;
1444

1445
done:
1446
    remoteDriverUnlock(priv);
1447
    return rv;
1448 1449
}

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
/* 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)
{
1461
    char *rv = NULL;
1462
    remote_get_type_ret ret;
1463
    struct private_data *priv = conn->privateData;
1464

1465 1466
    remoteDriverLock(priv);

1467
    /* Cached? */
1468 1469 1470 1471
    if (priv->type) {
        rv = priv->type;
        goto done;
    }
1472 1473 1474 1475 1476

    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)
1477
        goto done;
1478 1479

    /* Stash. */
1480 1481 1482
    rv = priv->type = ret.type;

done:
1483
    remoteDriverUnlock(priv);
1484
    return rv;
1485 1486 1487
}

static int
1488
remoteGetVersion (virConnectPtr conn, unsigned long *hvVer)
1489
{
1490
    int rv = -1;
1491
    remote_get_version_ret ret;
1492
    struct private_data *priv = conn->privateData;
1493

1494 1495
    remoteDriverLock(priv);

1496 1497 1498 1499
    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)
1500
        goto done;
1501 1502

    if (hvVer) *hvVer = ret.hv_ver;
1503 1504 1505
    rv = 0;

done:
1506
    remoteDriverUnlock(priv);
1507
    return rv;
1508 1509
}

1510 1511 1512
static char *
remoteGetHostname (virConnectPtr conn)
{
1513
    char *rv = NULL;
1514
    remote_get_hostname_ret ret;
1515
    struct private_data *priv = conn->privateData;
1516

1517 1518
    remoteDriverLock(priv);

1519 1520 1521 1522
    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)
1523
        goto done;
1524 1525

    /* Caller frees this. */
1526 1527 1528
    rv = ret.hostname;

done:
1529
    remoteDriverUnlock(priv);
1530
    return rv;
1531 1532
}

1533 1534 1535
static int
remoteGetMaxVcpus (virConnectPtr conn, const char *type)
{
1536
    int rv = -1;
1537 1538
    remote_get_max_vcpus_args args;
    remote_get_max_vcpus_ret ret;
1539
    struct private_data *priv = conn->privateData;
1540

1541 1542
    remoteDriverLock(priv);

1543
    memset (&ret, 0, sizeof ret);
1544
    args.type = type == NULL ? NULL : (char **) &type;
1545 1546 1547
    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)
1548 1549 1550
        goto done;

    rv = ret.max_vcpus;
1551

1552
done:
1553
    remoteDriverUnlock(priv);
1554
    return rv;
1555 1556 1557 1558 1559
}

static int
remoteNodeGetInfo (virConnectPtr conn, virNodeInfoPtr info)
{
1560
    int rv = -1;
1561
    remote_node_get_info_ret ret;
1562
    struct private_data *priv = conn->privateData;
1563

1564 1565
    remoteDriverLock(priv);

1566 1567 1568 1569
    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)
1570
        goto done;
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580

    strncpy (info->model, ret.model, 32);
    info->model[31] = '\0';
    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;
1581 1582 1583
    rv = 0;

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

static char *
remoteGetCapabilities (virConnectPtr conn)
{
1591
    char *rv = NULL;
1592
    remote_get_capabilities_ret ret;
1593
    struct private_data *priv = conn->privateData;
1594

1595 1596
    remoteDriverLock(priv);

1597 1598 1599 1600
    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)
1601
        goto done;
1602 1603

    /* Caller frees this. */
1604 1605 1606
    rv = ret.capabilities;

done:
1607
    remoteDriverUnlock(priv);
1608
    return rv;
1609 1610
}

1611 1612 1613 1614 1615 1616
static int
remoteNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
1617
    int rv = -1;
1618 1619 1620
    remote_node_get_cells_free_memory_args args;
    remote_node_get_cells_free_memory_ret ret;
    int i;
1621
    struct private_data *priv = conn->privateData;
1622

1623 1624
    remoteDriverLock(priv);

1625 1626 1627 1628 1629
    if (maxCells > REMOTE_NODE_MAX_CELLS) {
        errorf (conn, VIR_ERR_RPC,
                _("too many NUMA cells: %d > %d"),
                maxCells,
                REMOTE_NODE_MAX_CELLS);
1630
        goto done;
1631 1632 1633 1634 1635 1636 1637 1638 1639
    }

    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)
1640
        goto done;
1641 1642 1643 1644 1645 1646

    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);

1647 1648 1649
    rv = ret.freeMems.freeMems_len;

done:
1650
    remoteDriverUnlock(priv);
1651
    return rv;
1652 1653 1654 1655 1656
}

static unsigned long long
remoteNodeGetFreeMemory (virConnectPtr conn)
{
1657
    unsigned long long rv = 0; /* 0 is error value this special function*/
1658
    remote_node_get_free_memory_ret ret;
1659
    struct private_data *priv = conn->privateData;
1660

1661 1662
    remoteDriverLock(priv);

1663 1664 1665 1666
    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)
1667 1668 1669
        goto done;

    rv = ret.freeMem;
1670

1671
done:
1672
    remoteDriverUnlock(priv);
1673
    return rv;
1674 1675 1676
}


1677 1678 1679
static int
remoteListDomains (virConnectPtr conn, int *ids, int maxids)
{
1680
    int rv = -1;
1681 1682 1683
    int i;
    remote_list_domains_args args;
    remote_list_domains_ret ret;
1684
    struct private_data *priv = conn->privateData;
1685

1686 1687
    remoteDriverLock(priv);

1688
    if (maxids > REMOTE_DOMAIN_ID_LIST_MAX) {
1689 1690 1691
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                maxids, REMOTE_DOMAIN_ID_LIST_MAX);
1692
        goto done;
1693 1694 1695 1696 1697 1698 1699
    }
    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)
1700
        goto done;
1701 1702

    if (ret.ids.ids_len > maxids) {
1703 1704 1705
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                ret.ids.ids_len, maxids);
1706
        goto cleanup;
1707 1708 1709 1710 1711
    }

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

1712 1713 1714
    rv = ret.ids.ids_len;

cleanup:
1715 1716
    xdr_free ((xdrproc_t) xdr_remote_list_domains_ret, (char *) &ret);

1717
done:
1718
    remoteDriverUnlock(priv);
1719
    return rv;
1720 1721 1722 1723 1724
}

static int
remoteNumOfDomains (virConnectPtr conn)
{
1725
    int rv = -1;
1726
    remote_num_of_domains_ret ret;
1727
    struct private_data *priv = conn->privateData;
1728

1729 1730
    remoteDriverLock(priv);

1731 1732 1733 1734
    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)
1735 1736 1737
        goto done;

    rv = ret.num;
1738

1739
done:
1740
    remoteDriverUnlock(priv);
1741
    return rv;
1742 1743 1744
}

static virDomainPtr
1745
remoteDomainCreateXML (virConnectPtr conn,
1746 1747 1748
                         const char *xmlDesc,
                         unsigned int flags)
{
1749
    virDomainPtr dom = NULL;
1750 1751
    remote_domain_create_xml_args args;
    remote_domain_create_xml_ret ret;
1752
    struct private_data *priv = conn->privateData;
1753

1754 1755
    remoteDriverLock(priv);

1756 1757 1758 1759
    args.xml_desc = (char *) xmlDesc;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
1760 1761 1762
    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)
1763
        goto done;
1764 1765

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

1768
done:
1769
    remoteDriverUnlock(priv);
1770 1771 1772 1773 1774 1775
    return dom;
}

static virDomainPtr
remoteDomainLookupByID (virConnectPtr conn, int id)
{
1776
    virDomainPtr dom = NULL;
1777 1778
    remote_domain_lookup_by_id_args args;
    remote_domain_lookup_by_id_ret ret;
1779
    struct private_data *priv = conn->privateData;
1780

1781 1782
    remoteDriverLock(priv);

1783 1784 1785 1786 1787 1788
    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)
1789
        goto done;
1790 1791 1792 1793

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

1794
done:
1795
    remoteDriverUnlock(priv);
1796 1797 1798 1799 1800 1801
    return dom;
}

static virDomainPtr
remoteDomainLookupByUUID (virConnectPtr conn, const unsigned char *uuid)
{
1802
    virDomainPtr dom = NULL;
1803 1804
    remote_domain_lookup_by_uuid_args args;
    remote_domain_lookup_by_uuid_ret ret;
1805
    struct private_data *priv = conn->privateData;
1806

1807 1808
    remoteDriverLock(priv);

1809 1810 1811 1812 1813 1814
    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)
1815
        goto done;
1816 1817 1818

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

done:
1821
    remoteDriverUnlock(priv);
1822 1823 1824 1825 1826 1827
    return dom;
}

static virDomainPtr
remoteDomainLookupByName (virConnectPtr conn, const char *name)
{
1828
    virDomainPtr dom = NULL;
1829 1830
    remote_domain_lookup_by_name_args args;
    remote_domain_lookup_by_name_ret ret;
1831
    struct private_data *priv = conn->privateData;
1832

1833 1834
    remoteDriverLock(priv);

1835 1836 1837 1838 1839 1840
    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)
1841
        goto done;
1842 1843 1844 1845

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

1846
done:
1847
    remoteDriverUnlock(priv);
1848 1849 1850 1851 1852 1853
    return dom;
}

static int
remoteDomainSuspend (virDomainPtr domain)
{
1854
    int rv = -1;
1855
    remote_domain_suspend_args args;
1856
    struct private_data *priv = domain->conn->privateData;
1857

1858 1859
    remoteDriverLock(priv);

1860 1861 1862 1863 1864
    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)
1865
        goto done;
1866

1867 1868 1869
    rv = 0;

done:
1870
    remoteDriverUnlock(priv);
1871
    return rv;
1872 1873 1874 1875 1876
}

static int
remoteDomainResume (virDomainPtr domain)
{
1877
    int rv = -1;
1878
    remote_domain_resume_args args;
1879
    struct private_data *priv = domain->conn->privateData;
1880

1881 1882
    remoteDriverLock(priv);

1883 1884 1885 1886 1887
    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)
1888
        goto done;
1889

1890 1891 1892
    rv = 0;

done:
1893
    remoteDriverUnlock(priv);
1894
    return rv;
1895 1896 1897 1898 1899
}

static int
remoteDomainShutdown (virDomainPtr domain)
{
1900
    int rv = -1;
1901
    remote_domain_shutdown_args args;
1902
    struct private_data *priv = domain->conn->privateData;
1903

1904 1905
    remoteDriverLock(priv);

1906 1907 1908 1909 1910
    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)
1911
        goto done;
1912

1913 1914 1915
    rv = 0;

done:
1916
    remoteDriverUnlock(priv);
1917
    return rv;
1918 1919 1920 1921 1922
}

static int
remoteDomainReboot (virDomainPtr domain, unsigned int flags)
{
1923
    int rv = -1;
1924
    remote_domain_reboot_args args;
1925
    struct private_data *priv = domain->conn->privateData;
1926

1927 1928
    remoteDriverLock(priv);

1929 1930 1931 1932 1933 1934
    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)
1935
        goto done;
1936

1937 1938 1939
    rv = 0;

done:
1940
    remoteDriverUnlock(priv);
1941
    return rv;
1942 1943 1944 1945 1946
}

static int
remoteDomainDestroy (virDomainPtr domain)
{
1947
    int rv = -1;
1948
    remote_domain_destroy_args args;
1949
    struct private_data *priv = domain->conn->privateData;
1950

1951 1952
    remoteDriverLock(priv);

1953 1954 1955 1956 1957
    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)
1958
        goto done;
1959

1960
    rv = 0;
1961
    domain->id = -1;
1962 1963

done:
1964
    remoteDriverUnlock(priv);
1965
    return rv;
1966 1967 1968 1969 1970
}

static char *
remoteDomainGetOSType (virDomainPtr domain)
{
1971
    char *rv = NULL;
1972 1973
    remote_domain_get_os_type_args args;
    remote_domain_get_os_type_ret ret;
1974
    struct private_data *priv = domain->conn->privateData;
1975

1976 1977
    remoteDriverLock(priv);

1978 1979 1980 1981 1982 1983
    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)
1984
        goto done;
1985 1986

    /* Caller frees. */
1987 1988 1989
    rv = ret.type;

done:
1990
    remoteDriverUnlock(priv);
1991
    return rv;
1992 1993 1994 1995 1996
}

static unsigned long
remoteDomainGetMaxMemory (virDomainPtr domain)
{
1997
    unsigned long rv = 0;
1998 1999
    remote_domain_get_max_memory_args args;
    remote_domain_get_max_memory_ret ret;
2000
    struct private_data *priv = domain->conn->privateData;
2001

2002 2003
    remoteDriverLock(priv);

2004 2005 2006 2007 2008 2009
    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)
2010 2011 2012
        goto done;

    rv = ret.memory;
2013

2014
done:
2015
    remoteDriverUnlock(priv);
2016
    return rv;
2017 2018 2019 2020 2021
}

static int
remoteDomainSetMaxMemory (virDomainPtr domain, unsigned long memory)
{
2022
    int rv = -1;
2023
    remote_domain_set_max_memory_args args;
2024
    struct private_data *priv = domain->conn->privateData;
2025

2026 2027
    remoteDriverLock(priv);

2028 2029 2030 2031 2032 2033
    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)
2034
        goto done;
2035

2036 2037 2038
    rv = 0;

done:
2039
    remoteDriverUnlock(priv);
2040
    return rv;
2041 2042 2043 2044 2045
}

static int
remoteDomainSetMemory (virDomainPtr domain, unsigned long memory)
{
2046
    int rv = -1;
2047
    remote_domain_set_memory_args args;
2048
    struct private_data *priv = domain->conn->privateData;
2049

2050 2051
    remoteDriverLock(priv);

2052 2053 2054 2055 2056 2057
    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)
2058
        goto done;
2059

2060 2061 2062
    rv = 0;

done:
2063
    remoteDriverUnlock(priv);
2064
    return rv;
2065 2066 2067 2068 2069
}

static int
remoteDomainGetInfo (virDomainPtr domain, virDomainInfoPtr info)
{
2070
    int rv = -1;
2071 2072
    remote_domain_get_info_args args;
    remote_domain_get_info_ret ret;
2073
    struct private_data *priv = domain->conn->privateData;
2074

2075 2076
    remoteDriverLock(priv);

2077 2078 2079 2080 2081 2082
    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)
2083
        goto done;
2084 2085 2086 2087 2088 2089

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

2091 2092 2093
    rv = 0;

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

static int
remoteDomainSave (virDomainPtr domain, const char *to)
{
2101
    int rv = -1;
2102
    remote_domain_save_args args;
2103
    struct private_data *priv = domain->conn->privateData;
2104

2105 2106
    remoteDriverLock(priv);

2107 2108 2109 2110 2111 2112
    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)
2113
        goto done;
2114

2115 2116 2117
    rv = 0;

done:
2118
    remoteDriverUnlock(priv);
2119
    return rv;
2120 2121 2122 2123 2124
}

static int
remoteDomainRestore (virConnectPtr conn, const char *from)
{
2125
    int rv = -1;
2126
    remote_domain_restore_args args;
2127
    struct private_data *priv = conn->privateData;
2128

2129 2130
    remoteDriverLock(priv);

2131 2132 2133 2134 2135
    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)
2136
        goto done;
2137

2138 2139 2140
    rv = 0;

done:
2141
    remoteDriverUnlock(priv);
2142
    return rv;
2143 2144 2145 2146 2147
}

static int
remoteDomainCoreDump (virDomainPtr domain, const char *to, int flags)
{
2148
    int rv = -1;
2149
    remote_domain_core_dump_args args;
2150
    struct private_data *priv = domain->conn->privateData;
2151

2152 2153
    remoteDriverLock(priv);

2154 2155 2156 2157 2158 2159 2160
    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)
2161
        goto done;
2162

2163 2164 2165
    rv = 0;

done:
2166
    remoteDriverUnlock(priv);
2167
    return rv;
2168 2169 2170 2171 2172
}

static int
remoteDomainSetVcpus (virDomainPtr domain, unsigned int nvcpus)
{
2173
    int rv = -1;
2174
    remote_domain_set_vcpus_args args;
2175
    struct private_data *priv = domain->conn->privateData;
2176

2177 2178
    remoteDriverLock(priv);

2179 2180 2181 2182 2183 2184
    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)
2185
        goto done;
2186

2187 2188 2189
    rv = 0;

done:
2190
    remoteDriverUnlock(priv);
2191
    return rv;
2192 2193 2194 2195 2196 2197 2198 2199
}

static int
remoteDomainPinVcpu (virDomainPtr domain,
                     unsigned int vcpu,
                     unsigned char *cpumap,
                     int maplen)
{
2200
    int rv = -1;
2201
    remote_domain_pin_vcpu_args args;
2202
    struct private_data *priv = domain->conn->privateData;
2203

2204 2205
    remoteDriverLock(priv);

2206
    if (maplen > REMOTE_CPUMAP_MAX) {
2207 2208 2209
        errorf (domain->conn, VIR_ERR_RPC,
                _("map length greater than maximum: %d > %d"),
                maplen, REMOTE_CPUMAP_MAX);
2210
        goto done;
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
    }

    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)
2221
        goto done;
2222

2223 2224 2225
    rv = 0;

done:
2226
    remoteDriverUnlock(priv);
2227
    return rv;
2228 2229 2230 2231 2232 2233 2234 2235 2236
}

static int
remoteDomainGetVcpus (virDomainPtr domain,
                      virVcpuInfoPtr info,
                      int maxinfo,
                      unsigned char *cpumaps,
                      int maplen)
{
2237
    int rv = -1;
2238 2239 2240
    int i;
    remote_domain_get_vcpus_args args;
    remote_domain_get_vcpus_ret ret;
2241
    struct private_data *priv = domain->conn->privateData;
2242

2243 2244
    remoteDriverLock(priv);

2245
    if (maxinfo > REMOTE_VCPUINFO_MAX) {
2246 2247 2248
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU count exceeds maximum: %d > %d"),
                maxinfo, REMOTE_VCPUINFO_MAX);
2249
        goto done;
2250
    }
2251
    if (maxinfo * maplen > REMOTE_CPUMAPS_MAX) {
2252 2253 2254
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU map buffer length exceeds maximum: %d > %d"),
                maxinfo * maplen, REMOTE_CPUMAPS_MAX);
2255
        goto done;
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
    }

    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)
2266
        goto done;
2267 2268

    if (ret.info.info_len > maxinfo) {
2269 2270 2271
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports too many vCPUs: %d > %d"),
                ret.info.info_len, maxinfo);
2272
        goto cleanup;
2273
    }
2274
    if (ret.cpumaps.cpumaps_len > maxinfo * maplen) {
2275 2276 2277
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports map buffer length exceeds maximum: %d > %d"),
                ret.cpumaps.cpumaps_len, maxinfo * maplen);
2278
        goto cleanup;
2279 2280
    }

2281 2282 2283
    memset (info, 0, sizeof (virVcpuInfo) * maxinfo);
    memset (cpumaps, 0, maxinfo * maplen);

2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
    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];

2294 2295 2296
    rv = ret.info.info_len;

cleanup:
2297
    xdr_free ((xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret);
2298 2299

done:
2300
    remoteDriverUnlock(priv);
2301
    return rv;
2302 2303 2304 2305 2306
}

static int
remoteDomainGetMaxVcpus (virDomainPtr domain)
{
2307
    int rv = -1;
2308 2309
    remote_domain_get_max_vcpus_args args;
    remote_domain_get_max_vcpus_ret ret;
2310
    struct private_data *priv = domain->conn->privateData;
2311

2312 2313
    remoteDriverLock(priv);

2314 2315 2316
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
2317
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_MAX_VCPUS,
2318 2319
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_ret, (char *) &ret) == -1)
2320
        goto done;
2321

2322 2323 2324
    rv = ret.num;

done:
2325
    remoteDriverUnlock(priv);
2326
    return rv;
2327 2328
}

2329 2330 2331 2332 2333 2334
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;
2335 2336 2337
    int rv = -1;

    remoteDriverLock(priv);
2338 2339 2340

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

2343 2344 2345
    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) {
2346
        goto done;
2347 2348 2349 2350 2351 2352
    }

    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);
2353
            goto done;
2354 2355 2356 2357 2358
        }
        strcpy (seclabel->label, ret.label.label_val);
        seclabel->enforcing = ret.enforcing;
    }

2359 2360 2361 2362 2363
    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
2364 2365 2366 2367 2368 2369 2370
}

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

    remoteDriverLock(priv);
2374 2375

    memset (&ret, 0, sizeof ret);
2376 2377
    memset (secmodel, 0, sizeof (*secmodel));

2378 2379 2380
    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) {
2381
        goto done;
2382 2383 2384 2385 2386 2387
    }

    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);
2388
            goto done;
2389 2390 2391 2392 2393 2394 2395 2396
        }
        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);
2397
            goto done;
2398 2399 2400
        }
        strcpy (secmodel->doi, ret.doi.doi_val);
    }
2401 2402 2403 2404 2405 2406

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
2407 2408
}

2409 2410 2411
static char *
remoteDomainDumpXML (virDomainPtr domain, int flags)
{
2412
    char *rv = NULL;
2413 2414
    remote_domain_dump_xml_args args;
    remote_domain_dump_xml_ret ret;
2415
    struct private_data *priv = domain->conn->privateData;
2416

2417 2418
    remoteDriverLock(priv);

2419 2420 2421 2422 2423 2424 2425
    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)
2426
        goto done;
2427 2428

    /* Caller frees. */
2429 2430 2431
    rv = ret.xml;

done:
2432
    remoteDriverUnlock(priv);
2433
    return rv;
2434 2435
}

2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 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
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;
}

2498 2499 2500 2501 2502 2503 2504
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)
{
2505
    int rv = -1;
2506 2507
    remote_domain_migrate_prepare_args args;
    remote_domain_migrate_prepare_ret ret;
2508
    struct private_data *priv = dconn->privateData;
2509

2510 2511
    remoteDriverLock(priv);

2512 2513 2514 2515 2516 2517 2518 2519 2520
    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)
2521
        goto done;
2522 2523 2524 2525 2526 2527 2528 2529

    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. */

2530 2531 2532
    rv = 0;

done:
2533
    remoteDriverUnlock(priv);
2534
    return rv;
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
}

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

2550 2551
    remoteDriverLock(priv);

2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
    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)
2563
        goto done;
2564

2565 2566 2567
    rv = 0;

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

static virDomainPtr
remoteDomainMigrateFinish (virConnectPtr dconn,
                           const char *dname,
                           const char *cookie,
                           int cookielen,
                           const char *uri,
                           unsigned long flags)
{
2580
    virDomainPtr ddom = NULL;
2581 2582
    remote_domain_migrate_finish_args args;
    remote_domain_migrate_finish_ret ret;
2583
    struct private_data *priv = dconn->privateData;
2584

2585 2586
    remoteDriverLock(priv);

2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
    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)
2597
        goto done;
2598 2599 2600 2601

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

2602
done:
2603
    remoteDriverUnlock(priv);
2604 2605 2606
    return ddom;
}

D
Daniel Veillard 已提交
2607 2608 2609 2610 2611 2612 2613 2614
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)
{
2615
    int rv = -1;
D
Daniel Veillard 已提交
2616 2617
    remote_domain_migrate_prepare2_args args;
    remote_domain_migrate_prepare2_ret ret;
2618
    struct private_data *priv = dconn->privateData;
D
Daniel Veillard 已提交
2619

2620 2621
    remoteDriverLock(priv);

D
Daniel Veillard 已提交
2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
    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)
2632
        goto done;
D
Daniel Veillard 已提交
2633 2634 2635 2636 2637 2638 2639 2640

    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. */

2641 2642 2643
    rv = 0;

done:
2644
    remoteDriverUnlock(priv);
2645
    return rv;
D
Daniel Veillard 已提交
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656
}

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

2662 2663
    remoteDriverLock(priv);

D
Daniel Veillard 已提交
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
    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)
2675
        goto done;
D
Daniel Veillard 已提交
2676 2677 2678 2679

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

2680
done:
2681
    remoteDriverUnlock(priv);
D
Daniel Veillard 已提交
2682 2683 2684
    return ddom;
}

2685 2686 2687
static int
remoteListDefinedDomains (virConnectPtr conn, char **const names, int maxnames)
{
2688
    int rv = -1;
2689 2690 2691
    int i;
    remote_list_defined_domains_args args;
    remote_list_defined_domains_ret ret;
2692
    struct private_data *priv = conn->privateData;
2693

2694 2695
    remoteDriverLock(priv);

2696
    if (maxnames > REMOTE_DOMAIN_NAME_LIST_MAX) {
2697 2698 2699
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                maxnames, REMOTE_DOMAIN_NAME_LIST_MAX);
2700
        goto done;
2701 2702 2703 2704 2705 2706 2707
    }
    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)
2708
        goto done;
2709 2710

    if (ret.names.names_len > maxnames) {
2711 2712 2713
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                ret.names.names_len, maxnames);
2714
        goto cleanup;
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    }

    /* 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]);

2725 2726 2727
    rv = ret.names.names_len;

cleanup:
2728 2729
    xdr_free ((xdrproc_t) xdr_remote_list_defined_domains_ret, (char *) &ret);

2730
done:
2731
    remoteDriverUnlock(priv);
2732
    return rv;
2733 2734 2735 2736 2737
}

static int
remoteNumOfDefinedDomains (virConnectPtr conn)
{
2738
    int rv = -1;
2739
    remote_num_of_defined_domains_ret ret;
2740
    struct private_data *priv = conn->privateData;
2741

2742 2743
    remoteDriverLock(priv);

2744 2745 2746 2747
    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)
2748
        goto done;
2749

2750 2751 2752
    rv = ret.num;

done:
2753
    remoteDriverUnlock(priv);
2754
    return rv;
2755 2756 2757 2758 2759
}

static int
remoteDomainCreate (virDomainPtr domain)
{
2760
    int rv = -1;
2761
    remote_domain_create_args args;
2762 2763
    remote_domain_lookup_by_uuid_args args2;
    remote_domain_lookup_by_uuid_ret ret2;
2764
    struct private_data *priv = domain->conn->privateData;
2765

2766 2767
    remoteDriverLock(priv);

2768 2769 2770 2771 2772
    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)
2773
        goto done;
2774

2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788
    /* 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);

2789 2790 2791
    rv = 0;

done:
2792
    remoteDriverUnlock(priv);
2793
    return rv;
2794 2795 2796 2797 2798
}

static virDomainPtr
remoteDomainDefineXML (virConnectPtr conn, const char *xml)
{
2799
    virDomainPtr dom = NULL;
2800 2801
    remote_domain_define_xml_args args;
    remote_domain_define_xml_ret ret;
2802
    struct private_data *priv = conn->privateData;
2803

2804 2805
    remoteDriverLock(priv);

2806 2807 2808 2809 2810 2811
    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)
2812
        goto done;
2813 2814 2815 2816

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

2817
done:
2818
    remoteDriverUnlock(priv);
2819 2820 2821 2822 2823 2824
    return dom;
}

static int
remoteDomainUndefine (virDomainPtr domain)
{
2825
    int rv = -1;
2826
    remote_domain_undefine_args args;
2827
    struct private_data *priv = domain->conn->privateData;
2828

2829 2830
    remoteDriverLock(priv);

2831 2832 2833 2834 2835
    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)
2836
        goto done;
2837

2838 2839 2840
    rv = 0;

done:
2841
    remoteDriverUnlock(priv);
2842
    return rv;
2843 2844 2845
}

static int
2846
remoteDomainAttachDevice (virDomainPtr domain, const char *xml)
2847
{
2848
    int rv = -1;
2849
    remote_domain_attach_device_args args;
2850
    struct private_data *priv = domain->conn->privateData;
2851

2852 2853
    remoteDriverLock(priv);

2854
    make_nonnull_domain (&args.dom, domain);
2855
    args.xml = (char *) xml;
2856 2857 2858 2859

    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)
2860
        goto done;
2861

2862 2863 2864
    rv = 0;

done:
2865
    remoteDriverUnlock(priv);
2866
    return rv;
2867 2868 2869
}

static int
2870
remoteDomainDetachDevice (virDomainPtr domain, const char *xml)
2871
{
2872
    int rv = -1;
2873
    remote_domain_detach_device_args args;
2874
    struct private_data *priv = domain->conn->privateData;
2875

2876 2877
    remoteDriverLock(priv);

2878
    make_nonnull_domain (&args.dom, domain);
2879
    args.xml = (char *) xml;
2880 2881 2882 2883

    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)
2884
        goto done;
2885

2886 2887 2888
    rv = 0;

done:
2889
    remoteDriverUnlock(priv);
2890
    return rv;
2891 2892 2893 2894 2895
}

static int
remoteDomainGetAutostart (virDomainPtr domain, int *autostart)
{
2896
    int rv = -1;
2897 2898
    remote_domain_get_autostart_args args;
    remote_domain_get_autostart_ret ret;
2899
    struct private_data *priv = domain->conn->privateData;
2900

2901 2902
    remoteDriverLock(priv);

2903 2904 2905 2906 2907 2908
    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)
2909
        goto done;
2910 2911

    if (autostart) *autostart = ret.autostart;
2912 2913 2914
    rv = 0;

done:
2915
    remoteDriverUnlock(priv);
2916
    return rv;
2917 2918 2919 2920 2921
}

static int
remoteDomainSetAutostart (virDomainPtr domain, int autostart)
{
2922
    int rv = -1;
2923
    remote_domain_set_autostart_args args;
2924
    struct private_data *priv = domain->conn->privateData;
2925

2926 2927
    remoteDriverLock(priv);

2928 2929 2930 2931 2932 2933
    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)
2934
        goto done;
2935

2936 2937 2938
    rv = 0;

done:
2939
    remoteDriverUnlock(priv);
2940
    return rv;
2941 2942
}

2943 2944 2945
static char *
remoteDomainGetSchedulerType (virDomainPtr domain, int *nparams)
{
2946
    char *rv = NULL;
2947 2948
    remote_domain_get_scheduler_type_args args;
    remote_domain_get_scheduler_type_ret ret;
2949
    struct private_data *priv = domain->conn->privateData;
2950

2951 2952
    remoteDriverLock(priv);

2953 2954 2955 2956 2957 2958
    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)
2959
        goto done;
2960 2961 2962 2963

    if (nparams) *nparams = ret.nparams;

    /* Caller frees this. */
2964 2965 2966
    rv = ret.type;

done:
2967
    remoteDriverUnlock(priv);
2968
    return rv;
2969 2970 2971 2972 2973 2974
}

static int
remoteDomainGetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int *nparams)
{
2975
    int rv = -1;
2976 2977
    remote_domain_get_scheduler_parameters_args args;
    remote_domain_get_scheduler_parameters_ret ret;
2978
    int i = -1;
2979
    struct private_data *priv = domain->conn->privateData;
2980

2981 2982
    remoteDriverLock(priv);

2983 2984 2985 2986 2987 2988 2989
    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)
2990
        goto done;
2991 2992 2993 2994

    /* Check the length of the returned list carefully. */
    if (ret.params.params_len > REMOTE_DOMAIN_SCHEDULER_PARAMETERS_MAX ||
        ret.params.params_len > *nparams) {
2995 2996 2997
        error (domain->conn, VIR_ERR_RPC,
               _("remoteDomainGetSchedulerParameters: "
                 "returned number of parameters exceeds limit"));
2998
        goto cleanup;
2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
    }
    *nparams = ret.params.params_len;

    /* Deserialise the result. */
    for (i = 0; i < *nparams; ++i) {
        strncpy (params[i].field, ret.params.params_val[i].field,
                 VIR_DOMAIN_SCHED_FIELD_LENGTH);
        params[i].field[VIR_DOMAIN_SCHED_FIELD_LENGTH-1] = '\0';
        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:
3022 3023 3024
            error (domain->conn, VIR_ERR_RPC,
                   _("remoteDomainGetSchedulerParameters: "
                     "unknown parameter type"));
3025
            goto cleanup;
3026 3027 3028
        }
    }

3029 3030 3031
    rv = 0;

cleanup:
3032
    xdr_free ((xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret);
3033
done:
3034
    remoteDriverUnlock(priv);
3035
    return rv;
3036 3037 3038 3039 3040 3041
}

static int
remoteDomainSetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int nparams)
{
3042
    int rv = -1;
3043 3044
    remote_domain_set_scheduler_parameters_args args;
    int i, do_error;
3045
    struct private_data *priv = domain->conn->privateData;
3046

3047 3048
    remoteDriverLock(priv);

3049 3050 3051 3052
    make_nonnull_domain (&args.dom, domain);

    /* Serialise the scheduler parameters. */
    args.params.params_len = nparams;
3053
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
3054
        error (domain->conn, VIR_ERR_RPC, _("out of memory allocating array"));
3055
        goto done;
3056 3057 3058 3059 3060 3061 3062
    }

    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) {
3063
            virReportOOMError (domain->conn);
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
            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:
3081
            error (domain->conn, VIR_ERR_RPC, _("unknown parameter type"));
3082 3083 3084 3085 3086 3087
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_scheduler_parameters_args, (char *) &args);
3088
        goto done;
3089 3090 3091 3092 3093
    }

    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)
3094
        goto done;
3095

3096 3097 3098
    rv = 0;

done:
3099
    remoteDriverUnlock(priv);
3100
    return rv;
3101 3102
}

3103 3104 3105 3106
static int
remoteDomainBlockStats (virDomainPtr domain, const char *path,
                        struct _virDomainBlockStats *stats)
{
3107
    int rv = -1;
3108 3109
    remote_domain_block_stats_args args;
    remote_domain_block_stats_ret ret;
3110
    struct private_data *priv = domain->conn->privateData;
3111

3112 3113
    remoteDriverLock(priv);

3114 3115 3116 3117 3118 3119 3120 3121
    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)
3122
        goto done;
3123 3124 3125 3126 3127 3128 3129

    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;

3130 3131 3132
    rv = 0;

done:
3133
    remoteDriverUnlock(priv);
3134
    return rv;
3135 3136 3137 3138 3139 3140
}

static int
remoteDomainInterfaceStats (virDomainPtr domain, const char *path,
                            struct _virDomainInterfaceStats *stats)
{
3141
    int rv = -1;
3142 3143
    remote_domain_interface_stats_args args;
    remote_domain_interface_stats_ret ret;
3144
    struct private_data *priv = domain->conn->privateData;
3145

3146 3147
    remoteDriverLock(priv);

3148 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_INTERFACE_STATS,
              (xdrproc_t) xdr_remote_domain_interface_stats_args,
                (char *) &args,
              (xdrproc_t) xdr_remote_domain_interface_stats_ret,
                (char *) &ret) == -1)
3157
        goto done;
3158 3159 3160 3161 3162 3163 3164 3165 3166 3167

    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;

3168 3169 3170
    rv = 0;

done:
3171
    remoteDriverUnlock(priv);
3172
    return rv;
3173 3174
}

3175 3176 3177 3178 3179 3180 3181 3182
static int
remoteDomainBlockPeek (virDomainPtr domain,
                       const char *path,
                       unsigned long long offset,
                       size_t size,
                       void *buffer,
                       unsigned int flags)
{
3183
    int rv = -1;
3184 3185
    remote_domain_block_peek_args args;
    remote_domain_block_peek_ret ret;
3186
    struct private_data *priv = domain->conn->privateData;
3187

3188 3189
    remoteDriverLock(priv);

3190 3191 3192 3193
    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);
3194
        goto done;
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
    }

    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)
3209
        goto done;
3210 3211

    if (ret.buffer.buffer_len != size) {
3212 3213 3214
        errorf (domain->conn, VIR_ERR_RPC,
                "%s", _("returned buffer is not same size as requested"));
        goto cleanup;
3215 3216 3217
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
3218 3219 3220
    rv = 0;

cleanup:
3221 3222
    free (ret.buffer.buffer_val);

3223
done:
3224
    remoteDriverUnlock(priv);
3225
    return rv;
3226 3227
}

R
Richard W.M. Jones 已提交
3228 3229 3230 3231 3232 3233 3234
static int
remoteDomainMemoryPeek (virDomainPtr domain,
                        unsigned long long offset,
                        size_t size,
                        void *buffer,
                        unsigned int flags)
{
3235
    int rv = -1;
R
Richard W.M. Jones 已提交
3236 3237
    remote_domain_memory_peek_args args;
    remote_domain_memory_peek_ret ret;
3238
    struct private_data *priv = domain->conn->privateData;
R
Richard W.M. Jones 已提交
3239

3240 3241
    remoteDriverLock(priv);

R
Richard W.M. Jones 已提交
3242 3243 3244 3245
    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);
3246
        goto done;
R
Richard W.M. Jones 已提交
3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
    }

    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)
3260
        goto done;
R
Richard W.M. Jones 已提交
3261 3262

    if (ret.buffer.buffer_len != size) {
3263 3264 3265
        errorf (domain->conn, VIR_ERR_RPC,
                "%s", _("returned buffer is not same size as requested"));
        goto cleanup;
R
Richard W.M. Jones 已提交
3266 3267 3268
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
3269 3270 3271
    rv = 0;

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

3274
done:
3275
    remoteDriverUnlock(priv);
3276
    return rv;
R
Richard W.M. Jones 已提交
3277 3278
}

3279 3280
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
3281
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
3282
remoteNetworkOpen (virConnectPtr conn,
3283
                   virConnectAuthPtr auth,
3284
                   int flags)
3285
{
3286 3287 3288
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
3289
    if (conn->driver &&
3290
        STREQ (conn->driver->name, "remote")) {
3291 3292 3293
        struct private_data *priv;

       /* If we're here, the remote driver is already
3294 3295 3296
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
3297 3298 3299 3300 3301
        priv = conn->privateData;
        remoteDriverLock(priv);
        priv->localUses++;
        conn->networkPrivateData = priv;
        remoteDriverUnlock(priv);
3302
        return VIR_DRV_OPEN_SUCCESS;
3303 3304 3305
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
3306 3307
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the network APIs.
3308
         */
3309
        struct private_data *priv;
3310 3311 3312 3313 3314 3315
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
3316 3317 3318
            conn->networkPrivateData = priv;
        return ret;
    }
3319 3320 3321
}

static int
3322 3323
remoteNetworkClose (virConnectPtr conn)
{
3324
    int rv = 0;
3325 3326
    struct private_data *priv = conn->networkPrivateData;

3327 3328 3329 3330 3331 3332 3333 3334
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        rv = doRemoteClose(conn, priv);
        conn->networkPrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
3335
    }
3336 3337
    if (priv)
        remoteDriverUnlock(priv);
3338
    return rv;
3339 3340 3341 3342 3343
}

static int
remoteNumOfNetworks (virConnectPtr conn)
{
3344
    int rv = -1;
3345
    remote_num_of_networks_ret ret;
3346
    struct private_data *priv = conn->networkPrivateData;
3347

3348 3349
    remoteDriverLock(priv);

3350 3351 3352 3353
    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)
3354 3355 3356
        goto done;

    rv = ret.num;
3357

3358
done:
3359
    remoteDriverUnlock(priv);
3360
    return rv;
3361 3362 3363 3364 3365
}

static int
remoteListNetworks (virConnectPtr conn, char **const names, int maxnames)
{
3366
    int rv = -1;
3367 3368 3369
    int i;
    remote_list_networks_args args;
    remote_list_networks_ret ret;
3370
    struct private_data *priv = conn->networkPrivateData;
3371

3372 3373
    remoteDriverLock(priv);

3374
    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
3375 3376 3377
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
3378
        goto done;
3379 3380 3381 3382 3383 3384 3385
    }
    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)
3386
        goto done;
3387 3388

    if (ret.names.names_len > maxnames) {
3389 3390 3391
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
3392
        goto cleanup;
3393 3394 3395 3396 3397 3398 3399 3400 3401 3402
    }

    /* 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]);

3403 3404 3405
    rv = ret.names.names_len;

cleanup:
3406 3407
    xdr_free ((xdrproc_t) xdr_remote_list_networks_ret, (char *) &ret);

3408
done:
3409
    remoteDriverUnlock(priv);
3410
    return rv;
3411 3412 3413 3414 3415
}

static int
remoteNumOfDefinedNetworks (virConnectPtr conn)
{
3416
    int rv = -1;
3417
    remote_num_of_defined_networks_ret ret;
3418
    struct private_data *priv = conn->networkPrivateData;
3419

3420 3421
    remoteDriverLock(priv);

3422 3423 3424 3425
    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)
3426 3427 3428
        goto done;

    rv = ret.num;
3429

3430
done:
3431
    remoteDriverUnlock(priv);
3432
    return rv;
3433 3434 3435 3436 3437 3438
}

static int
remoteListDefinedNetworks (virConnectPtr conn,
                           char **const names, int maxnames)
{
3439
    int rv = -1;
3440 3441 3442
    int i;
    remote_list_defined_networks_args args;
    remote_list_defined_networks_ret ret;
3443
    struct private_data *priv = conn->networkPrivateData;
3444

3445 3446
    remoteDriverLock(priv);

3447
    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
3448 3449 3450
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
3451
        goto done;
3452 3453 3454 3455 3456 3457 3458
    }
    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)
3459
        goto done;
3460 3461

    if (ret.names.names_len > maxnames) {
3462 3463 3464
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
3465
        goto cleanup;
3466 3467 3468 3469 3470 3471 3472 3473 3474 3475
    }

    /* 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]);

3476 3477 3478
    rv = ret.names.names_len;

cleanup:
3479 3480
    xdr_free ((xdrproc_t) xdr_remote_list_defined_networks_ret, (char *) &ret);

3481
done:
3482
    remoteDriverUnlock(priv);
3483
    return rv;
3484 3485 3486 3487 3488 3489
}

static virNetworkPtr
remoteNetworkLookupByUUID (virConnectPtr conn,
                           const unsigned char *uuid)
{
3490
    virNetworkPtr net = NULL;
3491 3492
    remote_network_lookup_by_uuid_args args;
    remote_network_lookup_by_uuid_ret ret;
3493
    struct private_data *priv = conn->networkPrivateData;
3494

3495 3496
    remoteDriverLock(priv);

3497 3498 3499 3500 3501 3502
    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)
3503
        goto done;
3504 3505 3506 3507

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

3508
done:
3509
    remoteDriverUnlock(priv);
3510 3511 3512 3513 3514 3515 3516
    return net;
}

static virNetworkPtr
remoteNetworkLookupByName (virConnectPtr conn,
                           const char *name)
{
3517
    virNetworkPtr net = NULL;
3518 3519
    remote_network_lookup_by_name_args args;
    remote_network_lookup_by_name_ret ret;
3520
    struct private_data *priv = conn->networkPrivateData;
3521

3522 3523
    remoteDriverLock(priv);

3524 3525 3526 3527 3528 3529
    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)
3530
        goto done;
3531 3532 3533 3534

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

3535
done:
3536
    remoteDriverUnlock(priv);
3537 3538 3539 3540 3541 3542
    return net;
}

static virNetworkPtr
remoteNetworkCreateXML (virConnectPtr conn, const char *xmlDesc)
{
3543
    virNetworkPtr net = NULL;
3544 3545
    remote_network_create_xml_args args;
    remote_network_create_xml_ret ret;
3546
    struct private_data *priv = conn->networkPrivateData;
3547

3548 3549
    remoteDriverLock(priv);

3550 3551 3552 3553 3554 3555
    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)
3556
        goto done;
3557 3558 3559 3560

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

3561
done:
3562
    remoteDriverUnlock(priv);
3563 3564 3565 3566 3567 3568
    return net;
}

static virNetworkPtr
remoteNetworkDefineXML (virConnectPtr conn, const char *xml)
{
3569
    virNetworkPtr net = NULL;
3570 3571
    remote_network_define_xml_args args;
    remote_network_define_xml_ret ret;
3572
    struct private_data *priv = conn->networkPrivateData;
3573

3574 3575
    remoteDriverLock(priv);

3576 3577 3578 3579 3580 3581
    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)
3582
        goto done;
3583 3584 3585 3586

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

3587
done:
3588
    remoteDriverUnlock(priv);
3589 3590 3591 3592 3593 3594
    return net;
}

static int
remoteNetworkUndefine (virNetworkPtr network)
{
3595
    int rv = -1;
3596
    remote_network_undefine_args args;
3597
    struct private_data *priv = network->conn->networkPrivateData;
3598

3599 3600
    remoteDriverLock(priv);

3601 3602 3603 3604 3605
    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)
3606
        goto done;
3607

3608 3609 3610
    rv = 0;

done:
3611
    remoteDriverUnlock(priv);
3612
    return rv;
3613 3614 3615 3616 3617
}

static int
remoteNetworkCreate (virNetworkPtr network)
{
3618
    int rv = -1;
3619
    remote_network_create_args args;
3620
    struct private_data *priv = network->conn->networkPrivateData;
3621

3622 3623
    remoteDriverLock(priv);

3624 3625 3626 3627 3628
    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)
3629
        goto done;
3630

3631 3632 3633
    rv = 0;

done:
3634
    remoteDriverUnlock(priv);
3635
    return rv;
3636 3637 3638 3639 3640
}

static int
remoteNetworkDestroy (virNetworkPtr network)
{
3641
    int rv = -1;
3642
    remote_network_destroy_args args;
3643
    struct private_data *priv = network->conn->networkPrivateData;
3644

3645 3646
    remoteDriverLock(priv);

3647 3648 3649 3650 3651
    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)
3652
        goto done;
3653

3654 3655 3656
    rv = 0;

done:
3657
    remoteDriverUnlock(priv);
3658
    return rv;
3659 3660 3661 3662 3663
}

static char *
remoteNetworkDumpXML (virNetworkPtr network, int flags)
{
3664
    char *rv = NULL;
3665 3666
    remote_network_dump_xml_args args;
    remote_network_dump_xml_ret ret;
3667
    struct private_data *priv = network->conn->networkPrivateData;
3668

3669 3670
    remoteDriverLock(priv);

3671 3672 3673 3674 3675 3676 3677
    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)
3678
        goto done;
3679 3680

    /* Caller frees. */
3681 3682 3683
    rv = ret.xml;

done:
3684
    remoteDriverUnlock(priv);
3685
    return rv;
3686 3687 3688 3689 3690
}

static char *
remoteNetworkGetBridgeName (virNetworkPtr network)
{
3691
    char *rv = NULL;
3692 3693
    remote_network_get_bridge_name_args args;
    remote_network_get_bridge_name_ret ret;
3694
    struct private_data *priv = network->conn->networkPrivateData;
3695

3696 3697
    remoteDriverLock(priv);

3698 3699 3700 3701 3702 3703
    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)
3704
        goto done;
3705 3706

    /* Caller frees. */
3707 3708 3709
    rv = ret.name;

done:
3710
    remoteDriverUnlock(priv);
3711
    return rv;
3712 3713 3714 3715 3716
}

static int
remoteNetworkGetAutostart (virNetworkPtr network, int *autostart)
{
3717
    int rv = -1;
3718 3719
    remote_network_get_autostart_args args;
    remote_network_get_autostart_ret ret;
3720
    struct private_data *priv = network->conn->networkPrivateData;
3721

3722 3723
    remoteDriverLock(priv);

3724 3725 3726 3727 3728 3729
    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)
3730
        goto done;
3731 3732 3733

    if (autostart) *autostart = ret.autostart;

3734 3735 3736
    rv = 0;

done:
3737
    remoteDriverUnlock(priv);
3738
    return rv;
3739 3740 3741 3742 3743
}

static int
remoteNetworkSetAutostart (virNetworkPtr network, int autostart)
{
3744
    int rv = -1;
3745
    remote_network_set_autostart_args args;
3746
    struct private_data *priv = network->conn->networkPrivateData;
3747

3748 3749
    remoteDriverLock(priv);

3750 3751 3752 3753 3754 3755
    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)
3756
        goto done;
3757

3758 3759 3760
    rv = 0;

done:
3761
    remoteDriverUnlock(priv);
3762
    return rv;
3763 3764
}

3765 3766 3767



D
Daniel Veillard 已提交
3768 3769
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
3770
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
D
Daniel Veillard 已提交
3771
remoteInterfaceOpen (virConnectPtr conn,
J
Jim Meyering 已提交
3772 3773
                     virConnectAuthPtr auth,
                     int flags)
D
Daniel Veillard 已提交
3774 3775 3776 3777
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
3778
    if (conn->driver &&
D
Daniel Veillard 已提交
3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 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
        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;
}

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 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
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 已提交
3974 3975 3976 3977
static virInterfacePtr
remoteInterfaceLookupByName (virConnectPtr conn,
                             const char *name)
{
3978
    virInterfacePtr iface = NULL;
D
Daniel Veillard 已提交
3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992
    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;

3993
    iface = get_nonnull_interface (conn, ret.iface);
D
Daniel Veillard 已提交
3994 3995 3996 3997
    xdr_free ((xdrproc_t) &xdr_remote_interface_lookup_by_name_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
3998
    return iface;
D
Daniel Veillard 已提交
3999 4000 4001 4002 4003 4004
}

static virInterfacePtr
remoteInterfaceLookupByMACString (virConnectPtr conn,
                                  const char *mac)
{
4005
    virInterfacePtr iface = NULL;
D
Daniel Veillard 已提交
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019
    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;

4020
    iface = get_nonnull_interface (conn, ret.iface);
D
Daniel Veillard 已提交
4021 4022 4023 4024
    xdr_free ((xdrproc_t) &xdr_remote_interface_lookup_by_mac_string_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
4025
    return iface;
D
Daniel Veillard 已提交
4026 4027 4028
}

static char *
4029
remoteInterfaceGetXMLDesc (virInterfacePtr iface,
D
Daniel Veillard 已提交
4030 4031 4032 4033 4034
                           unsigned int flags)
{
    char *rv = NULL;
    remote_interface_get_xml_desc_args args;
    remote_interface_get_xml_desc_ret ret;
4035
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4036 4037 4038

    remoteDriverLock(priv);

4039
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4040 4041 4042
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
4043
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_GET_XML_DESC,
D
Daniel Veillard 已提交
4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060
              (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)
{
4061
    virInterfacePtr iface = NULL;
D
Daniel Veillard 已提交
4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076
    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;

4077
    iface = get_nonnull_interface (conn, ret.iface);
D
Daniel Veillard 已提交
4078 4079 4080 4081
    xdr_free ((xdrproc_t) &xdr_remote_interface_define_xml_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
4082
    return iface;
D
Daniel Veillard 已提交
4083 4084 4085
}

static int
4086
remoteInterfaceUndefine (virInterfacePtr iface)
D
Daniel Veillard 已提交
4087 4088 4089
{
    int rv = -1;
    remote_interface_undefine_args args;
4090
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4091 4092 4093

    remoteDriverLock(priv);

4094
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4095

4096
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_UNDEFINE,
D
Daniel Veillard 已提交
4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108
              (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
4109
remoteInterfaceCreate (virInterfacePtr iface,
D
Daniel Veillard 已提交
4110 4111 4112 4113
                       unsigned int flags)
{
    int rv = -1;
    remote_interface_create_args args;
4114
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4115 4116 4117

    remoteDriverLock(priv);

4118
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4119 4120
    args.flags = flags;

4121
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_CREATE,
D
Daniel Veillard 已提交
4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133
              (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
4134
remoteInterfaceDestroy (virInterfacePtr iface,
D
Daniel Veillard 已提交
4135 4136 4137 4138
                        unsigned int flags)
{
    int rv = -1;
    remote_interface_destroy_args args;
4139
    struct private_data *priv = iface->conn->interfacePrivateData;
D
Daniel Veillard 已提交
4140 4141 4142

    remoteDriverLock(priv);

4143
    make_nonnull_interface (&args.iface, iface);
D
Daniel Veillard 已提交
4144 4145
    args.flags = flags;

4146
    if (call (iface->conn, priv, 0, REMOTE_PROC_INTERFACE_DESTROY,
D
Daniel Veillard 已提交
4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
              (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;
}

4158 4159
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
4160
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
4161 4162 4163 4164 4165 4166 4167
remoteStorageOpen (virConnectPtr conn,
                   virConnectAuthPtr auth,
                   int flags)
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
4168
    if (conn->driver &&
4169
        STREQ (conn->driver->name, "remote")) {
4170
        struct private_data *priv = conn->privateData;
4171 4172 4173 4174
        /* 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
         */
4175 4176 4177 4178
        remoteDriverLock(priv);
        priv->localUses++;
        conn->storagePrivateData = priv;
        remoteDriverUnlock(priv);
4179 4180 4181
        return VIR_DRV_OPEN_SUCCESS;
    } else if (conn->networkDriver &&
               STREQ (conn->networkDriver->name, "remote")) {
4182 4183 4184 4185 4186
        struct private_data *priv = conn->networkPrivateData;
        remoteDriverLock(priv);
        conn->storagePrivateData = priv;
        priv->localUses++;
        remoteDriverUnlock(priv);
4187 4188 4189 4190 4191 4192 4193
        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.
         */
4194
        struct private_data *priv;
4195 4196 4197 4198 4199 4200
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
4201 4202 4203 4204 4205 4206 4207 4208 4209
            conn->storagePrivateData = priv;
        return ret;
    }
}

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

4212 4213 4214 4215 4216 4217 4218 4219
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        ret = doRemoteClose(conn, priv);
        conn->storagePrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
4220
    }
4221 4222
    if (priv)
        remoteDriverUnlock(priv);
4223

4224 4225 4226 4227 4228 4229
    return ret;
}

static int
remoteNumOfStoragePools (virConnectPtr conn)
{
4230
    int rv = -1;
4231
    remote_num_of_storage_pools_ret ret;
4232
    struct private_data *priv = conn->storagePrivateData;
4233

4234 4235
    remoteDriverLock(priv);

4236 4237 4238 4239
    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)
4240 4241 4242
        goto done;

    rv = ret.num;
4243

4244
done:
4245
    remoteDriverUnlock(priv);
4246
    return rv;
4247 4248 4249 4250 4251
}

static int
remoteListStoragePools (virConnectPtr conn, char **const names, int maxnames)
{
4252
    int rv = -1;
4253 4254 4255
    int i;
    remote_list_storage_pools_args args;
    remote_list_storage_pools_ret ret;
4256
    struct private_data *priv = conn->storagePrivateData;
4257

4258 4259
    remoteDriverLock(priv);

4260 4261
    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
4262
        goto done;
4263 4264 4265 4266 4267 4268 4269
    }
    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)
4270
        goto done;
4271 4272 4273

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
4274
        goto cleanup;
4275 4276 4277 4278 4279 4280 4281 4282 4283 4284
    }

    /* 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]);

4285 4286 4287
    rv = ret.names.names_len;

cleanup:
4288 4289
    xdr_free ((xdrproc_t) xdr_remote_list_storage_pools_ret, (char *) &ret);

4290
done:
4291
    remoteDriverUnlock(priv);
4292
    return rv;
4293 4294 4295 4296 4297
}

static int
remoteNumOfDefinedStoragePools (virConnectPtr conn)
{
4298
    int rv = -1;
4299
    remote_num_of_defined_storage_pools_ret ret;
4300
    struct private_data *priv = conn->storagePrivateData;
4301

4302 4303
    remoteDriverLock(priv);

4304 4305 4306 4307
    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)
4308
        goto done;
4309

4310 4311 4312
    rv = ret.num;

done:
4313
    remoteDriverUnlock(priv);
4314
    return rv;
4315 4316 4317 4318 4319 4320
}

static int
remoteListDefinedStoragePools (virConnectPtr conn,
                               char **const names, int maxnames)
{
4321
    int rv = -1;
4322 4323 4324
    int i;
    remote_list_defined_storage_pools_args args;
    remote_list_defined_storage_pools_ret ret;
4325
    struct private_data *priv = conn->storagePrivateData;
4326

4327 4328
    remoteDriverLock(priv);

4329 4330
    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
4331
        goto done;
4332 4333 4334 4335 4336 4337 4338
    }
    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)
4339
        goto done;
4340 4341 4342

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
4343
        goto cleanup;
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353
    }

    /* 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]);

4354 4355 4356
    rv = ret.names.names_len;

cleanup:
4357 4358
    xdr_free ((xdrproc_t) xdr_remote_list_defined_storage_pools_ret, (char *) &ret);

4359
done:
4360
    remoteDriverUnlock(priv);
4361
    return rv;
4362 4363
}

4364 4365 4366 4367 4368 4369
static char *
remoteFindStoragePoolSources (virConnectPtr conn,
                              const char *type,
                              const char *srcSpec,
                              unsigned int flags)
{
4370
    char *rv = NULL;
4371 4372
    remote_find_storage_pool_sources_args args;
    remote_find_storage_pool_sources_ret ret;
4373
    struct private_data *priv = conn->storagePrivateData;
4374 4375
    const char *emptyString = "";

4376 4377
    remoteDriverLock(priv);

4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396
    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)
4397
        goto done;
4398

4399
    rv = ret.xml;
4400 4401 4402 4403
    ret.xml = NULL; /* To stop xdr_free free'ing it */

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

4404
done:
4405
    remoteDriverUnlock(priv);
4406
    return rv;
4407 4408
}

4409 4410 4411 4412
static virStoragePoolPtr
remoteStoragePoolLookupByUUID (virConnectPtr conn,
                               const unsigned char *uuid)
{
4413
    virStoragePoolPtr pool = NULL;
4414 4415
    remote_storage_pool_lookup_by_uuid_args args;
    remote_storage_pool_lookup_by_uuid_ret ret;
4416
    struct private_data *priv = conn->storagePrivateData;
4417

4418 4419
    remoteDriverLock(priv);

4420 4421 4422 4423 4424 4425
    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)
4426
        goto done;
4427 4428 4429 4430

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

4431
done:
4432
    remoteDriverUnlock(priv);
4433 4434 4435 4436 4437 4438 4439
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByName (virConnectPtr conn,
                               const char *name)
{
4440
    virStoragePoolPtr pool = NULL;
4441 4442
    remote_storage_pool_lookup_by_name_args args;
    remote_storage_pool_lookup_by_name_ret ret;
4443
    struct private_data *priv = conn->storagePrivateData;
4444

4445 4446
    remoteDriverLock(priv);

4447 4448 4449 4450 4451 4452
    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)
4453
        goto done;
4454 4455 4456 4457

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

4458
done:
4459
    remoteDriverUnlock(priv);
4460 4461 4462 4463 4464 4465
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByVolume (virStorageVolPtr vol)
{
4466
    virStoragePoolPtr pool = NULL;
4467 4468
    remote_storage_pool_lookup_by_volume_args args;
    remote_storage_pool_lookup_by_volume_ret ret;
4469
    struct private_data *priv = vol->conn->storagePrivateData;
4470

4471 4472
    remoteDriverLock(priv);

4473 4474 4475 4476 4477 4478
    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)
4479
        goto done;
4480 4481 4482 4483

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

4484
done:
4485
    remoteDriverUnlock(priv);
4486 4487 4488 4489 4490 4491 4492
    return pool;
}


static virStoragePoolPtr
remoteStoragePoolCreateXML (virConnectPtr conn, const char *xmlDesc, unsigned int flags)
{
4493
    virStoragePoolPtr pool = NULL;
4494 4495
    remote_storage_pool_create_xml_args args;
    remote_storage_pool_create_xml_ret ret;
4496
    struct private_data *priv = conn->storagePrivateData;
4497

4498 4499
    remoteDriverLock(priv);

4500 4501 4502 4503 4504 4505 4506
    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)
4507
        goto done;
4508 4509 4510 4511

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

4512
done:
4513
    remoteDriverUnlock(priv);
4514 4515 4516 4517 4518 4519
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolDefineXML (virConnectPtr conn, const char *xml, unsigned int flags)
{
4520
    virStoragePoolPtr pool = NULL;
4521 4522
    remote_storage_pool_define_xml_args args;
    remote_storage_pool_define_xml_ret ret;
4523
    struct private_data *priv = conn->storagePrivateData;
4524

4525 4526
    remoteDriverLock(priv);

4527 4528 4529 4530 4531 4532 4533
    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)
4534
        goto done;
4535 4536 4537 4538

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

4539
done:
4540
    remoteDriverUnlock(priv);
4541 4542 4543 4544 4545 4546
    return pool;
}

static int
remoteStoragePoolUndefine (virStoragePoolPtr pool)
{
4547
    int rv = -1;
4548
    remote_storage_pool_undefine_args args;
4549
    struct private_data *priv = pool->conn->storagePrivateData;
4550

4551 4552
    remoteDriverLock(priv);

4553 4554 4555 4556 4557
    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)
4558
        goto done;
4559

4560 4561 4562
    rv = 0;

done:
4563
    remoteDriverUnlock(priv);
4564
    return rv;
4565 4566 4567 4568 4569
}

static int
remoteStoragePoolCreate (virStoragePoolPtr pool, unsigned int flags)
{
4570
    int rv = -1;
4571
    remote_storage_pool_create_args args;
4572
    struct private_data *priv = pool->conn->storagePrivateData;
4573

4574 4575
    remoteDriverLock(priv);

4576 4577 4578 4579 4580 4581
    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)
4582
        goto done;
4583

4584 4585 4586
    rv = 0;

done:
4587
    remoteDriverUnlock(priv);
4588
    return rv;
4589 4590 4591 4592 4593 4594
}

static int
remoteStoragePoolBuild (virStoragePoolPtr pool,
                        unsigned int flags)
{
4595
    int rv = -1;
4596
    remote_storage_pool_build_args args;
4597
    struct private_data *priv = pool->conn->storagePrivateData;
4598

4599 4600
    remoteDriverLock(priv);

4601 4602 4603 4604 4605 4606
    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)
4607
        goto done;
4608

4609 4610 4611
    rv = 0;

done:
4612
    remoteDriverUnlock(priv);
4613
    return rv;
4614 4615 4616 4617 4618
}

static int
remoteStoragePoolDestroy (virStoragePoolPtr pool)
{
4619
    int rv = -1;
4620
    remote_storage_pool_destroy_args args;
4621
    struct private_data *priv = pool->conn->storagePrivateData;
4622

4623 4624
    remoteDriverLock(priv);

4625 4626 4627 4628 4629
    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)
4630
        goto done;
4631

4632 4633 4634
    rv = 0;

done:
4635
    remoteDriverUnlock(priv);
4636
    return rv;
4637 4638 4639 4640 4641 4642
}

static int
remoteStoragePoolDelete (virStoragePoolPtr pool,
                         unsigned int flags)
{
4643
    int rv = -1;
4644
    remote_storage_pool_delete_args args;
4645
    struct private_data *priv = pool->conn->storagePrivateData;
4646

4647 4648
    remoteDriverLock(priv);

4649 4650 4651 4652 4653 4654
    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)
4655
        goto done;
4656

4657 4658 4659
    rv = 0;

done:
4660
    remoteDriverUnlock(priv);
4661
    return rv;
4662 4663 4664 4665 4666 4667
}

static int
remoteStoragePoolRefresh (virStoragePoolPtr pool,
                          unsigned int flags)
{
4668
    int rv = -1;
4669
    remote_storage_pool_refresh_args args;
4670
    struct private_data *priv = pool->conn->storagePrivateData;
4671

4672 4673
    remoteDriverLock(priv);

4674 4675 4676 4677 4678 4679
    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)
4680
        goto done;
4681

4682 4683 4684
    rv = 0;

done:
4685
    remoteDriverUnlock(priv);
4686
    return rv;
4687 4688 4689 4690 4691
}

static int
remoteStoragePoolGetInfo (virStoragePoolPtr pool, virStoragePoolInfoPtr info)
{
4692
    int rv = -1;
4693 4694
    remote_storage_pool_get_info_args args;
    remote_storage_pool_get_info_ret ret;
4695
    struct private_data *priv = pool->conn->storagePrivateData;
4696

4697 4698
    remoteDriverLock(priv);

4699 4700 4701 4702 4703 4704
    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)
4705
        goto done;
4706 4707 4708 4709 4710 4711

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

4712 4713 4714
    rv = 0;

done:
4715
    remoteDriverUnlock(priv);
4716
    return rv;
4717 4718 4719 4720 4721 4722
}

static char *
remoteStoragePoolDumpXML (virStoragePoolPtr pool,
                          unsigned int flags)
{
4723
    char *rv = NULL;
4724 4725
    remote_storage_pool_dump_xml_args args;
    remote_storage_pool_dump_xml_ret ret;
4726
    struct private_data *priv = pool->conn->storagePrivateData;
4727

4728 4729
    remoteDriverLock(priv);

4730 4731 4732 4733 4734 4735 4736
    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)
4737
        goto done;
4738 4739

    /* Caller frees. */
4740 4741 4742
    rv = ret.xml;

done:
4743
    remoteDriverUnlock(priv);
4744
    return rv;
4745 4746 4747 4748 4749
}

static int
remoteStoragePoolGetAutostart (virStoragePoolPtr pool, int *autostart)
{
4750
    int rv = -1;
4751 4752
    remote_storage_pool_get_autostart_args args;
    remote_storage_pool_get_autostart_ret ret;
4753
    struct private_data *priv = pool->conn->storagePrivateData;
4754

4755 4756
    remoteDriverLock(priv);

4757 4758 4759 4760 4761 4762
    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)
4763
        goto done;
4764 4765 4766

    if (autostart) *autostart = ret.autostart;

4767 4768 4769
    rv = 0;

done:
4770
    remoteDriverUnlock(priv);
4771
    return rv;
4772 4773 4774 4775 4776
}

static int
remoteStoragePoolSetAutostart (virStoragePoolPtr pool, int autostart)
{
4777
    int rv = -1;
4778
    remote_storage_pool_set_autostart_args args;
4779
    struct private_data *priv = pool->conn->storagePrivateData;
4780

4781 4782
    remoteDriverLock(priv);

4783 4784 4785 4786 4787 4788
    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)
4789
        goto done;
4790

4791 4792 4793
    rv = 0;

done:
4794
    remoteDriverUnlock(priv);
4795
    return rv;
4796 4797 4798 4799 4800 4801
}


static int
remoteStoragePoolNumOfVolumes (virStoragePoolPtr pool)
{
4802
    int rv = -1;
4803 4804
    remote_storage_pool_num_of_volumes_args args;
    remote_storage_pool_num_of_volumes_ret ret;
4805
    struct private_data *priv = pool->conn->storagePrivateData;
4806

4807 4808
    remoteDriverLock(priv);

4809 4810 4811 4812 4813 4814
    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)
4815 4816 4817
        goto done;

    rv = ret.num;
4818

4819
done:
4820
    remoteDriverUnlock(priv);
4821
    return rv;
4822 4823 4824 4825 4826
}

static int
remoteStoragePoolListVolumes (virStoragePoolPtr pool, char **const names, int maxnames)
{
4827
    int rv = -1;
4828 4829 4830
    int i;
    remote_storage_pool_list_volumes_args args;
    remote_storage_pool_list_volumes_ret ret;
4831
    struct private_data *priv = pool->conn->storagePrivateData;
4832

4833 4834
    remoteDriverLock(priv);

4835 4836
    if (maxnames > REMOTE_STORAGE_VOL_NAME_LIST_MAX) {
        error (pool->conn, VIR_ERR_RPC, _("too many storage volumes requested"));
4837
        goto done;
4838 4839 4840 4841 4842 4843 4844 4845
    }
    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)
4846
        goto done;
4847 4848 4849

    if (ret.names.names_len > maxnames) {
        error (pool->conn, VIR_ERR_RPC, _("too many storage volumes received"));
4850
        goto cleanup;
4851 4852 4853 4854 4855 4856 4857 4858 4859 4860
    }

    /* 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]);

4861 4862 4863
    rv = ret.names.names_len;

cleanup:
4864 4865
    xdr_free ((xdrproc_t) xdr_remote_storage_pool_list_volumes_ret, (char *) &ret);

4866
done:
4867
    remoteDriverUnlock(priv);
4868
    return rv;
4869 4870 4871 4872 4873 4874 4875 4876
}



static virStorageVolPtr
remoteStorageVolLookupByName (virStoragePoolPtr pool,
                              const char *name)
{
4877
    virStorageVolPtr vol = NULL;
4878 4879
    remote_storage_vol_lookup_by_name_args args;
    remote_storage_vol_lookup_by_name_ret ret;
4880
    struct private_data *priv = pool->conn->storagePrivateData;
4881

4882 4883
    remoteDriverLock(priv);

4884 4885 4886 4887 4888 4889 4890
    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)
4891
        goto done;
4892 4893 4894 4895

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

4896
done:
4897
    remoteDriverUnlock(priv);
4898 4899 4900 4901 4902 4903 4904
    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByKey (virConnectPtr conn,
                             const char *key)
{
4905
    virStorageVolPtr  vol = NULL;
4906 4907
    remote_storage_vol_lookup_by_key_args args;
    remote_storage_vol_lookup_by_key_ret ret;
4908
    struct private_data *priv = conn->storagePrivateData;
4909

4910 4911
    remoteDriverLock(priv);

4912 4913 4914 4915 4916 4917
    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)
4918
        goto done;
4919 4920 4921 4922

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

4923
done:
4924
    remoteDriverUnlock(priv);
4925 4926 4927 4928 4929 4930 4931
    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByPath (virConnectPtr conn,
                              const char *path)
{
4932
    virStorageVolPtr vol = NULL;
4933 4934
    remote_storage_vol_lookup_by_path_args args;
    remote_storage_vol_lookup_by_path_ret ret;
4935
    struct private_data *priv = conn->storagePrivateData;
4936

4937 4938
    remoteDriverLock(priv);

4939 4940 4941 4942 4943 4944
    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)
4945
        goto done;
4946 4947 4948 4949

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

4950
done:
4951
    remoteDriverUnlock(priv);
4952 4953 4954 4955 4956 4957 4958
    return vol;
}

static virStorageVolPtr
remoteStorageVolCreateXML (virStoragePoolPtr pool, const char *xmlDesc,
                           unsigned int flags)
{
4959
    virStorageVolPtr vol = NULL;
4960 4961
    remote_storage_vol_create_xml_args args;
    remote_storage_vol_create_xml_ret ret;
4962
    struct private_data *priv = pool->conn->storagePrivateData;
4963

4964 4965
    remoteDriverLock(priv);

4966 4967 4968 4969 4970 4971 4972 4973
    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)
4974
        goto done;
4975 4976 4977 4978

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

4979
done:
4980
    remoteDriverUnlock(priv);
4981 4982 4983
    return vol;
}

4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015
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;
}

5016 5017 5018 5019
static int
remoteStorageVolDelete (virStorageVolPtr vol,
                        unsigned int flags)
{
5020
    int rv = -1;
5021
    remote_storage_vol_delete_args args;
5022
    struct private_data *priv = vol->conn->storagePrivateData;
5023

5024 5025
    remoteDriverLock(priv);

5026 5027 5028 5029 5030 5031
    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)
5032
        goto done;
5033

5034 5035 5036
    rv = 0;

done:
5037
    remoteDriverUnlock(priv);
5038
    return rv;
5039 5040 5041 5042 5043
}

static int
remoteStorageVolGetInfo (virStorageVolPtr vol, virStorageVolInfoPtr info)
{
5044
    int rv = -1;
5045 5046
    remote_storage_vol_get_info_args args;
    remote_storage_vol_get_info_ret ret;
5047
    struct private_data *priv = vol->conn->storagePrivateData;
5048

5049 5050
    remoteDriverLock(priv);

5051 5052 5053 5054 5055 5056
    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)
5057
        goto done;
5058 5059 5060 5061 5062

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

5063 5064 5065
    rv = 0;

done:
5066
    remoteDriverUnlock(priv);
5067
    return rv;
5068 5069 5070 5071 5072 5073
}

static char *
remoteStorageVolDumpXML (virStorageVolPtr vol,
                         unsigned int flags)
{
5074
    char *rv = NULL;
5075 5076
    remote_storage_vol_dump_xml_args args;
    remote_storage_vol_dump_xml_ret ret;
5077
    struct private_data *priv = vol->conn->storagePrivateData;
5078

5079 5080
    remoteDriverLock(priv);

5081 5082 5083 5084 5085 5086 5087
    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)
5088
        goto done;
5089 5090

    /* Caller frees. */
5091 5092 5093
    rv = ret.xml;

done:
5094
    remoteDriverUnlock(priv);
5095
    return rv;
5096 5097 5098 5099 5100
}

static char *
remoteStorageVolGetPath (virStorageVolPtr vol)
{
5101
    char *rv = NULL;
5102 5103
    remote_storage_vol_get_path_args args;
    remote_storage_vol_get_path_ret ret;
5104
    struct private_data *priv = vol->conn->storagePrivateData;
5105

5106 5107
    remoteDriverLock(priv);

5108 5109 5110 5111 5112 5113
    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)
5114
        goto done;
5115 5116

    /* Caller frees. */
5117 5118 5119
    rv = ret.name;

done:
5120
    remoteDriverUnlock(priv);
5121
    return rv;
5122 5123 5124
}


5125 5126
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
5127
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
5128 5129 5130 5131
remoteDevMonOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 int flags ATTRIBUTE_UNUSED)
{
5132 5133 5134
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
5135
    if (conn->driver &&
5136
        STREQ (conn->driver->name, "remote")) {
5137
        struct private_data *priv = conn->privateData;
5138 5139 5140 5141
        /* 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
         */
5142 5143 5144 5145
        remoteDriverLock(priv);
        priv->localUses++;
        conn->devMonPrivateData = priv;
        remoteDriverUnlock(priv);
5146
        return VIR_DRV_OPEN_SUCCESS;
5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161
    } 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;
5162 5163 5164 5165 5166 5167
        int ret;
        ret = remoteOpenSecondaryDriver(conn,
                                        auth,
                                        flags,
                                        &priv);
        if (ret == VIR_DRV_OPEN_SUCCESS)
5168 5169 5170
            conn->devMonPrivateData = priv;
        return ret;
    }
5171 5172 5173 5174 5175
}

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

5178 5179 5180 5181 5182 5183 5184 5185
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        ret = doRemoteClose(conn, priv);
        conn->devMonPrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
5186
    }
5187 5188
    if (priv)
        remoteDriverUnlock(priv);
5189 5190 5191 5192 5193 5194 5195
    return ret;
}

static int remoteNodeNumOfDevices(virConnectPtr conn,
                                  const char *cap,
                                  unsigned int flags)
{
5196
    int rv = -1;
5197 5198
    remote_node_num_of_devices_args args;
    remote_node_num_of_devices_ret ret;
5199
    struct private_data *priv = conn->devMonPrivateData;
5200

5201 5202
    remoteDriverLock(priv);

5203 5204 5205 5206 5207 5208 5209
    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)
5210 5211 5212
        goto done;

    rv = ret.num;
5213

5214
done:
5215
    remoteDriverUnlock(priv);
5216
    return rv;
5217 5218 5219 5220 5221 5222 5223 5224 5225
}


static int remoteNodeListDevices(virConnectPtr conn,
                                 const char *cap,
                                 char **const names,
                                 int maxnames,
                                 unsigned int flags)
{
5226
    int rv = -1;
5227 5228 5229
    int i;
    remote_node_list_devices_args args;
    remote_node_list_devices_ret ret;
5230
    struct private_data *priv = conn->devMonPrivateData;
5231

5232 5233
    remoteDriverLock(priv);

5234 5235
    if (maxnames > REMOTE_NODE_DEVICE_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many device names requested"));
5236
        goto done;
5237 5238 5239 5240 5241 5242 5243 5244 5245
    }
    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)
5246
        goto done;
5247 5248 5249

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many device names received"));
5250
        goto cleanup;
5251 5252 5253 5254 5255 5256 5257 5258 5259 5260
    }

    /* 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]);

5261 5262 5263
    rv = ret.names.names_len;

cleanup:
5264 5265
    xdr_free ((xdrproc_t) xdr_remote_node_list_devices_ret, (char *) &ret);

5266
done:
5267
    remoteDriverUnlock(priv);
5268
    return rv;
5269 5270 5271 5272 5273 5274 5275 5276
}


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

5280 5281
    remoteDriverLock(priv);

5282 5283 5284 5285 5286 5287
    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)
5288
        goto done;
5289 5290 5291 5292 5293

    dev = get_nonnull_node_device(conn, ret.dev);

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

5294
done:
5295
    remoteDriverUnlock(priv);
5296 5297 5298 5299 5300 5301
    return dev;
}

static char *remoteNodeDeviceDumpXML(virNodeDevicePtr dev,
                                     unsigned int flags)
{
5302
    char *rv = NULL;
5303 5304
    remote_node_device_dump_xml_args args;
    remote_node_device_dump_xml_ret ret;
5305
    struct private_data *priv = dev->conn->devMonPrivateData;
5306

5307 5308
    remoteDriverLock(priv);

5309 5310 5311 5312 5313 5314 5315
    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)
5316
        goto done;
5317 5318

    /* Caller frees. */
5319 5320 5321
    rv = ret.xml;

done:
5322
    remoteDriverUnlock(priv);
5323
    return rv;
5324 5325 5326 5327
}

static char *remoteNodeDeviceGetParent(virNodeDevicePtr dev)
{
5328
    char *rv = NULL;
5329 5330
    remote_node_device_get_parent_args args;
    remote_node_device_get_parent_ret ret;
5331
    struct private_data *priv = dev->conn->devMonPrivateData;
5332

5333 5334
    remoteDriverLock(priv);

5335 5336 5337 5338 5339 5340
    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)
5341
        goto done;
5342 5343

    /* Caller frees. */
5344
    rv = ret.parent ? *ret.parent : NULL;
5345
    VIR_FREE(ret.parent);
5346 5347

done:
5348
    remoteDriverUnlock(priv);
5349
    return rv;
5350 5351 5352 5353
}

static int remoteNodeDeviceNumOfCaps(virNodeDevicePtr dev)
{
5354
    int rv = -1;
5355 5356
    remote_node_device_num_of_caps_args args;
    remote_node_device_num_of_caps_ret ret;
5357
    struct private_data *priv = dev->conn->devMonPrivateData;
5358

5359 5360
    remoteDriverLock(priv);

5361 5362 5363 5364 5365 5366
    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)
5367 5368 5369
        goto done;

    rv = ret.num;
5370

5371
done:
5372
    remoteDriverUnlock(priv);
5373
    return rv;
5374 5375 5376 5377 5378 5379
}

static int remoteNodeDeviceListCaps(virNodeDevicePtr dev,
                                    char **const names,
                                    int maxnames)
{
5380
    int rv = -1;
5381 5382 5383
    int i;
    remote_node_device_list_caps_args args;
    remote_node_device_list_caps_ret ret;
5384
    struct private_data *priv = dev->conn->devMonPrivateData;
5385

5386 5387
    remoteDriverLock(priv);

5388 5389
    if (maxnames > REMOTE_NODE_DEVICE_CAPS_LIST_MAX) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names requested"));
5390
        goto done;
5391 5392 5393 5394 5395 5396 5397 5398
    }
    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)
5399
        goto done;
5400 5401 5402

    if (ret.names.names_len > maxnames) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names received"));
5403
        goto cleanup;
5404 5405 5406 5407 5408 5409 5410 5411 5412 5413
    }

    /* 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]);

5414 5415 5416
    rv = ret.names.names_len;

cleanup:
5417 5418
    xdr_free ((xdrproc_t) xdr_remote_node_device_list_caps_ret, (char *) &ret);

5419
done:
5420
    remoteDriverUnlock(priv);
5421
    return rv;
5422 5423
}

5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 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
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;
}

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 5528 5529 5530 5531 5532 5533
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;

5534
    if (call(dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_DESTROY,
5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546
             (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;
}


5547 5548
/*----------------------------------------------------------------------*/

5549
static int
5550
remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
5551 5552 5553 5554 5555 5556
                    virConnectAuthPtr auth
#if !HAVE_SASL && !HAVE_POLKIT
                    ATTRIBUTE_UNUSED
#endif
                    ,
                    const char *authtype)
5557 5558
{
    struct remote_auth_list_ret ret;
5559
    int err, type = REMOTE_AUTH_NONE;
5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575

    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;

5576 5577 5578 5579 5580 5581 5582 5583
    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 {
5584
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5585 5586 5587
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("unknown authentication type %s"), authtype);
5588 5589 5590 5591 5592 5593 5594
            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) {
5595
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5596
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5597 5598
                             _("requested authentication type %s rejected"),
                             authtype);
5599 5600 5601 5602 5603 5604 5605
            return -1;
        }
    } else {
        type = ret.types.types_val[0];
    }

    switch (type) {
5606
#if HAVE_SASL
5607 5608 5609 5610 5611 5612 5613
    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) {
5614
            VIR_FREE(ret.types.types_val);
5615 5616 5617
            return -1;
        }
        break;
5618
    }
5619 5620
#endif

5621 5622
#if HAVE_POLKIT
    case REMOTE_AUTH_POLKIT:
5623
        if (remoteAuthPolkit(conn, priv, in_open, auth) < 0) {
5624
            VIR_FREE(ret.types.types_val);
5625 5626 5627 5628 5629
            return -1;
        }
        break;
#endif

5630 5631 5632 5633 5634
    case REMOTE_AUTH_NONE:
        /* Nothing todo, hurrah ! */
        break;

    default:
5635
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5636 5637 5638 5639
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
                         _("unsupported authentication type %d"),
                         ret.types.types_val[0]);
5640
        VIR_FREE(ret.types.types_val);
5641 5642 5643
        return -1;
    }

5644
    VIR_FREE(ret.types.types_val);
5645 5646 5647 5648 5649 5650 5651 5652

    return 0;
}



#if HAVE_SASL
/*
5653
 * NB, keep in sync with similar method in remote/remote.c
5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664
 */
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) {
5665
        virRaiseError (NULL, NULL, NULL, VIR_FROM_REMOTE,
5666 5667 5668 5669
                       VIR_ERR_UNKNOWN_HOST, VIR_ERR_ERROR,
                       NULL, NULL, NULL, 0, 0,
                       _("Cannot resolve address %d: %s"),
                       err, gai_strerror(err));
5670 5671 5672
        return NULL;
    }

5673 5674
    if (virAsprintf(&addr, "%s;%s", host, port) == -1) {
        virReportOOMError(NULL);
5675 5676 5677 5678 5679 5680 5681
        return NULL;
    }

    return addr;
}


5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 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
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)
{
5760
    sasl_callback_t *cbs;
5761
    int i, n;
5762
    if (VIR_ALLOC_N(cbs, ncredtype+1) < 0) {
5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781
        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
5782
 *
5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796
 * 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 */

5797
    if (VIR_ALLOC_N(*cred, ninteract) < 0)
5798 5799 5800 5801 5802
        return -1;

    for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
        (*cred)[ninteract].type = remoteAuthCredSASL2Vir(interact[ninteract].id);
        if (!(*cred)[ninteract].type) {
5803
            VIR_FREE(*cred);
5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821
            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++)
5822 5823
        VIR_FREE(cred[i].result);
    VIR_FREE(cred);
5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844
}


/*
 * @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
5845 5846
 */
static int
5847 5848
remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                virConnectAuthPtr auth, const char *wantmech)
5849 5850
{
    sasl_conn_t *saslconn = NULL;
5851
    sasl_security_properties_t secprops;
5852 5853 5854 5855 5856 5857
    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;
5858
    char *serverin = NULL;
5859 5860 5861 5862 5863
    unsigned int clientoutlen, serverinlen;
    const char *mech;
    int err, complete;
    struct sockaddr_storage sa;
    socklen_t salen;
5864
    char *localAddr = NULL, *remoteAddr = NULL;
5865 5866
    const void *val;
    sasl_ssf_t ssf;
5867 5868 5869 5870 5871 5872
    sasl_callback_t *saslcb = NULL;
    sasl_interact_t *interact = NULL;
    virConnectCredentialPtr cred = NULL;
    int ncred = 0;
    int ret = -1;
    const char *mechlist;
5873

5874
    DEBUG0("Client initialize SASL authentication");
5875 5876 5877
    /* Sets up the SASL library as a whole */
    err = sasl_client_init(NULL);
    if (err != SASL_OK) {
5878
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5879
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5880
                         _("failed to initialize SASL library: %d (%s)"),
5881
                         err, sasl_errstring(err, NULL, NULL));
5882
        goto cleanup;
5883 5884 5885 5886 5887
    }

    /* Get local address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getsockname(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
5888 5889
        virReportSystemError(in_open ? NULL : conn, errno, "%s",
                             _("failed to get sock address"));
5890
        goto cleanup;
5891
    }
5892 5893
    if ((localAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;
5894 5895 5896 5897

    /* Get remote address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getpeername(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
5898 5899
        virReportSystemError(in_open ? NULL : conn, errno, "%s",
                             _("failed to get peer address"));
5900
        goto cleanup;
5901
    }
5902 5903 5904
    if ((remoteAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;

5905 5906 5907 5908 5909 5910
    if (auth) {
        if ((saslcb = remoteAuthMakeCallbacks(auth->credtype, auth->ncredtype)) == NULL)
            goto cleanup;
    } else {
        saslcb = NULL;
    }
5911 5912 5913 5914 5915 5916

    /* Setup a handle for being a client */
    err = sasl_client_new("libvirt",
                          priv->hostname,
                          localAddr,
                          remoteAddr,
5917
                          saslcb,
5918 5919
                          SASL_SUCCESS_DATA,
                          &saslconn);
5920

5921
    if (err != SASL_OK) {
5922
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5923
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5924
                         _("Failed to create SASL client context: %d (%s)"),
5925
                         err, sasl_errstring(err, NULL, NULL));
5926
        goto cleanup;
5927 5928
    }

5929 5930 5931 5932 5933 5934
    /* 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))) {
5935
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5936
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5937
                             "%s", _("invalid cipher size for TLS session"));
5938
            goto cleanup;
5939 5940 5941
        }
        ssf *= 8; /* key size is bytes, sasl wants bits */

5942
        DEBUG("Setting external SSF %d", ssf);
5943 5944
        err = sasl_setprop(saslconn, SASL_SSF_EXTERNAL, &ssf);
        if (err != SASL_OK) {
5945
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5946
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5947
                             _("cannot set external SSF %d (%s)"),
5948
                             err, sasl_errstring(err, NULL, NULL));
5949
            goto cleanup;
5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963
        }
    }

    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) {
5964
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5965
                         VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5966
                         _("cannot set security props %d (%s)"),
5967
                         err, sasl_errstring(err, NULL, NULL));
5968
        goto cleanup;
5969 5970
    }

5971 5972 5973 5974
    /* 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,
5975 5976
              (xdrproc_t) xdr_remote_auth_sasl_init_ret, (char *) &iret) != 0)
        goto cleanup;
5977 5978


5979 5980 5981
    mechlist = iret.mechlist;
    if (wantmech) {
        if (strstr(mechlist, wantmech) == NULL) {
5982
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5983 5984 5985 5986
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("SASL mechanism %s not supported by server"),
                             wantmech);
5987
            VIR_FREE(iret.mechlist);
5988 5989 5990 5991 5992
            goto cleanup;
        }
        mechlist = wantmech;
    }
 restart:
5993
    /* Start the auth negotiation on the client end first */
5994
    DEBUG("Client start negotiation mechlist '%s'", mechlist);
5995
    err = sasl_client_start(saslconn,
5996 5997
                            mechlist,
                            &interact,
5998 5999 6000
                            &clientout,
                            &clientoutlen,
                            &mech);
6001
    if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
6002
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6003
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6004
                         _("Failed to start SASL negotiation: %d (%s)"),
6005
                         err, sasl_errdetail(saslconn));
6006
        VIR_FREE(iret.mechlist);
6007 6008 6009 6010 6011
        goto cleanup;
    }

    /* Need to gather some credentials from the client */
    if (err == SASL_INTERACT) {
6012
        const char *msg;
6013 6014 6015 6016 6017 6018
        if (cred) {
            remoteAuthFreeCredentials(cred, ncred);
            cred = NULL;
        }
        if ((ncred =
             remoteAuthMakeCredentials(interact, &cred)) < 0) {
6019
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6020 6021 6022
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             "%s", _("Failed to make auth credentials"));
6023
            VIR_FREE(iret.mechlist);
6024 6025 6026
            goto cleanup;
        }
        /* Run the authentication callback */
6027
        if (auth && auth->cb) {
6028 6029 6030
            if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                remoteAuthFillInteract(cred, interact);
                goto restart;
6031
            }
6032
            msg = "Failed to collect auth credentials";
6033
        } else {
6034
            msg = "No authentication callback available";
6035
        }
6036
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6037
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
6038
                         0, 0, "%s", msg);
6039
        goto cleanup;
6040
    }
6041
    VIR_FREE(iret.mechlist);
6042 6043

    if (clientoutlen > REMOTE_AUTH_SASL_DATA_MAX) {
6044
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6045
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6046 6047
                         _("SASL negotiation data too long: %d bytes"),
                         clientoutlen);
6048
        goto cleanup;
6049 6050 6051 6052 6053 6054 6055
    }
    /* 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;
6056
    DEBUG("Server start negotiation with mech %s. Data %d bytes %p", mech, clientoutlen, clientout);
6057 6058 6059 6060 6061

    /* 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,
6062 6063
              (xdrproc_t) xdr_remote_auth_sasl_start_ret, (char *) &sret) != 0)
        goto cleanup;
6064 6065 6066 6067 6068

    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;
6069 6070
    DEBUG("Client step result complete: %d. Data %d bytes %p",
          complete, serverinlen, serverin);
6071 6072 6073

    /* Loop-the-loop...
     * Even if the server has completed, the client must *always* do at least one step
D
Daniel Veillard 已提交
6074
     * in this loop to verify the server isn't lying about something. Mutual auth */
6075
    for (;;) {
6076
    restep:
6077 6078 6079
        err = sasl_client_step(saslconn,
                               serverin,
                               serverinlen,
6080
                               &interact,
6081 6082
                               &clientout,
                               &clientoutlen);
6083
        if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
6084
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6085
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6086
                             _("Failed SASL step: %d (%s)"),
6087
                             err, sasl_errdetail(saslconn));
6088 6089 6090 6091
            goto cleanup;
        }
        /* Need to gather some credentials from the client */
        if (err == SASL_INTERACT) {
6092
            const char *msg;
6093 6094 6095 6096 6097
            if (cred) {
                remoteAuthFreeCredentials(cred, ncred);
                cred = NULL;
            }
            if ((ncred = remoteAuthMakeCredentials(interact, &cred)) < 0) {
6098
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6099
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6100
                                 "%s", _("Failed to make auth credentials"));
6101 6102 6103
                goto cleanup;
            }
            /* Run the authentication callback */
6104
            if (auth && auth->cb) {
6105 6106 6107
                if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                    remoteAuthFillInteract(cred, interact);
                    goto restep;
6108
                }
6109
                msg = "Failed to collect auth credentials";
6110
            } else {
6111
                msg = "No authentication callback available";
6112
            }
6113
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6114
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
6115
                             0, 0, "%s", msg);
6116
            goto cleanup;
6117 6118
        }

6119
        VIR_FREE(serverin);
6120
        DEBUG("Client step result %d. Data %d bytes %p", err, clientoutlen, clientout);
6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131

        /* 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;
6132
        DEBUG("Server step with %d bytes %p", clientoutlen, clientout);
6133 6134 6135 6136

        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,
6137 6138
                  (xdrproc_t) xdr_remote_auth_sasl_step_ret, (char *) &pret) != 0)
            goto cleanup;
6139 6140 6141 6142 6143 6144

        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;

6145 6146
        DEBUG("Client step result complete: %d. Data %d bytes %p",
              complete, serverinlen, serverin);
6147 6148 6149

        /* This server call shows complete, and earlier client step was OK */
        if (complete && err == SASL_OK) {
6150
            VIR_FREE(serverin);
6151 6152 6153 6154
            break;
        }
    }

6155 6156 6157 6158
    /* Check for suitable SSF if non-TLS */
    if (!priv->uses_tls) {
        err = sasl_getprop(saslconn, SASL_SSF, &val);
        if (err != SASL_OK) {
6159
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6160
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6161
                             _("cannot query SASL ssf on connection %d (%s)"),
6162
                             err, sasl_errstring(err, NULL, NULL));
6163
            goto cleanup;
6164 6165
        }
        ssf = *(const int *)val;
6166
        DEBUG("SASL SSF value %d", ssf);
6167
        if (ssf < 56) { /* 56 == DES level, good for Kerberos */
6168
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6169
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
6170
                             _("negotiation SSF %d was not strong enough"), ssf);
6171
            goto cleanup;
6172 6173 6174
        }
    }

6175
    DEBUG0("SASL authentication complete");
6176
    priv->saslconn = saslconn;
6177 6178 6179
    ret = 0;

 cleanup:
6180 6181 6182
    VIR_FREE(localAddr);
    VIR_FREE(remoteAddr);
    VIR_FREE(serverin);
6183

6184
    VIR_FREE(saslcb);
6185 6186 6187
    remoteAuthFreeCredentials(cred, ncred);
    if (ret != 0 && saslconn)
        sasl_dispose(&saslconn);
6188

6189
    return ret;
6190 6191 6192
}
#endif /* HAVE_SASL */

6193 6194

#if HAVE_POLKIT
6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213
#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
6214 6215 6216 6217 6218 6219 6220
/* Perform the PolicyKit authentication process
 */
static int
remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                  virConnectAuthPtr auth)
{
    remote_auth_polkit_ret ret;
6221
    int i, allowcb = 0;
6222 6223 6224 6225 6226 6227 6228 6229
    virConnectCredential cred = {
        VIR_CRED_EXTERNAL,
        conn->flags & VIR_CONNECT_RO ? "org.libvirt.unix.monitor" : "org.libvirt.unix.manage",
        "PolicyKit",
        NULL,
        NULL,
        0,
    };
6230
    DEBUG0("Client initialize PolicyKit-0 authentication");
6231

6232
    if (auth && auth->cb) {
6233
        /* Check if the necessary credential type for PolicyKit is supported */
6234 6235 6236 6237
        for (i = 0 ; i < auth->ncredtype ; i++) {
            if (auth->credtype[i] == VIR_CRED_EXTERNAL)
                allowcb = 1;
        }
6238

6239
        if (allowcb) {
6240
            DEBUG0("Client run callback for PolicyKit authentication");
6241 6242
            /* Run the authentication callback */
            if ((*(auth->cb))(&cred, 1, auth->cbdata) < 0) {
6243
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
6244
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
J
Jim Meyering 已提交
6245
                                 "%s", _("Failed to collect auth credentials"));
6246 6247
                return -1;
            }
6248
        } else {
6249
            DEBUG0("Client auth callback does not support PolicyKit");
6250 6251
        }
    } else {
6252
        DEBUG0("No auth callback provided");
6253 6254 6255 6256 6257 6258 6259 6260 6261
    }

    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 */
    }

6262
    DEBUG0("PolicyKit-0 authentication complete");
6263 6264
    return 0;
}
6265
#endif /* HAVE_POLKIT0 */
6266
#endif /* HAVE_POLKIT */
6267 6268 6269
/*----------------------------------------------------------------------*/

static int remoteDomainEventRegister (virConnectPtr conn,
6270 6271
                                      virConnectDomainEventCallback callback,
                                      void *opaque,
6272
                                      virFreeCallback freecb)
6273
{
6274
    int rv = -1;
6275 6276
    struct private_data *priv = conn->privateData;

6277 6278
    remoteDriverLock(priv);

6279 6280
    if (priv->eventFlushTimer < 0) {
         error (conn, VIR_ERR_NO_SUPPORT, _("no event support"));
6281
         goto done;
6282
    }
6283
    if (virDomainEventCallbackListAdd(conn, priv->callbackList,
6284
                                      callback, opaque, freecb) < 0) {
6285
         error (conn, VIR_ERR_RPC, _("adding cb to list"));
6286
         goto done;
6287 6288 6289 6290 6291 6292 6293
    }

    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)
6294
            goto done;
6295 6296
    }

6297 6298 6299
    rv = 0;

done:
6300
    remoteDriverUnlock(priv);
6301
    return rv;
6302 6303 6304
}

static int remoteDomainEventDeregister (virConnectPtr conn,
6305
                                        virConnectDomainEventCallback callback)
6306 6307
{
    struct private_data *priv = conn->privateData;
6308
    int rv = -1;
6309

6310 6311
    remoteDriverLock(priv);

6312 6313 6314 6315
    if (priv->domainEventDispatching) {
        if (virDomainEventCallbackListMarkDelete(conn, priv->callbackList,
                                                 callback) < 0) {
            error (conn, VIR_ERR_RPC, _("marking cb for deletion"));
6316
            goto done;
6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331
        }
    } 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;
        }
6332 6333
    }

6334 6335 6336
    rv = 0;

done:
6337
    remoteDriverUnlock(priv);
6338
    return rv;
6339
}
6340

J
Jim Meyering 已提交
6341
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
6342 6343 6344 6345 6346 6347 6348
remoteSecretOpen (virConnectPtr conn,
                  virConnectAuthPtr auth,
                  int flags)
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
6349
    if (conn->driver &&
6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 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
        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
6478
remoteSecretLookupByUUID (virConnectPtr conn, const unsigned char *uuid)
6479 6480
{
    virSecretPtr rv = NULL;
6481 6482
    remote_secret_lookup_by_uuid_args args;
    remote_secret_lookup_by_uuid_ret ret;
6483 6484 6485 6486
    struct private_data *priv = conn->secretPrivateData;

    remoteDriverLock (priv);

6487
    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);
6488 6489

    memset (&ret, 0, sizeof (ret));
6490 6491 6492
    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)
6493 6494 6495
        goto done;

    rv = get_nonnull_secret (conn, ret.secret);
6496
    xdr_free ((xdrproc_t) xdr_remote_secret_lookup_by_uuid_ret,
6497 6498 6499 6500 6501 6502 6503
              (char *) &ret);

done:
    remoteDriverUnlock (priv);
    return rv;
}

6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531
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;
}

6532 6533 6534 6535 6536
static virSecretPtr
remoteSecretDefineXML (virConnectPtr conn, const char *xml, unsigned int flags)
{
    virSecretPtr rv = NULL;
    remote_secret_define_xml_args args;
6537
    remote_secret_define_xml_ret ret;
6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551
    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);
6552
    xdr_free ((xdrproc_t) xdr_remote_secret_define_xml_ret,
6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 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
              (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;
}

6665 6666
/*----------------------------------------------------------------------*/

6667

6668 6669 6670 6671 6672 6673 6674 6675
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)
{
6676
    XDR xdr;
6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689
    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;
    }
6690 6691

    /* Get a unique serial number for this message. */
6692 6693 6694 6695
    rv->serial = priv->counter++;
    rv->proc_nr = proc_nr;
    rv->ret_filter = ret_filter;
    rv->ret = ret;
6696 6697 6698 6699

    hdr.prog = REMOTE_PROGRAM;
    hdr.vers = REMOTE_PROTOCOL_VERSION;
    hdr.proc = proc_nr;
6700
    hdr.type = REMOTE_CALL;
6701
    hdr.serial = rv->serial;
6702 6703 6704
    hdr.status = REMOTE_OK;

    /* Serialise header followed by args. */
6705
    xdrmem_create (&xdr, rv->buffer+4, REMOTE_MESSAGE_MAX, XDR_ENCODE);
6706
    if (!xdr_remote_message_header (&xdr, &hdr)) {
6707
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
6708
               VIR_ERR_RPC, _("xdr_remote_message_header failed"));
6709
        goto error;
6710 6711 6712
    }

    if (!(*args_filter) (&xdr, args)) {
6713 6714
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
               _("marshalling args"));
6715
        goto error;
6716 6717 6718
    }

    /* Get the length stored in buffer. */
6719
    rv->bufferLength = xdr_getpos (&xdr);
6720 6721 6722 6723 6724
    xdr_destroy (&xdr);

    /* Length must include the length word itself (always encoded in
     * 4 bytes as per RFC 4506).
     */
6725
    rv->bufferLength += REMOTE_MESSAGE_HEADER_XDR_LEN;
6726 6727

    /* Encode the length word. */
6728 6729
    xdrmem_create (&xdr, rv->buffer, REMOTE_MESSAGE_HEADER_XDR_LEN, XDR_ENCODE);
    if (!xdr_u_int (&xdr, &rv->bufferLength)) {
6730
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
6731
               _("xdr_u_int (length word)"));
6732
        goto error;
6733 6734 6735
    }
    xdr_destroy (&xdr);

6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746
    return rv;

error:
    xdr_destroy (&xdr);
    VIR_FREE(rv);
    return NULL;
}



static int
6747 6748 6749 6750
remoteIOWriteBuffer(virConnectPtr conn,
                    struct private_data *priv,
                    int in_open /* if we are in virConnectOpen */,
                    const char *bytes, int len)
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
{
    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;

6776 6777
            virReportSystemError(in_open ? NULL : conn, errno,
                                 "%s", _("cannot send data"));
6778 6779 6780 6781 6782 6783 6784 6785 6786 6787
            return -1;

        }
    }

    return ret;
}


static int
6788 6789 6790 6791
remoteIOReadBuffer(virConnectPtr conn,
                   struct private_data *priv,
                   int in_open /* if we are in virConnectOpen */,
                   char *bytes, int len)
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
{
    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;

6826 6827
                virReportSystemError(in_open ? NULL : conn, errno,
                                     "%s", _("cannot recv data"));
6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841
            } else {
                errorf (in_open ? NULL : conn,
                        VIR_ERR_SYSTEM_ERROR,
                        "%s", _("server closed connection"));
            }
            return -1;
        }
    }

    return ret;
}


static int
6842 6843 6844 6845
remoteIOWriteMessage(virConnectPtr conn,
                     struct private_data *priv,
                     int in_open,
                     struct remote_thread_call *thecall)
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
{
#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;
        }

6871 6872 6873
        ret = remoteIOWriteBuffer(conn, priv, in_open,
                                  priv->saslEncoded + priv->saslEncodedOffset,
                                  priv->saslEncodedLength - priv->saslEncodedOffset);
6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885
        if (ret < 0)
            return ret;
        priv->saslEncodedOffset += ret;

        if (priv->saslEncodedOffset == priv->saslEncodedLength) {
            priv->saslEncoded = NULL;
            priv->saslEncodedOffset = priv->saslEncodedLength = 0;
            thecall->mode = REMOTE_MODE_WAIT_RX;
        }
    } else {
#endif
        int ret;
6886 6887 6888
        ret = remoteIOWriteBuffer(conn, priv, in_open,
                                  thecall->buffer + thecall->bufferOffset,
                                  thecall->bufferLength - thecall->bufferOffset);
6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904
        if (ret < 0)
            return ret;
        thecall->bufferOffset += ret;

        if (thecall->bufferOffset == thecall->bufferLength) {
            thecall->bufferOffset = thecall->bufferLength = 0;
            thecall->mode = REMOTE_MODE_WAIT_RX;
        }
#if HAVE_SASL
    }
#endif
    return 0;
}


static int
6905 6906
remoteIOHandleOutput(virConnectPtr conn, struct private_data *priv,
                     int in_open) {
6907 6908 6909 6910 6911 6912 6913 6914 6915 6916
    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) {
6917
        int ret = remoteIOWriteMessage(conn, priv, in_open, thecall);
6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930
        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
6931
remoteIOReadMessage(virConnectPtr conn, struct private_data *priv,
6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946
                    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];
            unsigned int encodedLen = sizeof(encoded);
            int ret, err;
6947 6948
            ret = remoteIOReadBuffer(conn, priv, in_open,
                                     encoded, encodedLen);
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
            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;

6983 6984 6985
        ret = remoteIOReadBuffer(conn, priv, in_open,
                                 priv->buffer + priv->bufferOffset,
                                 wantData);
6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;

        priv->bufferOffset += ret;

        return ret;
#if HAVE_SASL
    }
#endif
}
6998 6999


7000
static int
7001 7002
remoteIODecodeMessageLength(virConnectPtr conn, struct private_data *priv,
                            int in_open) {
7003
    XDR xdr;
7004
    unsigned int len;
7005 7006

    xdrmem_create (&xdr, priv->buffer, priv->bufferLength, XDR_DECODE);
7007
    if (!xdr_u_int (&xdr, &len)) {
7008
        error (in_open ? NULL : conn,
7009
               VIR_ERR_RPC, _("xdr_u_int (length word, reply)"));
7010 7011 7012 7013
        return -1;
    }
    xdr_destroy (&xdr);

7014 7015 7016 7017 7018 7019
    if (len < REMOTE_MESSAGE_HEADER_XDR_LEN) {
        error (in_open ? NULL : conn,
               VIR_ERR_RPC, _("packet received from server too small"));
        return -1;
    }

7020
    /* Length includes length word - adjust to real length to read. */
7021
    len -= REMOTE_MESSAGE_HEADER_XDR_LEN;
7022

7023
    if (len > REMOTE_MESSAGE_MAX) {
7024
        error (in_open ? NULL : conn,
7025
               VIR_ERR_RPC, _("packet received from server too large"));
7026 7027 7028
        return -1;
    }

7029 7030 7031 7032 7033 7034 7035 7036 7037
    /* 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
7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052
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);


static int
processCallDispatch(virConnectPtr conn, struct private_data *priv,
                    int in_open) {
7053 7054 7055
    XDR xdr;
    struct remote_message_header hdr;
    int len = priv->bufferLength - 4;
7056
    int rv = -1;
7057 7058

    /* Deserialise reply header. */
7059
    xdrmem_create (&xdr, priv->buffer + 4, len, XDR_DECODE);
7060
    if (!xdr_remote_message_header (&xdr, &hdr)) {
7061
        error (in_open ? NULL : conn,
7062
               VIR_ERR_RPC, _("invalid header in reply"));
7063 7064 7065 7066 7067
        return -1;
    }

    /* Check program, version, etc. are what we expect. */
    if (hdr.prog != REMOTE_PROGRAM) {
7068 7069 7070 7071 7072
        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);
7073 7074 7075
        return -1;
    }
    if (hdr.vers != REMOTE_PROTOCOL_VERSION) {
7076 7077 7078 7079 7080
        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);
7081 7082 7083
        return -1;
    }

7084 7085 7086 7087 7088
    switch (hdr.type) {
    case REMOTE_REPLY: /* Normal RPC replies */
        rv = processCallDispatchReply(conn, priv, in_open,
                                      &hdr, &xdr);
        break;
7089

7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102
    case REMOTE_MESSAGE: /* Async notifications */
        rv = processCallDispatchMessage(conn, priv, in_open,
                                        &hdr, &xdr);
        break;

    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;
7103
    }
7104

7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116
    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;

7117 7118 7119 7120
    /* Ok, definitely got an RPC reply now find
       out who's been waiting for it */
    thecall = priv->waitDispatch;
    while (thecall &&
7121
           thecall->serial != hdr->serial)
7122 7123 7124 7125 7126 7127 7128
        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"),
7129
                       hdr->serial);
7130 7131
        return -1;
    }
7132

7133
    if (hdr->proc != thecall->proc_nr) {
7134 7135 7136 7137
        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)"),
7138
                       hdr->proc, thecall->proc_nr);
7139 7140 7141 7142 7143 7144 7145
        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).
     */
7146
    switch (hdr->status) {
7147
    case REMOTE_OK:
7148
        if (!(*thecall->ret_filter) (xdr, thecall->ret)) {
7149
            error (in_open ? NULL : conn, VIR_ERR_RPC,
7150
                   _("unmarshalling ret"));
7151 7152
            return -1;
        }
7153
        thecall->mode = REMOTE_MODE_COMPLETE;
7154 7155 7156
        return 0;

    case REMOTE_ERROR:
7157
        memset (&thecall->err, 0, sizeof thecall->err);
7158
        if (!xdr_remote_error (xdr, &thecall->err)) {
7159
            error (in_open ? NULL : conn,
7160
                   VIR_ERR_RPC, _("unmarshalling remote_error"));
7161 7162
            return -1;
        }
7163 7164
        thecall->mode = REMOTE_MODE_ERROR;
        return 0;
7165 7166

    default:
7167 7168 7169
        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)"),
7170
                       hdr->status);
7171 7172 7173 7174
        return -1;
    }
}

7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199
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;
}

7200 7201

static int
7202 7203
remoteIOHandleInput(virConnectPtr conn, struct private_data *priv,
                    int in_open)
7204
{
7205
    /* Read as much data as is available, until we get
7206
     * EAGAIN
7207
     */
7208
    for (;;) {
7209
        int ret = remoteIOReadMessage(conn, priv, in_open);
7210

7211 7212 7213 7214
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;  /* Blocking on read */
7215

7216 7217 7218
        /* Check for completion of our goal */
        if (priv->bufferOffset == priv->bufferLength) {
            if (priv->bufferOffset == 4) {
7219
                ret = remoteIODecodeMessageLength(conn, priv, in_open);
7220 7221 7222 7223 7224 7225 7226 7227 7228
                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.
                 */
7229
            } else {
7230
                ret = processCallDispatch(conn, priv, in_open);
7231
                priv->bufferOffset = priv->bufferLength = 0;
7232 7233 7234 7235 7236 7237 7238 7239
                /*
                 * 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;
7240 7241 7242
            }
        }
    }
7243 7244
}

7245 7246 7247 7248 7249
/*
 * Process all calls pending dispatch/receive until we
 * get a reply to our own call. Then quit and pass the buck
 * to someone else.
 */
7250
static int
7251 7252 7253 7254
remoteIOEventLoop(virConnectPtr conn,
                  struct private_data *priv,
                  int in_open,
                  struct remote_thread_call *thiscall)
7255
{
7256 7257
    struct pollfd fds[2];
    int ret;
7258

7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297
    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;
        }

        /* 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;
7298 7299
            virReportSystemError(in_open ? NULL : conn, errno,
                                 "%s", _("poll on socket failed"));
7300
            goto error;
7301 7302 7303
        }

        if (fds[0].revents & POLLOUT) {
7304
            if (remoteIOHandleOutput(conn, priv, in_open) < 0)
7305
                goto error;
7306
        }
7307 7308

        if (fds[0].revents & POLLIN) {
7309
            if (remoteIOHandleInput(conn, priv, in_open) < 0)
7310
                goto error;
7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334
        }

        /* 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);
7335
            }
7336 7337
            prev = tmp;
            tmp = tmp->next;
7338 7339
        }

7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355
        /* 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;
        }
7356

7357 7358 7359 7360

        if (fds[0].revents & (POLLHUP | POLLERR)) {
            errorf(in_open ? NULL : conn, VIR_ERR_INTERNAL_ERROR,
                   "%s", _("received hangup / error event on socket"));
7361
            goto error;
7362 7363
        }
    }
7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375


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;
7376 7377
}

7378
/*
7379
 * This function sends a message to remote server and awaits a reply
7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410
 *
 * 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!
 */
7411
static int
7412 7413 7414 7415
remoteIO(virConnectPtr conn,
         struct private_data *priv,
         int flags,
         struct remote_thread_call *thiscall)
7416
{
7417 7418
    int rv;

7419 7420 7421
    DEBUG("Do proc=%d serial=%d length=%d wait=%p",
          thiscall->proc_nr, thiscall->serial,
          thiscall->bufferLength, priv->waitDispatch);
7422

7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433
    /* 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;
7434

7435 7436
        /* Force other thread to wakup from poll */
        safewrite(priv->wakeupSendFD, &ignore, sizeof(ignore));
7437

7438
        DEBUG("Going to sleep %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455
        /* 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);
7456
            return -1;
7457
        }
7458

7459
        DEBUG("Wokeup from sleep %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473
        /* 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;
7474
        }
7475 7476 7477

        /* Grr, someone passed the buck onto us ... */

7478
    } else {
7479 7480 7481 7482
        /* We're first to catch the buck */
        priv->waitDispatch = thiscall;
    }

7483
    DEBUG("We have the buck %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500
    /*
     * 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);

7501 7502 7503
    rv = remoteIOEventLoop(conn, priv,
                           flags & REMOTE_CALL_IN_OPEN ? 1 : 0,
                           thiscall);
7504 7505 7506 7507 7508 7509 7510 7511 7512 7513

    if (priv->watch >= 0)
        virEventUpdateHandle(priv->watch, VIR_EVENT_HANDLE_READABLE);

    if (rv < 0) {
        VIR_FREE(thiscall);
        return -1;
    }

cleanup:
7514
    DEBUG("All done with our call %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
7515 7516 7517 7518 7519 7520 7521
    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 &&
7522
            thiscall->err.message &&
7523 7524 7525
            STRPREFIX(*thiscall->err.message, "unknown procedure")) {
            rv = -2;
        } else {
7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536
            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);
7537
            rv = -1;
7538
        }
7539
        xdr_free((xdrproc_t)xdr_remote_error,  (char *)&thiscall->err);
7540 7541
    } else {
        rv = 0;
7542
    }
7543 7544 7545
    VIR_FREE(thiscall);
    return rv;
}
7546

7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574

/*
 * 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);
}



7575 7576 7577 7578 7579 7580 7581 7582
/**
 * remoteDomainReadEvent
 *
 * Read the event data off the wire
 */
static virDomainEventPtr
remoteDomainReadEvent(virConnectPtr conn, XDR *xdr)
{
7583
    remote_domain_event_msg msg;
7584 7585
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
7586
    memset (&msg, 0, sizeof msg);
7587 7588

    /* unmarshall parameters, and process it*/
7589
    if (! xdr_remote_domain_event_msg(xdr, &msg) ) {
7590
        error (conn, VIR_ERR_RPC,
7591
               _("remoteDomainProcessEvent: unmarshalling msg"));
7592 7593 7594
        return NULL;
    }

7595
    dom = get_nonnull_domain(conn,msg.dom);
7596 7597 7598
    if (!dom)
        return NULL;

7599
    event = virDomainEventNewFromDom(dom, msg.event, msg.detail);
7600 7601 7602

    virDomainFree(dom);
    return event;
7603 7604
}

7605 7606
static void
remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr)
7607
{
7608 7609
    struct private_data *priv = conn->privateData;
    virDomainEventPtr event;
7610

7611 7612 7613
    event = remoteDomainReadEvent(conn, xdr);
    if (!event)
        return;
7614

7615 7616 7617 7618 7619
    if (virDomainEventQueuePush(priv->domainEvents,
                                event) < 0) {
        DEBUG0("Error adding event to queue");
        virDomainEventFree(event);
    }
7620 7621
}

7622 7623 7624 7625 7626 7627 7628 7629 7630 7631
/** remoteDomainEventFired:
 *
 * The callback for monitoring the remote socket
 * for event data
 */
void
remoteDomainEventFired(int watch,
                       int fd,
                       int event,
                       void *opaque)
7632
{
7633 7634
    virConnectPtr        conn = opaque;
    struct private_data *priv = conn->privateData;
7635

7636
    remoteDriverLock(priv);
7637

7638 7639 7640
    /* This should be impossible, but it doesn't hurt to check */
    if (priv->waitDispatch)
        goto done;
7641

7642
    DEBUG("Event fired %d %d %d %X", watch, fd, event, event);
7643

7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657
    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;
    }

7658
    if (remoteIOHandleInput(conn, priv, 0) < 0)
7659 7660 7661 7662
        DEBUG0("Something went wrong during async message processing");

done:
    remoteDriverUnlock(priv);
7663 7664
}

7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678
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);
}

7679 7680
void
remoteDomainEventQueueFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
7681
{
7682 7683
    virConnectPtr conn = opaque;
    struct private_data *priv = conn->privateData;
7684
    virDomainEventQueue tempQueue;
7685 7686 7687

    remoteDriverLock(priv);

7688 7689 7690 7691 7692 7693 7694 7695 7696 7697
    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);
7698 7699
    virEventUpdateTimeout(priv->eventFlushTimer, -1);

7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712
    /* 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;

7713
    remoteDriverUnlock(priv);
7714 7715
}

7716

7717 7718
/* get_nonnull_domain and get_nonnull_network turn an on-wire
 * (name, uuid) pair into virDomainPtr or virNetworkPtr object.
7719
 * These can return NULL if underlying memory allocations fail,
7720
 * but if they do then virterror_internal.has been set.
7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736
 */
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 已提交
7737
static virInterfacePtr
7738
get_nonnull_interface (virConnectPtr conn, remote_nonnull_interface iface)
D
Daniel Veillard 已提交
7739
{
7740
    return virGetInterface (conn, iface.name, iface.mac);
D
Daniel Veillard 已提交
7741 7742
}

7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754
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);
}

7755 7756 7757 7758 7759 7760
static virNodeDevicePtr
get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev)
{
    return virGetNodeDevice(conn, dev.name);
}

7761 7762 7763
static virSecretPtr
get_nonnull_secret (virConnectPtr conn, remote_nonnull_secret secret)
{
7764
    return virGetSecret(conn, BAD_CAST secret.uuid, secret.usageType, secret.usageID);
7765 7766
}

7767 7768 7769 7770
/* Make remote_nonnull_domain and remote_nonnull_network. */
static void
make_nonnull_domain (remote_nonnull_domain *dom_dst, virDomainPtr dom_src)
{
7771
    dom_dst->id = dom_src->id;
7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782
    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 已提交
7783 7784 7785 7786 7787 7788 7789 7790
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;
}

7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805
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;
}

7806 7807 7808
static void
make_nonnull_secret (remote_nonnull_secret *secret_dst, virSecretPtr secret_src)
{
7809
    memcpy (secret_dst->uuid, secret_src->uuid, VIR_UUID_BUFLEN);
7810 7811
    secret_dst->usageType = secret_src->usageType;
    secret_dst->usageID = secret_src->usageID;
7812 7813
}

7814 7815
/*----------------------------------------------------------------------*/

7816 7817 7818 7819 7820
unsigned long remoteVersion(void)
{
    return REMOTE_PROTOCOL_VERSION;
}

7821
static virDriver remote_driver = {
7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858
    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 */
7859 7860
    remoteDomainXMLFromNative, /* domainXMLFromNative */
    remoteDomainXMLToNative, /* domainXMLToNative */
7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888
    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 */
7889 7890 7891
};

static virNetworkDriver network_driver = {
7892
    .name = "remote",
7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911
    .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 已提交
7912 7913 7914 7915 7916 7917
static virInterfaceDriver interface_driver = {
    .name = "remote",
    .open = remoteInterfaceOpen,
    .close = remoteInterfaceClose,
    .numOfInterfaces = remoteNumOfInterfaces,
    .listInterfaces = remoteListInterfaces,
7918 7919
    .numOfDefinedInterfaces = remoteNumOfDefinedInterfaces,
    .listDefinedInterfaces = remoteListDefinedInterfaces,
D
Daniel Veillard 已提交
7920 7921 7922 7923 7924 7925 7926 7927 7928
    .interfaceLookupByName = remoteInterfaceLookupByName,
    .interfaceLookupByMACString = remoteInterfaceLookupByMACString,
    .interfaceGetXMLDesc = remoteInterfaceGetXMLDesc,
    .interfaceDefineXML = remoteInterfaceDefineXML,
    .interfaceUndefine = remoteInterfaceUndefine,
    .interfaceCreate = remoteInterfaceCreate,
    .interfaceDestroy = remoteInterfaceDestroy,
};

7929 7930 7931 7932 7933 7934 7935 7936
static virStorageDriver storage_driver = {
    .name = "remote",
    .open = remoteStorageOpen,
    .close = remoteStorageClose,
    .numOfPools = remoteNumOfStoragePools,
    .listPools = remoteListStoragePools,
    .numOfDefinedPools = remoteNumOfDefinedStoragePools,
    .listDefinedPools = remoteListDefinedStoragePools,
7937
    .findPoolSources = remoteFindStoragePoolSources,
7938
    .poolLookupByName = remoteStoragePoolLookupByName,
7939
    .poolLookupByUUID = remoteStoragePoolLookupByUUID,
7940 7941 7942
    .poolLookupByVolume = remoteStoragePoolLookupByVolume,
    .poolCreateXML = remoteStoragePoolCreateXML,
    .poolDefineXML = remoteStoragePoolDefineXML,
7943
    .poolBuild = remoteStoragePoolBuild,
7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959
    .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,
7960
    .volCreateXMLFrom = remoteStorageVolCreateXMLFrom,
7961 7962 7963 7964 7965 7966
    .volDelete = remoteStorageVolDelete,
    .volGetInfo = remoteStorageVolGetInfo,
    .volGetXMLDesc = remoteStorageVolDumpXML,
    .volGetPath = remoteStorageVolGetPath,
};

7967 7968 7969 7970 7971 7972
static virSecretDriver secret_driver = {
    .name = "remote",
    .open = remoteSecretOpen,
    .close = remoteSecretClose,
    .numOfSecrets = remoteSecretNumOfSecrets,
    .listSecrets = remoteSecretListSecrets,
7973
    .lookupByUUID = remoteSecretLookupByUUID,
7974
    .lookupByUsage = remoteSecretLookupByUsage,
7975 7976 7977 7978 7979 7980 7981
    .defineXML = remoteSecretDefineXML,
    .getXMLDesc = remoteSecretGetXMLDesc,
    .setValue = remoteSecretSetValue,
    .getValue = remoteSecretGetValue,
    .undefine = remoteSecretUndefine
};

7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992
static virDeviceMonitor dev_monitor = {
    .name = "remote",
    .open = remoteDevMonOpen,
    .close = remoteDevMonClose,
    .numOfDevices = remoteNodeNumOfDevices,
    .listDevices = remoteNodeListDevices,
    .deviceLookupByName = remoteNodeDeviceLookupByName,
    .deviceDumpXML = remoteNodeDeviceDumpXML,
    .deviceGetParent = remoteNodeDeviceGetParent,
    .deviceNumOfCaps = remoteNodeDeviceNumOfCaps,
    .deviceListCaps = remoteNodeDeviceListCaps,
7993 7994
    .deviceCreateXML = remoteNodeDeviceCreateXML,
    .deviceDestroy = remoteNodeDeviceDestroy
7995 7996 7997
};


A
Atsushi SAKAI 已提交
7998
#ifdef WITH_LIBVIRTD
7999
static virStateDriver state_driver = {
8000
    .initialize = remoteStartup,
8001
};
A
Atsushi SAKAI 已提交
8002
#endif
8003 8004


8005
/** remoteRegister:
8006 8007
 *
 * Register driver with libvirt driver system.
8008 8009
 *
 * Returns -1 on error.
8010 8011 8012 8013
 */
int
remoteRegister (void)
{
8014
    if (virRegisterDriver (&remote_driver) == -1) return -1;
8015
    if (virRegisterNetworkDriver (&network_driver) == -1) return -1;
D
Daniel Veillard 已提交
8016
    if (virRegisterInterfaceDriver (&interface_driver) == -1) return -1;
8017
    if (virRegisterStorageDriver (&storage_driver) == -1) return -1;
8018
    if (virRegisterDeviceMonitor (&dev_monitor) == -1) return -1;
8019
    if (virRegisterSecretDriver (&secret_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
8020
#ifdef WITH_LIBVIRTD
8021
    if (virRegisterStateDriver (&state_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
8022
#endif
8023 8024 8025

    return 0;
}